core.py 72.6 KB
Newer Older
Sebastian Heimann's avatar
Sebastian Heimann committed
1
2
3
4
5
6
7
import math
import os
import sys
import logging
import time
import copy
import shutil
Sebastian Heimann's avatar
Sebastian Heimann committed
8
import glob
Sebastian Heimann's avatar
Sebastian Heimann committed
9
import os.path as op
10
from string import Template
Sebastian Heimann's avatar
Sebastian Heimann committed
11
12
13
14

import numpy as num

from pyrocko.guts import load, Object, String, Float, Int, Bool, List, \
Sebastian Heimann's avatar
Sebastian Heimann committed
15
    StringChoice, Dict, Timestamp
Sebastian Heimann's avatar
Sebastian Heimann committed
16
from pyrocko import orthodrome as od, gf, trace, guts, util, weeding
17
from pyrocko import parimap, model, marker as pmarker
18
from pyrocko.guts_array import Array
Sebastian Heimann's avatar
Sebastian Heimann committed
19
20
21
22
23
24
25
26

from grond import dataset

logger = logging.getLogger('grond.core')

guts_prefix = 'grond'


27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def float_or_none(x):
    if x is None:
        return x
    else:
        return float(x)


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

47
48
49
50
51
52
    def get_ydata(self):
        return self.ydata

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

53

Sebastian Heimann's avatar
Sebastian Heimann committed
54
55
56
57
58
59
60
def mahalanobis_distance(xs, mx, cov):
    imask = num.diag(cov) != 0.
    icov = num.linalg.inv(cov[imask, :][:, imask])
    temp = xs[:, imask] - mx[imask]
    return num.sqrt(num.sum(temp * num.dot(icov, temp.T).T, axis=1))


Sebastian Heimann's avatar
Sebastian Heimann committed
61
62
63
64
65
class Parameter(Object):
    name = String.T()
    unit = String.T(optional=True)
    scale_factor = Float.T(default=1., optional=True)
    scale_unit = String.T(optional=True)
66
    label = String.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
67
68
69
70
71
72
73
74
75

    def __init__(self, *args, **kwargs):
        if len(args) >= 1:
            kwargs['name'] = args[0]
        if len(args) >= 2:
            kwargs['unit'] = args[1]

        Object.__init__(self, **kwargs)

76
77
78
79
80
81
    def get_label(self, with_unit=True):
        l = [self.label or self.name]
        if with_unit:
            unit = self.get_unit_label()
            if unit:
                l.append('[%s]' % unit)
Sebastian Heimann's avatar
Sebastian Heimann committed
82
83
84

        return ' '.join(l)

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    def get_value_label(self, value, format='%(value)g%(unit)s'):
        value = self.scaled(value)
        unit = self.get_unit_suffix()
        return format % dict(value=value, unit=unit)

    def get_unit_label(self):
        if self.scale_unit is not None:
            return self.scale_unit
        elif self.unit:
            return self.unit
        else:
            return None

    def get_unit_suffix(self):
        unit = self.get_unit_label()
        if not unit:
            return ''
        else:
            return ' %s' % unit

Sebastian Heimann's avatar
Sebastian Heimann committed
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
    def scaled(self, x):
        if isinstance(x, tuple):
            return tuple(v/self.scale_factor for v in x)
        if isinstance(x, list):
            return list(v/self.scale_factor for v in x)
        else:
            return x/self.scale_factor


class ADict(dict):
    def __getattr__(self, k):
        return self[k]

    def __setattr__(self, k, v):
        self[k] = v


class Problem(Object):
    name = String.T()
    parameters = List.T(Parameter.T())
    dependants = List.T(Parameter.T())
126
    apply_balancing_weights = Bool.T(default=True)
127
    base_source = gf.Source.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
128
129
130
131
132

    def __init__(self, **kwargs):
        Object.__init__(self, **kwargs)
        self._bootstrap_weights = None
        self._target_weights = None
Sebastian Heimann's avatar
Sebastian Heimann committed
133
        self._engine = None
134
        self._group_mask = None
Sebastian Heimann's avatar
Sebastian Heimann committed
135
136
137

    def get_engine(self):
        return self._engine
Sebastian Heimann's avatar
Sebastian Heimann committed
138
139
140
141
142
143
144
145
146
147
148
149
150

    def copy(self):
        o = copy.copy(self)
        o._bootstrap_weights = None
        o._target_weights = None
        return o

    def parameter_dict(self, x):
        return ADict((p.name, v) for (p, v) in zip(self.parameters, x))

    def parameter_array(self, d):
        return num.array([d[p.name] for p in self.parameters], dtype=num.float)

Sebastian Heimann's avatar
Sebastian Heimann committed
151
152
153
154
    @property
    def parameter_names(self):
        return [p.name for p in self.combined]

Sebastian Heimann's avatar
Sebastian Heimann committed
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
    def dump_problem_info(self, dirname):
        fn = op.join(dirname, 'problem.yaml')
        util.ensuredirs(fn)
        guts.dump(self, filename=fn)

    def dump_problem_data(self, dirname, x, ms, ns):
        fn = op.join(dirname, 'x')
        with open(fn, 'ab') as f:
            x.astype('<f8').tofile(f)

        fn = op.join(dirname, 'misfits')
        with open(fn, 'ab') as f:
            ms.astype('<f8').tofile(f)
            ns.astype('<f8').tofile(f)

    def name_to_index(self, name):
        pnames = [p.name for p in self.combined]
        return pnames.index(name)

    @property
    def nparameters(self):
        return len(self.parameters)

    @property
    def ntargets(self):
        return len(self.targets)

    @property
    def ndependants(self):
        return len(self.dependants)

    @property
    def ncombined(self):
        return len(self.parameters) + len(self.dependants)

    @property
    def combined(self):
        return self.parameters + self.dependants

    def make_bootstrap_weights(self, nbootstrap):
195
        ntargets = self.ntargets
Sebastian Heimann's avatar
Sebastian Heimann committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        ws = num.zeros((nbootstrap, ntargets))
        rstate = num.random.RandomState(23)
        for ibootstrap in xrange(nbootstrap):
            ii = rstate.randint(0, ntargets, size=self.ntargets)
            ws[ibootstrap, :] = num.histogram(
                ii, ntargets, (-0.5, ntargets - 0.5))[0]

        return ws

    def get_bootstrap_weights(self, ibootstrap=None):
        if self._bootstrap_weights is None:
            self._bootstrap_weights = self.make_bootstrap_weights(
                self.nbootstrap)

        if ibootstrap is None:
            return self._bootstrap_weights
        else:
            return self._bootstrap_weights[ibootstrap, :]

Sebastian Heimann's avatar
Sebastian Heimann committed
215
216
217
    def set_engine(self, engine):
        self._engine = engine

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    def make_group_mask(self):
        super_group_names = set()
        groups = num.zeros(len(self.targets), dtype=num.int)
        ngroups = 0
        for itarget, target in enumerate(self.targets):
            if target.super_group not in super_group_names:
                super_group_names.add(target.super_group)
                ngroups += 1

            groups[itarget] = ngroups - 1

        return groups, ngroups

    def get_group_mask(self):
        if self._group_mask is None:
            self._group_mask = self.make_group_mask()

        return self._group_mask

237
238
239
    def xref(self):
        return self.pack(self.base_source)

Sebastian Heimann's avatar
Sebastian Heimann committed
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257

class ProblemConfig(Object):
    name_template = String.T()
    apply_balancing_weights = Bool.T(default=True)


class Forbidden(Exception):
    pass


class DirectoryAlreadyExists(Exception):
    pass


class GrondError(Exception):
    pass


258
259
260
261
262
263
264
265
266
class DomainChoice(StringChoice):
    choices = [
        'time_domain',
        'frequency_domain',
        'envelope',
        'absolute',
        'cc_max_norm']


Sebastian Heimann's avatar
Sebastian Heimann committed
267
268
269
270
class InnerMisfitConfig(Object):
    fmin = Float.T()
    fmax = Float.T()
    ffactor = Float.T(default=1.5)
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
    tmin = gf.Timing.T(
        help='Start of main time window used for waveform fitting.')
    tmax = gf.Timing.T(
        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))
    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``')
Sebastian Heimann's avatar
Sebastian Heimann committed
302

303
304
305
    def get_full_frequency_range(self):
        return self.fmin / self.ffactor, self.fmax * self.ffactor

Sebastian Heimann's avatar
Sebastian Heimann committed
306
307
308
309
310
311
312
313
314

class TargetAnalysisResult(Object):
    balancing_weight = Float.T()


class NoAnalysisResults(Exception):
    pass


315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
class MisfitResult(gf.Result):
    misfit_value = Float.T()
    misfit_norm = Float.T()
    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)
    taper = trace.Taper.T(optional=True)
    tobs_shift = Float.T(optional=True)
    tsyn_pick = Timestamp.T(optional=True)
    cc_shift = Float.T(optional=True)
    cc = Trace.T(optional=True)


Sebastian Heimann's avatar
Sebastian Heimann committed
331
332
333
334
335
class MisfitTarget(gf.Target):
    misfit_config = InnerMisfitConfig.T()
    flip_norm = Bool.T(default=False)
    manual_weight = Float.T(default=1.0)
    analysis_result = TargetAnalysisResult.T(optional=True)
336
337
    super_group = gf.StringID.T()
    group = gf.StringID.T()
Sebastian Heimann's avatar
Sebastian Heimann committed
338
339
340
341

    def __init__(self, **kwargs):
        gf.Target.__init__(self, **kwargs)
        self._ds = None
342
        self._result_mode = 'sparse'
343
344
345
346

    def string_id(self):
        return '.'.join(x for x in (
            self.super_group, self.group) + self.codes if x)
Sebastian Heimann's avatar
Sebastian Heimann committed
347
348
349
350
351
352
353
354
355
356
357
358

    def get_plain_target(self):
        d = dict(
            (k, getattr(self, k)) for k in gf.Target.T.propnames)
        return gf.Target(**d)

    def get_dataset(self):
        return self._ds

    def set_dataset(self, ds):
        self._ds = ds

359
360
361
    def set_result_mode(self, result_mode):
        self._result_mode = result_mode

Sebastian Heimann's avatar
Sebastian Heimann committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
    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:
            raise NoAnalysisResults('no balancing weights available')

        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
381
382
383
384
385
386
        if config.tfade is None:
            tfade_taper = tfade
        else:
            tfade_taper = config.tfade

        return tmin_fit, tmax_fit, tfade, tfade_taper
Sebastian Heimann's avatar
Sebastian Heimann committed
387

388
    def get_backazimuth_for_waveform(self):
Sebastian Heimann's avatar
Sebastian Heimann committed
389
        nslc = self.codes
390
391
392
393
394
395
        if nslc[-1] == 'R':
            backazimuth = self.azimuth + 180.
        elif nslc[-1] == 'T':
            backazimuth = self.azimuth + 90.
        else:
            backazimuth = None
Sebastian Heimann's avatar
Sebastian Heimann committed
396

397
398
399
        return backazimuth

    def get_freqlimits(self):
Sebastian Heimann's avatar
Sebastian Heimann committed
400
401
        config = self.misfit_config

402
403
404
405
        return (
            config.fmin/config.ffactor,
            config.fmin, config.fmax,
            config.fmax*config.ffactor)
Sebastian Heimann's avatar
Sebastian Heimann committed
406

407
408
409
410
    def get_pick_shift(self, engine, source):
        config = self.misfit_config
        tobs = None
        tsyn = None
Sebastian Heimann's avatar
Sebastian Heimann committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
        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

426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
        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()
Sebastian Heimann's avatar
Sebastian Heimann committed
449

450
451
452
453
454
        tobs, tsyn = self.get_pick_shift(engine, source)
        if None not in (tobs, tsyn):
            tobs_shift = tobs - tsyn
        else:
            tobs_shift = 0.0
Sebastian Heimann's avatar
Sebastian Heimann committed
455
456
457
458
459
460

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

461
462
        freqlimits = self.get_freqlimits()

