rectangular.py 7.33 KB
Newer Older
Marius Isken's avatar
Marius Isken committed
1
import math
Sebastian Heimann's avatar
Sebastian Heimann committed
2
3
4
5
import logging

import numpy as num

Marius Isken's avatar
Marius Isken committed
6
from pyrocko import gf, moment_tensor as mtm
Sebastian Heimann's avatar
Sebastian Heimann committed
7
8
9
10
11
from pyrocko.guts import Float, String, Dict, List, Int
from grond import core

guts_prefix = 'grond'

Marius Isken's avatar
Marius Isken committed
12
logger = logging.getLogger('grond.cmt')
Sebastian Heimann's avatar
Sebastian Heimann committed
13
14
15
16
17
18

km = 1000.

as_km = dict(scale_factor=km, scale_unit='km')


Marius Isken's avatar
Marius Isken committed
19
class RectangularProblem(core.Problem):
Sebastian Heimann's avatar
Sebastian Heimann committed
20
21
22
23
24

    parameters = [
        core.Parameter('north_shift', 'm', label='Northing', **as_km),
        core.Parameter('east_shift', 'm', label='Easting', **as_km),
        core.Parameter('depth', 'm', label='Depth', **as_km),
Marius Isken's avatar
Marius Isken committed
25
26
27
28
29
30
31
        core.Parameter('length', 'm', label='Length', **as_km),
        core.Parameter('width', 'm', label='Width', **as_km),
        core.Parameter('dip', 'deg', label='Dip'),
        core.Parameter('strike', 'deg', label='Strike'),
        core.Parameter('rake', 'deg', label='Rake'),
        core.Parameter('slip', 'm', label='Slip'),
        ]
Sebastian Heimann's avatar
Sebastian Heimann committed
32
33
34

    dependants = []

Marius Isken's avatar
Marius Isken committed
35
    targets = List.T(gf.Target.T())
Sebastian Heimann's avatar
Sebastian Heimann committed
36
    ranges = Dict.T(String.T(), gf.Range.T())
Marius Isken's avatar
Marius Isken committed
37
38
    
    nbootstrap = 0
Sebastian Heimann's avatar
Sebastian Heimann committed
39

Marius Isken's avatar
Marius Isken committed
40
41
    def pack(self, source):
        return self.parameter_array(source)
Sebastian Heimann's avatar
Sebastian Heimann committed
42

Marius Isken's avatar
Marius Isken committed
43
44
    def unpack(self, x):
        source = self.base_source.clone(**self.parameter_dict(x))
Sebastian Heimann's avatar
Sebastian Heimann committed
45
46
47
48
49
50
        return source

    def extract(self, xs, i):
        if xs.ndim == 1:
            return self.extract(xs[num.newaxis, :], i)[0]

Marius Isken's avatar
Marius Isken committed
51
        return xs[:, i]
Sebastian Heimann's avatar
Sebastian Heimann committed
52
53
54

    def random_uniform(self, xbounds):
        x = num.zeros(self.nparameters)
Marius Isken's avatar
Marius Isken committed
55
        for i in [0, 1, 2, 3, 4, 11]:
Sebastian Heimann's avatar
Sebastian Heimann committed
56
57
            x[i] = num.random.uniform(xbounds[i, 0], xbounds[i, 1])

Marius Isken's avatar
Marius Isken committed
58
59
        x[5:11] = mtm.random_m6()

Sebastian Heimann's avatar
Sebastian Heimann committed
60
61
62
63
64
65
66
        return x.tolist()

    def preconstrain(self, x):
        source = self.unpack(x)
        if any(self.distance_min > source.distance_to(t)
               for t in self.targets):
            raise core.Forbidden()
Marius Isken's avatar
Marius Isken committed
67
        return x
Sebastian Heimann's avatar
Sebastian Heimann committed
68
69
70
71
72
73
74
75
76

    def bounds(self):
        out = []
        for p in self.parameters:
            r = self.ranges[p.name]
            out.append((r.start, r.stop))
        return out

    def dependant_bounds(self):
Marius Isken's avatar
Marius Isken committed
77
78
79
80
        print('dependent_bounds')
        out = [
            (-1., 1.),
            (-1., 1.)]
Sebastian Heimann's avatar
Sebastian Heimann committed
81
82
        return out

Marius Isken's avatar
Marius Isken committed
83
    def evaluate(self, x, result_mode='sparse', mask=None):
Sebastian Heimann's avatar
Sebastian Heimann committed
84
85
86
87
88
89
        source = self.unpack(x)
        engine = self.get_engine()

        for target in self.targets:
            target.set_result_mode(result_mode)

Marius Isken's avatar
Marius Isken committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
        if mask is not None:
            assert len(mask) == len(self.targets)
            targets_ok = [
                target for (target, ok) in zip(self.targets, mask) if ok]
        else:
            targets_ok = self.targets

        resp = engine.process(source, targets_ok)

        if mask is not None:
            ires_ok = 0
            results = []
            for target, ok in zip(self.targets, mask):
                if ok:
                    results.append(resp.results_list[0][ires_ok])
                    ires_ok += 1
                else:
                    results.append(
                        gf.SeismosizerError(
                            'skipped because of previous failure'))
        else:
            results = list(resp.results_list[0])
Sebastian Heimann's avatar
Sebastian Heimann committed
112
113

        data = []
Marius Isken's avatar
Marius Isken committed
114
        for target, result in zip(self.targets, results):
