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

import numpy as num

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

from grond import dataset

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

guts_prefix = 'grond'


Sebastian Heimann's avatar
Sebastian Heimann committed
24
25
26
27
28
29
30
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
31
32
33
34
35
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)
36
    label = String.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
37
38
39
40
41
42
43
44
45

    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)

46
47
48
49
50
51
    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
52
53
54

        return ' '.join(l)

55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    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())
96
    apply_balancing_weights = Bool.T(default=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
97
98
99
100
101

    def __init__(self, **kwargs):
        Object.__init__(self, **kwargs)
        self._bootstrap_weights = None
        self._target_weights = None
Sebastian Heimann's avatar
Sebastian Heimann committed
102
103
104
105
        self._engine = None

    def get_engine(self):
        return self._engine
Sebastian Heimann's avatar
Sebastian Heimann committed
106
107
108
109
110
111
112
113
114
115
116
117
118

    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
119
120
121
122
    @property
    def parameter_names(self):
        return [p.name for p in self.combined]

Sebastian Heimann's avatar
Sebastian Heimann committed
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
    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):
        ntargets = len(self.targets)
        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
183
184
185
    def set_engine(self, engine):
        self._engine = engine

Sebastian Heimann's avatar
Sebastian Heimann committed
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209

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


class InnerMisfitConfig(Object):
    fmin = Float.T()
    fmax = Float.T()
    ffactor = Float.T(default=1.5)
    tmin = gf.Timing.T()
    tmax = gf.Timing.T()
Sebastian Heimann's avatar
Sebastian Heimann committed
210
211
    pick_synthetic_traveltime = gf.Timing.T(optional=True)
    pick_phasename = String.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    domain = trace.DomainChoice.T(default='time_domain')


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


class NoAnalysisResults(Exception):
    pass


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)
    groupname = gf.StringID.T(optional=True)

    def __init__(self, **kwargs):
        gf.Target.__init__(self, **kwargs)
        self._ds = None
        self._return_traces = False

    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

    def set_return_traces(self, return_traces):
        self._return_traces = return_traces

    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
        return tmin_fit, tmax_fit, tfade

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

        tr_syn = tr_syn.pyrocko_trace()
Sebastian Heimann's avatar
Sebastian Heimann committed
273
        print tr_syn.deltat
Sebastian Heimann's avatar
Sebastian Heimann committed
274
275
276
277
278
279
        nslc = self.codes

        config = self.misfit_config

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

Sebastian Heimann's avatar
Sebastian Heimann committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        ds = self.get_dataset()

        tobs_shift = 0.0
        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
                tobs_shift = tobs - tsyn

        print tobs_shift

Sebastian Heimann's avatar
Sebastian Heimann committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        freqlimits = (
            config.fmin/config.ffactor,
            config.fmin, config.fmax,
            config.fmax*config.ffactor)

        tinc_obs = 1.0/config.fmin

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

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

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

Sebastian Heimann's avatar
Sebastian Heimann committed
317
318
        tmin_obs = (math.floor((tmin_fit - tfade + tobs_shift) / tinc_obs) - 1.0) * tinc_obs
        tmax_obs = (math.ceil((tmax_fit + tfade + tobs_shift) / tinc_obs) + 1.0) * tinc_obs
Sebastian Heimann's avatar
Sebastian Heimann committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338


        try:
            if nslc[-1] == 'R':
                backazimuth = self.azimuth + 180.
            elif nslc[-1] == 'T':
                backazimuth = self.azimuth + 90.
            else:
                backazimuth = None

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

Sebastian Heimann's avatar
Sebastian Heimann committed
339
340
341
342
            if tobs_shift != 0.0:
                tr_obs = tr_obs.copy()
                tr_obs.shift(-tobs_shift)

