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

17
18
from pyrocko.plot import mpl_init, mpl_papersize, mpl_margins

19
20
logger = logging.getLogger('grond.plot')

Sebastian Heimann's avatar
Sebastian Heimann committed
21
22
23
km = 1000.


24
25
26
27
28
29
30
31
32
33
34
35
36
def amp_spec_max(spec_trs, key):
    amaxs = {}
    for spec_tr in spec_trs:
        amax = num.max(num.abs(spec_tr.ydata))
        k = key(spec_tr)
        if k not in amaxs:
            amaxs[k] = amax
        else:
            amaxs[k] = max(amaxs[k], amax)

    return amaxs


Sebastian Heimann's avatar
Sebastian Heimann committed
37
38
39
40
41
42
43
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def nextpow2(i):
    return 2**int(math.ceil(math.log(i)/math.log(2.)))


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):
Sebastian Heimann's avatar
Sebastian Heimann committed
67
68
69
    s = ''
    if t < 0.:
        s = '-'
Sebastian Heimann's avatar
Sebastian Heimann committed
70

Sebastian Heimann's avatar
Sebastian Heimann committed
71
    t = abs(t)
Sebastian Heimann's avatar
Sebastian Heimann committed
72

Sebastian Heimann's avatar
Sebastian Heimann committed
73
74
    if t < 10.0:
        return s + '%.2g s' % t
Sebastian Heimann's avatar
Sebastian Heimann committed
75
    elif 10.0 <= t < 3600.:
Sebastian Heimann's avatar
Sebastian Heimann committed
76
77
78
79
80
        return s + util.time_to_str(t, format='%M:%S min')
    elif 3600. <= t < 24*3600.:
        return s + util.time_to_str(t, format='%H:%M h')
    else:
        return s + '%.1f d' % (t / (24.*3600.))
Sebastian Heimann's avatar
Sebastian Heimann committed
81
82


Marius Isken's avatar
Marius Isken committed
83
84
85
86
87
88
89
90
91
92
93
94
def scale_axes(ax, scale):
    from matplotlib.ticker import ScalarFormatter

    class FormatScaled(ScalarFormatter):
        @staticmethod
        def __call__(value, pos):
            return u'%d' % (value * scale)

    ax.get_xaxis().set_major_formatter(FormatScaled())
    ax.get_yaxis().set_major_formatter(FormatScaled())


Sebastian Heimann's avatar
Sebastian Heimann committed
95
96
97
98
99
100
def eigh_sorted(mat):
    evals, evecs = num.linalg.eigh(mat)
    iorder = num.argsort(evals)
    return evals[iorder], evecs[:, iorder]


101
102
103
104
105
106
107
108
109
def make_norm_trace(a, b, exponent):
    tmin = max(a.tmin, b.tmin)
    tmax = min(a.tmax, b.tmax)
    c = a.chop(tmin, tmax, inplace=False)
    bc = b.chop(tmin, tmax, inplace=False)
    c.set_ydata(num.abs(c.get_ydata() - bc.get_ydata())**exponent)
    return c


Sebastian Heimann's avatar
Sebastian Heimann committed
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
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()


Sebastian Heimann's avatar
Sebastian Heimann committed
188
def draw_sequence_figures(model, plt, misfit_cutoff=None, sort_by='misfit'):
Sebastian Heimann's avatar
Sebastian Heimann committed
189
190
191
    problem = model.problem

    imodels = num.arange(model.nmodels)
Sebastian Heimann's avatar
wip...    
Sebastian Heimann committed
192
    bounds = problem.get_parameter_bounds() + problem.get_dependant_bounds()
Sebastian Heimann's avatar
Sebastian Heimann committed
193

194
    xref = problem.get_xref()
Sebastian Heimann's avatar
Sebastian Heimann committed
195
196
197
198
199
200
201
202
203
204
205

    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]

206
207
208
209
210
211
212
    if sort_by == 'iteration':
        imodels = imodels[isort]
    elif sort_by == 'misfit':
        imodels = num.arange(imodels.size)
    else:
        assert False

Sebastian Heimann's avatar
Sebastian Heimann committed
213
214
215
216
217
218
219
220
221
222
223
224
    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

225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    def config_axes(axes, nfx, nfy, impl, iplot, nplots):
        if (impl - 1) % nfx != nfx - 1:
            axes.get_yaxis().tick_left()

        if (impl - 1) >= (nfx * (nfy-1)) or iplot >= nplots - nfx:
            axes.set_xlabel('Iteration')
            if not (impl - 1) / nfx == 0:
                axes.get_xaxis().tick_bottom()
        elif (impl - 1) / nfx == 0:
            axes.get_xaxis().tick_top()
            axes.set_xticklabels([])
        else:
            axes.get_xaxis().set_visible(False)

    fontsize = 10.0

Sebastian Heimann's avatar
Sebastian Heimann committed
241
    nfx = 2
242
    nfy = 3
Sebastian Heimann's avatar
Sebastian Heimann committed
243
244
245
    # nfz = (npar + ndep + 1 - 1) / (nfx*nfy) + 1
    cmap = cm.YlOrRd
    cmap = cm.jet
246
    msize = 1.5
Sebastian Heimann's avatar
Sebastian Heimann committed
247
    axes = None
248
    figs = []
