def test_fomosto_vs_psgrn_pscmp_shear(self): origin = gf.Location( lat=10., lon=-15.) # test GF store TestRF = dict( lat=origin.lat, lon=origin.lon, depth=2. * km, width=0.2 * km, length=7. * km, rake=uniform(-90., 90.), dip=uniform(0., 90.), strike=uniform(0., 360.), slip=uniform(1., 5.)) source_plain = gf.RectangularSource(**TestRF) source_with_time = gf.RectangularSource(time=123.5, **TestRF) gf_sources = [source_plain, source_with_time] pscmp_sources = [psgrn_pscmp.PsCmpRectangularSource(**TestRF)] self.fomosto_vs_psgrn_pscmp( pscmp_sources=pscmp_sources, gf_sources=gf_sources, atol=5*mm)
def test_discretize_rect_source_stf(self): store = self.dummy_homogeneous_store() target = gf.Target(interpolation='nearest_neighbor') stf = gf.HalfSinusoidSTF(duration=3.) for source in [ gf.RectangularSource(depth=10 * km, slip=0.5, width=5 * km, length=5 * km, stf=stf, stf_mode='pre'), gf.RectangularSource(depth=10 * km, magnitude=5.0, width=5 * km, length=5 * km, decimation_factor=2, stf=stf, stf_mode='pre') ]: dsource = source.discretize_basesource(store, target) amplitudes = source._discretize(store, target)[2] assert amplitudes[0] != amplitudes[1] m1 = source.get_moment(store, target) m2 = dsource.centroid().pyrocko_moment_tensor().scalar_moment() assert abs(m1 - m2) < abs(m1 + m2) * 1e-6
def test_process_static(self): src_length = 5 * km src_width = 2 * km ntargets = 1600 interp = ['nearest_neighbor', 'multilinear'] interpolation = interp[0] source = gf.RectangularSource(lat=0., lon=0., north_shift=0., east_shift=0., depth=6.5 * km, width=src_width, length=src_length, dip=90., rake=90., strike=90., slip=1.) phi = num.zeros(ntargets) # Horizontal from E theta = num.ones(ntargets) * num.pi / 2 # Vertical from vertical phi.fill(num.deg2rad(192.)) theta.fill(num.deg2rad(90. - 23.)) sattarget = gf.SatelliteTarget( north_shifts=(random.rand(ntargets) - .5) * 25. * km, east_shifts=(random.rand(ntargets) - .5) * 25. * km, tsnapshot=20, interpolation=interpolation, phi=phi, theta=theta) static_target = gf.StaticTarget( north_shifts=(random.rand(ntargets) - .5) * 25. * km, east_shifts=(random.rand(ntargets) - .5) * 25. * km, tsnapshot=20, interpolation=interpolation) engine = gf.LocalEngine(store_dirs=[self.get_pscmp_store_dir()]) def process_target(nprocs): @benchmark.labeled('process-nearest_neighbor-np%d' % nprocs) def process_nearest_neighbor(): sattarget.interpolation = 'nearest_neighbor' return engine.process(source, sattarget, nprocs=nprocs) @benchmark.labeled('process-multilinear-np%d' % nprocs) def process_multilinear(): sattarget.interpolation = 'multilinear' return engine.process(source, sattarget, nprocs=nprocs) return process_nearest_neighbor(), process_multilinear() def process_multiple_targets(): return engine.process(source, [sattarget, static_target]) for np in [1, 2, 4]: nn, ml = process_target(nprocs=np) process_multiple_targets()
def test_gnss_target(self): src_length = 5 * km src_width = 2 * km nstations = 100 interp = ['nearest_neighbor', 'multilinear'] interpolation = interp[0] source = gf.RectangularSource(lat=0., lon=0., north_shift=0., east_shift=0., depth=6.5 * km, width=src_width, length=src_length, dip=90., rake=90., strike=90., slip=1.) gnss_target = gf.GNSSCampaignTarget( lats=(random.uniform(-.2, .2, nstations)), lons=(random.uniform(-.2, .2, nstations)), interpolation=interpolation) engine = gf.LocalEngine(store_dirs=[self.get_pscmp_store_dir()]) res = engine.process(source, gnss_target, nprocs=0) statics = res.static_results() for static in statics: assert len(static.campaign.stations) == nstations
def test_fomosto_vs_psgrn_pscmp_tensile_shear(self): origin = gf.Location(lat=10., lon=-15.) # test GF store TestRF = dict(lat=origin.lat, lon=origin.lon, depth=3. * km, width=2. * km, length=5. * km, rake=uniform(-90., 90.), dip=uniform(0., 90.), strike=uniform(0., 360.)) opening_fraction = 0.4 slip = uniform(1., 5.) opening = slip * opening_fraction pscmp_slip = slip - opening source_plain = gf.RectangularSource(**TestRF) source_plain.update(slip=slip, opening_fraction=opening_fraction) source_with_time = deepcopy(source_plain) source_with_time.update(time=123.5) gf_sources = [source_plain, source_with_time] pscmp_sources = [ psgrn_pscmp.PsCmpRectangularSource(opening=opening, slip=pscmp_slip, **TestRF) ] self.fomosto_vs_psgrn_pscmp(pscmp_sources=pscmp_sources, gf_sources=gf_sources, atol=7 * mm)
def test_discretize_rect_source(self): store = self.dummy_homogeneous_store() target = gf.Target(interpolation='nearest_neighbor') for source in [ gf.RectangularSource(depth=10 * km, slip=0.5, width=5 * km, length=5 * km), gf.RectangularSource(depth=10 * km, magnitude=5.0, width=5 * km, length=5 * km) ]: dsource = source.discretize_basesource(store, target) m1 = source.get_moment(store, target) m2 = dsource.centroid().pyrocko_moment_tensor().scalar_moment() assert abs(m1 - m2) < abs(m1 + m2) * 1e-6
def test_rect_source(self): store = self.dummy_homogeneous_store() rect1 = gf.RectangularSource(depth=10 * km, magnitude=5.0, width=5 * km, length=5 * km) rect2 = gf.RectangularSource( depth=10 * km, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * store.config.earthmodel_1d.material(10 * km).shear_modulus()), width=5 * km, length=5 * km) self.assertAlmostEqual( rect1.get_magnitude(), rect2.get_magnitude(store, gf.Target(interpolation='nearest_neighbor')))
def patches(self, nl, nw, datatype): """ Cut source into n by m sub-faults and return n times m :class:`RectangularSource` Objects. Discretization starts at shallow depth going row-wise deeper. REQUIRES: self.depth to be TOP DEPTH!!! Parameters ---------- nl : int number of patches in length direction (strike) nw : int number of patches in width direction (dip) datatype : string 'geodetic' or 'seismic' determines the source to be returned Returns ------- :class:`pscmp.PsCmpRectangularSource` or :class:`pyrocko.gf.seismosizer.RectangularSource` depending on datatype. Depth is being updated from top_depth to center_depth. """ length = self.length / float(nl) width = self.width / float(nw) patches = [] for j in range(nw): for i in range(nl): sub_center = self.center(self.width) + \ self.strikevector * ((i + 0.5 - 0.5 * nl) * length) + \ self.dipvector * ((j + 0.5 - 0.5 * nw) * width) patch = gf.RectangularSource(lat=float(self.lat), lon=float(self.lon), east_shift=float(sub_center[0]), north_shift=float(sub_center[1]), depth=float(sub_center[2]), strike=self.strike, dip=self.dip, rake=self.rake, length=length, width=width, stf=self.stf, time=self.time, slip=self.slip, anchor='center') patches.append(patch) return patches
def test_outline(self): s = gf.MTSource(east_shift=5. * km, north_shift=-3. * km, depth=7. * km) outline = s.outline() numeq(outline, num.array([[-3000., 5000., 7000.]]), 1e-8) rs = gf.RectangularSource(length=2 * km, width=2 * km) outline = rs.outline() numeq( outline, num.array([[-1.e3, 0.0, 0.0], [1.e3, 0.0, 0.0], [1.e3, 0.0, 2.e3], [-1.e3, 0.0, 2.e3], [-1.e3, 0.0, 0.0]]), 1e-8)
def get_source(self, ievent): rstate = self.get_rstate(ievent) time = rstate.uniform(self.time_min, self.time_max) lat, lon = self.get_latlon(ievent) depth = rstate.uniform(self.depth_min, self.depth_max) magnitude = self.draw_magnitude(rstate) moment = moment_tensor.magnitude_to_moment(magnitude) # After Mai and Beroza (2000) length = num.exp(-6.27 + 0.4*num.log(moment)) width = num.exp(-4.24 + 0.32*num.log(moment)) length = length if not self.length else self.length width = width if not self.width else self.width depth = depth if not self.depth else self.depth if self.strike is None and self.dip is None and self.rake is None: strike, rake = rstate.uniform(-180., 180., 2) dip = rstate.uniform(0., 90.) else: if None in (self.strike, self.dip, self.rake): raise ScenarioError( 'RectangularFaultGenerator: ' 'strike, dip, rake' ' must be used in combination') strike = self.strike dip = self.dip rake = self.rake source = gf.RectangularSource( time=float(time), lat=float(lat), lon=float(lon), anchor='top', depth=float(depth), length=float(length), width=float(width), strike=float(strike), dip=float(dip), rake=float(rake), magnitude=magnitude, decimation_factor=self.decimation_factor) return source
def test_static_timing(self): src_length = 5 * km src_width = 2 * km nstations = 100 day = 3600 * 24 interp = ['nearest_neighbor', 'multilinear'] interpolation = interp[0] source = gf.RectangularSource( lat=0., lon=0., north_shift=0., east_shift=0., depth=6.5*km, width=src_width, length=src_length, dip=90., rake=90., strike=90., slip=1., time=time.time()-day) source = gf.DCSource( lat=0., lon=0., north_shift=0., east_shift=0., depth=6.5*km, dip=90., rake=90., strike=90., time=time.time()-day) lats = random.uniform(-.2, .2, nstations) lons = random.uniform(-.2, .2, nstations) target_1 = gf.StaticTarget( lats=lats, lons=lons, interpolation=interpolation, tsnapshot=time.time() + day) target_2 = gf.StaticTarget( lats=lats, lons=lons, interpolation=interpolation, tsnapshot=time.time()) engine = gf.LocalEngine(store_dirs=[self.get_store_dir('pscmp')]) res = engine.process(source, [target_1, target_2], nprocs=0)\ statics_1, statics_2 = res.static_results() num.testing.assert_equal( statics_1.result['displacement.n'], statics_2.result['displacement.n'])
def test_rectangular_source(self): # WIP nsrc = 5 rect_sources = [] for n in range(nsrc): src = gf.RectangularSource(lat=0., lon=0., anchor='bottom', north_shift=5000., east_shift=9000., depth=4. * km, width=2. * km, length=8. * km, dip=0., rake=0., strike=(180. / nsrc + 1) * n, slip=1.) rect_sources.append(src)
def test_rect_source_anchors(self): sources = {} for anchor in ['top', 'center', 'bottom']: sources[anchor] = gf.RectangularSource(width=5 * km, length=20 * km, anchor=anchor, dip=120., strike=45., east_shift=0 * km, north_shift=0 * km) def plot_sources(sources): import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca() colors = ['b', 'r', 'y'] for i, src in enumerate(sources.itervalues()): n, e = src.outline(cs='xy').T ax.fill(e, n, color=colors[i], alpha=0.5) plt.show()
def test_sum_static(self): from pyrocko.gf import store_ext benchmark.show_factor = True store = gf.Store(self.get_qseis_store_dir()) store.open() src_length = 2 * km src_width = 5 * km ntargets = 1600 interp = ['nearest_neighbor', 'multilinear'] interpolation = interp[0] source = gf.RectangularSource(lat=0., lon=0., depth=5 * km, north_shift=0., east_shift=0., width=src_width, length=src_length) static_target = gf.StaticTarget( north_shifts=5 * km + random.rand(ntargets) * 5 * km, east_shifts=0 * km + random.rand(ntargets) * 5 * km) targets = static_target.get_targets() dsource = source.discretize_basesource(store, targets[0]) source_coords_arr = dsource.coords5() mts_arr = dsource.m6s receiver_coords_arr = num.empty((len(targets), 5)) for itarget, target in enumerate(targets): receiver = target.receiver(store) receiver_coords_arr[itarget, :] = \ [receiver.lat, receiver.lon, receiver.north_shift, receiver.east_shift, receiver.depth] def sum_target(cstore, irecords, delays_t, delays_s, weights, pos, nthreads): @benchmark.labeled('sum-timeseries-np%d' % nthreads) def sum_timeseries(): nsummands = weights.size // ntargets res = num.zeros(ntargets) for t in range(ntargets): sl = slice(t * nsummands, (t + 1) * nsummands) r = store_ext.store_sum(cstore, irecords[sl], delays_t[sl], weights[sl], pos, 1) res[t] = r[0] return res @benchmark.labeled('sum-static-np%d' % nthreads) def sum_static(): return store_ext.store_sum_static(cstore, irecords, delays_s, weights, pos, ntargets, nthreads) return sum_timeseries(), sum_static() args = (store.cstore, source_coords_arr, mts_arr, receiver_coords_arr, 'elastic10', interpolation, 0) benchmark.clear() for nthreads in [1, 2, 4]: for (weights, irecords) in store_ext.make_sum_params(*args): delays_t = num.zeros_like(weights, dtype=num.float64) delays_s = dsource.times.astype(num.float64) pos = 6 t, s = sum_target(store.cstore, irecords, delays_t, delays_s, weights, pos, nthreads) # print benchmark.__str__(header=False) num.testing.assert_equal(t, s) benchmark.clear()
if not os.path.exists(store_id): gf.ws.download_gf_store(site='kinherd', store_id=store_id) # Setup the modelling LocalEngine # *store_superdirs* is a list of directories where to look for GF Stores. engine = gf.LocalEngine(store_superdirs=['.']) rect_source = gf.RectangularSource( # Geographical position [deg] lat=0., lon=0., # Relative cartesian offsets [m] north_shift=10 * km, east_shift=10 * km, depth=6.5 * km, # Dimensions of the fault [m] width=5 * km, length=8 * km, strike=104., dip=90., rake=0., # Slip in [m] slip=1., anchor='top') # Define the scene's frame frame = FrameConfig( # Lower left geographical reference [deg] llLat=0., llLon=0., # Pixel spacing [m] or [degrees]
def plot_gf_distance_sampling(self): origin = gf.Location(lat=10., lon=-15.) # test GF store TestRF = dict(lat=origin.lat, lon=origin.lon, depth=2. * km, width=1. * km, length=3. * km, rake=uniform(-90., 90.), dip=uniform(0., 90.), strike=uniform(0., 360.), slip=uniform(1., 5.)) source_plain = gf.RectangularSource(**TestRF) N, E = num.meshgrid(num.linspace(-20. * km, 20. * km, nnorth), num.linspace(-20. * km, 20. * km, neast)) starget_ml = gf.StaticTarget(lats=num.full(N.size, origin.lat), lons=num.full(N.size, origin.lon), north_shifts=N.flatten(), east_shifts=E.flatten(), interpolation='multilinear') # Getting reference gf_distance_sampling = 10. def get_displacements(source): store_dir, c = self.get_pscmp_store_info() engine = gf.LocalEngine(store_dirs=[store_dir]) r = engine.process(source, starget_ml) ref_result = r.static_results()[0] compare_results = {} for gf_dist_spacing in ( 0.25, .5, 1., 2., 4., 8., 10., ): extra_config = psgrn_pscmp.PsGrnPsCmpConfig() extra_config.psgrn_config.gf_distance_spacing = gf_dist_spacing extra_config.psgrn_config.gf_depth_spacing = .5 store_dir, c = self._create_psgrn_pscmp_store(extra_config) engine = gf.LocalEngine(store_dirs=[store_dir]) t0 = time() r = engine.process(source, starget_ml) logger.info('pyrocko stacking time %f s' % (time() - t0)) static_result = r.static_results()[0] compare_results[gf_dist_spacing] = static_result num.testing.assert_allclose( ref_result.result['displacement.n'], static_result.result['displacement.n'], atol=1 * mm) num.testing.assert_allclose( ref_result.result['displacement.e'], static_result.result['displacement.e'], atol=1 * mm) num.testing.assert_allclose( ref_result.result['displacement.d'], static_result.result['displacement.d'], atol=1 * mm) return ref_result, compare_results # ref_result, compare_results = get_displacements(source_plain) # self.plot_displacement_differences(ref_result, compare_results) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca() for depth in (2., 4., 8., 12.): source_plain.depth = depth * km ref_result, compare_results = get_displacements(source_plain) self.plot_differences(ax, ref_result, compare_results, label='Source Depth %.2f km' % depth) ax.legend() if show_plot: plt.show()
dt = tmax / nsteps satellite_target = gf.SatelliteTarget(east_shifts=east_shifts, north_shifts=north_shifts, phi=num.full(npx, d2r * (90. - look)), theta=num.full(npx, d2r * (-90. - heading)), interpolation='nearest_neighbor') creep_source = gf.RectangularSource(lat=0., lon=0., north_shift=3 * km, east_shift=0., depth=25 * km, width=15 * km, length=80 * km, strike=100., dip=90., rake=0., slip=0.08, anchor='top', decimation_factor=4) coseismic_sources = gf.RectangularSource(lat=0., lon=0., north_shift=3 * km, east_shift=0., depth=15 * km, width=10 * km, length=60 * km, strike=100.,
# We define a grid for the targets. left, right, bottom, top = -10 * km, 10 * km, -10 * km, 10 * km ntargets = 1000 # Ignite the LocalEngine and point it to fomosto stores stored on a # USB stick, for this example we use a static store with id 'static_store' engine = gf.LocalEngine(store_superdirs=['.']) store_id = 'gf_abruzzo_nearfield_vmod_Ameri' # We define two finite sources # The first one is a purely vertical strike-slip fault strikeslip = gf.RectangularSource(north_shift=0., east_shift=0., depth=6 * km, width=4 * km, length=10 * km, dip=90., rake=0., strike=90., slip=1.) # The second one is a ramp connecting to the root of the strike-slip fault # ramp north shift (n) and width (w) depend on its dip angle and on # the strike slip fault width n, w = 2 / num.tan(num.deg2rad(45.)), 2. * (2. / (num.sin(num.deg2rad(45.)))) thrust = gf.RectangularSource(north_shift=n * km, east_shift=0., depth=6 * km, width=w * km, length=10 * km, dip=45.,
def test_rect_source(self): store = self.dummy_homogeneous_store() depth = 10 * km # shear rect1 = gf.RectangularSource(depth=10 * km, magnitude=5.0, width=5 * km, length=5 * km) rect2 = gf.RectangularSource( depth=depth, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * store.config.earthmodel_1d.material(depth).shear_modulus()), width=5 * km, length=5 * km) self.assertAlmostEqual( rect1.get_magnitude(), rect2.get_magnitude(store, gf.Target(interpolation='nearest_neighbor'))) # tensile rect3 = gf.RectangularSource(depth=depth, magnitude=5.0, width=5 * km, length=5 * km, opening_fraction=1.) rect4 = gf.RectangularSource( depth=depth, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * store.config.earthmodel_1d.material(depth).bulk()), width=5 * km, length=5 * km, opening_fraction=1.) self.assertAlmostEqual( rect3.get_magnitude(), rect4.get_magnitude(store, gf.Target(interpolation='nearest_neighbor'))) # mixed of = -0.4 rect5 = gf.RectangularSource(depth=depth, magnitude=5.0, width=5 * km, length=5 * km, opening_fraction=of) rect6 = gf.RectangularSource( depth=depth, slip=pmt.magnitude_to_moment(5.0) / (5 * km * 5 * km * (store.config.earthmodel_1d.material(depth).bulk() * abs(of) + store.config.earthmodel_1d.material(depth).shear_modulus() * (1 - abs(of)))), width=5 * km, length=5 * km, opening_fraction=of) self.assertAlmostEqual( rect5.get_magnitude(), rect6.get_magnitude(store, gf.Target(interpolation='nearest_neighbor')))
def test_against_kiwi(self): engine = gf.get_engine() store_id = 'chile_70km_crust' try: store = engine.get_store(store_id) except gf.NoSuchStore: logger.warn('GF Store %s not available - skipping test' % store_id) return base_source = gf.RectangularSource( depth=15*km, strike=0., dip=90., rake=0., magnitude=4.5, nucleation_x=-1., length=10*km, width=0*km, stf=gf.BoxcarSTF(duration=1.0)) base_event = base_source.pyrocko_event() channels = 'NEZ' nstations = 10 stations = [] targets = [] for istation in xrange(nstations): dist = rand(40.*km, 900*km) azi = rand(-180., 180.) north_shift = dist * math.cos(azi*d2r) east_shift = dist * math.sin(azi*d2r) lat, lon = od.ne_to_latlon(0., 0., north_shift, east_shift) sta = 'S%02i' % istation station = model.Station( '', sta, '', lat=lat, lon=lon) station.set_channels_by_name('N', 'E', 'Z') stations.append(station) for cha in channels: target = gf.Target( codes=station.nsl() + (cha,), lat=lat, lon=lon, quantity='displacement', interpolation='multilinear', optimization='enable', store_id=store_id) targets.append(target) from tunguska import glue nsources = 10 # nprocs_max = multiprocessing.cpu_count() nprocs = 1 try: seis = glue.start_seismosizer( gfdb_path=op.join(store.store_dir, 'db'), event=base_event, stations=stations, hosts=['localhost']*nprocs, balance_method='123321', effective_dt=0.5, verbose=False) ksource = to_kiwi_source(base_source) seis.set_source(ksource) recs = seis.get_receivers_snapshot(('syn',), (), 'plain') trs = [] for rec in recs: for tr in rec.get_traces(): tr.set_codes(channel=transchan[tr.channel]) trs.append(tr) trs2 = engine.process(base_source, targets).pyrocko_traces() trace.snuffle(trs + trs2) seis.set_synthetic_reference() for sourcetype in ['point', 'rect']: sources = [] for isource in xrange(nsources): m = pmt.MomentTensor.random_dc() strike, dip, rake = map(float, m.both_strike_dip_rake()[0]) if sourcetype == 'point': source = gf.RectangularSource( north_shift=rand(-20.*km, 20*km), east_shift=rand(-20.*km, 20*km), depth=rand(10*km, 20*km), nucleation_x=0.0, nucleation_y=0.0, strike=strike, dip=dip, rake=rake, magnitude=rand(4.0, 5.0), stf=gf.BoxcarSTF(duration=1.0)) elif sourcetype == 'rect': source = gf.RectangularSource( north_shift=rand(-20.*km, 20*km), east_shift=rand(-20.*km, 20*km), depth=rand(10*km, 20*km), length=10*km, width=5*km, nucleation_x=-1., nucleation_y=0, strike=strike, dip=dip, rake=rake, magnitude=rand(4.0, 5.0), stf=gf.BoxcarSTF(duration=1.0)) else: assert False sources.append(source) for temperature in ['cold', 'hot']: t0 = time.time() resp = engine.process(sources, targets, nprocs=nprocs) t1 = time.time() if temperature == 'hot': dur_pyrocko = t1 - t0 del resp ksources = map(to_kiwi_source, sources) for temperature in ['cold', 'hot']: t0 = time.time() seis.make_misfits_for_sources( ksources, show_progress=False) t1 = time.time() if temperature == 'hot': dur_kiwi = t1 - t0 print 'pyrocko %-5s %5.2fs %5.1fx' % ( sourcetype, dur_pyrocko, 1.0) print 'kiwi %-5s %5.2fs %5.1fx' % ( sourcetype, dur_kiwi, dur_pyrocko/dur_kiwi) finally: seis.close() del seis
def test_new_static(self): from pyrocko.gf import store_ext benchmark.show_factor = True store = gf.Store(self.get_pscmp_store_dir()) store.open() src_length = 2 * km src_width = 2 * km ntargets = 20 north_shifts, east_shifts = num.meshgrid( num.linspace(-20 * km, 20 * km, ntargets), num.linspace(-20 * km, 20 * km, ntargets)) interp = ['nearest_neighbor', 'multilinear'] interpolation = interp[1] source = gf.RectangularSource(lat=0., lon=0., depth=5 * km, north_shift=0., east_shift=0., anchor='top', width=src_width, length=src_length) static_target = gf.GNSSCampaignTarget( north_shifts=north_shifts, east_shifts=east_shifts, lats=num.zeros_like(north_shifts), lons=num.zeros_like(north_shifts)) targets = static_target.get_targets() dsource = source.discretize_basesource(store, targets[0]) mts_arr = dsource.m6s delays_s = dsource.times.astype(num.float64) pos = 1 scheme_desc = ['displacement.n', 'displacement.e', 'displacement.d'] benchmark.clear() def run(interpolation=interp[0], nthreads=1, niter=1): @benchmark.labeled(' sum_statics %d cpu (%s)' % (nthreads, interpolation)) def fwd_model_seperate(interpolation=interp[0]): args = (store.cstore, dsource.coords5(), mts_arr, static_target.coords5, 'elastic10', interpolation, nthreads) sum_params = store_ext.make_sum_params(*args) out = {} for icomp, comp in enumerate(scheme_desc): weights, irecords = sum_params[icomp] out[comp] = store_ext.store_sum_static( store.cstore, irecords, delays_s, weights, pos, ntargets**2, nthreads) return out @benchmark.labeled('calc_statics %d cpu (%s)' % (nthreads, interpolation)) def fwd_model_unified(interpolation=interp[0]): out = {} res = store_ext.store_calc_static(store.cstore, dsource.coords5(), mts_arr, dsource.times, static_target.coords5, 'elastic10', interpolation, pos, nthreads) for comp, r in zip(scheme_desc, res): out[comp] = r return out for _ in range(niter): res1 = fwd_model_seperate(interpolation) for _ in range(niter): res2 = fwd_model_unified(interpolation) for r1, r2 in zip(res1.values(), res2.values()): num.testing.assert_equal(r1, r2) for interpolation in interp: continue for nthreads in [1, 2, 4, 8, 0]: run(interpolation, nthreads) print(benchmark) benchmark.clear() run(interpolation, nthreads=0, niter=30) print(benchmark) def plot(displ): import matplotlib.pyplot as plt size = int(num.sqrt(displ.size)) fig = plt.figure() ax = fig.gca() ax.imshow(displ.reshape((size, size))) plt.show()
store_id = 'gf_abruzzo_nearfield_vmod_Ameri' if not os.path.exists(store_id): gf.ws.download_gf_store(site='kinherd', store_id=store_id) km = 1e3 dip = 88 depth = 2 patches = [] rect_source = gf.RectangularSource( # Geographical position [deg] lat=0., lon=0., # Relative cartesian offsets [m] north_shift=16*km, east_shift=8*km, depth=depth*km, # Dimensions of the fault [m] width=1*km, length=3*km, # what is width /length ratio strike=104., dip=dip, rake=-160., # Slip in [m] slip=1., anchor='top') patches.append(rect_source) rect_source2 = gf.RectangularSource( # Geographical position [deg] lat=0., lon=0., # Relative cartesian offsets [m] north_shift=16*km, east_shift=22*km, depth=depth*km, # Dimensions of the fault [m] width=1*km, length=3*km, # what is width /length ratio
def test_regional(self): engine = gf.get_engine() store_id = 'crust2_mf' try: engine.get_store(store_id) except gf.NoSuchStore: logger.warn('GF Store %s not available - skipping test' % store_id) return nsources = 10 nstations = 10 print 'cache source channels par wallclock seismograms_per_second' nprocs_max = multiprocessing.cpu_count() for sourcetype, channels in [ ['point', 'Z'], ['point', 'NEZ'], ['rect', 'Z'], ['rect', 'NEZ']]: for nprocs in [1, 2, 4, 8, 16, 32]: if nprocs > nprocs_max: continue sources = [] for isource in xrange(nsources): m = pmt.MomentTensor.random_dc() strike, dip, rake = map(float, m.both_strike_dip_rake()[0]) if sourcetype == 'point': source = gf.DCSource( north_shift=rand(-20.*km, 20*km), east_shift=rand(-20.*km, 20*km), depth=rand(10*km, 20*km), strike=strike, dip=dip, rake=rake, magnitude=rand(4.0, 5.0)) elif sourcetype == 'rect': source = gf.RectangularSource( north_shift=rand(-20.*km, 20*km), east_shift=rand(-20.*km, 20*km), depth=rand(10*km, 20*km), length=10*km, width=5*km, nucleation_x=0., nucleation_y=-1., strike=strike, dip=dip, rake=rake, magnitude=rand(4.0, 5.0)) else: assert False sources.append(source) targets = [] for istation in xrange(nstations): dist = rand(40.*km, 900*km) azi = rand(-180., 180.) north_shift = dist * math.cos(azi*d2r) east_shift = dist * math.sin(azi*d2r) for cha in channels: target = gf.Target( codes=('', 'S%04i' % istation, '', cha), north_shift=north_shift, east_shift=east_shift, quantity='displacement', interpolation='multilinear', optimization='enable', store_id=store_id) targets.append(target) ntraces = len(targets) * len(sources) for temperature in ['cold', 'hot']: t0 = time.time() resp = engine.process(sources, targets, nprocs=nprocs) # print resp.stats t1 = time.time() duration = t1 - t0 sps = ntraces / duration if temperature == 'hot': if nprocs == 1: sps_ref = sps print '%-5s %-6s %-8s %3i %9.3f %12.1f %12.1f' % ( temperature, sourcetype, channels, nprocs, t1-t0, sps, sps/sps_ref) del resp
# We want to reproduce the USGS Solution of an event, e.g. dep, strike, dip, leng, wid, rake, slip = 10.5, 90., 40., 10., 10., 90., .5 km = 1e3 # distance in kilometer, for convenienve # We compute the magnitude of the event potency = leng*km*wid*km*slip rigidity = 31.5e9 m0 = potency*rigidity mw = (2./3) * num.log10(m0) - 6.07 # We define an extended rectangular source thrust = gf.RectangularSource( north_shift=0., east_shift=0., depth=dep*km, width=wid*km, length=leng*km, dip=dip, rake=rake, strike=strike, slip=slip) # We will define a grid of targets # number in east and north directions, and total ngrid = 40 # ngrid = 90 # for better resolution # extension from origin in all directions obs_size = 20.*km ntargets = ngrid**2 # make regular line vector norths = num.linspace(-obs_size, obs_size, ngrid) easts = num.linspace(-obs_size, obs_size, ngrid)
def test_make_params_bench(store, dim, ntargets, interpolation, nthreads): source = gf.RectangularSource(lat=0., lon=0., depth=10 * km, north_shift=0.1, east_shift=0.1, width=dim, length=dim) targets = [ gf.Target(lat=random.random() * 10., lon=random.random() * 10., north_shift=0.1, east_shift=0.1) for x in xrange(ntargets) ] dsource = source.discretize_basesource(store, targets[0]) source_coords_arr = dsource.coords5() mts_arr = dsource.m6s receiver_coords_arr = num.empty((len(targets), 5)) for itarget, target in enumerate(targets): receiver = target.receiver(store) receiver_coords_arr[itarget, :] = \ [receiver.lat, receiver.lon, receiver.north_shift, receiver.east_shift, receiver.depth] ns = mts_arr.shape[0] label = '_ns%04d_nt%04d_%s_np%02d' % (ns, len(targets), interpolation, nthreads) @benchmark.labeled('c%s' % label) def make_param_c(): return store_ext.make_sum_params(store.cstore, source_coords_arr, mts_arr, receiver_coords_arr, 'elastic10', interpolation, nthreads) @benchmark.labeled('p%s' % label) def make_param_python(): weights_c = [] irecords_c = [] for itar, target in enumerate(targets): receiver = target.receiver(store) dsource = source.discretize_basesource(store, target) for i, (component, args, delays, weights) in \ enumerate(store.config.make_sum_params( dsource, receiver)): if len(weights_c) <= i: weights_c.append([]) irecords_c.append([]) if interpolation == 'nearest_neighbor': irecords = num.array(store.config.irecords(*args)) weights = num.array(weights) else: assert interpolation == 'multilinear' irecords, ip_weights =\ store.config.vicinities(*args) neach = irecords.size / args[0].size weights = num.repeat(weights, neach) * ip_weights delays = num.repeat(delays, neach) weights_c[i].append(weights) irecords_c[i].append(irecords) for c in xrange(len(weights_c)): weights_c[c] = num.concatenate([w for w in weights_c[c]]) irecords_c[c] = num.concatenate( [ir for ir in irecords_c[c]]) return zip(weights_c, irecords_c) rc = make_param_c() rp = make_param_python() logger.info(benchmark.__str__(header=False)) benchmark.clear() # Comparing the results if isinstance(store.config, gf.meta.ConfigTypeA): idim = 4 elif isinstance(store.config, gf.meta.ConfigTypeB): idim = 8 if interpolation == 'nearest_neighbor': idim = 1 nsummands_scheme = [5, 5, 3] # elastic8 nsummands_scheme = [6, 6, 4] # elastic10 for i, nsummands in enumerate(nsummands_scheme): for r in [0, 1]: r_c = rc[i][r] r_p = rp[i][r].reshape(ntargets, nsummands, ns * idim) r_p = num.transpose(r_p, axes=[0, 2, 1]) num.testing.assert_almost_equal(r_c, r_p.flatten())
def __init__(self, *args, **kwargs): SandboxSourceRectangular.__init__(self, *args, **kwargs) self.pyrocko_source = gf.RectangularSource(**self._src_args)
def test_calc_timeseries(self): from pyrocko.gf import store_ext benchmark.show_factor = True rstate = num.random.RandomState(123) def test_timeseries(store, source, dim, ntargets, interpolation, nthreads, niter=1, random_itmin=False, random_nsamples=False): source = gf.RectangularSource(lat=0., lon=0., depth=3 * km, length=dim, width=dim, anchor='top') targets = [ gf.Target(lat=rstate.uniform(), lon=rstate.uniform()) for x in range(ntargets) ] dsource = source.discretize_basesource(store, targets[0]) source_coords_arr = dsource.coords5() mts_arr = dsource.m6s receiver_coords_arr = num.empty((len(targets), 5)) for itarget, target in enumerate(targets): receiver = target.receiver(store) receiver_coords_arr[itarget, :] = \ [receiver.lat, receiver.lon, receiver.north_shift, receiver.east_shift, receiver.depth] nsources = mts_arr.shape[0] delays = num.zeros(nsources) itmin = num.zeros(ntargets, dtype=num.int32) nsamples = num.full(ntargets, -1, dtype=num.int32) if random_itmin: itmin = num.random.randint(-20, 5, size=ntargets, dtype=num.int32) if random_nsamples: nsamples = num.random.randint(10, 100, size=ntargets, dtype=num.int32) @benchmark.labeled('calc_timeseries-%s' % interpolation) def calc_timeseries(): return store_ext.store_calc_timeseries( store.cstore, source_coords_arr, mts_arr, delays, receiver_coords_arr, 'elastic10', interpolation, itmin, nsamples, nthreads) @benchmark.labeled('sum_timeseries-%s' % interpolation) def sum_timeseries(): results = [] for itarget, target in enumerate(targets): params = store_ext.make_sum_params( store.cstore, source_coords_arr, mts_arr, target.coords5[num.newaxis, :].copy(), 'elastic10', interpolation, nthreads) for weights, irecords in params: d = num.zeros(irecords.shape[0], dtype=num.float32) r = store_ext.store_sum(store.cstore, irecords, d, weights, int(itmin[itarget]), int(nsamples[itarget])) results.append(r) return results for _ in range(niter): res_calc = calc_timeseries() for _ in range(niter): res_sum = sum_timeseries() for c, s in zip(res_calc, res_sum): num.testing.assert_equal(c[0], s[0], verbose=True) for cc, cs in zip(c[1:-1], s[1:]): continue assert cc == cs store = gf.Store(self.get_pulse_store_dir()) store.open() sources = [ gf.DCSource(lat=0., lon=0., depth=1 * km, magnitude=8.), gf.RectangularSource(lat=0., lon=0., anchor='top', depth=5 * km, width=10 * km, length=20 * km) ] for source in sources: for interp in ['multilinear', 'nearest_neighbor']: for random_itmin in [True, False]: for random_nsamples in [True, False]: test_timeseries(store, source, dim=10 * km, niter=1, ntargets=20, interpolation=interp, nthreads=0, random_itmin=random_itmin, random_nsamples=random_nsamples) print(benchmark) benchmark.clear() def plot(res): import matplotlib.pyplot as plt plt.plot(res[0]) plt.show()
def test_timeseries(store, source, dim, ntargets, interpolation, nthreads, niter=1, random_itmin=False, random_nsamples=False): source = gf.RectangularSource(lat=0., lon=0., depth=3 * km, length=dim, width=dim, anchor='top') targets = [ gf.Target(lat=rstate.uniform(), lon=rstate.uniform()) for x in range(ntargets) ] dsource = source.discretize_basesource(store, targets[0]) source_coords_arr = dsource.coords5() mts_arr = dsource.m6s receiver_coords_arr = num.empty((len(targets), 5)) for itarget, target in enumerate(targets): receiver = target.receiver(store) receiver_coords_arr[itarget, :] = \ [receiver.lat, receiver.lon, receiver.north_shift, receiver.east_shift, receiver.depth] nsources = mts_arr.shape[0] delays = num.zeros(nsources) itmin = num.zeros(ntargets, dtype=num.int32) nsamples = num.full(ntargets, -1, dtype=num.int32) if random_itmin: itmin = num.random.randint(-20, 5, size=ntargets, dtype=num.int32) if random_nsamples: nsamples = num.random.randint(10, 100, size=ntargets, dtype=num.int32) @benchmark.labeled('calc_timeseries-%s' % interpolation) def calc_timeseries(): return store_ext.store_calc_timeseries( store.cstore, source_coords_arr, mts_arr, delays, receiver_coords_arr, 'elastic10', interpolation, itmin, nsamples, nthreads) @benchmark.labeled('sum_timeseries-%s' % interpolation) def sum_timeseries(): results = [] for itarget, target in enumerate(targets): params = store_ext.make_sum_params( store.cstore, source_coords_arr, mts_arr, target.coords5[num.newaxis, :].copy(), 'elastic10', interpolation, nthreads) for weights, irecords in params: d = num.zeros(irecords.shape[0], dtype=num.float32) r = store_ext.store_sum(store.cstore, irecords, d, weights, int(itmin[itarget]), int(nsamples[itarget])) results.append(r) return results for _ in range(niter): res_calc = calc_timeseries() for _ in range(niter): res_sum = sum_timeseries() for c, s in zip(res_calc, res_sum): num.testing.assert_equal(c[0], s[0], verbose=True) for cc, cs in zip(c[1:-1], s[1:]): continue assert cc == cs
def call(self): '''Main work routine of the snuffling.''' self.cleanup() # get time range visible in viewer viewer = self.get_viewer() event = viewer.get_active_event() if event: event, stations = self.get_active_event_and_stations( missing='warn') else: # event = model.Event(lat=self.lat, lon=self.lon) event = model.Event(lat=0., lon=0.) stations = [] stations = self.get_stations() s2c = {} for traces in self.chopper_selected_traces(fallback=True, mode='visible'): for tr in traces: net, sta, loc, cha = tr.nslc_id ns = net, sta if ns not in s2c: s2c[ns] = set() s2c[ns].add((loc, cha)) if not stations: stations = [] for (lat, lon) in [(5., 0.), (-5., 0.)]: s = model.Station(station='(%g, %g)' % (lat, lon), lat=lat, lon=lon) stations.append(s) viewer.add_stations(stations) for s in stations: ns = s.nsl()[:2] if ns not in s2c: s2c[ns] = set() for cha in 'NEZ': s2c[ns].add(('', cha)) source = gf.RectangularSource(time=event.time + self.time, lat=event.lat, lon=event.lon, north_shift=self.north_km * km, east_shift=self.east_km * km, depth=self.depth_km * km, magnitude=self.magnitude, strike=self.strike, dip=self.dip, rake=self.rake, length=self.length, width=self.width, nucleation_x=self.nucleation_x, velocity=self.velocity, stf=self.get_stf()) source.regularize() m = EventMarker(source.pyrocko_event()) self.add_marker(m) targets = [] if self.store_id == '<not loaded yet>': self.fail('Select a GF Store first') for station in stations: nsl = station.nsl() if nsl[:2] not in s2c: continue for loc, cha in s2c[nsl[:2]]: target = gf.Target(codes=(station.network, station.station, loc + '-syn', cha), quantity='displacement', lat=station.lat, lon=station.lon, depth=station.depth, store_id=self.store_id, optimization='enable', interpolation='nearest_neighbor') _, bazi = source.azibazi_to(target) if cha.endswith('T'): dip = 0. azi = bazi + 270. elif cha.endswith('R'): dip = 0. azi = bazi + 180. elif cha.endswith('1'): dip = 0. azi = 0. elif cha.endswith('2'): dip = 0. azi = 90. else: dip = None azi = None target.azimuth = azi target.dip = dip targets.append(target) req = gf.Request(sources=[source], targets=targets) req.regularize() try: resp = self.get_engine().process(req) except (gf.meta.OutOfBounds, gf.store_ext.StoreExtError) as e: self.fail(e) traces = resp.pyrocko_traces() if self.waveform_type.startswith('Velocity'): for tr in traces: tr.set_ydata(num.diff(tr.ydata) / tr.deltat) elif self.waveform_type.startswith('Acceleration'): for tr in traces: tr.set_ydata(num.diff(num.diff(tr.ydata)) / tr.deltat**2) if self.waveform_type.endswith('[nm]') or \ self.waveform_type.endswith('[nm/s]') or \ self.waveform_type.endswith('[nm/s^2]'): for tr in traces: tr.set_ydata(tr.ydata * 1e9) self.add_traces(traces)
homedir = '/Users/vasyurhm/Aqaba1995' datadir = homedir + '/data/' storehomedir = [homedir + '/GF/'] [stations, targets, event, data_traces] = inputf.load_seism_data(datadir) engine = gf.LocalEngine(store_superdirs=storehomedir) sources = [ gf.RectangularSource(lat=29.124977942689519, lon=34.871469702014863, width=24 * km, length=58 * km, time=817013725.5571846, depth=12 * km, strike=206.3701904106799, dip=73.0785305323845, rake=-8.135103051434966, magnitude=7.01, stf=gf.HalfSinusoidSTF(duration=3., anchor=-1.)) ] ## gf.RectangularSource( ## lat=29.0, ## lon=35.0, ## width=4 * km, ## length=5 * km, ## time=817013720.5571846, ## depth=5 * km, ## strike=180.0,