def make_figure_effect_by_mag(extractors, what): """ $ oq plot "effect_by_mag?" """ # NB: matplotlib is imported inside since it is a costly import import matplotlib.pyplot as plt [ex] = extractors gsims_by_trt = ex.get('gsims_by_trt', asdict=True) mags = ex.get('source_mags').array try: effect = ex.get('effect') except KeyError: onesite = ex.get('sitecol').one() maximum_distance = MagDepDistance(ex.oqparam.maximum_distance) imtls = ex.oqparam.imtls ebm = get_effect_by_mag(mags, onesite, gsims_by_trt, maximum_distance, imtls) effect = numpy.array(list(ebm.values())) fig, ax = plt.subplots() trti = 0 for trt in gsims_by_trt: ax.plot(mags, effect[:, -1, trti], label=trt) ax.set_xlabel('Mag') ax.set_ylabel('Intensity') ax.set_title('Effect at maximum distance') trti += 1 ax.legend() return plt
def test_single_site(self): # NB: the performance of get_mean_std is totally dominated by two # concomitant factors: # 1) source splitting (do not split the area source) # 2) collect the contexts in a single array # together they give a 200x speedup # numba is totally useless site = Site(Point(0, 0), vs30=760., z1pt0=48.0, z2pt5=0.607, vs30measured=True) sitecol = SiteCollection([site]) imtls = {"PGA": [.123]} for period in numpy.arange(.1, 1.3, .1): imtls['SA(%.2f)' % period] = [.123] assert len(imtls) == 13 # 13 periods oq = unittest.mock.Mock(imtls=DictArray(imtls), maximum_distance=MagDepDistance.new('300')) mon = Monitor() hcurve = calc_hazard_curve(sitecol, asource, [ExampleA2021()], oq, mon) for child in mon.children: print(child) got = hcurve.array[:, 0] exp = [ 0.103379, 0.468937, 0.403896, 0.278772, 0.213645, 0.142985, 0.103438, 0.079094, 0.062861, 0.051344, 0.04066, 0.031589, 0.024935 ] numpy.testing.assert_allclose(got, exp, atol=1E-5)
def test_international_date_line(self): # from a bug affecting a calculation in New Zealand fname = gettemp(characteric_source) [[src]] = nrml.to_python(fname) os.remove(fname) maxdist = MagDepDistance.new('200') sitecol = SiteCollection([ Site(location=Point(176.919, -39.489), vs30=760, vs30measured=True, z1pt0=100, z2pt5=5)]) srcfilter = SourceFilter(sitecol, maxdist) sites = srcfilter.get_close_sites(src) self.assertIsNotNone(sites)
def __init__(self, trt, gsims, param=None, monitor=Monitor()): param = param or {} # empty in the gmpe-smtk self.af = param.get('af', None) self.max_sites_disagg = param.get('max_sites_disagg', 10) self.collapse_level = param.get('collapse_level', False) self.trt = trt self.gsims = gsims self.single_site_opt = numpy.array( [hasattr(gsim, 'get_mean_std1') for gsim in gsims]) self.maximum_distance = (param.get('maximum_distance') or MagDepDistance({})) self.investigation_time = param.get('investigation_time') self.trunclevel = param.get('truncation_level') self.num_epsilon_bins = param.get('num_epsilon_bins', 1) self.grp_id = param.get('grp_id', 0) self.effect = param.get('effect') self.task_no = getattr(monitor, 'task_no', 0) for req in self.REQUIRES: reqset = set() for gsim in gsims: reqset.update(getattr(gsim, 'REQUIRES_' + req)) setattr(self, 'REQUIRES_' + req, reqset) # self.pointsource_distance is a dict mag -> dist, possibly empty psd = param.get('pointsource_distance') if hasattr(psd, 'ddic'): self.pointsource_distance = psd.ddic.get(trt, {}) else: self.pointsource_distance = {} if 'imtls' in param: self.imtls = param['imtls'] elif 'hazard_imtls' in param: self.imtls = DictArray(param['hazard_imtls']) else: self.imtls = {} self.imts = [imt_module.from_string(imt) for imt in self.imtls] self.reqv = param.get('reqv') if self.reqv is not None: self.REQUIRES_DISTANCES.add('repi') self.mon = monitor self.ctx_mon = monitor('make_contexts', measuremem=False) self.loglevels = DictArray(self.imtls) if self.imtls else {} self.shift_hypo = param.get('shift_hypo') 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) # instantiate monitors self.gmf_mon = monitor('computing mean_std', measuremem=False) self.poe_mon = monitor('get_poes', measuremem=False)
def __init__(self, trt, gsims, param=None, monitor=Monitor()): param = param or {} self.af = param.get('af', None) self.max_sites_disagg = param.get('max_sites_disagg', 10) self.split_sources = param.get('split_sources', True) self.collapse_level = param.get('collapse_level', False) self.point_rupture_bins = param.get('point_rupture_bins', 20) self.trt = trt self.gsims = gsims self.maximum_distance = (param.get('maximum_distance') or MagDepDistance({})) self.trunclevel = param.get('truncation_level') self.effect = param.get('effect') for req in self.REQUIRES: reqset = set() for gsim in gsims: reqset.update(getattr(gsim, 'REQUIRES_' + req)) setattr(self, 'REQUIRES_' + req, reqset) # self.pointsource_distance is a dict mag -> dist, possibly empty if param.get('pointsource_distance'): self.pointsource_distance = param['pointsource_distance'][trt] else: self.pointsource_distance = {} self.filter_distance = 'rrup' if 'imtls' in param: self.imtls = param['imtls'] elif 'hazard_imtls' in param: self.imtls = DictArray(param['hazard_imtls']) else: self.imtls = {} self.imts = [imt_module.from_string(imt) for imt in self.imtls] self.reqv = param.get('reqv') if self.reqv is not None: self.REQUIRES_DISTANCES.add('repi') self.mon = monitor self.ctx_mon = monitor('make_contexts', measuremem=False) self.loglevels = DictArray(self.imtls) self.shift_hypo = param.get('shift_hypo') 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) # instantiate monitors self.gmf_mon = monitor('computing mean_std', measuremem=False) self.poe_mon = monitor('get_poes', measuremem=False)
def test_two_sites(self): site1 = Site(Point(0, 0), vs30=760., z1pt0=48.0, z2pt5=0.607, vs30measured=True) site2 = Site(Point(0, 0.5), vs30=760., z1pt0=48.0, z2pt5=0.607, vs30measured=True) sitecol = SiteCollection([site1, site2]) srcfilter = SourceFilter(sitecol, MagDepDistance.new('200')) imtls = {"PGA": [.123]} for period in numpy.arange(.1, .5, .1): imtls['SA(%.2f)' % period] = [.123] assert len(imtls) == 5 # 5 periods gsim_by_trt = {'Stable Continental Crust': ExampleA2021()} hcurves = calc_hazard_curves([asource], srcfilter, DictArray(imtls), gsim_by_trt) print(hcurves)
def test_point_sources(self): sources = [ openquake.hazardlib.source.PointSource( source_id='point1', name='point1', tectonic_region_type=const.TRT.ACTIVE_SHALLOW_CRUST, mfd=openquake.hazardlib.mfd.EvenlyDiscretizedMFD( min_mag=4, bin_width=1, occurrence_rates=[5] ), nodal_plane_distribution=openquake.hazardlib.pmf.PMF([ (1, openquake.hazardlib.geo.NodalPlane(strike=0.0, dip=90.0, rake=0.0)) ]), hypocenter_distribution=openquake.hazardlib.pmf.PMF([(1, 10)]), upper_seismogenic_depth=0.0, lower_seismogenic_depth=10.0, magnitude_scaling_relationship= openquake.hazardlib.scalerel.PeerMSR(), rupture_aspect_ratio=2, temporal_occurrence_model=PoissonTOM(1.), rupture_mesh_spacing=1.0, location=Point(10, 10) ), openquake.hazardlib.source.PointSource( source_id='point2', name='point2', tectonic_region_type=const.TRT.ACTIVE_SHALLOW_CRUST, mfd=openquake.hazardlib.mfd.EvenlyDiscretizedMFD( min_mag=4, bin_width=2, occurrence_rates=[5, 6, 7] ), nodal_plane_distribution=openquake.hazardlib.pmf.PMF([ (1, openquake.hazardlib.geo.NodalPlane(strike=0, dip=90, rake=0.0)), ]), hypocenter_distribution=openquake.hazardlib.pmf.PMF([(1, 10)]), upper_seismogenic_depth=0.0, lower_seismogenic_depth=10.0, magnitude_scaling_relationship= openquake.hazardlib.scalerel.PeerMSR(), rupture_aspect_ratio=2, temporal_occurrence_model=PoissonTOM(1.), rupture_mesh_spacing=1.0, location=Point(10, 11) ), ] sites = [openquake.hazardlib.site.Site(Point(11, 10), 1, 2, 3), openquake.hazardlib.site.Site(Point(10, 16), 2, 2, 3), openquake.hazardlib.site.Site(Point(10, 10.6, 1), 3, 2, 3), openquake.hazardlib.site.Site(Point(10, 10.7, -1), 4, 2, 3)] sitecol = openquake.hazardlib.site.SiteCollection(sites) gsims = {const.TRT.ACTIVE_SHALLOW_CRUST: SadighEtAl1997()} truncation_level = 1 imts = {'PGA': [0.1, 0.5, 1.3]} s_filter = SourceFilter(sitecol, MagDepDistance.new('30')) result = calc_hazard_curves( sources, s_filter, imts, gsims, truncation_level)['PGA'] # there are two sources and four sites. The first source contains only # one rupture, the second source contains three ruptures. # # the first source has 'maximum projection radius' of 0.707 km # the second source has 'maximum projection radius' of 500.0 km # # the epicentral distances for source 1 are: [ 109.50558394, # 667.16955987, 66.71695599, 77.83644865] # the epicentral distances for source 2 are: [ 155.9412148 , # 555.97463322, 44.47797066, 33.35847799] # # Considering that the source site filtering distance is set to 30 km, # for source 1, all sites have epicentral distance larger than # 0.707 + 30 km. This means that source 1 ('point 1') is not considered # in the calculation because too far. # for source 2, the 1st, 3rd and 4th sites have epicentral distances # smaller than 500.0 + 30 km. This means that source 2 ('point 2') is # considered in the calculation for site 1, 3, and 4. # # JB distances for rupture 1 in source 2 are: [ 155.43860273, # 555.26752644, 43.77086388, 32.65137121] # JB distances for rupture 2 in source 2 are: [ 150.98882575, # 548.90356541, 37.40690285, 26.28741018] # JB distances for rupture 3 in source 2 are: [ 109.50545819, # 55.97463322, 0. , 0. ] # # Considering that the rupture site filtering distance is set to 30 km, # rupture 1 (magnitude 4) is not considered because too far, rupture 2 # (magnitude 6) affect only the 4th site, rupture 3 (magnitude 8) # affect the 3rd and 4th sites. self.assertEqual(result.shape, (4, 3)) # 4 sites, 3 levels numpy.testing.assert_allclose(result[0], 0) # no contrib to site 1 numpy.testing.assert_allclose(result[1], 0) # no contrib to site 2 # test that depths are kept after filtering (sites 3 and 4 remain) s_filter = SourceFilter(sitecol, MagDepDistance.new('100')) numpy.testing.assert_array_equal( s_filter.get_close_sites(sources[0]).depths, ([1, -1]))
def test_bounding_box(self): maxdist = MagDepDistance.new('400') aae(maxdist('ANY_TRT'), 400) bb = maxdist.get_bounding_box(0, 10, 'ANY_TRT') aae(bb, [-3.6527738, 6.40272, 3.6527738, 13.59728])
from openquake.hazardlib import read_input, valid from openquake.hazardlib.cross_correlation import BakerJayaram2008 from openquake.hazardlib.calc.filters import MagDepDistance OVERWRITE_EXPECTED = False CWD = os.path.dirname(__file__) SOURCES_XML = os.path.join(CWD, 'data', 'sm01.xml') GSIM_XML = os.path.join(CWD, 'data', 'lt02.xml') PARAM = dict(source_model_file=SOURCES_XML, gsim_logic_tree_file=GSIM_XML, sites=[(0, -0.8)], reference_vs30_value=600, reference_depth_to_2pt5km_per_sec=5, reference_depth_to_1pt0km_per_sec=100, maximum_distance=MagDepDistance.new('200'), rupture_mesh_spacing=5., width_of_mfd_bin=1., investigation_time=1, truncation_level=3, cross_correl=BakerJayaram2008(), imtls={"SA(0.05)": valid.logscale(0.005, 2.13, 45), "SA(0.075)": valid.logscale(0.005, 2.13, 45), "SA(0.1)": valid.logscale(0.005, 2.13, 45), "SA(0.15)": valid.logscale(0.005, 2.13, 45), "SA(0.2)": valid.logscale(0.005, 2.13, 45), "SA(0.25)": valid.logscale(0.005, 2.13, 45), "SA(0.3)": valid.logscale(0.005, 2.13, 45), "SA(0.5)": valid.logscale(0.005, 2.13, 45), "SA(0.75)": valid.logscale(0.005, 2.13, 45), "SA(1.0)": valid.logscale(0.005, 2.13, 45),
def main(params): # example with 2x2=4 realizations with weights .36, .24, .24, .16 inp = read_input(params) print(inp) print(inp.gsim_lt.get_rlzs_by_gsim_trt()) acc = AccumDict(accum=[]) ebrs = sample_ebruptures(inp.groups, inp.cmakerdict) ne = sum(ebr.n_occ for ebr in ebrs) print('There are %d ruptures and %d events' % (len(ebrs), ne)) df = get_ebr_df(ebrs, inp.cmakerdict) print(df.groupby('rlz').count()) # there are 8, 9, 11, 8 events per rlz for ebr in ebrs: cmaker = inp.cmakerdict[ebr.rupture.tectonic_region_type] gmf_dict, _ = GmfComputer(ebr, inp.sitecol, cmaker).compute_all() acc += gmf_dict print(pandas.DataFrame(acc)) if __name__ == '__main__': params = dict(maximum_distance=MagDepDistance.new('200'), imtls={'PGA': [0]}, source_model_file="source_model.xml", area_source_discretization=10, ses_seed=24, ses_per_logic_tree_path=20, investigation_time=1, site_model_file="site_model.csv", gsim_logic_tree_file="gmpe_logic_tree.xml") main(params)