Sebastian Heimann's avatar
Sebastian Heimann committed
249
250
251
252
253
254
    fig = None
    alpha = 0.5
    for ipar in xrange(npar):
        impl = ipar % (nfx*nfy) + 1

        if impl == 1:
255
256
257
            fig = plt.figure(figsize=mpl_papersize('a5', 'landscape'))
            labelpos = mpl_margins(fig, nw=nfx, nh=nfy, w=7., h=5., wspace=7.,
                                   hspace=2., units=fontsize)
258
            figs.append(fig)
Sebastian Heimann's avatar
Sebastian Heimann committed
259
260
261

        par = problem.parameters[ipar]

262
263
264
        axes = fig.add_subplot(nfy, nfx, impl)
        labelpos(axes, 2.5, 2.0)

Sebastian Heimann's avatar
Sebastian Heimann committed
265
266
        axes.set_ylabel(par.get_label())
        axes.get_yaxis().set_major_locator(plt.MaxNLocator(4))
267
268

        config_axes(axes, nfx, nfy, impl, ipar, npar+ndep+1)
Sebastian Heimann's avatar
Sebastian Heimann committed
269
270
271
272
273

        axes.set_ylim(*fixlim(*par.scaled(bounds[ipar])))
        axes.set_xlim(0, model.nmodels)

        axes.scatter(
274
275
276
277
            imodels[ibest], par.scaled(xs[ibest, ipar]), s=msize,
            c=iorder[ibest], edgecolors='none', cmap=cmap, alpha=alpha)

        axes.axhline(par.scaled(xref[ipar]), color='black', alpha=0.3)
Sebastian Heimann's avatar
Sebastian Heimann committed
278
279
280
281
282
283

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

        if impl == 1:
284
285
286
            fig = plt.figure(figsize=mpl_papersize('a5', 'landscape'))
            labelpos = mpl_margins(fig, nw=nfx, nh=nfy, w=7., h=5., wspace=7.,
                                   hspace=2., units=fontsize)
287
            figs.append(fig)
Sebastian Heimann's avatar
Sebastian Heimann committed
288
289
290

        par = problem.dependants[idep]

291
292
293
        axes = fig.add_subplot(nfy, nfx, impl)
        labelpos(axes, 2.5, 2.0)

Sebastian Heimann's avatar
Sebastian Heimann committed
294
295
        axes.set_ylabel(par.get_label())
        axes.get_yaxis().set_major_locator(plt.MaxNLocator(4))
296
297
298

        config_axes(axes, nfx, nfy, impl, npar+idep, npar+ndep+1)

Sebastian Heimann's avatar
Sebastian Heimann committed
299
300
301
302
303
        axes.set_ylim(*fixlim(*par.scaled(bounds[npar+idep])))
        axes.set_xlim(0, model.nmodels)

        ys = problem.make_dependant(xs[ibest, :], par.name)
        axes.scatter(
304
305
306
307
308
            imodels[ibest], par.scaled(ys), s=msize, c=iorder[ibest],
            edgecolors='none', cmap=cmap, alpha=alpha)

        y = problem.make_dependant(xref, par.name)
        axes.axhline(par.scaled(y), color='black', alpha=0.3)
Sebastian Heimann's avatar
Sebastian Heimann committed
309
310
311

    impl = (npar+ndep) % (nfx*nfy) + 1
    if impl == 1:
312
313
314
        fig = plt.figure(figsize=mpl_papersize('a5', 'landscape'))
        labelpos = mpl_margins(fig, nw=nfx, nh=nfy, w=7., h=5., wspace=7.,
                               hspace=2., units=fontsize)
315
        figs.append(fig)
Sebastian Heimann's avatar
Sebastian Heimann committed
316

317
318
319
320
    axes = fig.add_subplot(nfy, nfx, impl)
    labelpos(axes, 2.5, 2.0)

    config_axes(axes, nfx, nfy, impl, npar+ndep, npar+ndep+1)
Sebastian Heimann's avatar
Sebastian Heimann committed
321
322
323
324
325
326
327

    axes.set_ylim(0., 1.5)
    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],
328
329
330
331
        s=msize, edgecolors='none', cmap=cmap, alpha=alpha)

    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)
Sebastian Heimann's avatar
Sebastian Heimann committed
332
333
334
335
336
337

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

    axes.set_ylabel('Misfit')

338
    return figs
Sebastian Heimann's avatar
Sebastian Heimann committed
339
340
341


def draw_jointpar_figures(
342
        model, plt, misfit_cutoff=None, ibootstrap=None, color=None,
343
        exclude=None, include=None, draw_ellipses=False):
344

345
    color = 'misfit'
Sebastian Heimann's avatar
Sebastian Heimann committed
346
    # exclude = ['duration']
347
    # include = ['magnitude', 'rel_moment_iso', 'rel_moment_clvd', 'depth']
348
349
    neach = 6
    figsize = (8, 8)
Sebastian Heimann's avatar
Sebastian Heimann committed
350
351
    # cmap = cm.YlOrRd
    # cmap = cm.jet
352
    cmap = cm.coolwarm
353
    msize = 1.5
Sebastian Heimann's avatar
Sebastian Heimann committed
354
355
356

    problem = model.problem
    if not problem:
357
        return []
Sebastian Heimann's avatar
Sebastian Heimann committed
358
359
360

    xs = model.xs

