def test_regional_models(self): """ Tests small regional models as this used to not work. Note: It looks like too much work to get a 1-layer model working. The problem is first in finding the moho, and second in coarsely- sampling slowness. Also, why bother. """ model_names = ["2_layer_model", "5_layer_model"] expected_results = [ [("p", 18.143), ("Pn", 19.202), ("PcP", 19.884), ("sP", 22.054), ("ScP", 23.029), ("PcS", 26.410), ("s", 31.509), ("Sn", 33.395), ("ScS", 34.533)], [("Pn", 17.358), ("P", 17.666), ("p", 17.804), ("P", 17.869), ("PcP", 18.039), ("ScP", 19.988), ("sP", 22.640), ("sP", 22.716), ("sP", 22.992), ("PcS", 23.051), ("sP", 24.039), ("sP", 24.042), ("Sn", 30.029), ("S", 30.563), ("s", 30.801), ("S", 30.913), ("ScS", 31.208)]] for model_name, expects in zip(model_names, expected_results): with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) build_taup_model( filename=os.path.join(DATA, os.path.pardir, model_name + ".tvel"), output_folder=folder, verbose=False) model = TauPyModel(os.path.join(folder, model_name + ".npz")) arrvials = model.get_ray_paths(source_depth_in_km=18.0, distance_in_degree=1.0) self.assertEqual(len(arrvials), len(expects)) for arrival, expect in zip(arrvials, expects): self.assertEqual(arrival.name, expect[0]) self.assertAlmostEqual(arrival.time, expect[1], 3)
def _get_origtime_delays(self, vel_mod, target_depth, max_dist=1., num_vals=20): """ :param max_dist: maximum distance (degrees) at which to calculate :param num_vals: number of distances (from 0 to max_distance) at which to calculate delats :returns: dict with keys 'op' and 'ps' corresponding to sorted lists of delay times from origin-to-p and p-to-s """ try: model = TauPyModel(model=vel_mod) except Exception: build_taup_model(vel_mod) # converts from np or tvel to npz model = TauModel.from_file(vel_mod) # reads npz delays = {'op': [0], 'ps': [0]} # ps_delays, p_delays = [0], [0] step = max_dist / num_vals for distance in np.arange(step, max_dist + .001, step): arrivals = model.get_travel_times(target_depth, distance, phase_list=["P", "S"]) p_delay = [x.time for x in arrivals if x.phase == "P"] s_delay = [x.time for x in arrivals if x.phase == "S"] ps_delay = s_delay - p_delay if len(ps_delay) == 1 and len(p_delay) == 1: delays['ps'].append(ps_delay[0]) delays['op'].append(p_delay[0]) else: log( 'Could not calculate delays for dist={:.2g} degrees'. format(distance), 'warning') return delays
def test_regional_models(self): """ Tests small regional models as this used to not work. Note: It looks like too much work to get a 1-layer model working. The problem is first in finding the moho, and second in coarsely- sampling slowness. Also, why bother. """ model_names = ["2_layer_model", "5_layer_model"] expected_results = [ [("p", 18.143), ("Pn", 19.202), ("PcP", 19.884), ("sP", 22.054), ("ScP", 23.029), ("PcS", 26.410), ("s", 31.509), ("Sn", 33.395), ("ScS", 34.533)], [("Pn", 17.358), ("P", 17.666), ("p", 17.804), ("P", 17.869), ("PcP", 18.039), ("ScP", 19.988), ("sP", 22.640), ("sP", 22.716), ("sP", 22.992), ("PcS", 23.051), ("sP", 24.039), ("sP", 24.042), ("Sn", 30.029), ("S", 30.563), ("s", 30.801), ("S", 30.913), ("ScS", 31.208)]] for model_name, expects in zip(model_names, expected_results): with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) build_taup_model( filename=os.path.join(DATA, os.path.pardir, model_name + ".tvel"), output_folder=folder, verbose=False) model = TauPyModel(os.path.join(folder, model_name + ".npz")) arrvials = model.get_ray_paths(source_depth_in_km=18.0, distance_in_degree=1.0) self.assertEqual(len(arrvials), len(expects)) for arrival, expect in zip(arrvials, expects): self.assertEqual(arrival.name, expect[0]) self.assertAlmostEqual(arrival.time, expect[1], 3)
def makevelocitymodel(Vs, depth, fname, base='iasp91'): ''' Add a layer to a preexisting velocity model and create a .npz file to be read with obspy.taup Args: * Vs : S-wave velocuty (in km/s) * depth : Depth of the layer (km) * fname : name of npz file to write * base : preexisting model to use for larger depths ''' # Read base velocity file if base == 'iasp91': fid = os.path.join(os.environ['DATA'], 'VELMODEL/iasp91.tvel') Mod = np.loadtxt(fid) else: print('To implement') sys.exit(0) # Delete first layer D = Mod[:, 0] if depth > 35.: ix = np.where(D >= depth)[0] else: ix = np.where(D > 35.)[0] Mod = Mod[ix, :] # Get VpVs ratio and Vp VpVs = Mod[0, 1] / Mod[0, 2] Vp = VpVs * Vs Density = 2.92 # Make lines l0 = np.array((0., Vp, Vs, Density)) l1 = np.array((depth, Vp, Vs, Density)) l2 = np.array((depth, Mod[0, 1], Mod[0, 2], Mod[0, 3])) l = np.vstack((l0, l1, l2)) lines = np.vstack((l, Mod)) header = '#\n' np.savetxt('tmp.tvel', lines, header=header, fmt='%1.4f') # Build NPZ file from obspy.taup.taup_create import build_taup_model build_taup_model('./tmp.tvel', './') # Clean up os.remove('tmp.tvel') os.rename('tmp.npz', fname) # All done return
def test_high_slowness_crust(self): """ Check handling of sources located in a high slowness layer. """ model_name = "high_slowness_crust" with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) build_taup_model( filename=os.path.join(DATA, os.path.pardir, model_name + ".nd"), output_folder=folder, verbose=False) model = TauPyModel(os.path.join(folder, model_name + ".npz")) arrivals = model.get_ray_paths(20.0, 0.84, phase_list=["sS"]) assert len(arrivals) == 0
def create_taup_model(input_file: str, save_folder: str, ret=True): """ creates .npz file that can be used for obspy ray-tracing :param input_file: Either .nd or .tvel file :param save_folder: folder where the .npz file will be saved :param ret: if True, return value will be given (False = No returns) :returns full .npz file path """ from obspy.taup.taup_create import build_taup_model build_taup_model(input_file, save_folder) if ret: return input_file.replace(".tvel", ".npz")
def test_many_identically_named_phases(self): """ Regression test to make sure obspy.taup works with models that produce many identically names seismic phases. """ with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) model_name = "smooth_geodynamic_model" build_taup_model( filename=os.path.join(DATA, model_name + ".tvel"), output_folder=folder, verbose=False) m = TauPyModel(os.path.join(folder, model_name + ".npz")) arr = m.get_ray_paths(172.8000, 46.762440693494824, ["SS"]) self.assertGreater(len(arr), 10)
def test_small_regional_model(self): """ Tests a small regional model as this used to not work. """ with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) model_name = "regional_model" build_taup_model( filename=os.path.join(DATA, os.path.pardir, model_name + ".tvel"), output_folder=folder, verbose=False) m = TauPyModel(os.path.join(folder, model_name + ".npz")) arr = m.get_ray_paths(source_depth_in_km=18.0, distance_in_degree=1.0) self.assertEqual(len(arr), 9) for a, d in zip(arr, [("p", 18.143), ("Pn", 19.202), ("PcP", 19.884), ("sP", 22.054), ("ScP", 23.029), ("PcS", 26.410), ("s", 31.509), ("Sn", 33.395), ("ScS", 34.533)]): self.assertEqual(a.name, d[0]) self.assertAlmostEqual(a.time, d[1], 3)
def test_regional_models(self): """ Tests small regional models as this used to not work. Note: It looks like too much work to get a 1-layer model working. The problem is first in finding the moho, and second in coarsely- sampling slowness. Also, why bother. """ model_names = ["2_layer_model", "5_layer_model", "2_layer_no_discontinuity_model"] expected_results = [ [("p", 18.143), ("P", 19.202), ("Pn", 19.202), ("P", 19.884), ("sP", 22.054), ("pP", 23.023), ("pP", 23.038), ("sP", 25.656), ("sP", 25.759), ("s", 31.509), ("S", 33.395), ("Sn", 33.395), ("S", 34.533), ("sS", 39.991), ("sS", 40.009), ("PP", 3110.537), ("SP", 4267.568), ("PS", 4269.707), ("SS", 5426.732)], [("P", 17.358), ("Pn", 17.358), ("P", 17.666), ("p", 17.804), ("P", 17.869), ("P", 18.039), ("pP", 21.125), ("pP", 21.164), ("sP", 22.640), ("sP", 22.716), ("sP", 22.992), ("sP", 23.766), ("sP", 23.918), ("sP", 24.039), ("sP", 24.041), ("S", 30.029), ("Sn", 30.029), ("S", 30.563), ("s", 30.800), ("S", 30.913), ("S", 31.208), ("sS", 36.547), ("sS", 36.613), ("PP", 3147.085), ("SP", 4294.699), ("PS", 4296.826), ("SS", 5444.434)], [("p", 18.143), ("sP", 22.054), ("s", 31.509), ("PP", 3562.683), ("SP", 4881.292), ("PS", 4883.430), ("SS", 6202.037)] ] for model_name, expects in zip(model_names, expected_results): with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) build_taup_model( filename=os.path.join(DATA, os.path.pardir, model_name + ".tvel"), output_folder=folder, verbose=False) model = TauPyModel(os.path.join(folder, model_name + ".npz")) arrivals = model.get_ray_paths(source_depth_in_km=18.0, distance_in_degree=1.0) assert len(arrivals) == len(expects) for arrival, expect in zip(arrivals, expects): assert arrival.name == expect[0] assert round(abs(arrival.time-expect[1]), 2) == 0
def test_small_regional_model(self): """ Tests a small regional model as this used to not work. """ with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) model_name = "regional_model" build_taup_model(filename=os.path.join(DATA, os.path.pardir, model_name + ".tvel"), output_folder=folder, verbose=False) m = TauPyModel(os.path.join(folder, model_name + ".npz")) arr = m.get_ray_paths(source_depth_in_km=18.0, distance_in_degree=1.0) self.assertEqual(len(arr), 9) for a, d in zip(arr, [("p", 18.143), ("Pn", 19.202), ("PcP", 19.884), ("sP", 22.054), ("ScP", 23.029), ("PcS", 26.410), ("s", 31.509), ("Sn", 33.395), ("ScS", 34.533)]): self.assertEqual(a.name, d[0]) self.assertAlmostEqual(a.time, d[1], 3)
def test_fruit(self): """ Check handling of low velocity zones. Test case where bottom of mantle has a negative velocity gradient so phase cannot turn. """ model_name = "fruit" with TemporaryWorkingDirectory(): folder = os.path.abspath(os.curdir) build_taup_model( filename=os.path.join(DATA, os.path.pardir, model_name + ".nd"), output_folder=folder, verbose=False) model = TauPyModel(os.path.join(folder, model_name + ".npz")) s_mod = model.model.s_mod high_slow_range = s_mod.high_slowness_layer_depths_p[0] assert s_mod.depth_in_high_slowness(1360, 18, True) assert s_mod.depth_in_high_slowness( 1360, high_slow_range.ray_param+0.00000001, True) assert not s_mod.depth_in_high_slowness( 1360, high_slow_range.ray_param, True) assert not s_mod.depth_in_high_slowness( 1360, high_slow_range.ray_param-0.00000001, True) p = SeismicPhase("P", model.model) atol = 1e-2 np.testing.assert_allclose(p.min_distance, 0.0, atol=atol) np.testing.assert_allclose(p.max_distance*180.0/np.pi, 72.66, atol=atol) assert p.branch_seq == [0, 0]
def create_taup(model_file, taup_path='taup_files'): from obspy.taup.taup_create import build_taup_model with h5py.File(model_file, 'r') as f: mantle = f['mantle'] index_moho = int(mantle['moho_layer'].value) index_cmb = int(mantle['cmb_layer'].value) fnam_out = os.path.splitext(model_file)[0] + '.nd' nlayer = len(mantle['vp']) with open(fnam_out, 'w') as fid: for i in np.arange(nlayer - 1, 0, -1): if i == index_moho - 1: fid.write('mantle\n') if i == index_cmb: fid.write('outer-core\n') fid.write('%7.2f %6.4f %6.4f %6.4f\n' % (1e-3 * (mantle['radius'][-1] - mantle['radius'][i]), 1e-3 * mantle['vp'][i], 1e-3 * mantle['vs'][i], 1e-3 * mantle['rho'][i])) fid.write('%7.2f %6.4f %6.4f %6.4f\n' % (3389.3, 1e-3 * mantle['vp'][0], 1e-3 * mantle['vs'][0], 1e-3 * mantle['rho'][0])) # Create an artificial inner core, so that TauPy # works correctly for core phases fid.write('inner-core\n') fid.write( '%7.2f %6.4f %6.4f %6.4f\n' % (3389.3, 1e-3 * mantle['vp'][0], 3.0, 1e-3 * mantle['rho'][0])) fid.write( '%7.2f %6.4f %6.4f %6.4f\n' % (3389.5, 1e-3 * mantle['vp'][0], 3.0, 1e-3 * mantle['rho'][0])) model_name = os.path.splitext(os.path.split(fnam_out)[-1])[0] taup_name = os.path.join(taup_path, model_name + '.npz') if not os.path.exists(taup_name): build_taup_model(fnam_out, output_folder=taup_path) return taup_name
# Here the P and S traveltimes are predicted by velocity model # not our ouput picks import glob import os from obspy import read, UTCDateTime, Stream from matplotlib.transforms import blended_transform_factory from obspy.geodetics import locations2degrees import matplotlib.pyplot as plt from obspy.geodetics import gps2dist_azimuth import shutil from obspy.io.sac.util import obspy_to_sac_header from obspy.taup import TauPyModel from obspy.taup.taup_create import build_taup_model os.system('cp ../tt_db/itvel.nd mymodel.nd') build_taup_model("mymodel.nd") model = TauPyModel(model="mymodel") numID = 686 # plot the waveforms with event ID maxdt = 50 / 2.5 # maxdist/2.5 estimate the used length of waveform tleng = maxdt # time window for waveform plotting freqmin = 2 # low pass freqmax = 15 # high pass sacdir = '/Users/miao/Desktop/LOCFLOW/Data/waveform_sac/' # sac file dir phasefile = '../hypolocSA.dat' # phase list iok = 0 with open(phasefile, "r") as f: for line in f: year, mon, day, hh, mm, sec, lat, lon, dep, mag, nofps, gap, res, num = line.split( )
def main(fnams_nd, times, phase_list_dist, phase_list_pred=('PP', 'PPP', 'SS', 'SSS', 'ScS', 'SKS'), fnam_out='tstars.txt', fnam_out_p='rayparams.txt', fnam_out_pred='phase_predictions.txt', depth=40., return_absolute_times=False, plot=False): with open(fnam_out, 'w') as f_tstar, \ open(fnam_out_p, 'w') as f_p, \ open(fnam_out_pred, 'w') as f_pred: if type(fnams_nd) is list: fnams = fnams_nd else: fnams = [fnams_nd] for fnam_nd in fnams: fnam_npz = './taup_tmp/' \ + os.path.split(fnam_nd)[-1][:-3] + '.npz' build_taup_model(fnam_nd, output_folder='./taup_tmp') cache = OrderedDict() model = TauPyModel(model=fnam_npz, cache=cache) f_tstar.write('%s ' % os.path.split(fnam_nd)[-1]) for tSmP in times: dist = get_dist(model, tSmP=tSmP, phase_list=phase_list_dist, plot=plot, depth=depth) if dist is not None: tstar_P, time_P, ray_param_P = calc_tstar_tvel( model=model, fnam_tvel=fnam_nd, distance=dist, phase=phase_list_dist[0], depth=depth) tstar_S, time_S, ray_param_S = calc_tstar_tvel( model=model, fnam_tvel=fnam_nd, distance=dist, phase=phase_list_dist[1], depth=depth) else: tstar_P = -1. tstar_S = -1. ray_param_P = -1. ray_param_S = -1. if dist is None: dist = 0. f_tstar.write('%5.2f %5.3f %5.3f ' % (dist, tstar_P, tstar_S)) f_p.write('%5.2f %5.3f %5.3f ' % (dist, ray_param_P, ray_param_S)) f_pred.write('%5.2f ' % dist) for phase in phase_list_pred: tt_phase = get_TSmP(distance=dist, model=model, plot=False, tmeas=0., return_abs=return_absolute_times, phase_list=[phase_list_dist[0], phase], depth=depth) f_pred.write('%7.1f ' % tt_phase) f_pred.write('\n') f_tstar.write('\n')
def plot_rays_and_times(modelname): """ Calls obspy routines to plot ray paths and travel times for the model built in BurnMan and for a seismic reference model for comparison. Parameters ---------- modelname: Name for BurnMan model (*.tvel file must be present) """ # Arrivals to plot, some random examples of phase names to use ("P","S", "PcP", "Sdiff", "SKS", "PKIKP") # Phase naming in obspy.taup is explained at # https://docs.obspy.org/packages/obspy.taup.html phase_list = ["P", "PKP", "PKIKP"] source_depth = 10 # in km min_degrees = 60 # minimum distance for ray paths max_degrees = 300 # maximum distance for ray paths npoints = 9 # number of distances to plot ray paths ref_model = 'prem' # choice of models available in obpsy, or input an npz file name # Build a taup_model for Obspy taup_create.build_taup_model("./" + modelname + ".tvel", ".") # Time to plot some predictions using routines from Obspy plt.figure(figsize=[9, 7]) ax = plt.subplot(2, 2, 1) # plotting predicted travel times at all distances obspy.taup.plot_travel_times(ax=ax, model='./' + modelname + '.npz', source_depth=source_depth, phase_list=phase_list, show=False) plt.title(modelname) # plotting the same for PREM for reference ax = plt.subplot(2, 2, 2) obspy.taup.plot_travel_times(ax=ax, model=ref_model, source_depth=source_depth, phase_list=phase_list, show=False) # not sure why the grid dissapears on this subplot, reactivate here... ax.grid() plt.title(ref_model) # plotting predicted ray paths every 30 degrees between 60 and 300 # degrees ax = plt.subplot(2, 2, 3, polar=True) obspy.taup.plot_ray_paths(ax=ax, model='./' + modelname + '.npz', source_depth=source_depth, min_degrees=min_degrees, max_degrees=max_degrees, npoints=npoints, phase_list=phase_list, verbose=True, show=False) # plotting the same for PREM for reference ax = plt.subplot(2, 2, 4, polar=True) obspy.taup.plot_ray_paths(ax=ax, model=ref_model, source_depth=source_depth, min_degrees=min_degrees, max_degrees=max_degrees, npoints=npoints, phase_list=phase_list, verbose=True)
cont_dir, temp_dir, ttimes_dir, ev_catalog, start_det, stop_det, det_dur, taup_model, Flag_Save_Figure, Flag_Read_Stats, stat_tol, ] = read_input_par(vfile) # generate model for travel times gen_model = taup_model + ".tvel" build_taup_model(gen_model) # set inventory files invfiles = ["inv.ingv.iv", "inv.ingv.mn"] # read Template Catalog # read event coordinates from catalog print("event catalog should be ZMAP or QUAKEML") if _is_zmap(ev_catalog): print("reading ZMAP catalog") elif _is_quakeml(ev_catalog): print("reading QUAKEML catalog")
def main(fnam_nd: str, times: tuple, phase_list=("P", "S"), depth=40., plot_rays=False): """ Compute distance of an event, given S-P time :param fnam_nd: name of TauP compatible model file :param times: list of S-P time :param phase_list: list of phases between which the time difference is measured (usually P and S) :param depth: assumed depth of event :param plot_rays: create a plot with the ray paths """ fnam_npz = "./taup_tmp/" \ + psplit(fnam_nd)[-1][:-3] + ".npz" build_taup_model(fnam_nd, output_folder="./taup_tmp") cache = OrderedDict() model = TauPyModel(model=fnam_npz, cache=cache) if plot_rays: fig, ax = plt.subplots(1, 1) for itime, tSmP in enumerate(times): dist = get_dist(model, tSmP=tSmP, depth=depth, phase_list=phase_list) if dist is None: print(f"{fnam_nd}, S-P time: {tSmP:5.1f}: NO SOLUTION FOUND!") else: print(f"{fnam_nd}, S-P time: {tSmP:5.1f}, " f"taup_distance: {dist:5.1f}") if plot_rays: if dist is None: ax.plot((-200), (-200), label="%4.1f sec, NO SOLUTION" % (tSmP), c="white", lw=0.0) else: arrivals = model.get_ray_paths(distance_in_degree=dist, source_depth_in_km=depth, phase_list=["P", "S"]) RADIUS_MARS = 3389.5 already_plotted = dict(P=False, S=False) ls = dict(P="solid", S="dashed") label = dict(P="%4.1f sec, %5.1f°" % (tSmP, dist), S=None) for arr in arrivals: if not already_plotted[arr.name]: already_plotted[arr.name] = True x = (RADIUS_MARS - arr.path["depth"]) * \ np.sin(arr.path["dist"]) y = (RADIUS_MARS - arr.path["depth"]) * \ np.cos(arr.path["dist"]) ax.plot(x, y, c="C%d" % itime, ls=ls[arr.name], label=label[arr.name], lw=1.2) if plot_rays: for layer_depth in model.model.get_branch_depths( ): # (0, 10, 50, 1000, # 1500): angles = np.linspace(0, 2 * np.pi, 1000) x_circle = (RADIUS_MARS - layer_depth) * np.sin(angles) y_circle = (RADIUS_MARS - layer_depth) * np.cos(angles) ax.plot(x_circle, y_circle, c="k", ls="dashed", lw=0.5, zorder=-1) for layer_depth in (model.model.cmb_depth, 0.0): angles = np.linspace(0, 2 * np.pi, 1000) x_circle = (RADIUS_MARS - layer_depth) * np.sin(angles) y_circle = (RADIUS_MARS - layer_depth) * np.cos(angles) ax.plot(x_circle, y_circle, c="k", ls="solid", lw=1.0) # for layer_depth in [1100.0]: # angles = np.linspace(0, 2 * np.pi, 1000) # x_circle = (RADIUS_MARS - layer_depth) * np.sin(angles) # y_circle = (RADIUS_MARS - layer_depth) * np.cos(angles) # ax.plot(x_circle, y_circle, c="k", ls="dotted", lw=0.3) ax.set_xlim(-100, RADIUS_MARS + 100) ax.set_ylim(1000, RADIUS_MARS + 100) ax.set_xlabel("radius / km") ax.set_ylabel("radius / km") ax.set_title("Ray path for model %s" % fnam_nd) ax.set_aspect("equal", "box") ax.legend(loc="lower left") plt.show()
#!/home/samhaug/anaconda2/bin/python import numpy as np from obspy.taup.taup_create import build_taup_model depths = np.arange(50, 1805, 5) for depth in depths: build_taup_model('prem{}.tvel'.format(depth))
from obspy.taup import taup_create, TauPyModel tvel = u'/Users/dmelgar/FakeQuakes/M6_validation/structure/test.tvel' out = '/Users/dmelgar/FakeQuakes/M6_validation/structure/' print 'Building model' taup_create.build_taup_model(tvel, output_folder=out) print 'Loading model' velmod = TauPyModel( model='/Users/dmelgar/FakeQuakes/M6_validation/structure/test.npz', verbose=True) print 'Getting phases' #paths=velmod.get_ray_paths(10.1,1.0,phase_list=['S','s','Sn']) #paths2=velmod.get_ray_paths(10.1,3.0,phase_list=['S','s','Sn']) paths3 = velmod.get_ray_paths(18, 0.4, phase_list=['S', 's', 'Sn', 'SmS', 'Sm']) paths3.plot(plot_type='cartesian') #paths.plot(plot_type='cartesian') #paths2.plot(plot_type='cartesian') #from obspy.taup import TauPyModel # #velmod=TauPyModel(model='iasp91') #paths=velmod.get_ray_paths(10.1,3.0,phase_list=['p','P','Pn','S','s','Sn']) #paths.plot(plot_type='cartesian')
aa2 = aa1 - np.floor(aa1) aa3 = aa2 * 1000000 elif _is_quakeml(ev_catalog): print("reading QUAKEML catalog") else: print("warning error in reading ZMAP or QUAKEML") st = Stream() st1 = Stream() st2 = Stream() # create taup model from a tvel model tvel = "./" + taup_model + ".tvel" build_taup_model(tvel) # generate list of days to process year = int(dateperiod[0]) month = int(dateperiod[1]) day = int(dateperiod[2]) period = int(dateperiod[3]) days_from_par = listdays(year, month, day, period) days = create_day_list(cat, days_from_par) for ista in stations: for day in days: print("day == ", day) inpfiles = cont_dir + day + "." + ista + ".???" st.clear()
def build_TauPyModel(out_directory,vel_mod_file,background_model='PREM'): ''' This function will take the structure from the .mod file and paste it on top of a pre computed mantle structure such as PREM. This assumes that the .mod file provided by the user ends with a 0 thickness layer on the MANTLE side of the Moho ''' from numpy import genfromtxt from os import environ,path from obspy.taup import taup_create, TauPyModel import obspy #mudpy source folder #load user specified .mod infromation structure = genfromtxt(vel_mod_file) #load background velocity structure if background_model=='PREM': bg_model_file=obspy.__path__[0]+'/taup/data/prem.nd' #Q values Qkappa=1300 Qmu=600 #Write new _nd file one line at a time nd_name=path.basename(vel_mod_file).split('.')[0] nd_name=nd_name+'.nd' # f=open(out_directory+'/structure/'+nd_name,'w') f=open(out_directory+'/'+nd_name,'w') #initalize ztop=0 for k in range(len(structure)-1): #Variables for writing to file zbot=ztop+structure[k,0] vp=structure[k,2] vs=structure[k,1] rho=structure[k,3] # Write to the file line1=('%8.2f\t%8.5f %7.5f %7.5f\t%6.1f %5.1f\n' % (ztop,vp,vs,rho,Qkappa,Qmu)) line2=('%8.2f\t%8.5f %7.5f %7.5f\t%6.1f %5.1f\n' % (zbot,vp,vs,rho,Qkappa,Qmu)) f.write(line1) f.write(line2) #update ztop=zbot #now read PREM file libe by libne and find appropriate depth tos tart isnerting fprem=open(bg_model_file,'r') found_depth=False while True: line=fprem.readline() if line=='': #End of file break if found_depth==False: #Check that it's not a keyword line like 'mantle' if len(line.split())>1: #not a keyword, waht depth are we at? current_depth=float(line.split()[0]) if current_depth > zbot: #PREM depth alrger than .mod file last line found_depth=True f.write('mantle\n') #Ok you have found the depth write it to file if found_depth == True: f.write(line) fprem.close() f.close() # make TauPy npz # taup_in=home+project_name+'/structure/'+nd_name # taup_out=home+project_name+'/structure/' taup_in=out_directory+'/'+nd_name taup_out=out_directory+'/' taup_create.build_taup_model(taup_in,output_folder=taup_out) else: #To be done later (ha) print('ERROR: That background velocity model does not exist')
import math import obspy.taup import numpy as ny from obspy.taup import TauPyModel from obspy.taup.taup_create import build_taup_model build_taup_model("itvel.nd") model = TauPyModel(model="itvel") #model = TauPyModel(model="prem") with open("ttdb.txt", "w") as f: #f.write("dist dep tp ts tp_slowness ts_slowness tp_hslowness ts_hslowness p_elvecorr s_elvecorr\n") for dep in range(0, 21, 1): # search 0 - 20 km in depth for dist in range(1, 141, 1): # search 0.01 - 1.4 degree in horizontal dist = dist * 0.01 print(dep, dist) arrivals = model.get_travel_times(source_depth_in_km=dep, distance_in_degree=dist, phase_list=["P", "p", "S", "s"]) #print(arrivals) i = 0 pi = 0 si = 0 while (i < len(arrivals)): arr = arrivals[i] i = i + 1 if ((arr.name == 'P' or arr.name == 'p') and pi == 0): pname = arr.name p_time = arr.time p_ray_param = arr.ray_param * 2 * ny.pi / 360 p_hslowness = -1 * (p_ray_param / 111.19) / math.tan(
import obspy import os import numpy as np from obspy.geodetics.base import gps2dist_azimuth from obspy.taup import TauPyModel from obspy.taup.taup_create import build_taup_model build_taup_model("../tt_db/itvel.nd") model = TauPyModel(model="itvel") if not os.path.exists('pk'): os.makedirs('pk') with open("../station.dat", "r") as f: for station in f: stlo, stla, net, sta, chan, elev = station.split() print(net, sta) output1 = './pk/' + net + '.' + sta + '.' + 'P.txt' f1 = open(output1, 'w') output2 = './pk/' + net + '.' + sta + '.' + 'S.txt' f2 = open(output2, 'w') with open("catalog_use.txt", "r") as p: for event in p: time, lon, lat, dep, mag = event.split() date, time = time.split('T') hour, minute, sec0 = time.split(':') sec = sec0[:5] torg = float(hour) * 3600 + float(minute) * 60 + float(sec) ddist, az1, az2 = gps2dist_azimuth(lat1=float(lat), lon1=float(lon), lat2=float(stla),