Sebastian Heimann's avatar
Sebastian Heimann committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
            ms = trace.MisfitSetup(
                norm=2,
                domain=config.domain,
                filter=trace.PoleZeroResponse(),
                taper=trace.CosTaper(
                    tmin_fit - tfade,
                    tmin_fit,
                    tmax_fit,
                    tmax_fit + tfade))

            if not self.flip_norm:
                mv, mn, tr_obs_proc, tr_syn_proc = tr_obs.misfit(
                    tr_syn, ms, nocache=True, debug=True)
            else:
                mv, mn, tr_syn_proc, tr_obs_proc = tr_syn.misfit(
                    tr_obs, ms, nocache=True, debug=True)

            result = MisfitResult(misfit_value=mv, misfit_norm=mn)
            if self._return_traces:
                result.filtered_obs = tr_obs
                result.filtered_syn = tr_syn
                result.processed_obs = tr_obs_proc
                result.processed_syn = tr_syn_proc
                result.taper = ms.taper

            return result

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


class Trace(Object):
    pass


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)
    taper = trace.Taper.T(optional=True)


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
425
426
427
428
    def get_basepath(self):
        assert self._basepath is not None
        return self._basepath

Sebastian Heimann's avatar
Sebastian Heimann committed
429
430
431
432
433
434
    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
435
436
            self.path_prefix = op.normpath(xjoin(xrelpath(
                self._basepath, new_basepath), self.path_prefix))
Sebastian Heimann's avatar
Sebastian Heimann committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533

        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

    def expand_path(self, path):
        assert self._basepath is not None

        path_prefix = self.path_prefix or self._parent_path_prefix

        if path is None:
            return None
        elif isinstance(path, basestring):
            return op.normpath(xjoin(self._basepath, xjoin(path_prefix, path)))
        else:
            return [
                op.normpath(xjoin(self._basepath, xjoin(path_prefix, p)))
                for p in path]


class SyntheticTest(Object):
    random_seed = Int.T(default=0)
    inject_solution = Bool.T(default=False)
    x = Dict.T(String.T(), Float.T())

    def __init__(self, **kwargs):
        Object.__init__(self, **kwargs)
        self._synthetics = None

    def set_config(self, config):
        self._config = config

    def get_problem(self):
        ds = self._config.get_dataset()
        events = ds.get_events()
        rstate = num.random.RandomState(self.random_seed)
        event = events[rstate.randint(0, len(events))]
        return self._config.get_problem(event)

    def get_x_random(self):
        problem = self.get_problem()
        xbounds = num.array(problem.bounds(), dtype=num.float)
        npar = xbounds.shape[0]

        rstate = num.random.RandomState(self.random_seed)
        x = num.zeros(npar, dtype=num.float)
        while True:
            for i in xrange(npar):
                x[i] = rstate.uniform(xbounds[i, 0], xbounds[i, 1])

            try:
                x = problem.preconstrain(x)
                break

            except Forbidden:
                pass

        return x

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

        else:
            x = self.get_x_random()

        return x

    def get_synthetics(self):
        if self._synthetics is None:
            problem = self.get_problem()

            x = self.get_x()

            results = problem.forward(x)
            self._synthetics = results

        return self._synthetics

    def get_waveform(self, nslc, tmin, tmax, tfade=0., freqlimits=None):
        synthetics = self.get_synthetics()
        for result in synthetics:
            if result.trace.codes == nslc:
                tr = result.trace.pyrocko_trace()
                tr.extend(tmin - tfade * 2.0, tmax + tfade * 2.0)
                tr = tr.transfer(tfade=tfade, freqlimits=freqlimits)
                tr.chop(tmin, tmax)
                return tr


class DatasetConfig(HasPaths):

Sebastian Heimann's avatar
Sebastian Heimann committed
534
535
    stations_path = Path.T(optional=True)
    stations_stationxml_paths = List.T(Path.T())
Sebastian Heimann's avatar
Sebastian Heimann committed
536
537
538
539
540
541
542
543
    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
544
    picks_paths = List.T(Path.T())
Sebastian Heimann's avatar
Sebastian Heimann committed
545
546
547
548
549
550
551
552
553
554
555
556
    blacklist = List.T(String.T())
    whitelist = List.T(String.T(), optional=True)
    synthetic_test = SyntheticTest.T(optional=True)

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

    def get_dataset(self):
        if self._ds is None:
            fp = self.expand_path
            ds = dataset.Dataset()
