plot.py 33.6 KB
Newer Older
Sebastian Heimann's avatar
Sebastian Heimann committed
1
2
import math
import random
3
import logging
Sebastian Heimann's avatar
Sebastian Heimann committed
4
5
6
7
import os.path as op
import numpy as num
from scipy import signal
from pyrocko import automap, moment_tensor as mtm, beachball, guts, trace, util
8
from pyrocko import hudson
Sebastian Heimann's avatar
Sebastian Heimann committed
9
10
11
12
13
14
from grond import core
from matplotlib import pyplot as plt
from matplotlib import cm, patches
from pyrocko.cake_plot import mpl_init, labelspace, colors, \
    str_to_mpl_color as scolor, light

15
16
logger = logging.getLogger('grond.plot')

Sebastian Heimann's avatar
Sebastian Heimann committed
17
18
19
km = 1000.


Sebastian Heimann's avatar
Sebastian Heimann committed
20
21
22
23
24
25
26
def ordersort(x):
    isort = num.argsort(x)
    iorder = num.empty(isort.size)
    iorder[isort] = num.arange(isort.size)
    return iorder


Sebastian Heimann's avatar
Sebastian Heimann committed
27
28
29
30
def nextpow2(i):
    return 2**int(math.ceil(math.log(i)/math.log(2.)))


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def get_mean_source(problem, xs):
    x_mean = num.mean(xs, axis=0)
    source = problem.unpack(x_mean)
    return source


