/
contexts.py
1904 lines (1727 loc) · 71.7 KB
/
contexts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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
425
426
427
428
429
430
431
432
433
434
435
436
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
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
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2018-2023 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OpenQuake is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with OpenQuake. If not, see <http://www.gnu.org/licenses/>.
import abc
import copy
import time
import logging
import warnings
import itertools
import operator
import collections
from unittest.mock import patch
import numpy
import shapely
from scipy.interpolate import interp1d
from openquake.baselib import config
from openquake.baselib.general import (
AccumDict, DictArray, RecordBuilder, split_in_slices, block_splitter,
sqrscale)
from openquake.baselib.performance import Monitor, split_array, kround0
from openquake.baselib.python3compat import decode
from openquake.hazardlib import valid, imt as imt_module
from openquake.hazardlib.const import StdDev, OK_COMPONENTS
from openquake.hazardlib.tom import FatedTOM, NegativeBinomialTOM, PoissonTOM
from openquake.hazardlib.stats import ndtr
from openquake.hazardlib.site import SiteCollection, site_param_dt
from openquake.hazardlib.calc.filters import (
SourceFilter, IntegrationDistance, magdepdist,
get_dparam, get_distances, getdefault, MINMAG, MAXMAG)
from openquake.hazardlib.probability_map import ProbabilityMap
from openquake.hazardlib.geo import multiline
from openquake.hazardlib.geo.mesh import Mesh
from openquake.hazardlib.geo.surface.planar import (
project, project_back, get_distances_planar)
U8 = numpy.uint8
I32 = numpy.int32
U32 = numpy.uint32
F16 = numpy.float16
F32 = numpy.float32
F64 = numpy.float64
TWO20 = 2**20 # used when collapsing
TWO16 = 2**16
TWO24 = 2**24
TWO32 = 2**32
STD_TYPES = (StdDev.TOTAL, StdDev.INTER_EVENT, StdDev.INTRA_EVENT)
KNOWN_DISTANCES = frozenset('''rrup rx_ry0 rx ry0 rjb rhypo repi rcdpp azimuth
azimuthcp rvolc clon_clat clon clat'''.split())
NUM_BINS = 256
DIST_BINS = sqrscale(80, 1000, NUM_BINS)
# the MULTIPLIER is fundamental for the memory consumption in the contexts
MULTIPLIER = 50 # len(mean_stds arrays) / len(poes arrays)
MEA = 0
STD = 1
bymag = operator.attrgetter('mag')
# These coordinates were provided by M Gerstenberger (personal
# communication, 10 August 2018)
cshm_polygon = shapely.geometry.Polygon([(171.6, -43.3), (173.2, -43.3),
(173.2, -43.9), (171.6, -43.9)])
def _get(surfaces, param, dparam, mask=slice(None)):
arr = numpy.array([dparam[sec.idx, param][mask] for sec in surfaces])
return arr # shape (S, N, ...)
def _get_tu(rup, dparam, mask):
tor = rup.surface.tor
arr = _get(rup.surface.surfaces, 'tuw', dparam, mask)
S, N = arr.shape[:2]
# keep the flipped values and then reorder the surface indices
# arr has shape (S, N, 2, 3) where 2 refer to the flipping
tuw = numpy.zeros((S, N, 3), F32)
for s in range(S):
idx = tor.soidx[s]
flip = int(tor.flipped[idx])
tuw[s] = arr[idx, :, flip, :] # shape (N, 3)
return multiline.get_tu(tor.shift, tuw)
def set_distances(ctx, rup, r_sites, param, dparam, mask, tu):
"""
Set the distance attributes on the context; also manages paired
attributes like clon_lat and rx_ry0.
"""
if dparam is None:
# no multifault
dists = get_distances(rup, r_sites, param)
if '_' in param:
p0, p1 = param.split('_') # clon_clat
setattr(ctx, p0, dists[:, 0])
setattr(ctx, p1, dists[:, 1])
else:
setattr(ctx, param, dists)
else:
# use the MultiLine object
u_max = rup.surface.msparam['u_max']
if param in ('rx', 'ry0'):
tut, uut = tu
'''
# sanity check with the right parameters t, u
t, u = rup.surface.tor.get_tu(r_sites)
numpy.testing.assert_allclose(tut, t)
numpy.testing.assert_allclose(uut, u)
'''
if param == 'rx':
ctx.rx = tut
elif param == 'ry0':
neg = uut < 0
ctx.ry0[neg] = numpy.abs(uut[neg])
big = uut > u_max
ctx.ry0[big] = uut[big] - u_max
elif param == 'rjb' :
rjbs = _get(rup.surface.surfaces, 'rjb', dparam, mask)
ctx['rjb'] = numpy.min(rjbs, axis=0)
'''
# sanity check with the right rjb
rjb = rup.surface.get_joyner_boore_distance(r_sites)
numpy.testing.assert_allclose(ctx.rjb, rjb)
'''
elif param == 'clon_clat':
coos = _get(rup.surface.surfaces, 'clon_clat', dparam, mask)
# shape (numsections, numsites, 3)
m = Mesh(coos[:, :, 0], coos[:, :, 1]).get_closest_points(r_sites)
# shape (numsites, 3)
ctx['clon'] = m.lons
ctx['clat'] = m.lats
def round_dist(dst):
idx = numpy.searchsorted(DIST_BINS, dst)
idx[idx == NUM_BINS] -= 1
return DIST_BINS[idx]
def is_modifiable(gsim):
"""
:returns: True if it is a ModifiableGMPE
"""
return hasattr(gsim, 'gmpe') and hasattr(gsim, 'params')
def split_by_occur(ctx):
"""
:returns: [poissonian] or [poissonian, nonpoissonian,...]
"""
nan = numpy.isnan(ctx.occurrence_rate)
out = []
if 0 < nan.sum() < len(ctx):
out.append(ctx[~nan])
nonpoisson = ctx[nan]
for shp in set(np.probs_occur.shape[1] for np in nonpoisson):
# ctxs with the same shape of prob_occur are concatenated
p_array = [p for p in nonpoisson if p.probs_occur.shape[1] == shp]
arr = numpy.concatenate(p_array, p_array[0].dtype)
out.append(arr.view(numpy.recarray))
else:
out.append(ctx)
return out
def concat(ctxs):
"""
Concatenate context arrays.
:returns: [] or [poisson_ctx] or [poisson_ctx, nonpoisson_ctx, ...]
"""
out, poisson, nonpoisson, nonparam = [], [], [], []
for ctx in ctxs:
if numpy.isnan(ctx.occurrence_rate).all():
nonparam.append(ctx)
# If ctx has probs_occur and occur_rate is parametric non-poisson
elif hasattr(ctx, 'probs_occur') and ctx.probs_occur.shape[1] >= 1:
nonpoisson.append(ctx)
else:
poisson.append(ctx)
if poisson:
out.append(numpy.concatenate(poisson).view(numpy.recarray))
if nonpoisson:
# Ctxs with the same shape of prob_occur are concatenated
# and different shape sets are appended separately
for shp in set(ctx.probs_occur.shape[1] for ctx in nonpoisson):
p_array = [p for p in nonpoisson
if p.probs_occur.shape[1] == shp]
out.append(numpy.concatenate(p_array).view(numpy.recarray))
if nonparam:
out.append(numpy.concatenate(nonparam).view(numpy.recarray))
return out
def get_maxsize(M, G):
"""
:returns: an integer N such that arrays N*M*G fit in the CPU cache
"""
maxs = TWO20 // (2*M*G)
assert maxs > 1, maxs
return maxs * MULTIPLIER
def size(imtls):
"""
:returns: size of the dictionary of arrays imtls
"""
imls = imtls[next(iter(imtls))]
return len(imls) * len(imtls)
def trivial(ctx, name):
"""
:param ctx: a recarray
:param name: name of a parameter
:returns: True if the parameter is missing or single valued
"""
if name not in ctx.dtype.names:
return True
return len(numpy.unique(numpy.float32(ctx[name]))) == 1
class Oq(object):
def __init__(self, **hparams):
vars(self).update(hparams)
def get_reqv(self):
if 'reqv' not in self.inputs:
return
return {key: valid.RjbEquivalent(value)
for key, value in self.inputs['reqv'].items()}
class DeltaRatesGetter(object):
"""
Read the delta rates from an aftershock datastore
"""
def __init__(self, dstore):
self.dstore = dstore
def __call__(self, src_id):
with self.dstore.open('r') as dstore:
return dstore['delta_rates'][src_id]
# same speed as performance.kround, round more
def kround1(ctx, kfields):
kdist = 2. * ctx.mag**2 # heuristic collapse distance from 32 to 200 km
close = ctx.rrup < kdist
far = ~close
out = numpy.zeros(len(ctx), [(k, ctx.dtype[k]) for k in kfields])
for kfield in kfields:
kval = ctx[kfield]
if kfield == 'vs30':
out[kfield][close] = numpy.round(kval[close]) # round less
out[kfield][far] = numpy.round(kval[far], 1) # round more
elif kval.dtype == F64 and kfield != 'mag':
out[kfield][close] = F16(kval[close]) # round less
out[kfield][far] = numpy.round(kval[far]) # round more
else:
out[kfield] = ctx[kfield]
return out
def kround2(ctx, kfields):
kdist = 5. * ctx.mag**2 # from 80 to 500 km
close = ctx.rrup < kdist
far = ~close
out = numpy.zeros(len(ctx), [(k, ctx.dtype[k]) for k in kfields])
for kfield in kfields:
kval = ctx[kfield]
if kfield == 'rx': # can be negative
out[kfield] = numpy.round(kval)
elif kfield in KNOWN_DISTANCES:
out[kfield][close] = numpy.ceil(kval[close]) # round to 1 km
out[kfield][far] = round_dist(kval[far]) # round more
elif kfield == 'vs30':
out[kfield][close] = numpy.round(kval[close]) # round less
out[kfield][far] = numpy.round(kval[far], 1) # round more
elif kval.dtype == F64 and kfield != 'mag':
out[kfield][close] = F16(kval[close]) # round less
out[kfield][far] = numpy.round(kval[far]) # round more
else:
out[kfield] = ctx[kfield]
return out
kround = {0: kround0, 1: kround1, 2: kround2}
class Collapser(object):
"""
Class managing the collapsing logic.
"""
def __init__(self, collapse_level, kfields):
self.collapse_level = collapse_level
self.kfields = sorted(kfields)
self.cfactor = numpy.zeros(3)
def collapse(self, ctx, mon, rup_indep, collapse_level=None):
"""
Collapse a context recarray if possible.
:param ctx: a recarray with "sids"
:param rup_indep: False if the ruptures are mutually exclusive
:param collapse_level: if None, use .collapse_level
:returns: the collapsed array and the inverting indices
"""
clevel = (collapse_level if collapse_level is not None
else self.collapse_level)
if not rup_indep or clevel < 0:
# no collapse
self.cfactor[0] += len(ctx)
self.cfactor[1] += len(ctx)
self.cfactor[2] += 1
return ctx, None
with mon:
krounded = kround[clevel](ctx, self.kfields)
out, inv = numpy.unique(krounded, return_inverse=True)
self.cfactor[0] += len(out)
self.cfactor[1] += len(ctx)
self.cfactor[2] += 1
return out.view(numpy.recarray), inv.astype(U32)
class FarAwayRupture(Exception):
"""Raised if the rupture is outside the maximum distance for all sites"""
def get_num_distances(gsims):
"""
:returns: the number of distances required for the given GSIMs
"""
dists = set()
for gsim in gsims:
dists.update(gsim.REQUIRES_DISTANCES)
return len(dists)
# NB: minimum_magnitude is ignored
def _interp(param, name, trt):
try:
mdd = param[name]
except KeyError:
return magdepdist([(MINMAG, 1000), (MAXMAG, 1000)])
if isinstance(mdd, IntegrationDistance):
return mdd(trt)
elif isinstance(mdd, dict):
if mdd:
magdist = getdefault(mdd, trt)
else:
magdist = [(MINMAG, 1000), (MAXMAG, 1000)]
return magdepdist(magdist)
return mdd
def simple_cmaker(gsims, imts, **params):
"""
:returns: a simplified ContextMaker for use in the tests
"""
dic = dict(imtls={imt: [0] for imt in imts})
dic.update(**params)
return ContextMaker('*', gsims, dic)
# ############################ genctxs ################################## #
# generator of quartets (rup_index, mag, planar_array, sites)
def _quartets(cmaker, src, sitecol, cdist, magdist, planardict):
minmag = cmaker.maximum_distance.x[0]
maxmag = cmaker.maximum_distance.x[-1]
# splitting by magnitude
if src.count_nphc() == 1:
# one rupture per magnitude
for m, (mag, pla) in enumerate(planardict.items()):
if minmag < mag < maxmag:
yield m, mag, pla, sitecol
else:
for m, rup in enumerate(src.iruptures()):
mag = rup.mag
if mag > maxmag or mag < minmag:
continue
arr = [rup.surface.array.reshape(-1, 3)]
pla = planardict[mag]
# NB: having a good psdist is essential for performance!
psdist = src.get_psdist(m, mag, cmaker.pointsource_distance,
magdist)
close = sitecol.filter(cdist <= psdist)
far = sitecol.filter(cdist > psdist)
if cmaker.fewsites:
if close is None: # all is far, common for small mag
yield m, mag, arr, sitecol
else: # something is close
yield m, mag, pla, sitecol
else: # many sites
if close is None: # all is far
yield m, mag, arr, far
elif far is None: # all is close
yield m, mag, pla, close
else: # some sites are far, some are close
yield m, mag, arr, far
yield m, mag, pla, close
# helper used to populate contexts for planar ruptures
def _get_ctx_planar(cmaker, zeroctx, mag, planar, sites, src_id, tom):
# computing distances
rrup, xx, yy = project(planar, sites.xyz) # (3, U, N)
# get the closest points on the surface
if cmaker.fewsites or 'clon' in cmaker.REQUIRES_DISTANCES:
closest = project_back(planar, xx, yy) # (3, U, N)
# set distances
zeroctx['rrup'] = rrup
for par in cmaker.REQUIRES_DISTANCES - {'rrup'}:
zeroctx[par] = get_distances_planar(planar, sites, par)
for par in cmaker.REQUIRES_DISTANCES:
dst = zeroctx[par]
if cmaker.minimum_distance:
dst[dst < cmaker.minimum_distance] = cmaker.minimum_distance
# ctx has shape (U, N), ctxt (N, U)
ctxt = zeroctx.T # smart trick taking advantage of numpy magic
ctxt['src_id'] = src_id
# setting rupture parameters
for par in cmaker.ruptparams:
if par == 'mag':
ctxt[par] = mag
elif par == 'occurrence_rate':
ctxt[par] = planar.wlr[:, 2] # shape U-> (N, U)
elif par == 'width':
ctxt[par] = planar.wlr[:, 0]
elif par == 'strike':
ctxt[par] = planar.sdr[:, 0]
elif par == 'dip':
ctxt[par] = planar.sdr[:, 1]
elif par == 'rake':
ctxt[par] = planar.sdr[:, 2]
elif par == 'ztor': # top edge depth
ctxt[par] = planar.corners[:, 2, 0]
elif par == 'zbot': # bottom edge depth
ctxt[par] = planar.corners[:, 2, 3]
elif par == 'hypo_lon':
ctxt[par] = planar.hypo[:, 0]
elif par == 'hypo_lat':
ctxt[par] = planar.hypo[:, 1]
elif par == 'hypo_depth':
ctxt[par] = planar.hypo[:, 2]
if cmaker.fewsites:
zeroctx['clon'] = closest[0]
zeroctx['clat'] = closest[1]
# setting site parameters
for par in cmaker.siteparams:
zeroctx[par] = sites.array[par] # shape N-> (U, N)
if hasattr(tom, 'get_pmf'): # NegativeBinomialTOM
# read Probability Mass Function from model and reshape it
# into predetermined shape of probs_occur
pmf = tom.get_pmf(planar.wlr[:, 2],
n_max=zeroctx['probs_occur'].shape[2])
zeroctx['probs_occur'] = pmf[:, numpy.newaxis, :]
return zeroctx.flatten() # shape N*U
def genctxs_Pp(src, sitecol, cmaker):
"""
Context generator for point sources and collapsed point sources
"""
dd = cmaker.defaultdict.copy()
tom = getattr(src, 'temporal_occurrence_model', None)
if tom and isinstance(tom, NegativeBinomialTOM):
if hasattr(src, 'pointsources'): # CollapsedPointSource
maxrate = max(max(ps.mfd.occurrence_rates)
for ps in src.pointsources)
else: # regular source
maxrate = max(src.mfd.occurrence_rates)
p_size = tom.get_pmf(maxrate).shape[1]
dd['probs_occur'] = numpy.zeros(p_size)
else:
dd['probs_occur'] = numpy.zeros(0)
builder = RecordBuilder(**dd)
cmaker.siteparams = [par for par in sitecol.array.dtype.names
if par in dd]
cmaker.ruptparams = cmaker.REQUIRES_RUPTURE_PARAMETERS | {'occurrence_rate'}
with cmaker.ir_mon:
# building planar geometries
planardict = src.get_planar(cmaker.shift_hypo)
magdist = {mag: cmaker.maximum_distance(mag)
for mag, rate in src.get_annual_occurrence_rates()}
# cmaker.maximum_distance(mag) can be 0 if outside the mag range
maxmag = max(mag for mag, dist in magdist.items() if dist > 0)
maxdist = magdist[maxmag]
cdist = sitecol.get_cdist(src.location)
# NB: having a decent max_radius is essential for performance!
mask = cdist <= maxdist + src.max_radius(maxdist)
sitecol = sitecol.filter(mask)
if sitecol is None:
return []
for magi, mag, planarlist, sites in _quartets(
cmaker, src, sitecol, cdist[mask], magdist, planardict):
if not planarlist:
continue
elif len(planarlist) > 1: # when using ps_grid_spacing
pla = numpy.concatenate(planarlist).view(numpy.recarray)
else:
pla = planarlist[0]
offset = src.offset + magi * len(pla)
zctx = builder.zeros((len(pla), len(sites))) # shape (N, U)
if cmaker.fewsites:
rup_ids = zctx['rup_id'].T # numpy trick, shape (U, N)
rup_ids[:] = numpy.arange(offset, offset+len(pla))
# building contexts
ctx = _get_ctx_planar(cmaker, zctx, mag, pla, sites, src.id, tom)
ctxt = ctx[ctx.rrup < magdist[mag]]
if len(ctxt):
yield ctxt
def _build_dparam(src, sitecol, cmaker):
dparams = {'rjb', 'tuw'}
if cmaker.fewsites:
dparams |= {'clon_clat'}
sections = src.get_sections(src.get_unique_idxs())
out = {}
for sec in sections:
out[sec.idx, 'rrup'] = get_dparam(sec, sitecol, 'rrup')
for param in dparams:
out[sec.idx, param] = get_dparam(sec, sitecol, param)
# use multi_fault_test to debug this
# from openquake.baselib.general import getsizeof
# print(getsizeof(out))
return out
# ############################ ContextMaker ############################### #
class ContextMaker(object):
"""
A class to manage the creation of contexts and to compute mean/stddevs
and possibly PoEs.
:param trt: tectonic region type string
:param gsims: list of GSIMs or a dictionary gsim -> rlz indices
:param oq:
dictionary of parameters like the maximum_distance, the IMTLs,
the investigation time, etc, or an OqParam instance
:param extraparams:
additional site parameters to consider, used only in the tests
NB: the trt can be different from the tectonic region type for which
the underlying GSIMs are defined. This is intentional.
"""
REQUIRES = ['DISTANCES', 'SITES_PARAMETERS', 'RUPTURE_PARAMETERS']
scenario = False
deltagetter = None
fewsites = False
tom = None
def __init__(self, trt, gsims, oq, monitor=Monitor(), extraparams=()):
self.trt = trt
self.gsims = gsims
if isinstance(oq, dict):
param = oq
oq = Oq(**param)
self.mags = param.get('mags', ()) # list of strings %.2f
self.cross_correl = param.get('cross_correl') # cond_spectra_test
else: # OqParam
param = vars(oq)
param['split_sources'] = oq.split_sources
param['min_iml'] = oq.min_iml
param['reqv'] = oq.get_reqv()
param['af'] = getattr(oq, 'af', None)
self.cross_correl = oq.cross_correl
self.imtls = oq.imtls
try:
self.mags = oq.mags_by_trt[trt]
except AttributeError:
self.mags = ()
except KeyError: # missing TRT but there is only one
[(_, self.mags)] = oq.mags_by_trt.items()
self.oq = oq
self.monitor = monitor
self._init1(param)
self._init2(param, extraparams)
self.set_imts_conv()
self.init_monitoring(self.monitor)
def _init1(self, param):
if 'poes' in param:
self.poes = param['poes']
if 'imtls' in param:
for imt in param['imtls']:
if not isinstance(imt, str):
raise TypeError('Expected string, got %s' % type(imt))
self.imtls = param['imtls']
elif 'hazard_imtls' in param:
self.imtls = DictArray(
imt_module.sort_by_imt(param['hazard_imtls']))
elif not hasattr(self, 'imtls'):
raise KeyError('Missing imtls in ContextMaker!')
self.cache_distances = param.get('cache_distances', False)
self.max_sites_disagg = param.get('max_sites_disagg', 10)
self.time_per_task = param.get('time_per_task', 60)
self.collapse_level = int(param.get('collapse_level', -1))
self.disagg_by_src = param.get('disagg_by_src', False)
self.horiz_comp = param.get('horiz_comp_to_geom_mean', False)
self.maximum_distance = _interp(param, 'maximum_distance', self.trt)
if 'pointsource_distance' not in param:
self.pointsource_distance = float(
config.performance.pointsource_distance)
else:
self.pointsource_distance = getdefault(
param['pointsource_distance'], self.trt)
self.minimum_distance = param.get('minimum_distance', 0)
self.investigation_time = param.get('investigation_time')
self.ses_seed = param.get('ses_seed', 42)
self.ses_per_logic_tree_path = param.get('ses_per_logic_tree_path', 1)
self.truncation_level = param.get('truncation_level', 99.)
self.phi_b = ndtr(self.truncation_level)
self.num_epsilon_bins = param.get('num_epsilon_bins', 1)
self.disagg_bin_edges = param.get('disagg_bin_edges', {})
self.ps_grid_spacing = param.get('ps_grid_spacing')
self.split_sources = param.get('split_sources')
def _init2(self, param, extraparams):
for gsim in self.gsims:
if hasattr(gsim, 'set_tables'):
if len(self.mags) == 0 and not is_modifiable(gsim):
raise ValueError(
'You must supply a list of magnitudes as 2-digit '
'strings, like mags=["6.00", "6.10", "6.20"]')
gsim.set_tables(self.mags, self.imtls)
self.effect = param.get('effect')
for req in self.REQUIRES:
reqset = set()
for gsim in self.gsims:
reqset.update(getattr(gsim, 'REQUIRES_' + req))
if getattr(self.oq, 'af', None) and req == 'SITES_PARAMETERS':
reqset.add('ampcode')
if is_modifiable(gsim) and req == 'SITES_PARAMETERS':
reqset.add('vs30') # required by the ModifiableGMPE
reqset.update(gsim.gmpe.REQUIRES_SITES_PARAMETERS)
if 'apply_swiss_amplification' in gsim.params:
reqset.add('amplfactor')
if ('apply_swiss_amplification_sa' in gsim.params):
reqset.add('ch_ampl03')
reqset.add('ch_ampl06')
reqset.add('ch_phis2s03')
reqset.add('ch_phis2s06')
reqset.add('ch_phiss03')
reqset.add('ch_phiss06')
setattr(self, 'REQUIRES_' + req, reqset)
try:
self.min_iml = param['min_iml']
except KeyError:
self.min_iml = numpy.array([0. for imt in self.imtls])
self.reqv = param.get('reqv')
if self.reqv is not None:
self.REQUIRES_DISTANCES.add('repi')
# NB: REQUIRES_DISTANCES is empty when gsims = [FromFile]
REQUIRES_DISTANCES = self.REQUIRES_DISTANCES | {'rrup'}
reqs = (sorted(self.REQUIRES_RUPTURE_PARAMETERS) +
sorted(self.REQUIRES_SITES_PARAMETERS | set(extraparams)) +
sorted(REQUIRES_DISTANCES))
dic = {}
for req in reqs:
if req in site_param_dt:
dt = site_param_dt[req]
if isinstance(dt, tuple): # (string_, size)
dic[req] = b'X' * dt[1]
else:
dic[req] = dt(0)
else:
dic[req] = 0.
dic['src_id'] = I32(0)
dic['rup_id'] = U32(0)
dic['sids'] = U32(0)
dic['rrup'] = F64(0)
dic['occurrence_rate'] = F64(0)
self.defaultdict = dic
self.shift_hypo = param.get('shift_hypo')
def init_monitoring(self, monitor):
# instantiating child monitors, may be called in the workers
self.pla_mon = monitor('planar contexts', measuremem=False)
self.ctx_mon = monitor('nonplanar contexts', measuremem=False)
self.gmf_mon = monitor('computing mean_std', measuremem=False)
self.poe_mon = monitor('get_poes', measuremem=False)
self.pne_mon = monitor('composing pnes', measuremem=False)
self.ir_mon = monitor('iter_ruptures', measuremem=False)
self.sec_mon = monitor('building dparam', measuremem=True)
self.delta_mon = monitor('getting delta_rates', measuremem=False)
self.col_mon = monitor('collapsing contexts', measuremem=False)
self.task_no = getattr(monitor, 'task_no', 0)
self.out_no = getattr(monitor, 'out_no', self.task_no)
kfields = (self.REQUIRES_DISTANCES |
self.REQUIRES_RUPTURE_PARAMETERS |
self.REQUIRES_SITES_PARAMETERS)
self.collapser = Collapser(self.collapse_level, kfields)
def restrict(self, imts):
"""
:param imts: a list of IMT strings subset of the full list
:returns: a new ContextMaker involving less IMTs
"""
new = copy.copy(self)
new.imtls = DictArray({imt: self.imtls[imt] for imt in imts})
new.set_imts_conv()
return new
def set_imts_conv(self):
"""
Set the .imts list and .conv dictionary for the horizontal component
conversion (if any).
"""
self.loglevels = DictArray(self.imtls) if self.imtls else {}
with warnings.catch_warnings():
# avoid RuntimeWarning: divide by zero encountered in log
warnings.simplefilter("ignore")
for imt, imls in self.imtls.items():
if imt != 'MMI':
self.loglevels[imt] = numpy.log(imls)
self.imts = tuple(imt_module.from_string(im) for im in self.imtls)
self.conv = {} # gsim -> imt -> (conv_median, conv_sigma, rstd)
if not self.horiz_comp:
return # do not convert
for gsim in self.gsims:
self.conv[gsim] = {}
imc = gsim.DEFINED_FOR_INTENSITY_MEASURE_COMPONENT
if imc.name == 'GEOMETRIC_MEAN':
pass # nothing to do
elif imc.name in OK_COMPONENTS:
dic = {imt: imc.apply_conversion(imt) for imt in self.imts}
self.conv[gsim].update(dic)
else:
logging.info(f'Conversion from {imc.name} not applicable to'
f' {gsim.__class__.__name__}')
def horiz_comp_to_geom_mean(self, mean_stds):
"""
This function converts ground-motion obtained for a given description
of horizontal component into ground-motion values for geometric_mean.
The conversion equations used are from:
- Beyer and Bommer (2006): for arithmetic mean, GMRot and random
- Boore and Kishida (2017): for RotD50
"""
for g, gsim in enumerate(self.gsims):
if not self.conv[gsim]:
continue
for m, imt in enumerate(self.imts):
me, si, ta, ph = mean_stds[:, g, m]
conv_median, conv_sigma, rstd = self.conv[gsim][imt]
me[:] = numpy.log(numpy.exp(me) / conv_median)
si[:] = ((si**2 - conv_sigma**2) / rstd**2)**0.5
@property
def Z(self):
"""
:returns: the number of realizations associated to self
"""
return sum(len(rlzs) for rlzs in self.gsims.values())
def new_ctx(self, size):
"""
:returns: a recarray of the given size full of zeros
"""
return RecordBuilder(**self.defaultdict).zeros(size)
def recarray(self, ctxs):
"""
:params ctxs: a non-empty list of homogeneous contexts
:returns: a recarray, possibly collapsed
"""
assert ctxs
dd = self.defaultdict.copy()
if not hasattr(ctxs[0], 'probs_occur'):
for ctx in ctxs:
ctx.probs_occur = numpy.zeros(0)
np = 0
else:
shps = [ctx.probs_occur.shape for ctx in ctxs]
np = max(i[1] if len(i) > 1 else i[0] for i in shps)
dd['probs_occur'] = numpy.zeros(np)
C = sum(len(ctx) for ctx in ctxs)
ra = RecordBuilder(**dd).zeros(C)
start = 0
for ctx in ctxs:
if self.minimum_distance:
for name in self.REQUIRES_DISTANCES:
array = ctx[name]
small_distances = array < self.minimum_distance
if small_distances.any():
array = numpy.array(array) # make a copy first
array[small_distances] = self.minimum_distance
array.flags.writeable = False
ctx[name] = array
slc = slice(start, start + len(ctx))
for par in dd:
if par == 'rup_id':
val = getattr(ctx, par)
else:
val = getattr(ctx, par, numpy.nan)
if par == 'clon_clat':
ra['clon'][slc] = ctx.clon
ra['clat'][slc] = ctx.clat
else:
getattr(ra, par)[slc] = val
ra.sids[slc] = ctx.sids
start = slc.stop
return ra
def get_ctx_params(self):
"""
:returns: the interesting attributes of the context
"""
params = {'occurrence_rate', 'sids', 'src_id',
'probs_occur', 'clon', 'clat', 'rrup'}
params.update(self.REQUIRES_RUPTURE_PARAMETERS)
for dparam in self.REQUIRES_DISTANCES:
params.add(dparam + '_')
return params
def from_planar(self, rup, hdist, step, point='TC', toward_azimuth=90,
direction='positive'):
"""
:param rup:
a BaseRupture instance with a PlanarSurface and site parameters
:returns: a context array for the sites around the rupture
"""
sitecol = SiteCollection.from_planar(
rup, point='TC', toward_azimuth=90,
direction='positive', hdist=hdist, step=5.,
req_site_params=self.REQUIRES_SITES_PARAMETERS)
ctxs = list(self.genctxs([rup], sitecol, src_id=0))
return self.recarray(ctxs)
def from_srcs(self, srcs, sitecol):
# used in disagg.disaggregation
"""
:param srcs: a list of Source objects
:param sitecol: a SiteCollection instance
:returns: a list of context arrays
"""
ctxs = []
srcfilter = SourceFilter(sitecol, self.maximum_distance)
for i, src in enumerate(srcs):
if src.id == -1: # not set yet
src.id = i
sites = srcfilter.get_close_sites(src)
if sites is not None:
ctxs.extend(self.get_ctx_iter(src, sites))
return concat(ctxs)
def get_rparams(self, rup):
"""
:returns: a dictionary with the rupture parameters
"""
dic = {}
if hasattr(self, 'dparam') and self.dparam:
msparam = rup.surface.msparam
else:
msparam = None
for param in self.REQUIRES_RUPTURE_PARAMETERS:
if param == 'mag':
value = numpy.round(rup.mag, 3)
elif param == 'strike':
if msparam:
value = msparam['strike']
else:
value = rup.surface.get_strike()
elif param == 'dip':
if msparam:
value = msparam['dip']
else:
value = rup.surface.get_dip()
elif param == 'rake':
value = rup.rake
elif param == 'ztor':
if msparam:
value = msparam['ztor']
else:
value = rup.surface.get_top_edge_depth()
elif param == 'hypo_lon':
value = rup.hypocenter.longitude
elif param == 'hypo_lat':
value = rup.hypocenter.latitude
elif param == 'hypo_depth':
value = rup.hypocenter.depth
elif param == 'width':
if msparam:
value = msparam['width']
else:
value = rup.surface.get_width()
elif param == 'in_cshm':
# used in McVerry and Bradley GMPEs
if rup.surface:
# this is really expensive
lons = rup.surface.mesh.lons.flatten()
lats = rup.surface.mesh.lats.flatten()
points_in_polygon = (
shapely.geometry.Point(lon, lat).within(cshm_polygon)
for lon, lat in zip(lons, lats))
value = any(points_in_polygon)
else:
value = False
elif param == 'zbot':
# needed for width estimation in CampbellBozorgnia2014
if msparam:
value = msparam['zbot']
elif rup.surface and hasattr(rup, 'surfaces'):
value = rup.surface.zbot
elif rup.surface:
value = rup.surface.mesh.depths.max()
else:
value = rup.hypocenter.depth
else:
raise ValueError('%s requires unknown rupture parameter %r' %
(type(self).__name__, param))
dic[param] = value
dic['occurrence_rate'] = getattr(rup, 'occurrence_rate', numpy.nan)
if hasattr(rup, 'temporal_occurrence_model'):
if isinstance(rup.temporal_occurrence_model, NegativeBinomialTOM):
dic['probs_occur'] = rup.temporal_occurrence_model.get_pmf(
rup.occurrence_rate)
elif hasattr(rup, 'probs_occur'):
dic['probs_occur'] = rup.probs_occur
return dic
def genctxs(self, same_mag_rups, sites, src_id):
"""
:params same_mag_rups: a list of ruptures
:param sites: a (filtered) site collection
:param src_id: source index
:yields: a context array for each rupture
"""
magdist = self.maximum_distance(same_mag_rups[0].mag)
dparam = getattr(self, 'dparam', None)
for rup in same_mag_rups:
if dparam:
rrups = _get(rup.surface.surfaces, 'rrup', dparam)
rrup = numpy.min(rrups, axis=0)
else:
rrup = get_distances(rup, sites, 'rrup')
mask = rrup <= magdist
if not mask.any():
continue
r_sites = sites.filter(mask)
# to debug you can insert here
# print(rup.surface.tor.get_tuw_df(r_sites))
# import pdb; pdb.set_trace()
''' # sanity check
true_rrup = rup.surface.get_min_distance(r_sites)
numpy.testing.assert_allclose(true_rrup, rrup[mask])
'''
rparams = self.get_rparams(rup)
dd = self.defaultdict.copy()
np = len(rparams.get('probs_occur', []))
dd['probs_occur'] = numpy.zeros(np)
ctx = RecordBuilder(**dd).zeros(len(r_sites))
for par, val in rparams.items():
ctx[par] = val
ctx.rrup = rrup[mask]
ctx.sids = r_sites.sids
params = self.REQUIRES_DISTANCES - {'rrup'}
if self.fewsites or 'clon' in params or 'clat' in params:
params.add('clon_clat')
# compute tu only once
if dparam and ('rx' in params or 'ry0' in params):
tu = _get_tu(rup, dparam, mask)