Sebastian Heimann's avatar
wip...    
Sebastian Heimann committed
361
    bounds = problem.get_parameter_bounds() + problem.get_dependant_bounds()
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
362
363
364
365
366
367
368
369
    for ipar in xrange(problem.ncombined):
        par = problem.combined[ipar]
        lo, hi = bounds[ipar]
        if lo == hi:
            if exclude is None:
                exclude = []

            exclude.append(par.name)
Sebastian Heimann's avatar
Sebastian Heimann committed
370

Sebastian Heimann's avatar
wip...    
Sebastian Heimann committed
371
    xref = problem.get_xref()
Sebastian Heimann's avatar
Sebastian Heimann committed
372
373
374
375
376
377
378
379
380
381
382

    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
383
    if misfit_cutoff is not None:
Sebastian Heimann's avatar
Sebastian Heimann committed
384
        ibest = gms < misfit_cutoff
Sebastian Heimann's avatar
Sebastian Heimann committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
        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
403

404
405
406
407
    smap = {}
    iselected = 0
    for ipar in xrange(problem.ncombined):
        par = problem.combined[ipar]
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
408
409
        if exclude and par.name in exclude or \
                include and par.name not in include:
410
            continue
Sebastian Heimann's avatar
Sebastian Heimann committed
411

412
413
414
415
        smap[iselected] = ipar
        iselected += 1

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

417
418
419
420
    if nselected < 2:
        logger.warn('cannot draw joinpar figures with less than two '
                    'parameters selected')
        return []
421
422

    nfig = (nselected-2) / neach + 1
Sebastian Heimann's avatar
Sebastian Heimann committed
423
424
425
426
427
428

    figs = []
    for ifig in xrange(nfig):
        figs_row = []
        for jfig in xrange(nfig):
            if ifig >= jfig:
429
                figs_row.append(plt.figure(figsize=figsize))
Sebastian Heimann's avatar
Sebastian Heimann committed
430
431
432
433
434
            else:
                figs_row.append(None)

        figs.append(figs_row)

435
436
    for iselected in xrange(nselected):
        ipar = smap[iselected]
Sebastian Heimann's avatar
Sebastian Heimann committed
437
        ypar = problem.combined[ipar]
438
439
        for jselected in xrange(iselected):
            jpar = smap[jselected]
Sebastian Heimann's avatar
Sebastian Heimann committed
440
441
            xpar = problem.combined[jpar]

442
443
            ixg = (iselected - 1)
            iyg = jselected
Sebastian Heimann's avatar
Sebastian Heimann committed
444
445
446
447
448
449
450
451
452
453
454
455
456

            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)

457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
            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
492
493
494
495

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

496
            if iselected == nselected - 1 or ix == neach - 1:
Sebastian Heimann's avatar
Sebastian Heimann committed
497
                axes.annotate(
498
                    xpar.get_label(with_unit=False),
Sebastian Heimann's avatar
Sebastian Heimann committed
499
500
501
502
503
504
505
506
                    xy=(0.5, -0.05),
                    xycoords='axes fraction',
                    verticalalignment='top',
                    horizontalalignment='right',
                    rotation=45.)

            if iy == 0:
                axes.annotate(
507
                    ypar.get_label(with_unit=False),
Sebastian Heimann's avatar
Sebastian Heimann committed
508
509
                    xy=(-0.05, 0.5),
                    xycoords='axes fraction',
510
511
512
                    verticalalignment='top',
                    horizontalalignment='right',
                    rotation=45.)
Sebastian Heimann's avatar
Sebastian Heimann committed
513

Sebastian Heimann's avatar
Sebastian Heimann committed
514
515
            fx = problem.extract(xs, jpar)
            fy = problem.extract(xs, ipar)
Sebastian Heimann's avatar
Sebastian Heimann committed
516
517
518
519
520

            axes.scatter(
                xpar.scaled(fx),
                ypar.scaled(fy),
                c=color,
521
                s=msize, alpha=0.5, cmap=cmap, edgecolors='none')
Sebastian Heimann's avatar
Sebastian Heimann committed
522

523
524
525
526
527
528
529
530
531
532
533
534
            if draw_ellipses:
                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)
Sebastian Heimann's avatar
Sebastian Heimann committed
535
536
537

            fx = problem.extract(xref, jpar)
            fy = problem.extract(xref, ipar)
538
539
540
541
542

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

545
546
547
548
549
550
    figs_flat = []
    for figs_row in figs:
        figs_flat.extend(fig for fig in figs_row if fig is not None)

    return figs_flat

Sebastian Heimann's avatar
Sebastian Heimann committed
551
552
553
554

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

Sebastian Heimann's avatar
Sebastian Heimann committed
555
556
557
558
559
    fontsize = 10.

    fig = plt.figure(figsize=(6, 2))
    axes = fig.add_subplot(1, 1, 1, aspect=1.0)
    fig.subplots_adjust(left=0., right=1., bottom=0., top=1.)
Sebastian Heimann's avatar
Sebastian Heimann committed
560
561
562

    problem = model.problem
    if not problem:
563
564
        logger.warn('problem not set')
        return []
Sebastian Heimann's avatar
Sebastian Heimann committed
565
566
567
568

    xs = model.xs

    if xs.size == 0:
569
570
        logger.warn('empty models vector')
        return []
Sebastian Heimann's avatar
Sebastian Heimann committed
571
572
573
574
575
576

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