Sebastian Heimann's avatar
Sebastian Heimann committed
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
            if isinstance(result, gf.SeismosizerError):
                logger.debug(
                    '%s.%s.%s.%s: %s' % (target.codes + (str(result),)))

                data.append((None, None))
            else:
                data.append((result.misfit_value, result.misfit_norm))

        ms, ns = num.array(data, dtype=num.float).T
        if result_mode == 'full':
            return ms, ns, results
        else:
            return ms, ns

    def forward(self, x):
        source = self.unpack(x)
        engine = self.get_engine()
        plain_targets = [target.get_plain_target() for target in self.targets]

        resp = engine.process(source, plain_targets)
        results = []
        for target, result in zip(self.targets, resp.results_list[0]):
            if isinstance(result, gf.SeismosizerError):
                logger.debug(
                    '%s.%s.%s.%s: %s' % (target.codes + (str(result),)))

                results.append(None)
            else:
                results.append(result)

        return results

    def get_target_weights(self):
        if self._target_weights is None:
            self._target_weights = num.array(
                [target.get_combined_weight(
                    apply_balancing_weights=self.apply_balancing_weights)
                 for target in self.targets], dtype=num.float)

        return self._target_weights

    def inter_group_weights(self, ns):
        group, ngroups = self.get_group_mask()

        ws = num.zeros(self.ntargets)
        for igroup in xrange(ngroups):
            mask = group == igroup
Marius Isken's avatar
Marius Isken committed
162
            ws[mask] = 1. / num.sqrt(num.nansum(ns[mask]**2))
Sebastian Heimann's avatar
Sebastian Heimann committed
163
164
165
166
167
168
169
170

        return ws

    def inter_group_weights2(self, ns):
        group, ngroups = self.get_group_mask()
        ws = num.zeros(ns.shape)
        for igroup in xrange(ngroups):
            mask = group == igroup
Marius Isken's avatar
Marius Isken committed
171
            ws[:, mask] = (1. / num.sqrt(
Sebastian Heimann's avatar
Sebastian Heimann committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
                num.nansum(ns[:, mask]**2, axis=1)))[:, num.newaxis]

        return ws

    def bootstrap_misfit(self, ms, ns, ibootstrap=None):
        w = self.get_bootstrap_weights(ibootstrap) * \
            self.get_target_weights() * self.inter_group_weights(ns)

        if ibootstrap is None:
            return num.sqrt(
                num.nansum((w*ms[num.newaxis, :])**2, axis=1) /
                num.nansum((w*ns[num.newaxis, :])**2, axis=1))
        else:
            return num.sqrt(num.nansum((w*ms)**2) / num.nansum((w*ns)**2))

    def bootstrap_misfits(self, misfits, ibootstrap):
        w = self.get_bootstrap_weights(ibootstrap)[num.newaxis, :] * \
            self.get_target_weights()[num.newaxis, :] * \
            self.inter_group_weights2(misfits[:, :, 1])

        bms = num.sqrt(num.nansum((w*misfits[:, :, 0])**2, axis=1) /
                       num.nansum((w*misfits[:, :, 1])**2, axis=1))
        return bms

    def global_misfit(self, ms, ns):
        ws = self.get_target_weights() * self.inter_group_weights(ns)
        m = num.sqrt(num.nansum((ws*ms)**2) / num.nansum((ws*ns)**2))
        return m

    def global_misfits(self, misfits):
        ws = self.get_target_weights()[num.newaxis, :] * \
            self.inter_group_weights2(misfits[:, :, 1])
        gms = num.sqrt(num.nansum((ws*misfits[:, :, 0])**2, axis=1) /
                       num.nansum((ws*misfits[:, :, 1])**2, axis=1))
        return gms

    def global_contributions(self, misfits):
        ws = self.get_target_weights()[num.newaxis, :] * \
            self.inter_group_weights2(misfits[:, :, 1])

        gcms = (ws*misfits[:, :, 0])**2 / \
            num.nansum((ws*misfits[:, :, 1])**2, axis=1)[:, num.newaxis]

        return gcms


Marius Isken's avatar
Marius Isken committed
218
class RectangularProblemConfig(core.ProblemConfig):
Sebastian Heimann's avatar
Sebastian Heimann committed
219
220

    ranges = Dict.T(String.T(), gf.Range.T())
Marius Isken's avatar
Marius Isken committed
221
    apply_balancing_weights = False
Sebastian Heimann's avatar
Sebastian Heimann committed
222

Marius Isken's avatar
Marius Isken committed
223
224
    def get_problem(self, rect_source, targets):
        base_source = gf.RecangularSource.load(rect_source)
Sebastian Heimann's avatar
Sebastian Heimann committed
225

Marius Isken's avatar
Marius Isken committed
226
        problem = RectangularProblem(
Marius Isken's avatar
Marius Isken committed
227
            name=core.expand_template(self.name_template),
Sebastian Heimann's avatar
Sebastian Heimann committed
228
229
230
231
            apply_balancing_weights=self.apply_balancing_weights,
            base_source=base_source,
            targets=targets,
            ranges=self.ranges,
Marius Isken's avatar
Marius Isken committed
232
            mt_type=self.mt_type)
Sebastian Heimann's avatar
Sebastian Heimann committed
233
234
235
236
237

        return problem


__all__ = [
Marius Isken's avatar
Marius Isken committed
238
239
    'RectangularProblem',
    'RectangularProblemConfig',
Sebastian Heimann's avatar
Sebastian Heimann committed
240
]