Sebastian Heimann's avatar
Sebastian Heimann committed
557
558
559
560
            ds.add_stations(
                pyrocko_stations_filename=fp(self.stations_path),
                stationxml_filenames=fp(self.stations_stationxml_paths))

Sebastian Heimann's avatar
Sebastian Heimann committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
            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
581
582
583
584
            for picks_path in self.picks_paths:
                ds.add_picks(
                    filename=fp(picks_path))

Sebastian Heimann's avatar
Sebastian Heimann committed
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
            ds.add_blacklist(self.blacklist)
            if self.whitelist:
                ds.add_whitelist(self.whitelist)

            ds.set_synthetic_test(self.synthetic_test)
            self._ds = ds

        return self._ds


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

    groupname = gf.StringID.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
618
619
    distance_min = Float.T(optional=True)
    distance_max = Float.T(optional=True)
Sebastian Heimann's avatar
Sebastian Heimann committed
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
    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)

    def get_targets(self, ds, event, default_groupname):

        origin = event

        targets = []
        for st in ds.get_stations():
            for cha in self.channels:
                target = MisfitTarget(
                    quantity='displacement',
                    codes=st.nsl() + (cha,),
                    lat=st.lat,
                    lon=st.lon,
                    interpolation=self.interpolation,
                    store_id=self.store_id,
                    misfit_config=self.inner_misfit_config,
                    manual_weight=self.weight,
                    groupname=self.groupname or default_groupname)

                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

                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
683
    niter_transition = Int.T(default=0)
Sebastian Heimann's avatar
Sebastian Heimann committed
684
685
686
687
688
689
690
691
    niter_explorative = Int.T(default=10000)
    niter_non_explorative = Int.T(default=0)
    sampler_distribution = SamplerDistributionChoice.T(
        default='multivariate_normal')

    def get_solver_kwargs(self):
        return dict(
            niter_uniform=self.niter_uniform,
Sebastian Heimann's avatar
Sebastian Heimann committed
692
            niter_transition=self.niter_transition,
Sebastian Heimann's avatar
Sebastian Heimann committed
693
694
695
696
697
            niter_explorative=self.niter_explorative,
            niter_non_explorative=self.niter_non_explorative,
            sampler_distribution=self.sampler_distribution)


Sebastian Heimann's avatar
Sebastian Heimann committed
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
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
718
719
720
721
722
723
724
725
class Config(HasPaths):
    rundir_template = Path.T()
    dataset_config = DatasetConfig.T()
    target_configs = List.T(TargetConfig.T())
    problem_config = ProblemConfig.T()
    niter_analyse_problem = Int.T(default=1000)
    analyser_config = AnalyserConfig.T(default=AnalyserConfig.D())
    solver_config = SolverConfig.T(default=SolverConfig.D())
Sebastian Heimann's avatar
Sebastian Heimann committed
726
    engine_config = EngineConfig.T(default=EngineConfig.D())
Sebastian Heimann's avatar
Sebastian Heimann committed
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749

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

    def get_dataset(self):
        ds = self.dataset_config.get_dataset()
        if ds.synthetic_test:
            ds.synthetic_test.set_config(self)

        return ds

    def get_targets(self, event):
        ds = self.get_dataset()

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

        return targets

    def get_problem(self, event):
        targets = self.get_targets(event)
Sebastian Heimann's avatar
Sebastian Heimann committed
750
751
752
        problem = self.problem_config.get_problem(event, targets)
        problem.set_engine(self.engine_config.get_engine())
        return problem
Sebastian Heimann's avatar
Sebastian Heimann committed
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796


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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
def get_mean_x(xs):
    return num.mean(xs, axis=0)