Sebastian Heimann's avatar
Sebastian Heimann committed
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
    mean_source = core.get_mean_source(problem, model.xs)
    best_source = core.get_best_source(problem, model.xs, model.misfits)
    ref_source = problem.base_source

    for xpos, label in [
            (0., 'Full'),
            (2., 'Isotropic'),
            (4., 'Deviatoric'),
            (6., 'CLVD'),
            (8., 'DC')]:

        axes.annotate(
            label,
            xy=(1+xpos, 3),
            xycoords='data',
            xytext=(0., 0.),
            textcoords='offset points',
            ha='center',
            va='center',
            color='black',
            fontsize=fontsize)

    decos = []
    for source in [best_source, mean_source, ref_source]:
        mt = source.pyrocko_moment_tensor()
        deco = mt.standard_decomposition()
        decos.append(deco)

    moment_full_max = max(deco[-1][0] for deco in decos)

    for ypos, label, deco, color_t in [
            (2., 'Ensemble best', decos[0], scolor('aluminium5')),
            (1., 'Ensemble mean', decos[1], scolor('scarletred1')),
            (0., 'Reference', decos[2], scolor('aluminium3'))]:

        [(moment_iso, ratio_iso, m_iso),
         (moment_dc, ratio_dc, m_dc),
         (moment_clvd, ratio_clvd, m_clvd),
         (moment_devi, ratio_devi, m_devi),
         (moment_full, ratio_full, m_full)] = deco

        size0 = moment_full / moment_full_max

        axes.annotate(
            label,
            xy=(-2., ypos),
            xycoords='data',
            xytext=(0., 0.),
            textcoords='offset points',
            ha='left',
            va='center',
            color='black',
            fontsize=fontsize)

        for xpos, mt_part, ratio, ops in [
                (0., m_full, ratio_full, '-'),
                (2., m_iso, ratio_iso, '='),
                (4., m_devi, ratio_devi, '='),
                (6., m_clvd, ratio_clvd, '+'),
                (8., m_dc, ratio_dc, None)]:

638
            if ratio > 1e-4:
639
640
641
642
643
644
645
646
647
648
649
650
                try:
                    beachball.plot_beachball_mpl(
                        mt_part, axes,
                        beachball_type='full',
                        position=(1.+xpos, ypos),
                        size=0.9*size0*math.sqrt(ratio),
                        size_units='data',
                        color_t=color_t,
                        linewidth=1.0)

                except beachball.BeachballError, e:
                    logger.warn(str(e))
Sebastian Heimann's avatar
Sebastian Heimann committed
651

652
653
654
655
656
657
658
659
                    axes.annotate(
                        'ERROR',
                        xy=(1.+xpos, ypos),
                        ha='center',
                        va='center',
                        color='red',
                        fontsize=fontsize)

Sebastian Heimann's avatar
Sebastian Heimann committed
660
661
662
            else:
                axes.annotate(
                    'N/A',
Sebastian Heimann's avatar
Sebastian Heimann committed
663
                    xy=(1.+xpos, ypos),
Sebastian Heimann's avatar
Sebastian Heimann committed
664
665
666
667
668
669
670
671
672
673
674
675
676
                    ha='center',
                    va='center',
                    color='black',
                    fontsize=fontsize)

            if ops is not None:
                axes.annotate(
                    ops,
                    xy=(2. + xpos, ypos),
                    ha='center',
                    va='center',
                    color='black',
                    fontsize=fontsize)
Sebastian Heimann's avatar
Sebastian Heimann committed
677
678

    axes.axison = False
Sebastian Heimann's avatar
Sebastian Heimann committed
679
680
    axes.set_xlim(-2.25, 9.75)
    axes.set_ylim(-0.5, 3.5)
Sebastian Heimann's avatar
Sebastian Heimann committed
681

682
683
    return [fig]

Sebastian Heimann's avatar
Sebastian Heimann committed
684
685
686

def draw_contributions_figure(model, plt):

687
688
689
690
691
    fontsize = 10.

    fig = plt.figure(figsize=mpl_papersize('a5', 'landscape'))
    labelpos = mpl_margins(fig, nw=2, nh=2, w=7., h=5., wspace=2.,
                           hspace=5., units=fontsize)
Sebastian Heimann's avatar
Sebastian Heimann committed
692
693
694

    problem = model.problem
    if not problem:
695
696
        logger.warn('problem not set')
        return []
Sebastian Heimann's avatar
Sebastian Heimann committed
697
698
699
700

    xs = model.xs

    if xs.size == 0:
701
702
        logger.warn('empty models vector')
        return []
Sebastian Heimann's avatar
Sebastian Heimann committed
703
704
705

    imodels = num.arange(model.nmodels)

Sebastian Heimann's avatar
Sebastian Heimann committed
706
    gms = problem.global_misfits(model.misfits)**problem.norm_exponent
Sebastian Heimann's avatar
Sebastian Heimann committed
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722

    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)
723
724
    labelpos(axes, 2.5, 2.0)

Sebastian Heimann's avatar
Sebastian Heimann committed
725
726
727
728
    axes.set_ylabel('Relative contribution (smoothed)')
    axes.set_ylim(0.0, 1.0)

    axes2 = fig.add_subplot(2, 2, 3, sharex=axes)
729
730
    labelpos(axes2, 2.5, 2.0)

