waveform.py 17.5 KB
Newer Older
1
2
3
4
5
import logging
import math
import numpy as num

from pyrocko import gf, trace, weeding
Marius Isken's avatar
Marius Isken committed
6
7
from pyrocko.guts import (Object, String, Float, Bool, Int, StringChoice,
                          Timestamp, List)
8
9
from pyrocko.guts_array import Array

Marius Isken's avatar
Marius Isken committed
10
11
12
13
from .base import (MisfitConfig, MisfitTarget, TargetGroup,
                   MisfitResult, TargetAnalysisResult)

from ..dataset import NotFound
14
15

guts_prefix = 'grond'
Marius Isken's avatar
Marius Isken committed
16
logger = logging.getLogger('grond.target').getChild('waveform')
17
18


Marius Isken's avatar
Marius Isken committed
19
20
21
22
23
24
25
26
27
28
class WaveformTargetGroup(TargetGroup):
    distance_min = Float.T(optional=True)
    distance_max = Float.T(optional=True)
    distance_3d_min = Float.T(optional=True)
    distance_3d_max = Float.T(optional=True)
    depth_min = Float.T(optional=True)
    depth_max = Float.T(optional=True)
    limit = Int.T(optional=True)
    channels = List.T(String.T(), optional=True)

29
    def get_targets(self, ds, event, default_path):
Marius Isken's avatar
Marius Isken committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
        logger.debug('Selecting waveform targets...')
        origin = event
        targets = []

        for st in ds.get_stations():
            for cha in self.channels:
                if ds.is_blacklisted((st.nsl() + (cha,))):
                    continue

                if not isinstance(self.misfit_config,
                                  WaveformMisfitConfig):
                    raise AttributeError('misfit_config must be of'
                                         ' type WaveformMisfitConfig')

                target = WaveformMisfitTarget(
                    quantity='displacement',
                    codes=st.nsl() + (cha,),
                    lat=st.lat,
                    lon=st.lon,
                    depth=st.depth,
                    interpolation=self.interpolation,
                    store_id=self.store_id,
                    misfit_config=self.misfit_config,
                    manual_weight=self.weight,
54
55
                    normalisation_family=self.normalisation_family,
                    path=self.path or default_path)
Marius Isken's avatar
Marius Isken committed
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

                if self.distance_min is not None and \
                   target.distance_to(origin) < self.distance_min:
                    continue

                if self.distance_max is not None and \
                   target.distance_to(origin) > self.distance_max:
                    continue

                if self.distance_3d_min is not None and \
                   target.distance_3d_to(origin) < self.distance_3d_min:
                    continue

                if self.distance_3d_max is not None and \
                   target.distance_3d_to(origin) > self.distance_3d_max:
                    continue

                if self.depth_min is not None and \
                   target.depth < self.depth_min:
                    continue

                if self.depth_max is not None and \
                   target.depth > self.depth_max:
                    continue

                azi, _ = target.azibazi_to(origin)
                if cha == 'R':
                    target.azimuth = azi - 180.
                    target.dip = 0.
                elif cha == 'T':
                    target.azimuth = azi - 90.
                    target.dip = 0.
                elif cha == 'Z':
                    target.azimuth = 0.
                    target.dip = -90.

                target.set_dataset(ds)
                targets.append(target)

        if self.limit:
            return self.weed(origin, targets, self.limit)[0]
        else:
            return targets

    @staticmethod
    def weed(origin, targets, limit, neighborhood=3):
        azimuths = num.zeros(len(targets))
        dists = num.zeros(len(targets))
        for i, target in enumerate(targets):
            _, azimuths[i] = target.azibazi_to(origin)
            dists[i] = target.distance_to(origin)

        badnesses = num.ones(len(targets), dtype=float)
        deleted, meandists_kept = weeding.weed(
            azimuths, dists, badnesses,
            nwanted=limit,
            neighborhood=neighborhood)

        targets_weeded = [
            target for (delete, target) in zip(deleted, targets) if not delete]

        return targets_weeded, meandists_kept, deleted
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


class DomainChoice(StringChoice):
    choices = [
        'time_domain',
        'frequency_domain',
        'envelope',
        'absolute',
        'cc_max_norm']


