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
def create_scenario(self, interactive=True): logger.info('Creating scenario...') scenario = self.get_scenario() util.ensuredir(self.get_gf_stores_dir()) engine1 = gf.LocalEngine(use_config=True, store_superdirs=[self.get_gf_stores_dir()]) scenario.init_modelling(engine=engine1) scenario.ensure_gfstores( interactive=interactive, gf_store_superdirs_extra=[self.get_gf_stores_dir()]) self.symlink_gfstores(engine1) engine2 = gf.LocalEngine(use_config=False, store_superdirs=[self.get_gf_stores_dir()]) scenario.init_modelling(engine=engine2) data_dir = op.join(self.project_dir, self.data_dir) util.ensuredir(data_dir) scenario.dump(filename=op.join(data_dir, 'scenario.yml')) scenario.dump_data(path=data_dir) scenario.make_map(op.join(self.project_dir, 'scenario_map.pdf')) shutil.move(op.join(data_dir, 'sources.yml'), op.join(data_dir, 'scenario_sources.yml'))
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_optimization(self): store_dir = self.get_pulse_store_dir() engine = gf.LocalEngine(store_dirs=[store_dir]) sources = [ gf.RectangularExplosionSource(time=0.0025, depth=depth, moment=1.0, length=100., width=0., nucleation_x=-1) for depth in [100., 200., 300.] ] targetss = [[ gf.Target(codes=('', 'STA', opt, component), north_shift=500., east_shift=125., depth=depth, interpolation='multilinear', optimization=opt) for component in 'ZNE' for depth in [0., 5., 10] ] for opt in ('disable', 'enable')] resps = [engine.process(sources, targets) for targets in targetss] iters = [resp.iter_results() for resp in resps] for i in xrange(len(sources) * len(targetss[0])): s1, t1, tr1 = iters[0].next() s2, t2, tr2 = iters[1].next() self.assertEqual(tr1.data_len(), tr2.data_len()) self.assertEqual(tr1.tmin, tr2.tmin) self.assertTrue(numeq(tr1.ydata, tr2.ydata, 0.0001))
def test_stf_pre_post(self): store_dir = self.get_pulse_store_dir() engine = gf.LocalEngine(store_dirs=[store_dir]) store = engine.get_store('pulse') for duration in [0., 0.05, 0.1]: trs = [] for mode in ['pre', 'post']: source = gf.ExplosionSource( time=store.config.deltat * 0.5, depth=200., moment=1.0, stf=gf.BoxcarSTF(duration=duration), stf_mode=mode) target = gf.Target(codes=('', 'STA', '', 'Z'), north_shift=500., east_shift=0., store_id='pulse') xtrs = engine.process(source, target).pyrocko_traces() for tr in xtrs: tr.set_codes(location='%3.1f_%s' % (duration, mode)) trs.append(tr) tmin = max(tr.tmin for tr in trs) tmax = min(tr.tmax for tr in trs) for tr in trs: tr.chop(tmin, tmax) amax = max(num.max(num.abs(tr.ydata)) for tr in trs) perc = num.max(num.abs(trs[0].ydata - trs[1].ydata) / amax) * 100. if perc > 0.1: logger.warn('test_stf_pre_post: max difference of %.1f %%' % perc)
def test_target_source_timing(self): store_dir = self.get_pulse_store_dir() engine = gf.LocalEngine(store_dirs=[store_dir]) for stime in [0., -160000., time.time()]: source = gf.ExplosionSource( depth=200., magnitude=4., time=stime) targets = [ gf.Target( codes=('', 'STA', '', component), north_shift=500., tmin=source.time-300., tmax=source.time+300., east_shift=500.) for component in 'ZNE' ] response = engine.process(source, targets) synthetic_traces = response.pyrocko_traces() data = num.zeros(num.shape(synthetic_traces[0].ydata)) for tr in synthetic_traces: data += tr.ydata sum_data = num.sum(abs(tr.ydata)) assert sum_data > 1.0
def test_qssp_build_2020_rotational(self): qssp.init(self.tmpdir, '2020', config_params=dict(stored_quantity='rotation', source_depth_max=10e3, distance_min=500e3, distance_max=600e3)) store = gf.store.Store(self.tmpdir, 'r') store.make_ttt() qssp.build(self.tmpdir) del store engine = gf.LocalEngine(store_dirs=[self.tmpdir]) source = gf.DCSource(lat=0., lon=0., depth=10e3, magnitude=6.0) targets = [ gf.Target(quantity='rotation', codes=('', 'ROT', '', comp), lat=0., lon=0., north_shift=500e3, east_shift=100e3) for comp in 'NEZ' ] engine.process(source, targets)
def get_engine(gf_store_superdirs): engine = gf.LocalEngine(store_superdirs=gf_store_superdirs, use_config=True) logger.info('Directories to be searched for GF stores:\n%s' % '\n'.join(' ' + s for s in engine.store_superdirs)) return engine
def create_scenario(self, force=False, interactive=True, gf_store_superdirs=None, make_map=True): logger.info('Creating scenario...') scenario = self.get_scenario() self.create_project_dir(force) util.ensuredir(self.get_gf_stores_dir()) data_dir = op.join(self.project_dir, self.data_dir) util.ensuredir(data_dir) scenario.dump(filename=op.join(data_dir, 'scenario.yml')) if gf_store_superdirs is None: engine1 = gf.LocalEngine( use_config=True, store_superdirs=[self.get_gf_stores_dir()]) else: engine1 = gf.LocalEngine(use_config=False, store_superdirs=gf_store_superdirs) scenario.init_modelling(engine=engine1) scenario.ensure_gfstores(interactive=interactive) self.symlink_gfstores(engine1) engine2 = gf.LocalEngine(use_config=False, store_superdirs=[self.get_gf_stores_dir()]) scenario.init_modelling(engine=engine2) scenario.dump_data(path=data_dir) if make_map: scenario.make_map(op.join(self.project_dir, 'scenario_map.pdf')) shutil.move(op.join(data_dir, 'sources.yml'), op.join(data_dir, 'scenario_sources.yml')) markers = scenario.get_onsets() marker_path = op.join(data_dir, 'picks', 'picks.markers') if markers: util.ensuredirs(marker_path) pmarker.save_markers(markers, marker_path)
def get_engine(self): if self._engine is None: fp = self.expand_path self._engine = gf.LocalEngine( use_config=self.gf_stores_from_pyrocko_config, store_superdirs=fp(self.gf_store_superdirs), store_dirs=fp(self.gf_store_dirs)) return self._engine
def test_pulse(self): store_dir = self.get_pulse_store_dir() engine = gf.LocalEngine(store_dirs=[store_dir]) sources = [ gf.ExplosionSource( time=0.0, depth=depth, moment=moment) for moment in (1.0, 2.0, 3.0) for depth in [100., 200., 300.] ] targets = [ gf.Target( codes=('', 'STA', '', component), north_shift=500., east_shift=0.) for component in 'ZNE' ] pulse = engine.get_store_extra(None, 'pulse') store = engine.get_store('pulse') response = engine.process(sources=sources, targets=targets) for source, target, tr in response.iter_results(): t = tr.get_xdata() dist = math.sqrt((source.depth - target.depth)**2 + source.distance_to(target)**2) data = pulse.evaluate(dist, t-source.time) phi = math.atan2((source.depth - target.depth), source.distance_to(target)) * r2d azi, bazi = source.azibazi_to(target) data *= source.get_moment(store) * math.sqrt(2./3.) if tr.channel.endswith('N'): data *= math.cos(phi*d2r) * math.cos(azi*d2r) elif tr.channel.endswith('E'): data *= math.cos(phi*d2r) * math.sin(azi*d2r) elif tr.channel.endswith('Z'): data *= math.sin(phi*d2r) tr2 = tr.copy(data=False) tr2.set_ydata(data) tr2.set_codes(location='X') num.testing.assert_almost_equal(data, tr.ydata, 2)
def command_server(args): from pyrocko.gf import server def setup(parser): parser.add_option( '--port', dest='port', metavar='PORT', type='int', default=8080, help='serve on port PORT') parser.add_option( '--ip', dest='ip', metavar='IP', default='', help='serve on ip address IP') parser, options, args = cl_parse('server', args, setup=setup) engine = gf.LocalEngine(store_superdirs=args) server.run(options.ip, options.port, engine)
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_process_timeseries(self): engine = gf.LocalEngine(use_config=True) sources = [ gf.ExplosionSource( time=0.0, depth=depth, moment=moment) for moment in [2., 4., 8.] for depth in [3000., 6000., 12000.] ] targets = [ gf.Target( codes=('', 'ST%d' % i, '', component), north_shift=shift*km, east_shift=0., tmin=tmin, store_id='global_2s', tmax=None if tmin is None else tmin+40.) for component in 'ZNE' for i, shift in enumerate([100]) for tmin in [None, 5., 20.] ] response_sum = engine.process(sources=sources, targets=targets, calc_timeseries=False, nthreads=1) response_calc = engine.process(sources=sources, targets=targets, calc_timeseries=True, nthreads=1) for (source, target, tr), (source_n, target_n, tr_n) in zip( response_sum.iter_results(), response_calc.iter_results()): assert source is source_n assert target is target_n t1 = tr.get_xdata() t2 = tr_n.get_xdata() num.testing.assert_equal(t1, t2) disp1 = tr.get_ydata() disp2 = tr_n.get_ydata() num.testing.assert_equal(disp1, disp2)
def create_kite_scene_asc(store_id, dip, depth, patches, llLat=0., llLon=0.): km = 1e3 d2r = num.pi/180. engine = gf.LocalEngine(store_superdirs=['.']) # Define the scene's frame frame = FrameConfig( # Lower left geographical reference [deg] llLat=llLat, llLon=llLon, # Pixel spacing [m] or [degrees] spacing='degrees', dE=550, dN=550) # Resolution of the scene npx_east = 1400 npx_north = 1400 # 2D arrays for displacement and look vector displacement = num.empty((npx_east, npx_north)) # Look vectors # Theta is elevation angle from horizon theta = num.full_like(displacement, 56.*d2r) # Phi is azimuth towards the satellite, counter-clockwise from East phi = num.full_like(displacement, -166.*d2r) scene = Scene( displacement=displacement, phi=phi, theta=theta, frame=frame) satellite_target = gf.KiteSceneTarget( scene, store_id=store_id) sources = CombiSource(subsources=patches) result = engine.process( sources, satellite_target, # Use all available cores nthreads=0) kite_scenes = result.kite_scenes() return kite_scenes
def test_pulse_decimate(self): store_dir = self.get_pulse_store_dir() store = gf.Store(store_dir) store.make_decimated(2) engine = gf.LocalEngine(store_dirs=[store_dir]) # pulse = engine.get_store_extra(None, 'pulse') source = gf.ExplosionSource( time=0.0, depth=100., moment=1.0) targets = [ gf.Target( codes=('', 'STA', '%s' % sample_rate, component), sample_rate=sample_rate, north_shift=500., east_shift=0.) for component in 'N' for sample_rate in [None, store.config.sample_rate / 2.0] ] response = engine.process(source, targets) trs = [] for source, target, tr in response.iter_results(): tr.extend(0., 1.) if target.sample_rate is None: tr.downsample_to(2./store.config.sample_rate, snap=True) trs.append(tr) tmin = max(tr.tmin for tr in trs) tmax = min(tr.tmax for tr in trs) for tr in trs: tr.chop(tmin, tmax) num.testing.assert_almost_equal( trs[0].ydata, trs[1].ydata, 2)
def setup(self): self.set_name('Cake Phase') # self._phase_names = ('PmP ~S ~P ~P(moho)s ~P(sill-top)s' # ' ~P(sill-bottom)s Pdiff').split() self._phase_names = ('~P Pg Sg pP p P Pdiff PKP PcP PcS PKIKP pPKIKP' ' SSP PPS SPP PSP SP PS ~PS ~SP Pn s S Sn PP PPP' ' ScS Sdiff SS SSS PcP SKS SKIKS').split() for iphase, name in enumerate(self._phase_names): self.add_parameter( Switch(name, 'wantphase_%i' % iphase, iphase == 0)) model_names = cake.builtin_models() model_names = [ 'Cake builtin: %s' % model_name for model_name in model_names ] self._engine = gf.LocalEngine(use_config=True) store_ids = self._engine.get_store_ids() for store_id in store_ids: model_names.append('GF Store: %s' % store_id) self._models = model_names self.model_choice = Choice('Model', 'chosen_model', 'ak135-f-continental.m', self._models) self.add_parameter(self.model_choice) self.add_parameter(Param('Global shift', 'tshift', 0., -20., 20.)) self.add_parameter( Switch('Use station depth', 'use_station_depth', False)) self.add_trigger('Add Phase', self.add_phase_definition) self.add_trigger('Add Model', self.add_model_to_choice) self.add_trigger('Plot Model', self.plot_model) self.add_trigger('Plot Rays', self.plot_rays) self._phases = {} self._model = None
def test_pyrocko_gf_vs_qseis(self): random.seed(2017) mod = cake.LayeredModel.from_scanlines( cake.read_nd_model_str(''' 0. 5.8 3.46 2.6 1264. 600. 20. 5.8 3.46 2.6 1264. 600. 20. 6.5 3.85 2.9 1283. 600. 35. 6.5 3.85 2.9 1283. 600. mantle 35. 8.04 4.48 3.58 1449. 600. 77.5 8.045 4.49 3.5 1445. 600. 77.5 8.045 4.49 3.5 180.6 75. 120. 8.05 4.5 3.427 180. 75. 120. 8.05 4.5 3.427 182.6 76.06 165. 8.175 4.509 3.371 188.7 76.55 210. 8.301 4.518 3.324 201. 79.4 210. 8.3 4.52 3.321 336.9 133.3 410. 9.03 4.871 3.504 376.5 146.1 410. 9.36 5.08 3.929 414.1 162.7 660. 10.2 5.611 3.918 428.5 172.9 660. 10.79 5.965 4.229 1349. 549.6'''.lstrip())) store_dir = mkdtemp(prefix='gfstore') self.tempdirs.append(store_dir) qsconf = qseis.QSeisConfig() qsconf.qseis_version = '2006a' qsconf.time_region = (gf.meta.Timing('0'), gf.meta.Timing('end+100')) qsconf.cut = (gf.meta.Timing('0'), gf.meta.Timing('end+100')) qsconf.wavelet_duration_samples = 0.001 qsconf.sw_flat_earth_transform = 0 config = gf.meta.ConfigTypeA(id='qseis_test', sample_rate=0.25, receiver_depth=0. * km, source_depth_min=10 * km, source_depth_max=10 * km, source_depth_delta=1 * km, distance_min=550 * km, distance_max=560 * km, distance_delta=1 * km, modelling_code_id='qseis.2006a', earthmodel_1d=mod, tabulated_phases=[ gf.meta.TPDef( id='begin', definition='p,P,p\\,P\\'), gf.meta.TPDef(id='end', definition='2.5'), ]) config.validate() gf.store.Store.create_editables(store_dir, config=config, extra={'qseis': qsconf}) store = gf.store.Store(store_dir, 'r') store.make_ttt() store.close() try: qseis.build(store_dir, nworkers=1) except qseis.QSeisError as e: if str(e).find('could not start qseis') != -1: logger.warn('qseis not installed; ' 'skipping test_pyrocko_gf_vs_qseis') return else: raise source = gf.MTSource(lat=0., lon=0., depth=10. * km) source.m6 = tuple(random.random() * 2. - 1. for x in range(6)) azi = random.random() * 365. dist = 553. * km dnorth = dist * math.cos(azi * d2r) deast = dist * math.sin(azi * d2r) targets = [] for cha in 'rtz': target = gf.Target(quantity='displacement', codes=('', '0000', 'PG', cha), north_shift=dnorth, east_shift=deast, depth=config.receiver_depth, store_id='qseis_test') dist = source.distance_to(target) azi, bazi = source.azibazi_to(target) if cha == 'r': target.azimuth = bazi + 180. target.dip = 0. elif cha == 't': target.azimuth = bazi - 90. target.dip = 0. elif cha == 'z': target.azimuth = 0. target.dip = 90. targets.append(target) runner = qseis.QSeisRunner() conf = qseis.QSeisConfigFull() conf.qseis_version = '2006a' conf.receiver_distances = [dist / km] conf.receiver_azimuths = [azi] conf.source_depth = source.depth / km conf.time_start = 0.0 conf.time_window = 508. conf.time_reduction_velocity = 0.0 conf.nsamples = 128 conf.source_mech = qseis.QSeisSourceMechMT(mnn=source.mnn, mee=source.mee, mdd=source.mdd, mne=source.mne, mnd=source.mnd, med=source.med) conf.earthmodel_1d = mod conf.sw_flat_earth_transform = 0 runner.run(conf) trs = runner.get_traces() for tr in trs: tr.shift(-config.deltat) tr.snap(interpolate=True) tr.lowpass(4, 0.05) tr.highpass(4, 0.01) engine = gf.LocalEngine(store_dirs=[store_dir]) def process_wrap(nthreads=0): @benchmark.labeled('pyrocko.gf.process (nthreads-%d)' % nthreads) def process(nthreads): return engine.process(source, targets, nthreads=nthreads)\ .pyrocko_traces() return process(nthreads) for nthreads in range(1, cpu_count() + 1): trs2 = process_wrap(nthreads) # print benchmark for tr in trs2: tr.snap(interpolate=True) tr.lowpass(4, 0.05) tr.highpass(4, 0.01) # trace.snuffle(trs+trs2) for cha in 'rtz': t1 = g(trs, cha) t2 = g(trs2, cha) tmin = max(t1.tmin, t2.tmin) tmax = min(t1.tmax, t2.tmax) t1.chop(tmin, tmax) t2.chop(tmin, tmax) d = 2.0 * num.sum((t1.ydata - t2.ydata)**2) / \ (num.sum(t1.ydata**2) + num.sum(t2.ydata**2)) assert d < 0.05
def test_qseis_vs_ahfull(self): random.seed(23) vp = 5.8 * km vs = 3.46 * km mod = cake.LayeredModel.from_scanlines( cake.read_nd_model_str(''' 0. %(vp)g %(vs)g 2.6 1264. 600. 20. %(vp)g %(vs)g 2.6 1264. 600.'''.lstrip() % dict(vp=vp / km, vs=vs / km))) store_id_qseis = 'homogeneous_qseis' store_id_ahfull = 'homogeneous_ahfull' qsconf = qseis.QSeisConfig() qsconf.qseis_version = '2006a' textra = 5.0 qsconf.time_region = (gf.meta.Timing('{vel:%g}-%g' % (vp / km, textra)), gf.meta.Timing('{vel:%g}+%g' % (vs / km, textra))) qsconf.cut = (gf.meta.Timing('{vel:%g}-%g' % (vp / km, textra)), gf.meta.Timing('{vel:%g}+%g' % (vs / km, textra))) qsconf.relevel_with_fade_in = True qsconf.fade = (gf.meta.Timing('{vel:%g}-%g' % (vp / km, textra)), gf.meta.Timing('{vel:%g}-%g' % (vp / km, 0.)), gf.meta.Timing('{vel:%g}+%g' % (vs / km, 0.)), gf.meta.Timing('{vel:%g}+%g' % (vs / km, textra))) qsconf.wavelet_duration_samples = 0.001 qsconf.sw_flat_earth_transform = 0 qsconf.filter_surface_effects = 1 qsconf.wavenumber_sampling = 5. qsconf.aliasing_suppression_factor = 0.01 sample_rate = 10. config = gf.meta.ConfigTypeA( id=store_id_qseis, sample_rate=sample_rate, receiver_depth=0. * km, source_depth_min=1. * km, source_depth_max=19 * km, source_depth_delta=6. * km, distance_min=2. * km, distance_max=20 * km, distance_delta=2 * km, modelling_code_id='qseis.2006a', earthmodel_1d=mod, tabulated_phases=[ gf.meta.TPDef(id='begin', definition='p,P,p\\,P\\'), gf.meta.TPDef(id='end', definition='s,S,s\\,S\\'), ]) config.validate() store_dir_qseis = mkdtemp(prefix=store_id_qseis) self.tempdirs.append(store_dir_qseis) gf.store.Store.create_editables(store_dir_qseis, config=config, extra={'qseis': qsconf}) store = gf.store.Store(store_dir_qseis, 'r') store.make_ttt() store.close() try: qseis.build(store_dir_qseis, nworkers=1) except qseis.QSeisError as e: if str(e).find('could not start qseis') != -1: logger.warn('qseis not installed; ' 'skipping test_pyrocko_gf_vs_qseis') return else: raise config = gf.meta.ConfigTypeA( id=store_id_ahfull, sample_rate=sample_rate, receiver_depth=0. * km, source_depth_min=1. * km, source_depth_max=19 * km, source_depth_delta=6. * km, distance_min=2. * km, distance_max=20 * km, distance_delta=2 * km, modelling_code_id='ahfullgreen', earthmodel_1d=mod, tabulated_phases=[ gf.meta.TPDef(id='begin', definition='p,P,p\\,P\\'), gf.meta.TPDef(id='end', definition='s,S,s\\,S\\'), ]) config.validate() store_dir_ahfull = mkdtemp(prefix=store_id_qseis) self.tempdirs.append(store_dir_ahfull) gf.store.Store.create_editables(store_dir_ahfull, config=config) store = gf.store.Store(store_dir_ahfull, 'r') store.make_ttt() store.close() ahfullgreen.build(store_dir_ahfull, nworkers=1) sdepth = rand(config.source_depth_min, config.source_depth_max) sdepth = round( (sdepth - config.source_depth_min) / config.source_depth_delta) * config.source_depth_delta \ + config.source_depth_min source = gf.MTSource(lat=0., lon=0., depth=sdepth) source.m6 = tuple(rand(-1., 1.) for x in range(6)) for ii in range(5): azi = random.random() * 365. dist = rand(config.distance_min, config.distance_max) dist = round(dist / config.distance_delta) * config.distance_delta dnorth = dist * math.cos(azi * d2r) deast = dist * math.sin(azi * d2r) targets = [] for cha in 'rtz': target = gf.Target(quantity='displacement', codes=('', '0000', 'PG', cha), north_shift=dnorth, east_shift=deast, depth=config.receiver_depth, store_id=store_id_ahfull) dist = source.distance_to(target) azi, bazi = source.azibazi_to(target) if cha == 'r': target.azimuth = bazi + 180. target.dip = 0. elif cha == 't': target.azimuth = bazi - 90. target.dip = 0. elif cha == 'z': target.azimuth = 0. target.dip = 90. targets.append(target) runner = qseis.QSeisRunner() conf = qseis.QSeisConfigFull() conf.qseis_version = '2006a' conf.receiver_distances = [dist / km] conf.receiver_azimuths = [azi] conf.receiver_depth = config.receiver_depth / km conf.source_depth = source.depth / km distance_3d_max = math.sqrt(config.distance_max**2 + (config.source_depth_max - config.source_depth_min)**2) nsamples = trace.nextpow2( int( math.ceil(distance_3d_max / vs * 2.0 + 2. * textra) * config.sample_rate)) conf.time_start = -textra conf.time_window = (nsamples - 1) / config.sample_rate conf.time_reduction_velocity = 0.0 conf.nsamples = nsamples conf.source_mech = qseis.QSeisSourceMechMT(mnn=source.mnn, mee=source.mee, mdd=source.mdd, mne=source.mne, mnd=source.mnd, med=source.med) conf.earthmodel_1d = mod conf.sw_flat_earth_transform = 0 conf.filter_surface_effects = 1 conf.wavenumber_sampling = 10. conf.wavelet_duration_samples = 0.001 conf.aliasing_suppression_factor = 0.01 conf.validate() runner.run(conf) trs = runner.get_traces() for tr in trs: pass tr.lowpass(4, config.sample_rate / 8., demean=False) tr.highpass(4, config.sample_rate / 80.) engine = gf.LocalEngine( store_dirs=[store_dir_ahfull, store_dir_qseis]) trs2 = engine.process(source, targets).pyrocko_traces() for tr in trs2: tr.shift(config.deltat) tr.lowpass(4, config.sample_rate / 8., demean=False) tr.highpass(4, config.sample_rate / 80.) # trace.snuffle(trs+trs2) tmin = store.t('{vel:%g}' % (vp / km), source, target) - textra * 0.2 tmax = store.t('{vel:%g}' % (vs / km), source, target) + textra * 0.2 for tr in trs + trs2: tr.chop(tmin, tmax) denom = 0.0 for cha in 'rtz': t1 = g(trs, cha) t2 = g(trs2, cha) denom += num.sum(t1.ydata**2) + num.sum(t2.ydata**2) ds = [] for cha in 'rtz': t1 = g(trs, cha) t2 = g(trs2, cha) ds.append(2.0 * num.sum((t1.ydata - t2.ydata)**2) / denom) ds = num.array(ds) # if not num.all(ds < 0.05): # trace.snuffle(trs+trs2) assert num.all(ds < 0.05)
def test_store_dir_type(self): with self.assertRaises(TypeError): gf.LocalEngine(store_dirs='dummy')
import os.path import numpy as num import matplotlib.pyplot as plt from pyrocko import gf # Download a Greens Functions store, programmatically. 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) # Ignite the LocalEngine and point it to your fomosto store, e.g. stored on a # USB stick, which for example has the id 'Abruzzo_Ameri_static_nearfield' engine = gf.LocalEngine(store_superdirs=['.']) # 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)
import utility import numpy as num from theano import shared, function from theano.compile import ProfileStats profile = ProfileStats() km = 1000. 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.)) ]
conf.filter_surface_effects = 1 conf.wavenumber_sampling = 10. conf.wavelet_duration_samples = 0.001 conf.aliasing_suppression_factor = 0.01 conf.validate() runner.run(conf) trs = runner.get_traces() for tr in trs: pass tr.lowpass(4, config.sample_rate / 8., demean=False) tr.highpass(4, config.sample_rate / 80.) engine = gf.LocalEngine( store_dirs=[store_dir_ahfull, store_dir_qseis]) trs2 = engine.process(source, targets).pyrocko_traces() for tr in trs2: tr.shift(config.deltat) tr.lowpass(4, config.sample_rate / 8., demean=False) tr.highpass(4, config.sample_rate / 80.) # trace.snuffle(trs+trs2) tmin = store.t('{vel:%g}' % (vp / km), source, target) - textra * 0.2 tmax = store.t('{vel:%g}' % (vs / km), source, target) + textra * 0.2 for tr in trs + trs2:
def fomosto_vs_psgrn_pscmp(self, pscmp_sources, gf_sources, atol=2 * mm): def plot_components_compare(fomosto_comps, psgrn_comps): import matplotlib.pyplot as plt fig, axes = plt.subplots(4, 3) for i, (fcomp, pscomp, cname) in enumerate( zip(fomosto_comps, psgrn_comps, ['N', 'E', 'D'])): fdispl = fcomp.reshape(nnorth, neast) pdispl = pscomp.reshape(nnorth, neast) pcbound = num.max([num.abs(pdispl.min()), pdispl.max()]) # fcbound = num.max([num.abs(fdispl.min()), fdispl.max()]) axes[0, i].imshow(pdispl, cmap='seismic', vmin=-pcbound, vmax=pcbound) axes[1, i].imshow(fdispl, cmap='seismic', vmin=-pcbound, vmax=pcbound) diff = pdispl - fdispl rdiff = pdispl / fdispl axes[2, i].imshow(diff, cmap='seismic') axes[3, i].imshow(rdiff, cmap='seismic') axes[0, i].set_title('PSCMP %s' % cname) axes[1, i].set_title('Fomosto %s' % cname) axes[2, i].set_title('abs diff min max %f, %f' % (diff.min(), diff.max())) axes[3, i].set_title('rel diff min max %f, %f' % (rdiff.min(), rdiff.max())) plt.show() store_dir, c = self.get_pscmp_store_info() origin = gf.Location(lat=10., lon=-15.) N, E = num.meshgrid(num.linspace(-20. * km, 20. * km, nnorth), num.linspace(-20. * km, 20. * km, neast)) # direct pscmp output lats, lons = ortd.ne_to_latlon(origin.lat, origin.lon, N.flatten(), E.flatten()) cc = c.pscmp_config cc.observation = psgrn_pscmp.PsCmpScatter(lats=lats, lons=lons) cc.rectangular_source_patches = pscmp_sources cc.snapshots = psgrn_pscmp.PsCmpSnapshots(tmin=0., tmax=1., deltatdays=1.) ccf = psgrn_pscmp.PsCmpConfigFull(**cc.items()) ccf.psgrn_outdir = os.path.join(store_dir, c.gf_outdir) + '/' t2 = time() runner = psgrn_pscmp.PsCmpRunner(keep_tmp=False) runner.run(ccf) ps2du = runner.get_results(component='displ')[0] logger.info('pscmp stacking time %f s' % (time() - t2)) un_pscmp = ps2du[:, 0] ue_pscmp = ps2du[:, 1] ud_pscmp = ps2du[:, 2] # test against engine starget_nn = 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='nearest_neighbor') 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') engine = gf.LocalEngine(store_dirs=[store_dir]) for source in gf_sources: t0 = time() r = engine.process(source, [starget_nn, starget_ml]) logger.info('pyrocko stacking time %f' % (time() - t0)) for i, static_result in enumerate(r.static_results()): un_fomosto = static_result.result['displacement.n'] ue_fomosto = static_result.result['displacement.e'] ud_fomosto = static_result.result['displacement.d'] if show_plot: fomosto_comps = [un_fomosto, ue_fomosto, ud_fomosto] psgrn_comps = [un_pscmp, ue_pscmp, ud_pscmp] plot_components_compare(fomosto_comps, psgrn_comps) num.testing.assert_allclose(un_fomosto, un_pscmp, atol=atol) num.testing.assert_allclose(ue_fomosto, ue_pscmp, atol=atol) num.testing.assert_allclose(ud_fomosto, ud_pscmp, atol=atol)
# listen(backlog) # Listen for connections made to the socket. The backlog argument # specifies the maximum number of queued connections and should # be at least 1; the maximum value is system-dependent (usually # 5). self.listen(5) def handle_accept(self): try: conn, addr = self.accept() except socket.error: self.log_info('warning: server accept() threw an exception', 'warning') return except TypeError: self.log_info('warning: server accept() threw EWOULDBLOCK', 'warning') return self.handler(conn, addr, self) def run(ip, port, engine): s = Server(ip, port, SeismosizerHandler, engine) asyncore.loop() if __name__ == '__main__': engine = gf.LocalEngine(store_superdirs=sys.argv[1:]) run_server('', 8080, engine)
import numpy as num import shutil from tempfile import mkdtemp from pyrocko import guts from pyrocko import gf, util, cake, ahfullgreen, trace from pyrocko.fomosto import ahfullgreen as fomosto_ahfullgreen from .common import Benchmark assert_ae = num.testing.assert_almost_equal logger = logging.getLogger('pyrocko.test.test_gf') benchmark = Benchmark() local_stores = gf.LocalEngine(use_config=True).get_store_ids() r2d = 180. / math.pi d2r = 1.0 / r2d km = 1000. def numeq(a, b, eps): return (num.all( num.asarray(a).shape == num.asarray(b).shape and num.abs(num.asarray(a) - num.asarray(b)) < eps)) def _make_traces_homogeneous(dsource, receiver, material, deltat, net, sta, loc):
def panel_visibility_changed(self, bool): if bool: self._engine = gf.LocalEngine(use_config=True) store_ids = self._engine.get_store_ids() self._models.extend(store_ids) self.update_model_choices()
def __init__(self, *args): SourceProcessor.__init__(self, *args) self.engine = gf.LocalEngine()
def get_engine(self): if not self._engine: self._engine = gf.LocalEngine(use_config=True) return self._engine