Sebastian Heimann's avatar
Sebastian Heimann committed
731
732
733
734
735
736
737
738
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
    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])

768
769
770
771
772
        add_args = {}
        if ii < 20:
            add_args['label'] = '%s (%.2g)' % (
                target.string_id(), num.mean(rel_ms[-1]))

Sebastian Heimann's avatar
Sebastian Heimann committed
773
774
775
776
        axes.fill(
            poly_x, rel_poly_y,
            alpha=0.5,
            color=colors[ii % len(colors)],
777
            **add_args)
Sebastian Heimann's avatar
Sebastian Heimann committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792

        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(
793
        title='Contributions (top twenty)',
Sebastian Heimann's avatar
Sebastian Heimann committed
794
795
        bbox_to_anchor=(1.05, 0.0, 1.0, 1.0),
        loc='upper left',
796
        ncol=1, borderaxespad=0., prop={'size': 9})
Sebastian Heimann's avatar
Sebastian Heimann committed
797
798
799
800

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

801
802
    return [fig]

Sebastian Heimann's avatar
Sebastian Heimann committed
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826

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])

        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
827
828
829
830
831
832
833
834
835
836
837
838
839
    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
840
841
    axes.plot(imodels, gms_softclip[isort], color='black')

Sebastian Heimann's avatar
Sebastian Heimann committed
842
843
    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
844

845
846
    return [fig]

847

Sebastian Heimann's avatar
Sebastian Heimann committed
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
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)


879
def plot_dtrace(axes, tr, space, mi, ma, **kwargs):
Sebastian Heimann's avatar
Sebastian Heimann committed
880
881
    t = tr.get_xdata()
    y = tr.get_ydata()
882
883
    y2 = (num.concatenate((y, num.zeros(y.size))) - mi) / \
        (ma-mi) * space - (1.0 + space)
Sebastian Heimann's avatar
Sebastian Heimann committed
884
    t2 = num.concatenate((t, t[::-1]))
885
    axes.fill(
Sebastian Heimann's avatar
Sebastian Heimann committed
886
887
888
889
        t2, y2,
        clip_on=False,
        **kwargs)

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
934
935
936
937
938
def plot_spectrum(
        axes, spec_syn, spec_obs, fmin, fmax, space, mi, ma,
        syn_color='red', obs_color='black',
        syn_lw=1.5, obs_lw=1.0, color_vline='gray', fontsize=9.):

    fpad = (fmax - fmin) / 6.

    for spec, color, lw in [
            (spec_syn, syn_color, syn_lw),
            (spec_obs, obs_color, obs_lw)]:

        f = spec.get_xdata()
        mask = num.logical_and(fmin - fpad <= f, f <= fmax + fpad)

        f = f[mask]
        y = num.abs(spec.get_ydata())[mask]

        y2 = (num.concatenate((y, num.zeros(y.size))) - mi) / \
            (ma-mi) * space - (1.0 + space)
        f2 = num.concatenate((f, f[::-1]))
        axes2 = axes.twiny()
        axes2.set_axis_off()

        axes2.set_xlim(fmin - fpad * 5, fmax + fpad * 5)

        axes2.plot(f2, y2, clip_on=False, color=color, lw=lw)
        axes2.fill(f2, y2, alpha=0.1, clip_on=False, color=color)

    axes2.plot([fmin, fmin], [-1.0 - space, -1.0], color=color_vline)
    axes2.plot([fmax, fmax], [-1.0 - space, -1.0], color=color_vline)

    for (text, fx, ha) in [
            ('%.3g Hz' % fmin, fmin, 'right'),
            ('%.3g Hz' % fmax, fmax, 'left')]:

        axes2.annotate(
            text,
            xy=(fx, -1.0),
            xycoords='data',
            xytext=(
                fontsize*0.4 * [-1, 1][ha == 'left'],
                -fontsize*0.2),
            textcoords='offset points',
            ha=ha,
            va='top',
            color=color_vline,
            fontsize=fontsize)

Sebastian Heimann's avatar
Sebastian Heimann committed
939

940
941
942
943
def plot_dtrace_vline(axes, t, space, **kwargs):
    axes.plot([t, t], [-1.0 - space, -1.0], **kwargs)


Andreas Steinberg's avatar
Andreas Steinberg committed
944
945
946
947
948
949
950
951
952
953
954
955
def draw_fits_figures_statics(ds, model, plt):
    from pyrocko.orthodrome import latlon_to_ne_numpy
    problem = model.problem

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

    gms = problem.global_misfits(model.misfits)
    isort = num.argsort(gms)
    gms = gms[isort]
    xs = model.xs[isort, :]
    xbest = xs[0, :]
Marius Isken's avatar
Marius Isken committed
956

Andreas Steinberg's avatar
Andreas Steinberg committed
957
958
959
960
961
962
    source = problem.get_source(xbest)

    ms, ns, results = problem.evaluate(xbest, result_mode='full')

    figures = []

Marius Isken's avatar
Marius Isken committed
963
964
    def decorateAxes(ax, title):
        ax.set_title(title)
Marius Isken's avatar
Marius Isken committed
965
966
        ax.set_xlabel('[km]')
        scale_axes(ax, 1./km)