class Trace(Object):
    pass


class TraceSpectrum(Object):
    network = String.T()
    station = String.T()
    location = String.T()
    channel = String.T()
    deltaf = Float.T(default=1.0)
    fmin = Float.T(default=0.0)
    ydata = Array.T(shape=(None,), dtype=num.complex, serialize_as='list')

    def get_ydata(self):
        return self.ydata

    def get_xdata(self):
        return self.fmin + num.arange(self.ydata.size) * self.deltaf


Marius Isken's avatar
Marius Isken committed
149
150
151
152
153
154
155
class WaveformMisfitResult(MisfitResult):
    processed_obs = Trace.T(optional=True)
    processed_syn = Trace.T(optional=True)
    filtered_obs = Trace.T(optional=True)
    filtered_syn = Trace.T(optional=True)
    spectrum_obs = TraceSpectrum.T(optional=True)
    spectrum_syn = TraceSpectrum.T(optional=True)
156

Marius Isken's avatar
Marius Isken committed
157
158
159
160
161
    taper = trace.Taper.T(optional=True)
    tobs_shift = Float.T(optional=True)
    tsyn_pick = Timestamp.T(optional=True)
    tshift = Float.T(optional=True)
    cc = Trace.T(optional=True)
162
163


Marius Isken's avatar
Marius Isken committed
164
class WaveformMisfitConfig(MisfitConfig):
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
    fmin = Float.T()
    fmax = Float.T()
    ffactor = Float.T(default=1.5)
    tmin = gf.Timing.T(
        optional=True,
        help='Start of main time window used for waveform fitting.')
    tmax = gf.Timing.T(
        optional=True,
        help='End of main time window used for waveform fitting.')
    tfade = Float.T(
        optional=True,
        help='Decay time of taper prepended and appended to main time window '
             'used for waveform fitting [s].')
    pick_synthetic_traveltime = gf.Timing.T(
        optional=True,
        help='Synthetic phase arrival definition for alignment of observed '
             'and synthetic traces.')
    pick_phasename = String.T(
        optional=True,
        help='Name of picked phase for alignment of observed and synthetic '
             'traces.')
    domain = DomainChoice.T(
        default='time_domain',
        help='Type of data characteristic to be fitted.\n\nAvailable choices '
             'are: %s' % ', '.join("``'%s'``" % s
                                   for s in DomainChoice.choices))
191
192
193
    norm_exponent = Int.T(
        default=2,
        help='Exponent to use in norm (1: L1-norm, 2: L2-norm)')
194
195
196
197
198
199
200
201
202
203
204
    tautoshift_max = Float.T(
        default=0.0,
        help='If non-zero, allow synthetic and observed traces to be shifted '
             'against each other by up to +/- the given value [s].')
    autoshift_penalty_max = Float.T(
        default=0.0,
        help='If non-zero, a penalty misfit is added for non-zero shift '
             'values.\n\nThe penalty value is computed as '
             '``autoshift_penalty_max * normalization_factor * tautoshift**2 '
             '/ tautoshift_max**2``')

205
206
    ranges = {}

207
208
209
210
    def get_full_frequency_range(self):
        return self.fmin / self.ffactor, self.fmax * self.ffactor


Marius Isken's avatar
Marius Isken committed
211
class WaveformMisfitTarget(gf.Target, MisfitTarget):
212
213
214
215
    flip_norm = Bool.T(default=False)

    def __init__(self, **kwargs):
        gf.Target.__init__(self, **kwargs)
Marius Isken's avatar
Marius Isken committed
216
        MisfitTarget.__init__(self)
217

Marius Isken's avatar
Marius Isken committed
218
        nmisfits = 1
219

220
    def string_id(self):
221
        return '.'.join(x for x in (self.path) + self.codes if x)
222

Marius Isken's avatar
wip    
Marius Isken committed
223
224
    @property
    def id(self):
225
        return '.'.join(self.codes)
Marius Isken's avatar
wip    
Marius Isken committed
226