Sebastian Heimann's avatar
Sebastian Heimann committed
463
464
465
466
467
468
        tr_syn = tr_syn.transfer(
            freqlimits=freqlimits,
            tfade=tfade)

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

469
470
        tmin_obs, tmax_obs = self.get_cutout_timespan(
            tmin_fit+tobs_shift, tmax_fit+tobs_shift, tfade)
Sebastian Heimann's avatar
Sebastian Heimann committed
471
472
473
474
475
476
477
478
479
480

        try:
            tr_obs = ds.get_waveform(
                nslc,
                tmin=tmin_obs,
                tmax=tmax_obs,
                tfade=tfade,
                freqlimits=freqlimits,
                deltat=tr_syn.deltat,
                cache=True,
481
                backazimuth=self.get_backazimuth_for_waveform())
Sebastian Heimann's avatar
Sebastian Heimann committed
482

Sebastian Heimann's avatar
Sebastian Heimann committed
483
484
485
486
            if tobs_shift != 0.0:
                tr_obs = tr_obs.copy()
                tr_obs.shift(-tobs_shift)

487
488
            mr = misfit(
                tr_obs, tr_syn,
Sebastian Heimann's avatar
Sebastian Heimann committed
489
                taper=trace.CosTaper(
490
                    tmin_fit - tfade_taper,
Sebastian Heimann's avatar
Sebastian Heimann committed
491
492
                    tmin_fit,
                    tmax_fit,
493
                    tmax_fit + tfade_taper),
494
495
                domain=config.domain,
                exponent=2,
496
                flip=self.flip_norm,
497
498
499
                result_mode=self._result_mode,
                tautoshift_max=config.tautoshift_max,
                autoshift_penalty_max=config.autoshift_penalty_max)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
500

501
502
            mr.tobs_shift = float(tobs_shift)
            mr.tsyn_pick = float_or_none(tsyn)
Sebastian Heimann's avatar
Sebastian Heimann committed
503

504
            return mr
Sebastian Heimann's avatar
Sebastian Heimann committed
505
506
507
508
509
510

        except dataset.NotFound, e:
            logger.debug(str(e))
            raise gf.SeismosizerError('no waveform data, %s' % str(e))


511
def misfit(
512
513
        tr_obs, tr_syn, taper, domain, exponent, tautoshift_max,
        autoshift_penalty_max, flip, result_mode='sparse'):
Sebastian Heimann's avatar
Sebastian Heimann committed
514

515
516
517
518
519
520
521
522
523
    '''
    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
524
525
526
527
528
529
    :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``
530
531
    :param flip: ``bool``, if set to ``True``, normalization factor is
        computed against *tr_syn* rather than *tr_obs*
532
533
    :param result_mode: ``'full'``, include traces and spectra or ``'sparse'``,
        include only misfit and normalization factor in result
534
535
536

    :returns: object of type :py:class:`MisfitResult`
    '''
Sebastian Heimann's avatar
Sebastian Heimann committed
537

538
539
540
541
542
543
544
545
    trace.assert_same_sampling_rate(tr_obs, tr_syn)
    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)

    cc_shift = None
    ctr = None
546
    deltat = tr_proc_obs.deltat
547
548
549
550
551
    if domain in ('time_domain', 'envelope', 'absolute'):
        a, b = tr_proc_syn.ydata, tr_proc_obs.ydata
        if flip:
            b, a = a, b

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
        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 = []
            for ishift in xrange(-nshift_max, nshift_max+1):
                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))

            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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598

    elif domain == 'cc_max_norm':

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

        cc_shift, cc_max = ctr.max()
        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)

599
600
601
602
603
604
605
606
607
608
609
610
611
    if result_mode == 'full':
        result = MisfitResult(
            misfit_value=m,
            misfit_norm=n,
            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,
            cc_shift=cc_shift,
            cc=ctr)
612

613
614
615
616
617
618
    elif result_mode == 'sparse':
        result = MisfitResult(
            misfit_value=m,
            misfit_norm=n)
    else:
        assert False
619
620
621
622
623
624
625
626
627

    return result


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

    df = None
628
    trspec_proc = None
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643

    if domain == 'envelope':
        tr_proc = tr_proc.envelope(inplace=False)

    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)

644
645
646
647
648
649
650
651
        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)
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675

    return tr_proc, trspec_proc


def _extend_extract(tr, tmin, tmax):
    deltat = tr.deltat
    itmin_frame = int(math.floor(tmin/deltat))
    itmax_frame = int(math.ceil(tmax/deltat))
    nframe = itmax_frame - itmin_frame
    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)
    tr.tmin = tmin
    tr.set_ydata(a)
    return tr
Sebastian Heimann's avatar
Sebastian Heimann committed
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


def xjoin(basepath, path):
    if path is None and basepath is not None:
        return basepath
    elif op.isabs(path) or basepath is None:
        return path
    else:
        return op.join(basepath, path)


def xrelpath(path, start):
    if op.isabs(path):
        return path
    else:
        return op.relpath(path, start)


class Path(String):
    pass


class HasPaths(Object):
    path_prefix = Path.T(optional=True)

    def __init__(self, *args, **kwargs):
        Object.__init__(self, *args, **kwargs)
        self._basepath = None
        self._parent_path_prefix = None

    def set_basepath(self, basepath, parent_path_prefix=None):
        self._basepath = basepath
        self._parent_path_prefix = parent_path_prefix
        for (prop, val) in self.T.ipropvals(self):
            if isinstance(val, HasPaths):
                val.set_basepath(
                    basepath, self.path_prefix or self._parent_path_prefix)

Sebastian Heimann's avatar
Sebastian Heimann committed
714
715
716
717
    def get_basepath(self):
        assert self._basepath is not None
        return self._basepath

Sebastian Heimann's avatar
Sebastian Heimann committed
718
719
720
721
722
723
    def change_basepath(self, new_basepath, parent_path_prefix=None):
        assert self._basepath is not None

        self._parent_path_prefix = parent_path_prefix
        if self.path_prefix or not self._parent_path_prefix:

Sebastian Heimann's avatar
Sebastian Heimann committed
724
725
            self.path_prefix = op.normpath(xjoin(xrelpath(
                self._basepath, new_basepath), self.path_prefix))