Marius Isken's avatar
Marius Isken committed
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
        ax.set_aspect('equal')

    def drawRectangularOutline(ax):
        source.regularize()
        fn, fe = source.outline(cs='xy').T
        offset_n, offset_e = latlon_to_ne_numpy(
            sat_target.lats[0], sat_target.lons[0],
            source.lat, source.lon)
        fn += offset_n
        fe += offset_e
        ax.plot(offset_e, offset_n, marker='o')
        ax.plot(fe, fn, marker='o')
        # ax.fill(fe, fn, color=(0.5, 0.5, 0.5), alpha=0.5)
        # ax.plot(fe[:2], fn[:2], linewidth=2., color='black', alpha=0.5)

Marius Isken's avatar
Marius Isken committed
982
983
984
985
986
987
    def mapDisplacementGrid(displacements, scene):
        qt = scene.quadtree
        array = num.empty_like(scene.displacement)
        array.fill(num.nan)
        for syn_v, l in zip(displacements, qt.leaves):
            array[l._slice_rows, l._slice_cols] = syn_v
Marius Isken's avatar
Marius Isken committed
988

Marius Isken's avatar
Marius Isken committed
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
        array[scene.displacement_mask] = num.nan
        return array

    def drawTiles(ax, scene):
        rect = scene.quadtree.getMPLRectangles()
        for r in rect:
            r.set_edgecolor((.4, .4, .4))
            r.set_linewidth(.5)
            r.set_facecolor('none')
        map(ax.add_artist, rect)

        ax.scatter(scene.quadtree.leaf_coordinates[:, 0],
                   scene.quadtree.leaf_coordinates[:, 1],
                   s=.25, c='black', alpha=.1)

    for sat_target, result in zip(problem.satellite_targets, results):
        fig = plt.figure()
        fig.set_size_inches(16, 4)
        axes = []
        gs = gridspec.GridSpec(1, 3,
                               hspace=.0001, left=.06, bottom=.1,
                               right=.9)
        axes.append(plt.subplot(gs[0, 0]))
        axes.append(plt.subplot(gs[0, 1]))
        axes.append(plt.subplot(gs[0, 2]))

        scene = ds.get_kite_scene(sat_target.scene_id)

        stat_obs = result.statics_obs
        cmw = cm.ScalarMappable(cmap='coolwarm')
        cmw.set_array(stat_obs)
        cmap = cmw.get_cmap()
        norm = cmw.norm
Andreas Steinberg's avatar
Andreas Steinberg committed
1022
1023
1024

        stat_syn = result.statics_syn['displacement.los']
        res = (stat_obs - stat_syn)
Marius Isken's avatar
Marius Isken committed
1025
1026
1027
1028
1029
1030
1031
1032
        im_extent = (scene.frame.E.min(), scene.frame.E.max(),
                     scene.frame.N.min(), scene.frame.N.max())

        ax = axes[0]
        ax.imshow(mapDisplacementGrid(stat_obs, scene),
                  extent=im_extent, cmap=cmap,
                  origin='lower', norm=norm)
        drawTiles(ax, scene)
Marius Isken's avatar
Marius Isken committed
1033
1034
        drawRectangularOutline(ax)
        decorateAxes(ax, 'Data')
Marius Isken's avatar
Marius Isken committed
1035
        ax.set_ylabel('[km]')
Andreas Steinberg's avatar
Andreas Steinberg committed
1036

Marius Isken's avatar
Marius Isken committed
1037
1038
1039
1040
1041
        ax = axes[1]
        ax.imshow(mapDisplacementGrid(stat_syn, scene),
                  extent=im_extent, cmap=cmap,
                  origin='lower', norm=norm)
        drawTiles(ax, scene)
Marius Isken's avatar
Marius Isken committed
1042
1043
        drawRectangularOutline(ax)
        decorateAxes(ax, 'Model')
Marius Isken's avatar
Marius Isken committed
1044
        ax.get_yaxis().set_visible(False)
Marius Isken's avatar
Marius Isken committed
1045

Marius Isken's avatar
Marius Isken committed
1046
1047
1048
1049
1050
        ax = axes[2]
        ax.imshow(mapDisplacementGrid(res, scene),
                  extent=im_extent, cmap=cmap,
                  origin='lower', norm=norm)
        drawTiles(ax, scene)
Marius Isken's avatar
Marius Isken committed
1051
1052
        drawRectangularOutline(ax)
        decorateAxes(ax, 'Residual')
Marius Isken's avatar
Marius Isken committed
1053
        ax.get_yaxis().set_visible(False)
Andreas Steinberg's avatar
Andreas Steinberg committed
1054

Marius Isken's avatar
Marius Isken committed
1055
1056
1057
1058
        pos = ax.get_position()
        cax = fig.add_axes([pos.x1 + .01, pos.y0, 0.02, pos.y1 - pos.y0])
        cbar = fig.colorbar(cmw, cax=cax, orientation='vertical')
        cbar.set_label('[m]')
Andreas Steinberg's avatar
Andreas Steinberg committed
1059
        figures.append(fig)
Marius Isken's avatar
Marius Isken committed
1060

Andreas Steinberg's avatar
Andreas Steinberg committed
1061
    return figures
1062

Marius Isken's avatar
Marius Isken committed
1063

Sebastian Heimann's avatar
Sebastian Heimann committed
1064
def draw_fits_figures(ds, model, plt):
1065
1066
    fontsize = 8
    fontsize_title = 10