227
228
229
230
231
232
233
234
235
236
237
238
239
    def get_plain_target(self):
        d = dict(
            (k, getattr(self, k)) for k in gf.Target.T.propnames)
        return gf.Target(**d)

    def get_combined_weight(self, apply_balancing_weights):
        w = self.manual_weight
        if apply_balancing_weights:
            w *= self.get_balancing_weight()
        return w

    def get_balancing_weight(self):
        if not self.analysis_result:
Marius Isken's avatar
Marius Isken committed
240
241
            raise TargetAnalysisResult.tNoResults(
                'no balancing weights available')
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258

        return self.analysis_result.balancing_weight

    def get_taper_params(self, engine, source):
        store = engine.get_store(self.store_id)
        config = self.misfit_config
        tmin_fit = source.time + store.t(config.tmin, source, self)
        tmax_fit = source.time + store.t(config.tmax, source, self)
        tfade = 1.0/config.fmin
        if config.tfade is None:
            tfade_taper = tfade
        else:
            tfade_taper = config.tfade

        return tmin_fit, tmax_fit, tfade, tfade_taper

    def get_backazimuth_for_waveform(self):
259
        return backazimuth_for_waveform(self.azimuth, self.codes)
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

    def get_freqlimits(self):
        config = self.misfit_config

        return (
            config.fmin/config.ffactor,
            config.fmin, config.fmax,
            config.fmax*config.ffactor)

    def get_pick_shift(self, engine, source):
        config = self.misfit_config
        tobs = None
        tsyn = None
        ds = self.get_dataset()

        if config.pick_synthetic_traveltime and config.pick_phasename:
            store = engine.get_store(self.store_id)
            tsyn = source.time + store.t(
                config.pick_synthetic_traveltime, source, self)

            marker = ds.get_pick(
                source.name,
                self.codes[:3],
                config.pick_phasename)

            if marker:
                tobs = marker.tmin

        return tobs, tsyn

    def get_cutout_timespan(self, tmin, tmax, tfade):
        tinc_obs = 1.0 / self.misfit_config.fmin

        tmin_obs = (math.floor(
            (tmin - tfade) / tinc_obs) - 1.0) * tinc_obs
        tmax_obs = (math.ceil(
            (tmax + tfade) / tinc_obs) + 1.0) * tinc_obs

        return tmin_obs, tmax_obs

    def post_process(self, engine, source, tr_syn):

        tr_syn = tr_syn.pyrocko_trace()
        nslc = self.codes

        config = self.misfit_config

        tmin_fit, tmax_fit, tfade, tfade_taper = \
            self.get_taper_params(engine, source)

        ds = self.get_dataset()

        tobs, tsyn = self.get_pick_shift(engine, source)
        if None not in (tobs, tsyn):
            tobs_shift = tobs - tsyn
        else:
            tobs_shift = 0.0

        tr_syn.extend(
            tmin_fit - tfade * 2.0,
            tmax_fit + tfade * 2.0,
            fillmethod='repeat')

        freqlimits = self.get_freqlimits()

        tr_syn = tr_syn.transfer(
            freqlimits=freqlimits,
            tfade=tfade)

        tr_syn.chop(tmin_fit - 2*tfade, tmax_fit + 2*tfade)

        tmin_obs, tmax_obs = self.get_cutout_timespan(
            tmin_fit+tobs_shift, tmax_fit+tobs_shift, tfade)

        try:
            tr_obs = ds.get_waveform(
                nslc,
                tmin=tmin_obs,
                tmax=tmax_obs,
                tfade=tfade,
                freqlimits=freqlimits,
                deltat=tr_syn.deltat,
                cache=True,
                backazimuth=self.get_backazimuth_for_waveform())

            if tobs_shift != 0.0:
                tr_obs = tr_obs.copy()
                tr_obs.shift(-tobs_shift)

            mr = misfit(
                tr_obs, tr_syn,
                taper=trace.CosTaper(
                    tmin_fit - tfade_taper,
                    tmin_fit,
                    tmax_fit,
                    tmax_fit + tfade_taper),
                domain=config.domain,
357
                exponent=config.norm_exponent,
358
359
360
361
362
363
364
365
366
367
                flip=self.flip_norm,
                result_mode=self._result_mode,
                tautoshift_max=config.tautoshift_max,
                autoshift_penalty_max=config.autoshift_penalty_max)

            mr.tobs_shift = float(tobs_shift)
            mr.tsyn_pick = float_or_none(tsyn)

            return mr