Sebastian Heimann's avatar
Sebastian Heimann committed
726
727
728
729
730
731
732
733

        for val in self.T.ivals(self):
            if isinstance(val, HasPaths):
                val.change_basepath(
                    new_basepath, self.path_prefix or self._parent_path_prefix)

        self._basepath = new_basepath

734
    def expand_path(self, path, extra=None):
Sebastian Heimann's avatar
Sebastian Heimann committed
735
736
        assert self._basepath is not None

737
738
739
740
        if extra is None:
            def extra(path):
                return path

Sebastian Heimann's avatar
Sebastian Heimann committed
741
742
743
744
745
        path_prefix = self.path_prefix or self._parent_path_prefix

        if path is None:
            return None
        elif isinstance(path, basestring):
746
747
            return extra(
                op.normpath(xjoin(self._basepath, xjoin(path_prefix, path))))
Sebastian Heimann's avatar
Sebastian Heimann committed
748
749
        else:
            return [
750
751
                extra(
                    op.normpath(xjoin(self._basepath, xjoin(path_prefix, p))))
Sebastian Heimann's avatar
Sebastian Heimann committed
752
753
754
                for p in path]


Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
755
756
757
758
759
760
761
762
763
class RandomResponse(trace.FrequencyResponse):

    scale = Float.T(default=0.0)

    def set_random_state(self, rstate):
        self._rstate = rstate

    def evaluate(self, freqs):
        n = freqs.size
764
        return 1.0 + (
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
765
            self._rstate.normal(scale=self.scale, size=n) +
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
766
767
768
769
770
771
772
            0.0J * self._rstate.normal(scale=self.scale, size=n))


class SyntheticWaveformNotAvailable(Exception):
    pass


Sebastian Heimann's avatar
Sebastian Heimann committed
773
774
class SyntheticTest(Object):
    inject_solution = Bool.T(default=False)
775
    respect_data_availability = Bool.T(default=False)
776
777
    real_noise_scale = Float.T(default=0.0)
    white_noise_scale = Float.T(default=0.0)
778
    random_response_scale = Float.T(default=0.0)
779
780
    real_noise_toffset = Float.T(default=-3600.)
    random_seed = Int.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
781
782
783
784
    x = Dict.T(String.T(), Float.T())

    def __init__(self, **kwargs):
        Object.__init__(self, **kwargs)
785
        self._problem = None
Sebastian Heimann's avatar
Sebastian Heimann committed
786
787
        self._synthetics = None

788
789
790
    def set_problem(self, problem):
        self._problem = problem
        self._synthetics = None
Sebastian Heimann's avatar
Sebastian Heimann committed
791
792

    def get_problem(self):
793
794
795
        if self._problem is None:
            raise SyntheticWaveformNotAvailable(
                'SyntheticTest.set_problem() has not been called yet')
Sebastian Heimann's avatar
Sebastian Heimann committed
796

797
        return self._problem
Sebastian Heimann's avatar
Sebastian Heimann committed
798
799
800
801
802
803
804
805

    def get_x(self):
        problem = self.get_problem()
        if self.x:
            x = problem.preconstrain(
                problem.parameter_array(self.x))

        else:
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
806
807
808
809
            x = problem.preconstrain(
                problem.pack(
                    problem.base_source))

Sebastian Heimann's avatar
Sebastian Heimann committed
810
811
812
        return x

    def get_synthetics(self):
813
        problem = self.get_problem()
Sebastian Heimann's avatar
Sebastian Heimann committed
814
815
816
        if self._synthetics is None:
            x = self.get_x()
            results = problem.forward(x)
817
818
819
820
821
822
823
824
            synthetics = {}
            for iresult, result in enumerate(results):
                tr = result.trace.pyrocko_trace()
                tfade = tr.tmax - tr.tmin
                tr.extend(tr.tmin - tfade, tr.tmax + tfade)

                if self.random_response_scale != 0:
                    tf = RandomResponse(scale=self.random_response_scale)
825
826
                    rstate = num.random.RandomState(
                        (self.random_seed or 0) + iresult)
827
828
829
830
831
                    tf.set_random_state(rstate)
                    tr = tr.transfer(
                        tfade=tfade,
                        transfer_function=tf)

832
833
834
835
836
                if self.white_noise_scale != 0.0:
                    rstate = num.random.RandomState(
                        (self.random_seed or 0) + iresult)
                    u = rstate.normal(
                        scale=self.white_noise_scale,
837
838
839
840
                        size=tr.data_len())

                    tr.ydata += u

841
842
843
                synthetics[result.trace.codes] = tr

            self._synthetics = synthetics
Sebastian Heimann's avatar
Sebastian Heimann committed
844
845
846
847
848

        return self._synthetics

    def get_waveform(self, nslc, tmin, tmax, tfade=0., freqlimits=None):
        synthetics = self.get_synthetics()
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
849

850
851
852
853
854
855
856
857
858
859
860
861
        if nslc not in synthetics:
            return None

        tr = synthetics[nslc]
        tr.extend(tmin - tfade * 2.0, tmax + tfade * 2.0)

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

        tr.chop(tmin, tmax)
        return tr
Sebastian Heimann's avatar
Sebastian Heimann committed
862
863
864
865


class DatasetConfig(HasPaths):

Sebastian Heimann's avatar
Sebastian Heimann committed
866
867
    stations_path = Path.T(optional=True)
    stations_stationxml_paths = List.T(Path.T())
Sebastian Heimann's avatar
Sebastian Heimann committed
868
869
870
871
872
873
874
875
    events_path = Path.T()
    waveform_paths = List.T(Path.T())
    clippings_path = Path.T(optional=True)
    responses_sacpz_path = Path.T(optional=True)
    responses_stationxml_paths = List.T(Path.T())
    station_corrections_path = Path.T(optional=True)
    apply_correction_factors = Bool.T(default=True)
    apply_correction_delays = Bool.T(default=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
876
    picks_paths = List.T(Path.T())
877
    blacklist_paths = List.T(Path.T())
878
879
880
881
    blacklist = List.T(
        String.T(),
        help='stations/components to be excluded according to their STA, '
             'NET.STA, NET.STA.LOC, or NET.STA.LOC.CHA codes.')
882
    whitelist_paths = List.T(Path.T())
Sebastian Heimann's avatar
flake8    
Sebastian Heimann committed
883
884
885
    whitelist = List.T(
        String.T(),
        optional=True,
886
887
888
889
        help='if not None, list of stations/components to included according '
             'to their STA, NET.STA, NET.STA.LOC, or NET.STA.LOC.CHA codes. '
             'Note: ''when whitelisting on channel level, both, the raw and '
             'the processed channel codes have to be listed.')
Sebastian Heimann's avatar
Sebastian Heimann committed
890
891
892
893
    synthetic_test = SyntheticTest.T(optional=True)

    def __init__(self, *args, **kwargs):
        HasPaths.__init__(self, *args, **kwargs)
894
        self._ds = {}
Sebastian Heimann's avatar
Sebastian Heimann committed
895

Sebastian Heimann's avatar
Sebastian Heimann committed
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
    def get_event_names(self):
        def extra(path):
            return expand_template(path, dict(
                event_name='*'))

        def fp(path):
            return self.expand_path(path, extra=extra)

        events = []
        for fn in glob.glob(fp(self.events_path)):
            events.extend(model.load_events(filename=fn))

        event_names = [ev.name for ev in events]
        return event_names

911
912
    def get_dataset(self, event_name):
        if event_name not in self._ds:
913
914
915
916
917
918
919
            def extra(path):
                return expand_template(path, dict(
                    event_name=event_name))

            def fp(path):
                return self.expand_path(path, extra=extra)

920
            ds = dataset.Dataset(event_name)
Sebastian Heimann's avatar
Sebastian Heimann committed
921
922
923
924
            ds.add_stations(
                pyrocko_stations_filename=fp(self.stations_path),
                stationxml_filenames=fp(self.stations_stationxml_paths))

Sebastian Heimann's avatar
Sebastian Heimann committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
            ds.add_events(filename=fp(self.events_path))
            ds.add_waveforms(paths=fp(self.waveform_paths))
            if self.clippings_path:
                ds.add_clippings(markers_filename=fp(self.clippings_path))

            if self.responses_sacpz_path:
                ds.add_responses(
                    sacpz_dirname=fp(self.responses_sacpz_path))

            if self.responses_stationxml_paths:
                ds.add_responses(
                    stationxml_filenames=fp(self.responses_stationxml_paths))

            if self.station_corrections_path:
                ds.add_station_corrections(
                    filename=fp(self.station_corrections_path))

            ds.apply_correction_factors = self.apply_correction_factors
            ds.apply_correction_delays = self.apply_correction_delays

Sebastian Heimann's avatar
Sebastian Heimann committed
945
946
947
948
            for picks_path in self.picks_paths:
                ds.add_picks(
                    filename=fp(picks_path))

Sebastian Heimann's avatar
Sebastian Heimann committed
949
            ds.add_blacklist(self.blacklist)
950
            ds.add_blacklist(filenames=fp(self.blacklist_paths))
Sebastian Heimann's avatar
Sebastian Heimann committed
951
952
            if self.whitelist:
                ds.add_whitelist(self.whitelist)
953
            if self.whitelist_paths:
954
                ds.add_whitelist(filenames=fp(self.whitelist_paths))
Sebastian Heimann's avatar
Sebastian Heimann committed
955

956
957
            ds.set_synthetic_test(copy.deepcopy(self.synthetic_test))
            self._ds[event_name] = ds
Sebastian Heimann's avatar
Sebastian Heimann committed
958

959
        return self._ds[event_name]
Sebastian Heimann's avatar
Sebastian Heimann committed
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983


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


class TargetConfig(Object):

984
985
    super_group = gf.StringID.T(default='', optional=True)
    group = gf.StringID.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
986
987
    distance_min = Float.T(optional=True)
    distance_max = Float.T(optional=True)
988
989
    distance_3d_min = Float.T(optional=True)
    distance_3d_max = Float.T(optional=True)
990
991
    depth_min = Float.T(optional=True)
    depth_max = Float.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
992
993
994
995
996
997
998
    limit = Int.T(optional=True)
    channels = List.T(String.T())
    inner_misfit_config = InnerMisfitConfig.T()
    interpolation = gf.InterpolationMethod.T()
    store_id = gf.StringID.T()
    weight = Float.T(default=1.0)

999
    def get_targets(self, ds, event, default_group):
Sebastian Heimann's avatar
Sebastian Heimann committed
1000
1001
1002
1003
1004
1005

        origin = event

        targets = []
        for st in ds.get_stations():
            for cha in self.channels:
1006
1007
1008
                if ds.is_blacklisted((st.nsl() + (cha,))):
                    continue

Sebastian Heimann's avatar
Sebastian Heimann committed
1009
1010
1011
1012
1013
                target = MisfitTarget(
                    quantity='displacement',
                    codes=st.nsl() + (cha,),
                    lat=st.lat,
                    lon=st.lon,
1014
                    depth=st.depth,
Sebastian Heimann's avatar
Sebastian Heimann committed
1015
1016
1017
1018
                    interpolation=self.interpolation,
                    store_id=self.store_id,
                    misfit_config=self.inner_misfit_config,
                    manual_weight=self.weight,
1019
1020
                    super_group=self.super_group,
                    group=self.group or default_group)
Sebastian Heimann's avatar
Sebastian Heimann committed
1021
1022
1023
1024
1025
1026
1027
1028
1029

                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

1030
1031
1032
1033
1034
1035
1036
1037
                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

1038
1039
1040
1041
1042
1043
1044
1045
                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

Sebastian Heimann's avatar
Sebastian Heimann committed
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
                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 weed(origin, targets, self.limit)[0]
        else:
            return targets


class AnalyserConfig(Object):
    niter = Int.T(default=1000)


class SamplerDistributionChoice(StringChoice):
    choices = ['multivariate_normal', 'normal']


class SolverConfig(Object):
    niter_uniform = Int.T(default=1000)
Sebastian Heimann's avatar
Sebastian Heimann committed
1076
    niter_transition = Int.T(default=0)
Sebastian Heimann's avatar
Sebastian Heimann committed
1077
1078
1079
1080
    niter_explorative = Int.T(default=10000)
    niter_non_explorative = Int.T(default=0)
    sampler_distribution = SamplerDistributionChoice.T(
        default='multivariate_normal')
1081
    scatter_scale_transition = Float.T(default=2.0)
1082
    scatter_scale = Float.T(default=1.0)
1083
1084
    chain_length_factor = Float.T(default=8.0)
    compensate_excentricity = Bool.T(default=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
1085
1086
1087
1088

    def get_solver_kwargs(self):
        return dict(
            niter_uniform=self.niter_uniform,
Sebastian Heimann's avatar
Sebastian Heimann committed
1089
            niter_transition=self.niter_transition,
Sebastian Heimann's avatar
Sebastian Heimann committed
1090
1091
            niter_explorative=self.niter_explorative,
            niter_non_explorative=self.niter_non_explorative,
1092
            sampler_distribution=self.sampler_distribution,
1093
            scatter_scale_transition=self.scatter_scale_transition,
1094
1095
1096
            scatter_scale=self.scatter_scale,
            chain_length_factor=self.chain_length_factor,
            compensate_excentricity=self.compensate_excentricity)
Sebastian Heimann's avatar
Sebastian Heimann committed
1097
1098


Sebastian Heimann's avatar
Sebastian Heimann committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
class EngineConfig(HasPaths):
    gf_stores_from_pyrocko_config = Bool.T(default=True)
    gf_store_superdirs = List.T(Path.T())
    gf_store_dirs = List.T(Path.T())

    def __init__(self, *args, **kwargs):
        HasPaths.__init__(self, *args, **kwargs)
        self._engine = None

    def get_engine(self):
        if self._engine is None:
            fp = self.expand_path
            self._engine = gf.LocalEngine(
                use_config=self.gf_stores_from_pyrocko_config,
                store_superdirs=fp(self.gf_store_superdirs),
                store_dirs=fp(self.gf_store_dirs))

        return self._engine


Sebastian Heimann's avatar
Sebastian Heimann committed
1119
1120
1121
1122
1123
1124
1125
class Config(HasPaths):
    rundir_template = Path.T()
    dataset_config = DatasetConfig.T()
    target_configs = List.T(TargetConfig.T())
    problem_config = ProblemConfig.T()
    analyser_config = AnalyserConfig.T(default=AnalyserConfig.D())
    solver_config = SolverConfig.T(default=SolverConfig.D())
Sebastian Heimann's avatar
Sebastian Heimann committed
1126
    engine_config = EngineConfig.T(default=EngineConfig.D())
Sebastian Heimann's avatar
Sebastian Heimann committed
1127
1128
1129
1130

    def __init__(self, *args, **kwargs):
        HasPaths.__init__(self, *args, **kwargs)

Sebastian Heimann's avatar
Sebastian Heimann committed
1131
1132
1133
    def get_event_names(self):
        return self.dataset_config.get_event_names()

1134
1135
    def get_dataset(self, event_name):
        return self.dataset_config.get_dataset(event_name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1136
1137

    def get_targets(self, event):
1138
        ds = self.get_dataset(event.name)
Sebastian Heimann's avatar
Sebastian Heimann committed
1139
1140
1141
1142
1143
1144
1145
1146

        targets = []
        for igroup, target_config in enumerate(self.target_configs):
            targets.extend(target_config.get_targets(
                ds, event, 'group_%i' % igroup))

        return targets

1147
1148
1149
1150
1151
1152
1153
1154
    def setup_modelling_environment(self, problem):
        problem.set_engine(self.engine_config.get_engine())
        ds = self.get_dataset(problem.base_source.name)
        synt = ds.synthetic_test
        if synt:
            synt.set_problem(problem)
            problem.base_source = problem.unpack(synt.get_x())

Sebastian Heimann's avatar
Sebastian Heimann committed
1155
1156
    def get_problem(self, event):
        targets = self.get_targets(event)
Sebastian Heimann's avatar
Sebastian Heimann committed
1157
        problem = self.problem_config.get_problem(event, targets)
1158
        self.setup_modelling_environment(problem)
Sebastian Heimann's avatar
Sebastian Heimann committed
1159
        return problem
Sebastian Heimann's avatar
Sebastian Heimann committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203


def sarr(a):
    return ' '.join('%15g' % x for x in a)


def load_problem_info_and_data(dirname, subset=None):
    problem = load_problem_info(dirname)
    xs, misfits = load_problem_data(xjoin(dirname, subset), problem)
    return problem, xs, misfits


def load_problem_info(dirname):
    fn = op.join(dirname, 'problem.yaml')
    return guts.load(filename=fn)


def load_problem_data(dirname, problem):
    fn = op.join(dirname, 'x')
    with open(fn, 'r') as f:
        nmodels = os.fstat(f.fileno()).st_size / (problem.nparameters * 8)
        data = num.fromfile(
            f, dtype='<f8',
            count=nmodels*problem.nparameters).astype(num.float)

    nmodels = data.size/problem.nparameters
    xs = data.reshape((nmodels, problem.nparameters))

    fn = op.join(dirname, 'misfits')
    with open(fn, 'r') as f:
        data = num.fromfile(
            f, dtype='<f8', count=nmodels*problem.ntargets*2).astype(num.float)

    data = data.reshape((nmodels, problem.ntargets*2))

    combi = num.empty_like(data)
    combi[:, 0::2] = data[:, :problem.ntargets]
    combi[:, 1::2] = data[:, problem.ntargets:]

    misfits = combi.reshape((nmodels, problem.ntargets, 2))

    return xs, misfits


Sebastian Heimann's avatar
Sebastian Heimann committed
1204
1205
1206
1207
def get_mean_x(xs):
    return num.mean(xs, axis=0)


1208
1209
1210
1211
1212
def get_mean_x_and_gm(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    return num.mean(xs, axis=0), num.mean(gms)


Sebastian Heimann's avatar
Sebastian Heimann committed
1213
1214
1215
1216
1217
1218
def get_best_x(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    ibest = num.argmin(gms)
    return xs[ibest, :]


1219
1220
1221
1222
1223
1224
def get_best_x_and_gm(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    ibest = num.argmin(gms)
    return xs[ibest, :], gms[ibest]


Sebastian Heimann's avatar
Sebastian Heimann committed
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
def get_mean_source(problem, xs):
    x_mean = get_mean_x(xs)
    source = problem.unpack(x_mean)
    return source


def get_best_source(problem, xs, misfits):
    x_best = get_best_x(problem, xs, misfits)
    source = problem.unpack(x_best)
    return source


Sebastian Heimann's avatar
Sebastian Heimann committed
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
def mean_latlondist(lats, lons):
    if len(lats) == 0:
        return 0., 0., 1000.
    else:
        ns, es = od.latlon_to_ne_numpy(lats[0], lons[0], lats, lons)
        n, e = num.mean(ns), num.mean(es)
        dists = num.sqrt((ns-n)**2 + (es-e)**2)
        lat, lon = od.ne_to_latlon(lats[0], lons[0], n, e)
        return float(lat), float(lon), float(num.max(dists))


def stations_mean_latlondist(stations):
    lats = num.array([s.lat for s in stations])
    lons = num.array([s.lon for s in stations])
    return mean_latlondist(lats, lons)


def read_config(path):
    config = load(filename=path)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1256
1257
1258
    if not isinstance(config, Config):
        raise GrondError('invalid Grond configuration in file "%s"' % path)

Sebastian Heimann's avatar
Sebastian Heimann committed
1259
1260
1261
1262
    config.set_basepath(op.dirname(path) or '.')
    return config


Sebastian Heimann's avatar
Sebastian Heimann committed
1263
1264
1265
1266
1267
1268
1269
1270
def write_config(config, path):
    basepath = config.get_basepath()
    dirname = op.dirname(path) or '.'
    config.change_basepath(dirname)
    guts.dump(config, filename=path)
    config.change_basepath(basepath)


Sebastian Heimann's avatar
Sebastian Heimann committed
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
def analyse(problem, niter=1000, show_progress=False):
    if niter == 0:
        return

    wtargets = []
    for target in problem.targets:
        wtarget = copy.copy(target)
        wtarget.flip_norm = True
        wtarget.weight = 1.0
        wtargets.append(wtarget)

1282
    groups, ngroups = problem.get_group_mask()
1283

Sebastian Heimann's avatar
Sebastian Heimann committed
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
    wproblem = problem.copy()
    wproblem.targets = wtargets

    xbounds = num.array(wproblem.bounds(), dtype=num.float)
    npar = xbounds.shape[0]

    mss = num.zeros((niter, problem.ntargets))
    rstate = num.random.RandomState(123)

    if show_progress:
        pbar = util.progressbar('analysing problem', niter)

1296
    isbad_mask = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1297
1298
1299
    for iiter in xrange(niter):
        while True:
            x = []
1300
1301
            for ipar in xrange(npar):
                v = rstate.uniform(xbounds[ipar, 0], xbounds[ipar, 1])
Sebastian Heimann's avatar
Sebastian Heimann committed
1302
1303
1304
1305
1306
1307
1308
1309
1310
                x.append(v)

            try:
                x = wproblem.preconstrain(x)
                break

            except Forbidden:
                pass

1311
1312
1313
1314
1315
1316
        if isbad_mask is not None and num.any(isbad_mask):
            isok_mask = num.logical_not(isbad_mask)
        else:
            isok_mask = None

        _, ms = wproblem.evaluate(x, mask=isok_mask)
Sebastian Heimann's avatar
Sebastian Heimann committed
1317
1318
        mss[iiter, :] = ms

1319
1320
        isbad_mask = num.isnan(ms)

Sebastian Heimann's avatar
Sebastian Heimann committed
1321
1322
1323
1324
1325
1326
1327
1328
1329
        if show_progress:
            pbar.update(iiter)

    if show_progress:
        pbar.finish()

    mean_ms = num.mean(mss, axis=0)

    weights = 1.0 / mean_ms
1330
1331
1332
1333
    for igroup in xrange(ngroups):
        weights[groups == igroup] /= (
            num.nansum(weights[groups == igroup]) /
            num.nansum(num.isfinite(weights[groups == igroup])))
Sebastian Heimann's avatar
Sebastian Heimann committed
1334
1335
1336
1337
1338
1339

    for weight, target in zip(weights, problem.targets):
        target.analysis_result = TargetAnalysisResult(
            balancing_weight=float(weight))


1340
def excentricity_compensated_probabilities(xs, sbx, factor):
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
    inonflat = num.where(sbx != 0.0)[0]
    scale = num.zeros_like(sbx)
    scale[inonflat] = 1.0 / (sbx[inonflat] * (factor if factor != 0. else 1.0))
    #distances_all = math.sqrt(num.sum(
    #    ((xs[num.newaxis, :, :] - xs[:, num.newaxis, :]) *
    #     scale[num.newaxis, num.newaxis, :])**2, axis=2))
    distances_sqr_all = num.sum(
        ((xs[num.newaxis, :, :] - xs[:, num.newaxis, :]) *
         scale[num.newaxis, num.newaxis, :])**2, axis=2)
    probabilities = 1.0 / num.sum(distances_sqr_all < 1.0, axis=1)
1351
    # print num.sort(num.sum(distances_sqr_all < 1.0, axis=1))
1352
    probabilities /= num.sum(probabilities)
1353
1354
1355
1356
1357
1358
    return probabilities


def excentricity_compensated_choice(xs, sbx, factor):
    probabilities = excentricity_compensated_probabilities(
        xs, sbx, factor)
1359
1360
1361
    r = num.random.random()
    ichoice = num.searchsorted(num.cumsum(probabilities), r)
    ichoice = min(ichoice, xs.shape[0]-1)
1362
    return ichoice
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376


def select_most_excentric(xcandidates, xs, sbx, factor):
    inonflat = num.where(sbx != 0.0)[0]
    scale = num.zeros_like(sbx)
    scale[inonflat] = 1.0 / (sbx[inonflat] * (factor if factor != 0. else 1.0))
    distances_sqr_all = num.sum(
        ((xcandidates[num.newaxis, :, :] - xs[:, num.newaxis, :]) *
         scale[num.newaxis, num.newaxis, :])**2, axis=2)
    #print num.sort(num.sum(distances_sqr_all < 1.0, axis=0))
    ichoice = num.argmin(num.sum(distances_sqr_all < 1.0, axis=0))
    return xcandidates[ichoice]


Sebastian Heimann's avatar
Sebastian Heimann committed
1377
1378
1379
1380
1381
1382
def solve(problem,
          rundir=None,
          niter_uniform=1000,
          niter_transition=1000,
          niter_explorative=10000,
          niter_non_explorative=0,
1383
          scatter_scale_transition=2.0,
1384
          scatter_scale=1.0,
1385
          chain_length_factor=8.0,
Sebastian Heimann's avatar
Sebastian Heimann committed
1386
1387
          xs_inject=None,
          sampler_distribution='multivariate_normal',
1388
          compensate_excentricity=True,
1389
1390
          status=(),
          plot=False):
Sebastian Heimann's avatar
Sebastian Heimann committed
1391
1392
1393
1394

    xbounds = num.array(problem.bounds(), dtype=num.float)
    npar = xbounds.shape[0]

1395
    nlinks_cap = int(round(chain_length_factor * npar + 1))
Sebastian Heimann's avatar
Sebastian Heimann committed
1396
1397
1398
    chains_m = num.zeros((1 + problem.nbootstrap, nlinks_cap), num.float)
    chains_i = num.zeros((1 + problem.nbootstrap, nlinks_cap), num.int)
    nlinks = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
1399
    mbx = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1400
1401
1402
1403
1404
1405

    if xs_inject is not None and xs_inject.size != 0:
        niter_inject = xs_inject.shape[0]
    else:
        niter_inject = 0

1406
    niter = niter_inject + niter_uniform + niter_transition + \
1407
        niter_explorative + niter_non_explorative
Sebastian Heimann's avatar
Sebastian Heimann committed
1408
1409

    iiter = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
1410
1411
    sbx = None
    mxs = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1412
1413
1414
1415
    covs = None
    xhist = num.zeros((niter, npar))
    isbad_mask = None
    accept_sum = num.zeros(1 + problem.nbootstrap, dtype=num.int)
1416
    accept_hist = num.zeros(niter, dtype=num.int)
Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1417
    pnames = [p.name for p in problem.parameters]
Sebastian Heimann's avatar
Sebastian Heimann committed
1418

1419
1420
1421
    if plot:
        from matplotlib import pyplot as plt
        from grond import plot as gplot
Sebastian Heimann's avatar
Sebastian Heimann committed
1422
1423
        #plt.ion()
        #plt.show()
1424
1425
        solver_plot = gplot.SolverPlot(problem, plt)

Sebastian Heimann's avatar
Sebastian Heimann committed
1426
    while iiter < niter:
1427
1428
        jchoice = None
        ichoice = None
Sebastian Heimann's avatar
Sebastian Heimann committed
1429

1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
        if iiter < niter_inject:
            phase = 'inject'
        elif iiter < niter_inject + niter_uniform:
            phase = 'uniform'
        elif iiter < niter_inject + niter_uniform + niter_transition:
            phase = 'transition'
        elif iiter < niter_inject + niter_uniform + niter_transition + \
                niter_explorative:
            phase = 'explorative'
        else:
            phase = 'non_explorative'

1442
        factor = 0.0
1443
        if phase == 'transition':
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
            T = float(niter_transition)
            A = scatter_scale_transition
            B = scatter_scale
            tau = T/(math.log(A) - math.log(B))
            t0 = math.log(A) * T / (math.log(A) - math.log(B))
            t = float(iiter - niter_uniform - niter_inject)
            factor = num.exp(-(t-t0) / tau)

        elif phase in ('explorative', 'non_explorative'):
            factor = scatter_scale
Sebastian Heimann's avatar
Sebastian Heimann committed
1454
1455
1456
1457

        ntries_preconstrain = 0
        ntries_sample = 0

1458
        if phase == 'inject':
Sebastian Heimann's avatar
Sebastian Heimann committed
1459
1460
1461
1462
1463
            x = xs_inject[iiter, :]
        else:
            while True:
                ntries_preconstrain += 1

1464
                if mbx is None or phase == 'uniform':
1465
                    x = problem.random_uniform(xbounds)
Sebastian Heimann's avatar
Sebastian Heimann committed
1466
1467
1468
1469
                else:
                    # jchoice = num.random.randint(0, 1 + problem.nbootstrap)
                    jchoice = num.argmin(accept_sum)

1470
                    if phase in ('transition', 'explorative'):
1471
1472

                        if compensate_excentricity:
1473
                            ichoice = excentricity_compensated_choice(
1474
1475
                                xhist[chains_i[jchoice, :], :], sbx, 3.)

1476
1477
                            xchoice = xhist[chains_i[jchoice, ichoice], :]

1478
1479
1480
                        else:
                            ichoice = num.random.randint(0, nlinks)
                            xchoice = xhist[chains_i[jchoice, ichoice]]
Sebastian Heimann's avatar
Sebastian Heimann committed
1481
                    else:
1482
                        xchoice = mxs[jchoice]
Sebastian Heimann's avatar
Sebastian Heimann committed
1483
1484
1485
1486

                    if sampler_distribution == 'multivariate_normal':
                        ntries_sample = 0

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed
1487
1488
                        ntry = 0
                        ok_mask_sum = num.zeros(npar, dtype=num.int)
Sebastian Heimann's avatar
Sebastian Heimann committed
1489
1490
1491
                        while True:
                            ntries_sample += 1
                            vs = num.random.multivariate_normal(
1492
                                xchoice, factor**2 * covs[jchoice])
Sebastian Heimann's avatar
Sebastian Heimann committed
1493

Sebastian Heimann's avatar
wip    
Sebastian Heimann committed