Sebastian Heimann's avatar
Sebastian Heimann committed
1067
1068
1069

    problem = model.problem

Marius Isken's avatar
Marius Isken committed
1070
    for target in problem.waveform_targets:
Sebastian Heimann's avatar
Sebastian Heimann committed
1071
1072
1073
        target.set_dataset(ds)

    target_index = dict(
Marius Isken's avatar
Marius Isken committed
1074
        (target, i) for (i, target) in enumerate(problem.waveform_targets))
Sebastian Heimann's avatar
Sebastian Heimann committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089

    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)

Andreas Steinberg's avatar
Andreas Steinberg committed
1090
    source = problem.get_source(xbest)
Sebastian Heimann's avatar
Sebastian Heimann committed
1091
1092
1093

    target_to_result = {}
    all_syn_trs = []
1094
    all_syn_specs = []
1095
    ms, ns, results = problem.evaluate(xbest, result_mode='full')
Sebastian Heimann's avatar
Sebastian Heimann committed
1096
1097

    dtraces = []
Marius Isken's avatar
Marius Isken committed
1098
    for target, result in zip(problem.waveform_targets, results):
1099
        if isinstance(result, gf.SeismosizerError):
Sebastian Heimann's avatar
Sebastian Heimann committed
1100
1101
1102
1103
1104
1105
            dtraces.append(None)
            continue

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

1106
1107
1108
1109
1110
1111
1112
1113
        if target.misfit_config.domain == 'cc_max_norm':
            tref = (result.filtered_obs.tmin + result.filtered_obs.tmax) * 0.5
            for tr_filt, tr_proc, tshift in (
                    (result.filtered_obs,
                     result.processed_obs,
                     0.),
                    (result.filtered_syn,
                     result.processed_syn,
1114
                     result.tshift)):
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133

                norm = num.sum(num.abs(tr_proc.ydata)) / tr_proc.data_len()
                tr_filt.ydata /= norm
                tr_proc.ydata /= norm

                tr_filt.shift(tshift)
                tr_proc.shift(tshift)

            ctr = result.cc
            ctr.shift(tref)

            dtrace = ctr

        else:
            for tr in (
                    result.filtered_obs,
                    result.filtered_syn,
                    result.processed_obs,
                    result.processed_syn):
Sebastian Heimann's avatar
Sebastian Heimann committed
1134

1135
                tr.ydata *= w
Sebastian Heimann's avatar
Sebastian Heimann committed
1136

1137
1138
1139
1140
1141
1142
1143
            for spec in (
                    result.spectrum_obs,
                    result.spectrum_syn):

                if spec is not None:
                    spec.ydata *= w

Sebastian Heimann's avatar
Sebastian Heimann committed
1144
            if result.tshift is not None and result.tshift != 0.0:
1145
                # result.filtered_syn.shift(result.tshift)
1146
1147
                result.processed_syn.shift(result.tshift)

1148
1149
1150
            dtrace = make_norm_trace(
                result.processed_syn, result.processed_obs,
                problem.norm_exponent)
Sebastian Heimann's avatar
Sebastian Heimann committed
1151
1152
1153

        target_to_result[target] = result

1154
1155
1156
        dtrace.meta = dict(
            normalisation_family=target.normalisation_family,
            path=target.path)
Sebastian Heimann's avatar
Sebastian Heimann committed
1157
        dtraces.append(dtrace)
1158

1159
        result.processed_syn.meta = dict(
1160
1161
            normalisation_family=target.normalisation_family,
            path=target.path)
1162

Sebastian Heimann's avatar
Sebastian Heimann committed
1163
1164
        all_syn_trs.append(result.processed_syn)

1165
        if result.spectrum_syn:
1166
            result.spectrum_syn.meta = dict(
1167
1168
                normalisation_family=target.normalisation_family,
                path=target.path)
1169

1170
1171
            all_syn_specs.append(result.spectrum_syn)

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1172
1173
    if not all_syn_trs:
        logger.warn('no traces to show')
1174
        return []
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1175

Sebastian Heimann's avatar
flake8    
Sebastian Heimann committed
1176
    def skey(tr):
1177
        return tr.meta['normalisation_family'], tr.meta['path']
1178
1179

    trace_minmaxs = trace.minmax(all_syn_trs, skey)
Sebastian Heimann's avatar
Sebastian Heimann committed
1180

1181
    amp_spec_maxs = amp_spec_max(all_syn_specs, skey)
1182

1183
    dminmaxs = trace.minmax([x for x in dtraces if x is not None], skey)
Sebastian Heimann's avatar
Sebastian Heimann committed
1184
1185
1186

    for tr in dtraces:
        if tr:
1187
            dmin, dmax = dminmaxs[skey(tr)]
1188
            tr.ydata /= max(abs(dmin), abs(dmax))
Sebastian Heimann's avatar
Sebastian Heimann committed
1189
1190

    cg_to_targets = gather(
Marius Isken's avatar
Marius Isken committed
1191
        problem.waveform_targets,
1192
        lambda t: (t.normalisation_family, t.path, t.codes[3]),
1193
        filter=lambda t: t in target_to_result)
Sebastian Heimann's avatar
Sebastian Heimann committed
1194
1195
1196

    cgs = sorted(cg_to_targets.keys())

1197
    figs = []
Sebastian Heimann's avatar
Sebastian Heimann committed
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
    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:
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
                    figures[iyy, ixx] = plt.figure(
                        figsize=mpl_papersize('a4', 'landscape'))

                    figures[iyy, ixx].subplots_adjust(
                        left=0.03,
                        right=1.0 - 0.03,
                        bottom=0.03,
                        top=1.0 - 0.06,
                        wspace=0.2,
                        hspace=0.2)

1284
                    figs.append(figures[iyy, ixx])
Sebastian Heimann's avatar
Sebastian Heimann committed
1285
1286
1287
1288

                fig = figures[iyy, ixx]

                target = frame_to_target[iy, ix]
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1289

1290
1291
                amin, amax = trace_minmaxs[
                    target.normalisation_family, target.path]
1292
                absmax = max(abs(amin), abs(amax))
Sebastian Heimann's avatar
Sebastian Heimann committed
1293

1294
1295
                ny_this = nymax  # min(ny, nymax)
                nx_this = nxmax  # min(nx, nxmax)
Sebastian Heimann's avatar
Sebastian Heimann committed
1296
1297
1298
1299
                i_this = (iy % ny_this) * nx_this + (ix % nx_this) + 1

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

1300
1301
                space = 0.5
                space_factor = 1.0 + space
Sebastian Heimann's avatar
Sebastian Heimann committed
1302
                axes2.set_axis_off()
1303
                axes2.set_ylim(-1.05 * space_factor, 1.05)
Sebastian Heimann's avatar
Sebastian Heimann committed
1304
1305
1306

                axes = axes2.twinx()
                axes.set_axis_off()
1307
1308
1309
1310
1311

                if target.misfit_config.domain == 'cc_max_norm':
                    axes.set_ylim(-10. * space_factor, 10.)
                else:
                    axes.set_ylim(-absmax*1.33 * space_factor, absmax*1.33)
Sebastian Heimann's avatar
Sebastian Heimann committed
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322

                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(
1323
                    axes2, result.processed_obs.get_xdata(), result.taper,
Sebastian Heimann's avatar
Sebastian Heimann committed
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
                    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')

1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
                cc_color = scolor('aluminium5')

                if target.misfit_config.domain == 'cc_max_norm':
                    tref = (result.filtered_obs.tmin +
                            result.filtered_obs.tmax) * 0.5

                    plot_dtrace(
                        axes2, dtrace, space, -1., 1.,
                        fc=light(cc_color, 0.5),
                        ec=cc_color)

                    plot_dtrace_vline(
                        axes2, tref, space, color=tap_color_annot)

1349
1350
                elif target.misfit_config.domain == 'frequency_domain':

1351
1352
                    asmax = amp_spec_maxs[
                        target.normalisation_family, target.path]
1353
1354
                    fmin, fmax = \
                        target.misfit_config.get_full_frequency_range()
1355
1356
1357
1358
1359
1360
1361
1362
1363

                    plot_spectrum(
                        axes2,
                        result.spectrum_syn,
                        result.spectrum_obs,
                        fmin, fmax,
                        space, 0., asmax,
                        syn_color=syn_color,
                        obs_color=obs_color,
1364
1365
                        syn_lw=1.0,
                        obs_lw=0.75,
1366
1367
1368
                        color_vline=tap_color_annot,
                        fontsize=fontsize)

1369
1370
1371
                else:
                    plot_dtrace(
                        axes2, dtrace, space, 0., 1.,
1372
                        fc=light(misfit_color, 0.3),
1373
                        ec=misfit_color)
Sebastian Heimann's avatar
Sebastian Heimann committed
1374
1375
1376

                plot_trace(
                    axes, result.filtered_syn,
1377
                    color=syn_color_light, lw=1.0)
Sebastian Heimann's avatar
Sebastian Heimann committed
1378
1379
1380

                plot_trace(
                    axes, result.filtered_obs,
1381
                    color=obs_color_light, lw=0.75)
Sebastian Heimann's avatar
Sebastian Heimann committed
1382
1383
1384

                plot_trace(
                    axes, result.processed_syn,
1385
                    color=syn_color, lw=1.0)
Sebastian Heimann's avatar
Sebastian Heimann committed
1386
1387
1388

                plot_trace(
                    axes, result.processed_obs,
1389
1390
1391
1392
                    color=obs_color, lw=0.75)

                xdata = result.filtered_obs.get_xdata()
                axes.set_xlim(xdata[0], xdata[-1])
Sebastian Heimann's avatar
Sebastian Heimann committed
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402

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

                for tmark in tmarks:
                    axes2.plot(
                        [tmark, tmark], [-0.9, 0.1], color=tap_color_annot)

                for tmark, text, ha in [
1403
1404
                        (tmarks[0],
                         '$\,$ ' + str_duration(tmarks[0] - source.time),
Sebastian Heimann's avatar
Sebastian Heimann committed
1405
                         'right'),
1406
1407
                        (tmarks[1],
                         '$\Delta$ ' + str_duration(tmarks[1] - tmarks[0]),
Sebastian Heimann's avatar
Sebastian Heimann committed
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
                         'left')]:

                    axes2.annotate(
                        text,
                        xy=(tmark, -0.9),
                        xycoords='data',
                        xytext=(
                            fontsize*0.4 * [-1, 1][ha == 'left'],
                            fontsize*0.2),
                        textcoords=