Marius Isken's avatar
Marius Isken committed
368
        except NotFound as e:
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
            logger.debug(str(e))
            raise gf.SeismosizerError('no waveform data, %s' % str(e))


def misfit(
        tr_obs, tr_syn, taper, domain, exponent, tautoshift_max,
        autoshift_penalty_max, flip, result_mode='sparse'):

    '''
    Calculate misfit between observed and synthetic trace.

    :param tr_obs: observed trace as :py:class:`pyrocko.trace.Trace`
    :param tr_syn: synthetic trace as :py:class:`pyrocko.trace.Trace`
    :param taper: taper applied in timedomain as
        :py:class:`pyrocko.trace.Taper`
    :param domain: how to calculate difference, see :py:class:`DomainChoice`
    :param exponent: exponent of Lx type norms
    :param tautoshift_max: if non-zero, return lowest misfit when traces are
        allowed to shift against each other by up to +/- ``tautoshift_max``
    :param autoshift_penalty_max: if non-zero, a penalty misfit is added for
        for non-zero shift values. The penalty value is
        ``autoshift_penalty_max * normalization_factor * \
tautoshift**2 / tautoshift_max**2``
    :param flip: ``bool``, if set to ``True``, normalization factor is
        computed against *tr_syn* rather than *tr_obs*
    :param result_mode: ``'full'``, include traces and spectra or ``'sparse'``,
        include only misfit and normalization factor in result

Marius Isken's avatar
Marius Isken committed
397
    :returns: object of type :py:class:`WaveformMisfitResult`
398
399
400
    '''

    trace.assert_same_sampling_rate(tr_obs, tr_syn)
401
    deltat = tr_obs.deltat
402
403
404
405
406
    tmin, tmax = taper.time_span()

    tr_proc_obs, trspec_proc_obs = _process(tr_obs, tmin, tmax, taper, domain)
    tr_proc_syn, trspec_proc_syn = _process(tr_syn, tmin, tmax, taper, domain)

407
    tshift = None
408
409
410
411
412
413
414
415
416
417
418
419
420
421
    ctr = None
    deltat = tr_proc_obs.deltat
    if domain in ('time_domain', 'envelope', 'absolute'):
        a, b = tr_proc_syn.ydata, tr_proc_obs.ydata
        if flip:
            b, a = a, b

        nshift_max = max(0, min(a.size-1,
                                int(math.floor(tautoshift_max / deltat))))

        if nshift_max == 0:
            m, n = trace.Lx_norm(a, b, norm=exponent)
        else:
            mns = []
Marius Isken's avatar
Marius Isken committed
422
            for ishift in range(-nshift_max, nshift_max+1):
423
424
425
426
427
428
429
430
431
432
433
                if ishift < 0:
                    a_cut = a[-ishift:]
                    b_cut = b[:ishift]
                elif ishift == 0:
                    a_cut = a
                    b_cut = b
                elif ishift > 0:
                    a_cut = a[:-ishift]
                    b_cut = b[ishift:]

                mns.append(trace.Lx_norm(a_cut, b_cut, norm=exponent))
434

435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
            ms, ns = num.array(mns).T

            iarg = num.argmin(ms)
            tshift = (iarg-nshift_max)*deltat

            m, n = ms[iarg], ns[iarg]
            m += autoshift_penalty_max * n * tshift**2 / tautoshift_max**2

    elif domain == 'cc_max_norm':

        ctr = trace.correlate(
            tr_proc_syn,
            tr_proc_obs,
            mode='same',
            normalization='normal')

451
        tshift, cc_max = ctr.max()
452
453
454
455
456
457
458
459
460
461
462
        m = 0.5 - 0.5 * cc_max
        n = 0.5

    elif domain == 'frequency_domain':
        a, b = trspec_proc_syn.ydata, trspec_proc_obs.ydata
        if flip:
            b, a = a, b

        m, n = trace.Lx_norm(num.abs(a), num.abs(b), norm=exponent)

    if result_mode == 'full':
Marius Isken's avatar
Marius Isken committed
463
        result = WaveformMisfitResult(
Andreas Steinberg's avatar
Andreas Steinberg committed
464
465
            misfit_value=float(m),
            misfit_norm=float(n),
466
467
468
469
470
471
472
            processed_obs=tr_proc_obs,
            processed_syn=tr_proc_syn,
            filtered_obs=tr_obs.copy(),
            filtered_syn=tr_syn,
            spectrum_obs=trspec_proc_obs,
            spectrum_syn=trspec_proc_syn,
            taper=taper,
473
            tshift=tshift,
474
475
476
            cc=ctr)

    elif result_mode == 'sparse':
Marius Isken's avatar
Marius Isken committed
477
        result = WaveformMisfitResult(
478
479
480
481
            misfit_value=m,
            misfit_norm=n)
    else:
        assert False
482

483
484
485
486
487
488
489
    return result


def _extend_extract(tr, tmin, tmax):
    deltat = tr.deltat
    itmin_frame = int(math.floor(tmin/deltat))
    itmax_frame = int(math.ceil(tmax/deltat))
490
    nframe = itmax_frame - itmin_frame + 1
491
492
493
494
495
496
497
498
499
500
501
502
    n = tr.data_len()
    a = num.empty(nframe, dtype=num.float)
    itmin_tr = int(round(tr.tmin / deltat))
    itmax_tr = itmin_tr + n
    icut1 = min(max(0, itmin_tr - itmin_frame), nframe)
    icut2 = min(max(0, itmax_tr - itmin_frame), nframe)
    icut1_tr = min(max(0, icut1 + itmin_frame - itmin_tr), n)
    icut2_tr = min(max(0, icut2 + itmin_frame - itmin_tr), n)
    a[:icut1] = tr.ydata[0]
    a[icut1:icut2] = tr.ydata[icut1_tr:icut2_tr]
    a[icut2:] = tr.ydata[-1]
    tr = tr.copy(data=False)
503
    tr.tmin = itmin_frame * deltat
504
505
506
507
508
509
510
511
512
513
514
515
516
    tr.set_ydata(a)
    return tr


def _process(tr, tmin, tmax, taper, domain):
    tr_proc = _extend_extract(tr, tmin, tmax)
    tr_proc.taper(taper)

    df = None
    trspec_proc = None

    if domain == 'envelope':
        tr_proc = tr_proc.envelope(inplace=False)
517
        tr_proc.set_ydata(num.abs(tr_proc.get_ydata()))
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541

    elif domain == 'absolute':
        tr_proc.set_ydata(num.abs(tr_proc.get_ydata()))

    elif domain == 'frequency_domain':
        ndata = tr_proc.ydata.size
        nfft = trace.nextpow2(ndata)
        padded = num.zeros(nfft, dtype=num.float)
        padded[:ndata] = tr_proc.ydata
        spectrum = num.fft.rfft(padded)
        df = 1.0 / (tr_proc.deltat * nfft)

        trspec_proc = TraceSpectrum(
            network=tr_proc.network,
            station=tr_proc.station,
            location=tr_proc.location,
            channel=tr_proc.channel,
            deltaf=df,
            fmin=0.0,
            ydata=spectrum)

    return tr_proc, trspec_proc


Marius Isken's avatar
Marius Isken committed
542
543
544
545
546
547
548
def backazimuth_for_waveform(azimuth, nslc):
    if nslc[-1] == 'R':
        backazimuth = azimuth + 180.
    elif nslc[-1] == 'T':
        backazimuth = azimuth + 90.
    else:
        backazimuth = None
549

Marius Isken's avatar
Marius Isken committed
550
    return backazimuth
551
552


Marius Isken's avatar
Marius Isken committed
553
554
555
556
557
def float_or_none(x):
    if x is None:
        return x
    else:
        return float(x)
Marius Isken's avatar
Marius Isken committed
558
559
560
561


__all__ = [WaveformMisfitConfig, WaveformMisfitTarget, WaveformMisfitResult,
           WaveformTargetGroup]