def get_best_x(problem, xs, misfits):
    gms = problem.global_misfits(misfits)
    ibest = num.argmin(gms)
    return xs[ibest, :]


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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
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)
    config.set_basepath(op.dirname(path) or '.')
    return config


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)

    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)

    for iiter in xrange(niter):
        while True:
            x = []
            for i in xrange(npar):
                v = rstate.uniform(xbounds[i, 0], xbounds[i, 1])
                x.append(v)

            try:
                x = wproblem.preconstrain(x)
                break

            except Forbidden:
                pass

        _, ms = wproblem.evaluate(x)
        mss[iiter, :] = ms

        if show_progress:
            pbar.update(iiter)

    if show_progress:
        pbar.finish()

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

    weights = 1.0 / mean_ms
    weights /= (num.nansum(weights)/num.nansum(num.isfinite(weights)))

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


def solve(problem,
          rundir=None,
          niter_uniform=1000,
          niter_transition=1000,
          niter_explorative=10000,
          niter_non_explorative=0,
          xs_inject=None,
          sampler_distribution='multivariate_normal',
          status=()):

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

    nlinks_cap = 8 * npar + 1
    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
915
    mbx = None
Sebastian Heimann's avatar
Sebastian Heimann committed
916
917
918
919
920
921
922
923
924
925

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

    niter = niter_inject + niter_uniform + niter_explorative + \
        niter_non_explorative

    iiter = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
926
927
    sbx = None
    mxs = None
Sebastian Heimann's avatar
Sebastian Heimann committed
928
929
930
931
    covs = None
    xhist = num.zeros((niter, npar))
    isbad_mask = None
    accept_sum = num.zeros(1 + problem.nbootstrap, dtype=num.int)
932
    accept_hist = num.zeros(niter, dtype=num.int)
Sebastian Heimann's avatar
Sebastian Heimann committed
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952

    while iiter < niter:

        if niter_inject + niter_uniform <= iiter and \
                iiter < niter_inject + niter_uniform + niter_transition:

            factor = 4.0 * (1.0 - (iiter - niter_uniform - niter_inject) /
                            float(niter_transition))
        else:
            factor = 1.0

        ntries_preconstrain = 0
        ntries_sample = 0

        if iiter < niter_inject:
            x = xs_inject[iiter, :]
        else:
            while True:
                ntries_preconstrain += 1

Sebastian Heimann's avatar
Sebastian Heimann committed
953
                if mbx is None or iiter < niter_inject + niter_uniform:
954
                    x = problem.random_uniform(xbounds)
Sebastian Heimann's avatar
Sebastian Heimann committed
955
956
957
958
959
960
961
962
963
964
                else:
                    # jchoice = num.random.randint(0, 1 + problem.nbootstrap)
                    jchoice = num.argmin(accept_sum)

                    if iiter < niter_inject + niter_uniform + \
                            niter_transition + niter_explorative:

                        ichoice = num.random.randint(0, nlinks)
                        xb = xhist[chains_i[jchoice, ichoice]]
                    else:
Sebastian Heimann's avatar
Sebastian Heimann committed
965
                        xb = mxs[jchoice]
Sebastian Heimann's avatar
Sebastian Heimann committed
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983

                    if sampler_distribution == 'multivariate_normal':
                        ntries_sample = 0

                        while True:
                            ntries_sample += 1
                            vs = num.random.multivariate_normal(
                                xb, factor*covs[jchoice])

                            if (num.all(xbounds[:, 0] <= vs) and
                                    num.all(vs <= xbounds[:, 1])):
                                break

                        x = vs.tolist()

                    if sampler_distribution == 'normal':
                        for i in xrange(npar):
                            while True:
Sebastian Heimann's avatar
Sebastian Heimann committed
984
985
986
                                v = num.random.normal(
                                    xb[i], math.sqrt(factor)*sbx[i])

Sebastian Heimann's avatar
Sebastian Heimann committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
                                if xbounds[i, 0] <= v and v <= xbounds[i, 1]:
                                    break

                            x.append(v)

                try:
                    x = problem.preconstrain(x)
                    break

                except Forbidden:
                    pass

        ms, ns = problem.evaluate(x)