def get_best_source(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    print gms.min(), gms.mean()
    ibest = num.argmin(gms)
    x_best = xs[ibest, :]
    source = problem.unpack(x_best)
    return source


Sebastian Heimann's avatar
Sebastian Heimann committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def fixlim(lo, hi):
    if lo == hi:
        return lo - 1.0, hi + 1.0
    else:
        return lo, hi


def str_dist(dist):
    if dist < 10.0:
        return '%g m' % dist
    elif 10. <= dist < 1.*km:
        return '%.0f m' % dist
    elif 1.*km <= dist < 10.*km:
        return '%.1f km' % (dist / km)
    else:
        return '%.0f km' % (dist / km)


def str_duration(t):
    if t < 1.0:
        return '%g s' % t
    elif 1.0 <= t < 10.0:
        return '%.1f s' % t
    elif 10.0 <= t < 3600.:
        return util.time_to_str(t, format='%M:%S min')
    elif 3600. <= t < 24*3600.:
        return util.time_to_str(t, format='%H:%M h')
    else:
        return '%.1f d' % (t / (24.*3600.))


def str_duration2(t):
    if t < 1.0:
        return '%g s' % t
    elif 1.0 <= t < 10.0:
        return '%.1f s' % t
    elif 10.0 <= t < 3600.:
        return '%.0f s' % t
    elif 10.0 <= t < 3600.:
        return '%.1f h' % (t / 3600.)


def eigh_sorted(mat):
    evals, evecs = num.linalg.eigh(mat)
    iorder = num.argsort(evals)
    return evals[iorder], evecs[:, iorder]


def plot(stations, center_lat, center_lon, radius, output_path,
         width=25., height=25.,
         show_station_labels=False):

    station_lats = num.array([s.lat for s in stations])
    station_lons = num.array([s.lon for s in stations])

    map = automap.Map(
        width=width,
        height=height,
        lat=center_lat,
        lon=center_lon,
        radius=radius,
        show_rivers=False,
        show_topo=False,
        illuminate_factor_land=0.35,
        color_dry=(240, 240, 235),
        topo_cpt_wet='white_sea_land',
        topo_cpt_dry='white_sea_land')

    map.gmt.psxy(
        in_columns=(station_lons, station_lats),
        S='t8p',
        G='black',
        *map.jxyr)

    if show_station_labels:
        for s in stations:
            map.add_label(s.lat, s.lon, '%s' % s.station)

    map.save(output_path)


def map_geometry(config, output_path):
    stations = config.get_dataset().get_stations()

    lat0, lon0, radius = core.stations_mean_latlondist(stations)

    radius *= 1.5

    plot(stations, lat0, lon0, radius, output_path,
         show_station_labels=True)


class GrondModel(object):
    def __init__(self, **kwargs):
        self.listeners = []
        self.set_problem(None)

    def add_listener(self, listener):
        self.listeners.append(listener)

    def set_problem(self, problem):

        self.problem = problem
        if problem:
            nparameters = problem.nparameters
            ntargets = problem.ntargets
        else:
            nparameters = 0
            ntargets = 0

        nmodels = 0
        nmodels_capacity = 1024

        self._xs_buffer = num.zeros(
            (nmodels_capacity, nparameters), dtype=num.float)
        self._misfits_buffer = num.zeros(
            (nmodels_capacity, ntargets, 2), dtype=num.float)

        self.xs = self._xs_buffer[:nmodels, :]
        self.misfits = self._misfits_buffer[:nmodels, :, :]

        self.data_changed()

    @property
    def nmodels(self):
        return self.xs.shape[0]

    @property
    def nmodels_capacity(self):
        return self._xs_buffer.shape[0]

    def append(self, xs, misfits):
        assert xs.shape[0] == misfits.shape[0]

        nmodels_add = xs.shape[0]

        nmodels = self.nmodels
        nmodels_new = nmodels + nmodels_add
        nmodels_capacity_new = max(1024, nextpow2(nmodels_new))

        nmodels_capacity = self.nmodels_capacity
        if nmodels_capacity_new > nmodels_capacity:
            xs_buffer = num.zeros(
                (nmodels_capacity_new, self.problem.nparameters),
                dtype=num.float)

            misfits_buffer = num.zeros(
                (nmodels_capacity_new, self.problem.ntargets, 2),
                dtype=num.float)

            xs_buffer[:nmodels, :] = self._xs_buffer[:nmodels]
            misfits_buffer[:nmodels, :] = self._misfits_buffer[:nmodels]
            self._xs_buffer = xs_buffer
            self._misfits_buffer = misfits_buffer

        self._xs_buffer[nmodels:nmodels+nmodels_add, :] = xs
        self._misfits_buffer[nmodels:nmodels+nmodels_add, :, :] = misfits

        nmodels = nmodels_new

        self.xs = self._xs_buffer[:nmodels, :]
        self.misfits = self._misfits_buffer[:nmodels, :, :]

        self.data_changed()

    def data_changed(self):
        for listener in self.listeners:
            listener()


def draw_sequence_figures(model, plt, misfit_cutoff=None):
    problem = model.problem
    if not problem:
        return

    imodels = num.arange(model.nmodels)
    bounds = problem.bounds() + problem.dependant_bounds()

    xref = problem.pack(problem.base_source)

    xs = model.xs

    npar = problem.nparameters
    ndep = problem.ndependants

    gms = problem.global_misfits(model.misfits)
    gms_softclip = num.where(gms > 1.0, 0.2 * num.log10(gms) + 1.0, gms)

    isort = num.argsort(gms)[::-1]

    imodels = imodels[isort]
    gms = gms[isort]
    gms_softclip = gms_softclip[isort]
    xs = xs[isort, :]

    iorder = num.empty_like(isort)
    iorder = num.arange(iorder.size)

    if misfit_cutoff is None:
        ibest = num.ones(gms.size, dtype=num.bool)
    else:
        ibest = gms < misfit_cutoff

    nfx = 2
    nfy = 4
    # nfz = (npar + ndep + 1 - 1) / (nfx*nfy) + 1
    cmap = cm.YlOrRd
    cmap = cm.jet
    axes = None
    fig = None
    alpha = 0.5
    for ipar in xrange(npar):
        impl = ipar % (nfx*nfy) + 1

        if impl == 1:
            fig = plt.figure()

        par = problem.parameters[ipar]

        axes = fig.add_subplot(nfy, nfx, impl, sharex=axes)
        axes.set_ylabel(par.get_label())
        axes.get_yaxis().set_major_locator(plt.MaxNLocator(4))
        if impl < (nfx*nfy-1):
            axes.get_xaxis().set_visible(False)
        else:
            axes.set_xlabel('Iteration')

        axes.set_ylim(*fixlim(*par.scaled(bounds[ipar])))
        axes.set_xlim(0, model.nmodels)
        axes.axhline(par.scaled(xref[ipar]), color='black', alpha=0.3)

        axes.scatter(
            imodels[ibest], par.scaled(xs[ibest, ipar]), s=3, c=iorder[ibest],
            lw=0, cmap=cmap, alpha=alpha)

    for idep in xrange(ndep):
        # ifz, ify, ifx = num.unravel_index(ipar, (nfz, nfy, nfx))
        impl = (npar+idep) % (nfx*nfy) + 1

        if impl == 1:
            fig = plt.figure()

        par = problem.dependants[idep]

        axes = fig.add_subplot(nfy, nfx, impl, sharex=axes)
        axes.set_ylabel(par.get_label())
        axes.get_yaxis().set_major_locator(plt.MaxNLocator(4))
        if impl < (nfx*nfy-1):
            axes.get_xaxis().set_visible(False)
        else:
            axes.set_xlabel('Iteration')
        axes.set_ylim(*fixlim(*par.scaled(bounds[npar+idep])))
        axes.set_xlim(0, model.nmodels)

        y = problem.make_dependant(xref, par.name)
        axes.axhline(par.scaled(y), color='black', alpha=0.3)

        ys = problem.make_dependant(xs[ibest, :], par.name)
        axes.scatter(
            imodels[ibest], par.scaled(ys), s=3, c=iorder[ibest],
            lw=0, cmap=cmap, alpha=alpha)

    impl = (npar+ndep) % (nfx*nfy) + 1
    if impl == 1:
        fig = plt.figure()

    axes = fig.add_subplot(nfy, nfx, impl, sharex=axes)

    axes.set_ylim(0., 1.5)
    axes.axhspan(1.0, 1.5, color=(0.8, 0.8, 0.8), alpha=0.2)
    axes.axhline(1.0, color=(0.5, 0.5, 0.5), zorder=2)
    axes.set_yticks([0., 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4])
    axes.set_yticklabels(['0.0', '0.2', '0.4', '0.6', '0.8', '1', '10', '100'])

    axes.scatter(
        imodels[ibest], gms_softclip[ibest], c=iorder[ibest],
        s=3, lw=0, cmap=cmap, alpha=alpha)

    axes.set_xlim(0, model.nmodels)
    axes.set_xlabel('Iteration')

    axes.set_ylabel('Misfit')

    fig.canvas.draw()


def draw_jointpar_figures(
333
334
335
336
337
338
339
340
341
342
        model, plt, misfit_cutoff=None, ibootstrap=None, color=None,
        exclude=None):

    color = 'magnitude'
    #exclude = ['duration']
    neach = 6
    figsize = (8, 8)
    #cmap = cm.YlOrRd
    #cmap = cm.jet
    cmap = cm.coolwarm
Sebastian Heimann's avatar
Sebastian Heimann committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363

    problem = model.problem
    if not problem:
        return

    xs = model.xs

    bounds = problem.bounds() + problem.dependant_bounds()

    xref = problem.pack(problem.base_source)

    if ibootstrap is not None:
        gms = problem.bootstrap_misfits(model.misfits, ibootstrap)
    else:
        gms = problem.global_misfits(model.misfits)

    isort = num.argsort(gms)[::-1]

    gms = gms[isort]
    xs = xs[isort, :]

Sebastian Heimann's avatar
Sebastian Heimann committed
364
    if misfit_cutoff is not None:
Sebastian Heimann's avatar
Sebastian Heimann committed
365
        ibest = gms < misfit_cutoff
Sebastian Heimann's avatar
Sebastian Heimann committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
        gms = gms[ibest]
        xs = xs[ibest]

    nmodels = xs.shape[0]

    if color == 'dist':
        mx = num.mean(xs, axis=0)
        cov = num.cov(xs.T)
        mdists = core.mahalanobis_distance(xs, mx, cov)
        color = ordersort(mdists)

    elif color == 'misfit':
        iorder = num.arange(nmodels)
        color = iorder

    elif color in problem.parameter_names:
        ind = problem.name_to_index(color)
        color = ordersort(problem.extract(xs, ind))
Sebastian Heimann's avatar
Sebastian Heimann committed
384

385
386
387
388
389
390
    smap = {}
    iselected = 0
    for ipar in xrange(problem.ncombined):
        par = problem.combined[ipar]
        if exclude and par.name in exclude:
            continue
Sebastian Heimann's avatar
Sebastian Heimann committed
391

392
393
394
395
        smap[iselected] = ipar
        iselected += 1

    nselected = iselected
Sebastian Heimann's avatar
Sebastian Heimann committed
396

397
398
399
400
401
    if nselected == 0:
        return


    nfig = (nselected-2) / neach + 1
Sebastian Heimann's avatar
Sebastian Heimann committed
402
403
404
405
406
407

    figs = []
    for ifig in xrange(nfig):
        figs_row = []
        for jfig in xrange(nfig):
            if ifig >= jfig:
408
                figs_row.append(plt.figure(figsize=figsize))
Sebastian Heimann's avatar
Sebastian Heimann committed
409
410
411
412
413
            else:
                figs_row.append(None)

        figs.append(figs_row)

414
415
    for iselected in xrange(nselected):
        ipar = smap[iselected]
Sebastian Heimann's avatar
Sebastian Heimann committed
416
        ypar = problem.combined[ipar]
417
418
        for jselected in xrange(iselected):
            jpar = smap[jselected]
Sebastian Heimann's avatar
Sebastian Heimann committed
419
420
            xpar = problem.combined[jpar]

421
422
            ixg = (iselected - 1)
            iyg = jselected
Sebastian Heimann's avatar
Sebastian Heimann committed
423
424
425
426
427
428
429
430
431
432
433
434
435

            ix = ixg % neach
            iy = iyg % neach

            ifig = ixg/neach
            jfig = iyg/neach

            aind = (neach, neach, (ix * neach) + iy + 1)

            fig = figs[ifig][jfig]

            axes = fig.add_subplot(*aind)

436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
            axes.axvline(0., color=scolor('aluminium3'), lw=0.5)
            axes.axhline(0., color=scolor('aluminium3'), lw=0.5)
            for spine in axes.spines.values():
                spine.set_edgecolor(scolor('aluminium5'))
                spine.set_linewidth(0.5)

            xmin, xmax = fixlim(*xpar.scaled(bounds[jpar]))
            ymin, ymax = fixlim(*ypar.scaled(bounds[ipar]))

            if ix == 0 or jselected + 1 == iselected:
                for (xpos, xoff, x) in [(0.0, 10., xmin), (1.0, -10., xmax)]:
                    axes.annotate(
                        '%.2g%s' % (x, xpar.get_unit_suffix()),
                        xy=(xpos, 1.05),
                        xycoords='axes fraction',
                        xytext=(xoff, 5.),
                        textcoords='offset points',
                        verticalalignment='bottom',
                        horizontalalignment='left',
                        rotation=45.)

            if iy == neach - 1 or jselected + 1 == iselected:
                for (ypos, yoff, y) in [(0., 10., ymin), (1.0, -10., ymax)]:
                    axes.annotate(
                        '%.2g%s' % (y, ypar.get_unit_suffix()),
                        xy=(1.0, ypos),
                        xycoords='axes fraction',
                        xytext=(5., yoff),
                        textcoords='offset points',
                        verticalalignment='bottom',
                        horizontalalignment='left',
                        rotation=45.)

            axes.set_xlim(xmin, xmax)
            axes.set_ylim(ymin, ymax)
Sebastian Heimann's avatar
Sebastian Heimann committed
471
472
473
474

            axes.get_xaxis().set_ticks([])
            axes.get_yaxis().set_ticks([])

475
            if iselected == nselected - 1 or ix == neach - 1:
Sebastian Heimann's avatar
Sebastian Heimann committed
476
                axes.annotate(
477
                    xpar.get_label(with_unit=False),
Sebastian Heimann's avatar
Sebastian Heimann committed
478
479
480
481
482
483
484
485
                    xy=(0.5, -0.05),
                    xycoords='axes fraction',
                    verticalalignment='top',
                    horizontalalignment='right',
                    rotation=45.)

            if iy == 0:
                axes.annotate(
486
                    ypar.get_label(with_unit=False),
Sebastian Heimann's avatar
Sebastian Heimann committed
487
488
                    xy=(-0.05, 0.5),
                    xycoords='axes fraction',
489
490
491
                    verticalalignment='top',
                    horizontalalignment='right',
                    rotation=45.)
Sebastian Heimann's avatar
Sebastian Heimann committed
492

Sebastian Heimann's avatar
Sebastian Heimann committed
493
494
            fx = problem.extract(xs, jpar)
            fy = problem.extract(xs, ipar)
Sebastian Heimann's avatar
Sebastian Heimann committed
495
496
497
498
499

            axes.scatter(
                xpar.scaled(fx),
                ypar.scaled(fy),
                c=color,
500
                s=3, alpha=0.5, cmap=cmap, edgecolors='none')
Sebastian Heimann's avatar
Sebastian Heimann committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

            cov = num.cov((xpar.scaled(fx), ypar.scaled(fy)))
            evals, evecs = eigh_sorted(cov)
            evals = num.sqrt(evals)
            ell = patches.Ellipse(
                xy=(num.mean(xpar.scaled(fx)), num.mean(ypar.scaled(fy))),
                width=evals[0]*2,
                height=evals[1]*2,
                angle=num.rad2deg(num.arctan2(evecs[1][0], evecs[0][0])))

            ell.set_facecolor('none')
            axes.add_artist(ell)

            fx = problem.extract(xref, jpar)
            fy = problem.extract(xref, ipar)
516
517
518
519
520
521
522
523
524
525
526

            ref_color = scolor('aluminium6')
            ref_color_light = 'none'
            axes.plot(
                xpar.scaled(fx), ypar.scaled(fy), 's',
                mew=1.5, ms=5, color=ref_color_light, mec=ref_color)

    for jfig, figs_row in enumerate(figs):
        for ifig, fig in enumerate(figs_row):
            if fig is not None:
                fig.savefig('jointpar-%i-%i.pdf' % (jfig, ifig))
Sebastian Heimann's avatar
Sebastian Heimann committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714


def draw_solution_figure(
        model, plt, misfit_cutoff=None, beachball_type='full'):

    fig = plt.figure()

    problem = model.problem
    if not problem:
        return

    xs = model.xs

    if xs.size == 0:
        return

    def get_mt_part(x):
        source = problem.unpack(x)
        mt = source.pyrocko_moment_tensor()
        res = mt.standard_decomposition()
        m = dict(
            dc=res[1][2],
            deviatoric=res[3][2],
            full=res[4][2])[beachball_type]

        return mtm.MomentTensor(m=m)

    gms = problem.global_misfits(model.misfits)
    isort = num.argsort(gms)
    iorder = num.empty_like(isort)
    iorder[isort] = num.arange(iorder.size)[::-1]

    if misfit_cutoff is None:
        iibest = num.where(iorder > iorder.size - 100)[0]
    else:
        iibest = num.where(gms < misfit_cutoff)[0]

    nsamp = 10
    for isamp in xrange(nsamp):
        ichoice = iibest[random.randint(0, iibest.size-1)]

        axes = fig.add_subplot(1, nsamp+1, isamp+1, aspect=1.)
        axes.axison = False
        axes.set_xlim(-1.05, 1.05)
        axes.set_ylim(-1.05, 1.05)
        axes.set_title('#%i' % (iorder.size - iorder[ichoice] + 1))

        x = xs[ichoice, :]
        mt = get_mt_part(x)
        beachball.plot_beachball_mpl(mt, axes)

    axes = fig.add_subplot(1, nsamp+1, nsamp+1, aspect=1.)
    axes.axison = False
    axes.set_xlim(-1.05, 1.05)
    axes.set_ylim(-1.05, 1.05)
    axes.set_title('Ref')

    xref = problem.pack(problem.base_source)
    mt = get_mt_part(xref)
    beachball.plot_beachball_mpl(mt, axes)


def draw_contributions_figure(model, plt):

    fig = plt.figure()

    problem = model.problem
    if not problem:
        return

    xs = model.xs

    if xs.size == 0:
        return

    imodels = num.arange(model.nmodels)

    gms = problem.global_misfits(model.misfits)**2

    isort = num.argsort(gms)[::-1]

    gms = gms[isort]

    gms_softclip = num.where(gms > 1.0, 0.1 * num.log10(gms) + 1.0, gms)

    gcms = problem.global_contributions(model.misfits)
    gcms = gcms[isort, :]

    jsort = num.argsort(gcms[-1, :])[::-1]

    # ncols = 4
    # nrows = ((problem.ntargets + 1) - 1) / ncols + 1

    axes = fig.add_subplot(2, 2, 1)
    labelspace(axes)
    axes.set_ylabel('Relative contribution (smoothed)')
    axes.set_ylim(0.0, 1.0)

    axes2 = fig.add_subplot(2, 2, 3, sharex=axes)
    labelspace(axes2)
    axes2.set_xlabel('Tested model, sorted descending by global misfit value')

    axes2.set_ylabel('Square of misfit')

    axes2.set_ylim(0., 1.5)
    axes2.axhspan(1.0, 1.5, color=(0.8, 0.8, 0.8))
    axes2.set_yticks([0., 0.2, 0.4, 0.6, 0.8, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5])
    axes2.set_yticklabels(
        ['0.0', '0.2', '0.4', '0.6', '0.8', '1', '10', '100', '1000', '10000',
         '100000'])

    axes2.set_xlim(imodels[0], imodels[-1])

    rel_ms_sum = num.zeros(model.nmodels)
    rel_ms_smooth_sum = num.zeros(model.nmodels)
    ms_smooth_sum = num.zeros(model.nmodels)
    b = num.hanning(100)
    b /= num.sum(b)
    a = [1]
    ii = 0

    for itarget in jsort:
        target = problem.targets[itarget]
        ms = gcms[:, itarget]
        ms = num.where(num.isfinite(ms), ms, 0.0)
        if num.all(ms == 0.0):
            continue

        rel_ms = ms / gms

        rel_ms_smooth = signal.filtfilt(b, a, rel_ms)

        ms_smooth = rel_ms_smooth * gms_softclip

        rel_poly_y = num.concatenate(
            [rel_ms_smooth_sum[::-1], rel_ms_smooth_sum + rel_ms_smooth])
        poly_x = num.concatenate([imodels[::-1], imodels])

        axes.fill(
            poly_x, rel_poly_y,
            alpha=0.5,
            color=colors[ii % len(colors)],
            label='%s.%s.%s.%s.%s (%.2g)' % (
                target.codes + (target.groupname, num.mean(rel_ms[-1]),)))

        poly_y = num.concatenate(
            [ms_smooth_sum[::-1], ms_smooth_sum + ms_smooth])

        axes2.fill(poly_x, poly_y, alpha=0.5, color=colors[ii % len(colors)])

        rel_ms_sum += rel_ms

        # axes.plot(imodels, rel_ms_sum, color='black', alpha=0.1, zorder=-1)

        ms_smooth_sum += ms_smooth
        rel_ms_smooth_sum += rel_ms_smooth
        ii += 1

    axes.legend(
        title='Contributions (large to small at minimal global misfit)',
        bbox_to_anchor=(1.05, 0.0, 1.0, 1.0),
        loc='upper left',
        ncol=2, borderaxespad=0., prop={'size': 12})

    axes2.plot(imodels, gms_softclip, color='black')
    axes2.axhline(1.0, color=(0.5, 0.5, 0.5))
    fig.tight_layout()


def draw_bootstrap_figure(model, plt):

    fig = plt.figure()

    problem = model.problem
    gms = problem.global_misfits(model.misfits)

    imodels = num.arange(model.nmodels)

    axes = fig.add_subplot(1, 1, 1)

    gms_softclip = num.where(gms > 1.0, 0.1 * num.log10(gms) + 1.0, gms)

    ibests = []
    for ibootstrap in xrange(problem.nbootstrap):
        bms = problem.bootstrap_misfits(model.misfits, ibootstrap)
        isort_bms = num.argsort(bms)[::-1]

        ibests.append(isort_bms[-1])
Sebastian Heimann's avatar
Sebastian Heimann committed
715
        print num.argmin(bms), isort_bms[-1]
Sebastian Heimann's avatar
Sebastian Heimann committed
716
717
718
719

        bms_softclip = num.where(bms > 1.0, 0.1 * num.log10(bms) + 1.0, bms)
        axes.plot(imodels, bms_softclip[isort_bms], color='red', alpha=0.2)

Sebastian Heimann's avatar
Sebastian Heimann committed
720
721
722
723
724
725
726
727
728
729
730
731
732
    isort = num.argsort(gms)[::-1]
    iorder = num.empty(isort.size)
    iorder[isort] = imodels

    axes.plot(iorder[ibests], gms_softclip[ibests], 'x', color='black')

    m = num.median(gms[ibests])
    s = num.std(gms[ibests])

    axes.axhline(m+s, color='black', alpha=0.5)
    axes.axhline(m, color='black')
    axes.axhline(m-s, color='black', alpha=0.5)

Sebastian Heimann's avatar
Sebastian Heimann committed
733
734
    axes.plot(imodels, gms_softclip[isort], color='black')

Sebastian Heimann's avatar
Sebastian Heimann committed
735
736
    axes.set_xlim(imodels[0], imodels[-1])
    axes.set_xlabel('Tested model, sorted descending by global misfit value')
Sebastian Heimann's avatar
Sebastian Heimann committed
737

738

Sebastian Heimann's avatar
Sebastian Heimann committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
def gather(l, key, sort=None, filter=None):
    d = {}
    for x in l:
        if filter is not None and not filter(x):
            continue

        k = key(x)
        if k not in d:
            d[k] = []

        d[k].append(x)

    if sort is not None:
        for v in d.itervalues():
            v.sort(key=sort)

    return d


def plot_trace(axes, tr, **kwargs):
    return axes.plot(tr.get_xdata(), tr.get_ydata(), **kwargs)


def plot_taper(axes, t, taper, **kwargs):
    y = num.ones(t.size) * 0.9
    taper(y, t[0], t[1] - t[0])
    y2 = num.concatenate((y, -y[::-1]))
    t2 = num.concatenate((t, t[::-1]))
    axes.fill(t2, y2, **kwargs)


def plot_dtrace(axes, tr, **kwargs):
    t = tr.get_xdata()
    y = tr.get_ydata()
    y2 = num.concatenate(((y*0.2), num.zeros(y.size))) - 1.0
    t2 = num.concatenate((t, t[::-1]))
    return axes.fill(
        t2, y2,
        clip_on=False,
        **kwargs)


def draw_fits_figures(ds, model, plt):
    fontsize = 10

    problem = model.problem

    for target in problem.targets:
        target.set_dataset(ds)

    target_index = dict(
        (target, i) for (i, target) in enumerate(problem.targets))

    gms = problem.global_misfits(model.misfits)
    isort = num.argsort(gms)
    gms = gms[isort]
    xs = model.xs[isort, :]
    misfits = model.misfits[isort, :]

    xbest = xs[0, :]

    ws = problem.get_target_weights()
    gcms = problem.global_contributions(misfits[:1])[0]

    w_max = num.nanmax(ws)
    gcm_max = num.nanmax(gcms)

    source = problem.unpack(xbest)

    target_to_result = {}
    all_syn_trs = []
    ms, ns, results = problem.evaluate(xbest, return_traces=True)

    dtraces = []
    for target, result in zip(problem.targets, results):
        if result is None:
            dtraces.append(None)
            continue

        itarget = target_index[target]
        w = target.get_combined_weight(problem.apply_balancing_weights)

        if target.misfit_config.domain != 'time_domain':
            continue

        for tr in (
                result.filtered_obs,
                result.filtered_syn,
                result.processed_obs,
                result.processed_syn):

            tr.ydata *= w

        target_to_result[target] = result

        dtrace = result.processed_syn.copy()
        dtrace.set_ydata(
            (
                (result.processed_syn.get_ydata() -
                 result.processed_obs.get_ydata())**2))
        dtraces.append(dtrace)

        all_syn_trs.append(result.processed_syn)

    amin, amax = trace.minmax(all_syn_trs, lambda tr: None)[None]

    dmin, dmax = trace.minmax([x for x in dtraces if x], lambda tr: None)[None]

    for tr in dtraces:
        if tr:
            tr.ydata /= dmax

    absmax = max(abs(amin), abs(amax))

    cg_to_targets = gather(
        problem.targets, lambda t:
            (t.codes[3], t.groupname), filter=lambda t: t in target_to_result)

    cgs = sorted(cg_to_targets.keys())

    for cg in cgs:
        targets = cg_to_targets[cg]
        nframes = len(targets)

        nx = int(math.ceil(math.sqrt(nframes)))
        ny = (nframes-1)/nx+1

        nxmax = 4
        nymax = 4

        nxx = (nx-1) / nxmax + 1
        nyy = (ny-1) / nymax + 1

        # nz = nxx * nyy

        xs = num.arange(nx) / ((max(2, nx) - 1.0) / 2.)
        ys = num.arange(ny) / ((max(2, ny) - 1.0) / 2.)

        xs -= num.mean(xs)
        ys -= num.mean(ys)

        fxs = num.tile(xs, ny)
        fys = num.repeat(ys, nx)

        data = []

        for target in targets:
            azi = source.azibazi_to(target)[0]
            dist = source.distance_to(target)
            x = dist*num.sin(num.deg2rad(azi))
            y = dist*num.cos(num.deg2rad(azi))
            data.append((x, y, dist))

        gxs, gys, dists = num.array(data, dtype=num.float).T

        iorder = num.argsort(dists)

        gxs = gxs[iorder]
        gys = gys[iorder]
        targets_sorted = [targets[ii] for ii in iorder]

        gxs -= num.mean(gxs)
        gys -= num.mean(gys)

        gmax = max(num.max(num.abs(gys)), num.max(num.abs(gxs)))
        if gmax == 0.:
            gmax = 1.

        gxs /= gmax
        gys /= gmax

        dists = num.sqrt(
            (fxs[num.newaxis, :] - gxs[:, num.newaxis])**2 +
            (fys[num.newaxis, :] - gys[:, num.newaxis])**2)

        distmax = num.max(dists)

        availmask = num.ones(dists.shape[1], dtype=num.bool)
        frame_to_target = {}
        for itarget, target in enumerate(targets_sorted):
            iframe = num.argmin(
                num.where(availmask, dists[itarget], distmax + 1.))
            availmask[iframe] = False
            iy, ix = num.unravel_index(iframe, (ny, nx))
            frame_to_target[iy, ix] = target

        figures = {}
        for iy in xrange(ny):
            for ix in xrange(nx):
                if (iy, ix) not in frame_to_target:
                    continue

                ixx = ix/nxmax
                iyy = iy/nymax
                if (iyy, ixx) not in figures:
934
                    figures[iyy, ixx] = plt.figure(figsize=(16, 9))
Sebastian Heimann's avatar
Sebastian Heimann committed
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

                fig = figures[iyy, ixx]

                target = frame_to_target[iy, ix]

                ny_this = min(ny, nymax)
                nx_this = min(nx, nxmax)
                i_this = (iy % ny_this) * nx_this + (ix % nx_this) + 1

                axes2 = fig.add_subplot(ny_this, nx_this, i_this)

                axes2.set_axis_off()
                axes2.set_ylim(-1.05, 1.05)

                axes = axes2.twinx()
                axes.set_axis_off()
                axes.set_ylim(-absmax*1.33, absmax*1.33)

                itarget = target_index[target]
                result = target_to_result[target]

                dtrace = dtraces[itarget]

                tap_color_annot = (0.35, 0.35, 0.25)
                tap_color_edge = (0.85, 0.85, 0.80)
                tap_color_fill = (0.95, 0.95, 0.90)

                plot_taper(
                    axes2, result.processed_syn.get_xdata(), result.taper,
                    fc=tap_color_fill, ec=tap_color_edge)

                obs_color = scolor('aluminium5')
                obs_color_light = light(obs_color, 0.5)

                syn_color = scolor('scarletred2')
                syn_color_light = light(syn_color, 0.5)

                misfit_color = scolor('scarletred2')
                weight_color = scolor('chocolate2')

                plot_dtrace(
                    axes2, dtrace,
                    fc=light(misfit_color, 0.5),
                    ec=misfit_color)

                plot_trace(
                    axes, result.filtered_syn,
                    color=syn_color_light, lw=1.5)

                plot_trace(
                    axes, result.filtered_obs,
                    color=obs_color_light)

                plot_trace(
                    axes, result.processed_syn,
                    color=syn_color, lw=1.5)

                plot_trace(
                    axes, result.processed_obs,
                    color=obs_color)

                tmarks = [
                    result.processed_obs.tmin,
                    result.processed_obs.tmax]

                for tmark in tmarks: