def test_p_iasp91_geo_fallback_manual(self): """ Manual test for P phase in IASP91 given geographical input. This version of the test checks that things still work when geographiclib is not installed. """ has_geographiclib_real = geodetics.HAS_GEOGRAPHICLIB geodetics.HAS_GEOGRAPHICLIB = False m = TauPyModel(model="iasp91") arrivals = m.get_travel_times_geo(source_depth_in_km=10.0, source_latitude_in_deg=20.0, source_longitude_in_deg=33.0, receiver_latitude_in_deg=55.0, receiver_longitude_in_deg=33.0, phase_list=["P"]) geodetics.HAS_GEOGRAPHICLIB = has_geographiclib_real self.assertEqual(len(arrivals), 1) p_arrival = arrivals[0] self.assertEqual(p_arrival.name, "P") self.assertAlmostEqual(p_arrival.time, 412.43, 2) self.assertAlmostEqual(p_arrival.ray_param_sec_degree, 8.613, 3) self.assertAlmostEqual(p_arrival.takeoff_angle, 26.74, 2) self.assertAlmostEqual(p_arrival.incident_angle, 26.70, 2) self.assertAlmostEqual(p_arrival.purist_distance, 35.00, 2) self.assertEqual(p_arrival.purist_name, "P")
def calculate_arrivals(event, sta_lat=47.1314, sta_lon=-88.5947): """ Use TauP to calculate theoretical arrivals from this event :param event: Event to calculate arrivals for at the shake :param sta_lat: Latitude of station (default to Hancock) :param sta_lon: Longitude of station (default to Hancock) :return: """ model = TauPyModel(model='iasp91') o = event.preferred_origin() return model.get_travel_times_geo(source_depth_in_km=o.depth / 1000., source_longitude_in_deg=o.longitude, source_latitude_in_deg=o.latitude, receiver_longitude_in_deg=sta_lon, receiver_latitude_in_deg=sta_lat)
def output_station_channel_window_onlybodywave(asdf_dir, list_input, min_period, max_period, time_increment, before_firarrival, after_finarrival): windows = np.zeros((len(list_input), 2), dtype=int) #print(windows.size) model = TauPyModel(model="iasp91") ds = pyasdf.ASDFDataSet(asdf_dir) event = ds.events[0] datetime = event.origins[0].time evlo = event.origins[0].longitude evla = event.origins[0].latitude evdp = event.origins[0].depth / 1000. otime = event.origins[0].time #list=ds.waveforms.list() #print(list) #st=Stream() i = 0 for stid in list_input: stla, stlo, evz = ds.waveforms[stid].coordinates.values() ####here need to test the existance of the Z components #st1=ds.waveforms[stid].preprocessed_30s_to_80s dist, az, baz = gps2dist_azimuth(evla, evlo, stla, stlo) dt = time_increment fmin = 1 / max_period fmax = 1 / min_period arrivals = model.get_travel_times(source_depth_in_km=evdp, distance_in_degree=dist / 111000) arrivals2 = model.get_travel_times_geo(source_depth_in_km=evdp, source_latitude_in_deg=evla, source_longitude_in_deg=evlo, receiver_latitude_in_deg=stla, receiver_longitude_in_deg=stlo) timewindow = int(arrivals[1].time / dt + after_finarrival / dt) timewindowLEFT = int(arrivals[0].time / dt - before_firarrival / dt) windows[i][0] = timewindowLEFT windows[i][1] = timewindow i += 1 return windows
def test_p_iasp91_geo_manual(self): """ Manual test for P phase in IASP91 given geographical input. This version of the test is used when geographiclib is installed """ m = TauPyModel(model="iasp91") arrivals = m.get_travel_times_geo(source_depth_in_km=10.0, source_latitude_in_deg=20.0, source_longitude_in_deg=33.0, receiver_latitude_in_deg=55.0, receiver_longitude_in_deg=33.0, phase_list=["P"]) self.assertEqual(len(arrivals), 1) p_arrival = arrivals[0] self.assertEqual(p_arrival.name, "P") self.assertAlmostEqual(p_arrival.time, 412.43, 2) self.assertAlmostEqual(p_arrival.ray_param_sec_degree, 8.613, 3) self.assertAlmostEqual(p_arrival.takeoff_angle, 26.74, 2) self.assertAlmostEqual(p_arrival.incident_angle, 26.70, 2) self.assertAlmostEqual(p_arrival.purist_distance, 35.00, 2) self.assertEqual(p_arrival.purist_name, "P")
def test_p_iasp91_geo_manual(self): """ Manual test for P phase in IASP91 given geographical input. This version of the test is used when geographiclib is installed """ m = TauPyModel(model="iasp91") arrivals = m.get_travel_times_geo(source_depth_in_km=10.0, source_latitude_in_deg=20.0, source_longitude_in_deg=33.0, receiver_latitude_in_deg=55.0, receiver_longitude_in_deg=33.0, phase_list=["P"]) assert len(arrivals) == 1 p_arrival = arrivals[0] assert p_arrival.name == "P" assert abs(p_arrival.time-412.43) < 2e-2 assert abs(p_arrival.ray_param_sec_degree-8.613) < 2e-3 assert abs(p_arrival.takeoff_angle-26.74) < 2e-2 assert abs(p_arrival.incident_angle-26.70) < 2e-2 assert abs(p_arrival.purist_distance-35.00) < 2e-2 assert p_arrival.purist_name == "P"
def read_data(path): try: dfile = os.listdir('C:/Users/kkapa/Desktop/RAJ-SKS') loop = len(dfile) inc = 0 except: raise Exception("file not found") while (inc != loop - 1 and inc != loop - 2 and inc != loop - 3): s1, s2, s3 = '', '', '' refile = '' while (True): try: ext = dfile[inc][-3::1] if (ext == 'sac' or ext == 'SAC'): s1 += dfile[inc] refile += dfile[inc] inc += 1 # print(s1) break else: inc += 1 except: inc += 1 while (True): try: ext = dfile[inc][-3::1] if (ext == 'sac' or ext == 'SAC'): s2 += dfile[inc] inc += 1 # print(s2) break else: inc += 1 except: inc += 1 while (True): try: ext = dfile[inc][-3::1] if (ext == 'sac' or ext == 'SAC'): s3 += dfile[inc] inc += 1 # print(s3) break else: inc += 1 except: inc += 1 st = read(path + '/' + s1, debug_headers=True) + read( path + '/' + s2, debug_headers=True) + read(path + '/' + s3, debug_headers=True) # st = read('2011.052.10.57.52.4000.XX.KTL.00.BHE.M.sac', debug_headers=True) # st += read('2011.052.10.57.52.4000.XX.KTL.00.BHN.M.sac', debug_headers=True) # st += read('2011.052.10.57.52.4000.XX.KTL.00.BHZ.M.sac', debug_headers=True) #2011.052.10.57.52.4000.XX.KTL.00.BHZ.M 2011.052.10.57.52.4000.XX.KTL.00.BHN.M 2011.052.10.57.52.4000.XX.KTL.00.BHE.M # for #extarcting the required information form the data tr = st[0] # print(tr.stats) # st.plot() evtime = tr.stats['starttime'] endtime = tr.stats['endtime'] tr = tr.stats['sac'] tr = dict(tr) b = tr['b'] evla = tr['evla'] evlo = tr['evlo'] stla = tr['stla'] stlo = tr['stlo'] evdp = tr['evdp'] model = TauPyModel('iasp91') arrivals = model.get_travel_times_geo(evdp, evla, evlo, stla, stlo, phase_list=['SKS']) skstime = evtime + arrivals[0].time - b # print(skstime) #applying filters dist, az, baz = geodetics.base.gps2dist_azimuth(evla, evlo, stla, stlo) figurefile = path + '/' + refile[0:30] resultfile = refile[0:30] + '_results.txt' resultfile = path + '/' + resultfile f = open(resultfile, 'w') # f=open('2011.052.10.57.52'+'_result1.txt','w') f.write(' EventId' + '\t ' + 'Baz' + '\t\t' + ' filter' + '\t\t' + 'SI' + '\t' + 'Split/Null' + '\t\t\t' + 'EigenM' + '\t\t\t' + ' TransM' + '\t\t\t' + ' CrossM' + '\t\t\t\t' + '\n') f.write('2011.052.10.57.52 ' + str(round(baz, 2)) + '\t' + 'f1' + '\t' + 'f2' + '\t' + '\t' + '\t\t' + '|' + 'phi' + '\t' + 'dev' + '\t' + 't' + '\t' + 'dt' + '\t' + '|' + 'phi' + '\t' + 'dev' + '\t' + 't' + '\t' + 'dt' + '\t' + '|' + 'phi' + '\t' + 'dev' + '\t' + 't' + '\t' + 'dt' + '\t' + '\n') f.close() for j in range(len(f1)): st.filter("bandpass", freqmin=f1[j], freqmax=f2[j]) # st.plot() # trim around SKS st.trim(skstime - minsks, skstime + maxsks) # st.plot() #creating pair north = st[1].data east = st[0].data sample_interval = st[0].stats.delta # print(sample_interval) realdata = sw.Pair(north, east, delta=sample_interval) si = realdata.splitting_intensity() x, y = realdata.cordinatewindow() diff = int(y - x) - windowsize # realdata.plot() try: #initial EigenM measure = sw.EigenM(realdata) temp = measure.measurements() print(-1, temp) temp = list(temp) temp.append(-1) m = [] m.append(temp) #initial TransM measure1 = sw.TransM(realdata, pol=baz) temp = measure1.measurements() print(-1, temp) temp = list(temp) temp.append(-1) m1 = [] m1.append(temp) #initial CrossM measure2 = sw.CrossM(realdata) temp = measure2.measurements() print(-1, temp) temp = list(temp) temp.append(-1) m2 = [] m2.append(temp) except: print("please check this data manually canot apply filter ", j + 1) print("for file names") print(s1, s2, s3) continue #setting windows for i in range(diff): a = realdata # a.plot() try: a.set_window(x + i, x + windowsize + i) # a.plot() try: #EigenM measure = sw.EigenM(a) temp = measure.measurements() print(i, measure.measurements()) temp = list(temp) temp.append(i) m.append(temp) #TransM measure1 = sw.TransM(realdata, pol=baz) temp = measure1.measurements() print(i, measure1.measurements()) temp = list(temp) temp.append(i) m1.append(temp) #CrossM measure2 = sw.CrossM(a) temp = measure2.measurements() print(i, measure2.measurements()) temp = list(temp) temp.append(i) m2.append(temp) except: continue except: continue try: index, ti = bestvalue(m) print(index) phi, dev, t, dt = m[ti][0], m[ti][1], m[ti][2], m[ti][3] a = realdata if (index == -1): a.set_window(x, y) else: a.set_window(x + index, x + windowsize + index) # a.plot() measure = sw.EigenM(a) # measure.plot() fname = figurefile + '_EigenM_' + str(j) + '.pdf' # to save the plot pass 'save' and file name # to save and show the plot pass 'showandsave' and file name #to show the plot pass nothing measure.plot('save', fname) # f=open('2011.052.10.57.52'+'_result.txt','a') # f.write('eigenm'+'\t'+str(f1[j])+'\t'+str(f2[j])+'\t'+str(phi)+'\t'+str(dev)+'\t'+str(t)+'\t'+str(dt)+'\n') # f.close() except: print("not saved") continue try: index, ti = bestvalue(m1) print(index) phi1, dev1, t1, dt1 = m1[ti][0], m1[ti][1], m1[ti][2], m1[ti][ 3] a = realdata if (index == -1): a.set_window(x, y) else: a.set_window(x + index, x + windowsize + index) # a.plot() measure1 = sw.TransM(a, pol=baz) # measure1.plot() fname = figurefile + '_TransM_' + str(j) + '.pdf' measure1.plot('save', fname) # f=open('2011.052.10.57.52'+'_result.txt','a') # f.write('transm'+'\t'+str(f1[j])+'\t'+str(f2[j])+'\t'+str(phi)+'\t'+str(dev)+'\t'+str(t)+'\t'+str(dt)+'\n') # f.close() except: continue try: index, ti = bestvalue(m2) print(index) phi2, dev2, t2, dt2 = m2[ti][0], m2[ti][1], m2[ti][2], m2[ti][ 3] a = realdata if (index == -1): a.set_window(x, y) else: a.set_window(x + index, x + windowsize + index) # a.plot() measure2 = sw.CrossM(a) # measure2.plot() fname = figurefile + '_CrossM_' + str(j) + '.pdf' measure2.plot('save', fname) # f=open('2011.052.10.57.52'+'_result.txt','a') # f.write('CrossM'+'\t'+str(f1[j])+'\t'+str(f2[j])+'\t'+str(phi)+'\t'+str(dev)+'\t'+str(t)+'\t'+str(dt)+'\n') # f.write('\n') # f.close() except: continue try: f = open(resultfile, 'a') f.write('\t' + '\t\t\t' + str(f1[j]) + '\t' + str(f2[j]) + '\t' + str(round(si, 2)) + '\t\t\t' + '|' + str(round(phi, 3)) + '\t' + str(round(dev, 3)) + '\t' + str(round(t, 3)) + '\t' + str(round(dt, 3)) + '\t' + '|' + str(round(phi1, 3)) + '\t' + str(round(dev1, 3)) + '\t' + str(round(t1, 3)) + '\t' + str(round(dt1, 3)) + '\t' + '|' + str(round(phi2, 3)) + '\t' + str(round(dev2, 3)) + '\t' + str(round(t2, 3)) + '\t' + str(round(dt2, 3)) + '\t' + '\n') f.close() except: print("canot write") continue
station = "ANMO" # Get a real station. from obspy.clients.fdsn import Client c_fdsn = Client("IRIS") print( c_fdsn.get_stations(network=network, station=station, format="text")[0][0]) # + {"deletable": true, "editable": true} # Plot the ray paths just to illustrate what we are working with. from obspy.taup import TauPyModel m = TauPyModel("ak135") print( m.get_travel_times_geo(source_depth_in_km=17.4, source_latitude_in_deg=-31.130, source_longitude_in_deg=-72.090, receiver_latitude_in_deg=34.95, receiver_longitude_in_deg=-106.46)) m.get_ray_paths_geo(source_depth_in_km=17.4, source_latitude_in_deg=-31.130, source_longitude_in_deg=-72.090, receiver_latitude_in_deg=34.95, receiver_longitude_in_deg=-106.46, phase_list=["P", "pP", "sP", "PcP", "PP"]).plot() # + {"deletable": true, "editable": true} # Calculate distance. from obspy.geodetics import locations2degrees locations2degrees(lat1=-31.130, long1=-72.090, lat2=34.95, long2=-106.46)
def rate(network, phase, preproloc, station=None, review=False, retained=False, decon_meth='it', test_tt_calculation=False): """ Module to rate and review the quality of Sp or Ps waveforms from the given station. Shows the automatic rating from qc. Tapers can be controlled with the mouse. Rating is done with the keyboard. Makes only sense if the files in preproloc have not been quality controlled (the script is a reminant from an earlier alpha version). Parameters ---------- network : STRING Network code (two letters). phase : STRING Either "P" for Ps or "S" Sp. The default is "S". preproloc : string Directory that contains the preprocessed files (not quality controlled) station : str or list, optional Station code (three letters). review : INTEGER, optional If true, already rated waveforms are shown. Can also be an integer between 1 and 4. Then, only waveforms rated with the respected rating are shown. The default is False. retained : Bool, optional Show only waveforms retained by qcp or qcs. The default is False. decon_meth : STRING, optional Deconvolution method, "waterlevel", 'dampedf' for constant damping level, 'it' for iterative time domain deconvoltuion, 'multit' for multitaper or 'fqd' for frequency dependently damped spectral division. The default is 'it' Raises ------ Exception For Typing mistakes. Returns ------- None. """ if phase == 'P': onset = 30 elif phase[-1] == 'S': onset = 120 inloc = os.path.join(preproloc, phase, 'by_station', network) infiles = [] # List of all files in folder pattern = [] # List of input constraints streams = [] # List of files filtered for input criteria for root, dirs, files in os.walk(inloc): for name in files: infiles.append(os.path.join(root, name)) # Set filter patterns if station: if type(station) == str: pattern.append('*%s*%s*.mseed' % (network, station)) elif type(station) == list: for stat in station: pattern.append('*%s*%s*.mseed' % (network, stat)) else: pattern.append('*%s*.mseed' % (network)) # Do filtering for pat in pattern: streams.extend(fnmatch.filter(infiles, pat)) # clear memory del pattern, infiles # For TauPy lookup model = TauPyModel() if test_tt_calculation: client = Client() for f in streams: # if file[:4] == "info": # Skip the info files # continue # try: # st = read(inloc + file) # except IsADirectoryError as e: # print(e) # continue st = read(f) # List for taper coordinates if "taper" in rating: del rating["taper"] rating["taper"] = [] st.normalize() # Additional filter "test" if phase == "S": st.filter("lowpass", freq=1.0, zerophase=True, corners=2) elif phase == "P": st.filter("lowpass", freq=1.0, zerophase=True, corners=2) y = [] ch = [] starttime = str(st[0].stats.starttime) dt = st[0].stats.delta sampling_f = st[0].stats.sampling_rate old = __r_file(network, st[0].stats.station, starttime) # old # read info file # location info file infof = os.path.join(inloc, st[0].stats.station, 'info') with shelve.open(infof) as info: ii = info["starttime"].index(st[0].stats.starttime) rdelta = info["rdelta"][ii] # epicentral distance mag = info["magnitude"][ii] statlat = info["statlat"] statlon = info["statlon"] rayp = info["rayp_s_deg"][ii] / 111319.9 evt_depth = info["evt_depth"][ii] / 1000 ot = info["ot_ret"][ii] evtlat = info['evtlat'][ii] evtlon = info['evtlon'][ii] if old and not review: # skip already rated files continue if type(review) == int: if review > 4: raise Exception("review has to be between 0 and 4") if review != int(old): continue # check automatic rating if phase == "S": st_f, crit, hf, noisemat = qcs(st, dt, sampling_f, onset=onset) elif phase == "P": st_f, crit, hf, noisemat = qcp(st, dt, sampling_f, onset=onset) # skip files that have not been retained if retained and not crit: continue # create RF if not test_tt_calculation: _, _, PSV = rotate_PSV(statlat, statlon, rayp, st_f) else: PSV = st_f # to see correlation at theoretical arrival try: RF = createRF(PSV, phase, method=decon_meth, shift=onset) except ValueError as e: # There were some problematic events print(e) continue # TauPy lookup ph_name = [] ph_time = [] if not test_tt_calculation: arrivals = model.get_travel_times(evt_depth, distance_in_degree=rdelta) primary_time = model.get_travel_times(evt_depth, distance_in_degree=rdelta, phase_list=phase)[0].time for arr in arrivals: if arr.time < primary_time - onset or arr.time > \ primary_time + 120 or arr.name == phase: continue ph_name.append(arr.name) ph_time.append(arr.time - primary_time) else: # Caluclate travel times with different methods ph_time.append( model.get_travel_times_geo(evt_depth, evtlat, evtlon, statlat, statlon, phase_list=phase)[0].time) d = [] d.append( client.distaz(statlat, statlon, evtlat, evtlon)['distance']) d.append( kilometer2degrees( gps2dist_azimuth(statlat, statlon, evtlat, evtlon)[0] / 1000)) for dis in d: ph_time.append( model.get_travel_times(evt_depth, dis, phase_list=phase)[0].time) ph_name = ['taup', 'iris', 'geodetics'] ph_time = np.array(ph_time) - (st[0].stats.starttime + onset - UTCDateTime(ot)) # waveform data st.sort() for tr in st: y.append(tr.data) ch.append(tr.stats.channel[2]) # create time vector t = np.linspace(0 - onset, tr.stats.npts * tr.stats.delta - onset, len(y[0])) # plot fig, ax = __draw_plot(starttime, t, y, ph_time, ph_name, ch, noisemat, RF, old, rdelta, mag, crit, ot, evt_depth, phase, test_tt_calculation) while not plt.waitforbuttonpress(30): # Taper when input is there if len(rating["taper"]) == 2: if rating["taper"][0] < rating["taper"][1]: trim = [rating["taper"][0], rating["taper"][1]] else: trim = [rating["taper"][1], rating["taper"][0]] trim[0] = trim[0] - t[0] trim[1] = t[-1] - trim[1] RF = createRF(PSV, phase, method=decon_meth, shift=onset, trim=trim) __draw_plot(starttime, t, y, ph_time, ph_name, ch, noisemat, RF, old, rdelta, mag, crit, ot, evt_depth, phase, test_tt_calculation) rating["taper"].clear() # fig.canvas.mpl_connect('key_press_event', ontype) if rating["k"] == "q": break elif "k" in rating: __w_file(network, st[0].stats.station, starttime)