def tunePickers(DF,picker='pkBaer',filt=[1,10,2,True]): DF['AutoPick']=dict DF['Resids']=float minresids=999999999999999999999.0 for p1 in np.linspace(2,160,num=50): for p2 in np.linspace(p1+1,800,num=50): for a in DF.iterrows(): if picker=='pkBaer': TR=obspy.core.read(a[1].FileName) TR.filter('bandpass',freqmin=filt[0],freqmax=filt[1],corners=filt[2],zerophase=filt[3]) TR=TR.select(channel="*Z") outdict={} for b in TR: cft=recSTALTA(b[0].data, int(p1), int(p2)) p_pick=cft.argmax() Pstamp=p_pick/(float(b.stats.sampling_rate))+b.stats.starttime.timestamp idd=b.stats.station outdict[idd]=Pstamp DF.AutoPick[a[0]]=outdict sq=np.square(pd.Series(outdict)-pd.Series(DF.UTCPtime[a[0]])) DF.Resids[a[0]]=np.sqrt(np.average(sq[~np.isnan(sq)])) Resids=np.sum(DF.Resids.values) if Resids<minresids: bestparams=[p1,p2] print Resids return bestparams """
def normalize(self, method='trace_max', **kwargs): """ Normalizes all trace in the stream. """ logging.info("Normalizing {:} traces with method '{:}'...", len(self.traces), method) if method == 'trace_max': ObspyStream.normalize(self, global_max=False) elif method == 'global_max': ObspyStream.normalize(self, global_max=True) elif method == 'onebit': for tr in self.traces: tr.data = np.sign(tr.data) elif method == 'stalta': _apply = kwargs.get('apply', True) sta = kwargs.get('sta', 3.) lta = kwargs.get('lta', 10.) trigger_on = kwargs.get('trigger_on', 1.1) trigger_off = kwargs.get('trigger_off', 1.0) for tr in self.traces: df = tr.stats['sampling_rate'] _sta = int(sta * df) _lta = int(lta * df) cft = trigger.recSTALTA(tr.data, _sta, _lta) tr.trg = trigger.triggerOnset(cft, trigger_on, trigger_off) if _apply: for on, off in tr.trg: tr.data[on:off] = 0 else: raise ValueError("Unknown method '{:}'".format(method))
from obspy.core import UTCDateTime from obspy.arclink import Client from obspy.signal.trigger import recSTALTA, triggerOnset import matplotlib.pyplot as plt import numpy as np # Retrieve waveforms via ArcLink client = Client(host="erde.geophysik.uni-muenchen.de", port=18001) t = UTCDateTime("2009-08-24 00:19:45") st = client.getWaveform('BW', 'RTSH', '', 'EHZ', t, t + 50) # For convenience tr = st[0] # only one trace in mseed volume df = tr.stats.sampling_rate # Characteristic function and trigger onsets cft = recSTALTA(tr.data, int(2.5 * df), int(10. * df)) on_of = triggerOnset(cft, 3.5, 0.5) # Plotting the results ax = plt.subplot(211) plt.plot(tr.data, 'k') ymin, ymax = ax.get_ylim() plt.vlines(on_of[:, 0], ymin, ymax, color='r', linewidth=2) plt.vlines(on_of[:, 1], ymin, ymax, color='b', linewidth=2) plt.subplot(212, sharex=ax) plt.plot(cft, 'k') plt.hlines([3.5, 0.5], 0, len(cft), color=['r', 'b'], linestyle='--') plt.axis('tight') plt.show()
from obspy.core import UTCDateTime from obspy.arclink import Client from obspy.signal.trigger import recSTALTA, triggerOnset import matplotlib.pyplot as plt # Retrieve waveforms via ArcLink client = Client(host="erde.geophysik.uni-muenchen.de", port=18001) t = UTCDateTime("2009-08-24 00:19:45") st = client.getWaveform('BW', 'RTSH', '', 'EHZ', t, t + 50) # For convenience tr = st[0] # only one trace in mseed volume df = tr.stats.sampling_rate # Characteristic function and trigger onsets cft = recSTALTA(tr.data, int(2.5 * df), int(10. * df)) on_of = triggerOnset(cft, 3.5, 0.5) # Plotting the results ax = plt.subplot(211) plt.plot(tr.data, 'k') ymin, ymax = ax.get_ylim() plt.vlines(on_of[:, 0], ymin, ymax, color='r', linewidth=2) plt.vlines(on_of[:, 1], ymin, ymax, color='b', linewidth=2) plt.subplot(212, sharex=ax) plt.plot(cft, 'k') plt.hlines([3.5, 0.5], 0, len(cft), color=['r', 'b'], linestyle='--') plt.axis('tight') plt.show()
def refTrigger(self, RefWaveform): Config = self.Config cfg = ConfigObj(dict=Config) name = ('%s.%s.%s.%s') % ( RefWaveform[0].stats.network, RefWaveform[0].stats.station, RefWaveform[0].stats.location, RefWaveform[0].stats.channel) i = self.searchMeta(name, self.StationMeta) de = loc2degrees(self.Origin, i) ptime = 0 Phase = cake.PhaseDef('P') model = cake.load_model() if cfg.colesseo_input() == True: arrivals = model.arrivals([de, de], phases=Phase, zstart=self.Origin.depth, zstop=0.) else: arrivals = model.arrivals([de, de], phases=Phase, zstart=self.Origin.depth * km, zstop=0.) try: ptime = arrivals[0].t except: arrivals = model.arrivals([de, de], phases=Phase, zstart=o_depth * km - 0.1) ptime = arrivals[0].t phasename = ('%sphase') % (os.path.basename(self.AF)) if ptime == 0: print '\033[31mAvailable phases for reference station %s in range %f deegree\033[0m' % ( i, de) print '\033[31m' + '|'.join( [str(item['phase_name']) for item in tt]) + '\033[0m' print '\033[31myou tried phase %s\033[0m' % ( self.Config[phasename]) raise Exception("\033[31mILLEGAL: phase definition\033[0m") tw = self.calculateTimeWindows(ptime) if cfg.pyrocko_download() == True: stP = self.readWaveformsPicker_pyrocko(i, tw, self.Origin, ptime) elif cfg.colesseo_input() == True: stP = self.readWaveformsPicker_colos(i, tw, self.Origin, ptime) else: stP = self.readWaveformsPicker(i, tw, self.Origin, ptime) refuntouchname = os.path.basename(self.AF) + '-refstation-raw.mseed' stP.write(os.path.join(self.EventPath, refuntouchname), format='MSEED', byteorder='>') stP.filter("bandpass", freqmin=float(self.Config['refstationfreqmin']), freqmax=float(self.Config['refstationfreqmax'])) stP.trim(tw['xcorrstart'], tw['xcorrend']) trP = stP[0] trP.stats.starttime = UTCDateTime(3600) refname = os.path.basename(self.AF) + '-refstation-filtered.mseed' trP.write(os.path.join(self.EventPath, refname), format='MSEED', byteorder='>') sta = float(self.Config['refsta']) lta = float(self.Config['reflta']) cft = recSTALTA(trP.data, int(sta * trP.stats.sampling_rate), int(lta * trP.stats.sampling_rate)) t = triggerOnset(cft, lta, sta) try: onset = t[0][0] / trP.stats.sampling_rate print 'ONSET ', onset except: onset = self.mintforerun trigger = trP.stats.starttime + onset print 'TRIGGER ', trigger print 'THEORETICAL: ', UTCDateTime(3600) + self.mintforerun tdiff = (trP.stats.starttime + onset) - (UTCDateTime(3600) + self.mintforerun) print 'TDIFF: ', tdiff refp = UTCDateTime(self.Origin.time) + ptime reftriggeronset = refp + onset - self.mintforerun if int(self.Config['autoxcorrcorrectur']) == 1: try: refmarkername = os.path.join(self.EventPath, ('%s-marker') % (os.path.basename(self.AF))) fobjrefmarkername = open(refmarkername, 'w') fobjrefmarkername.write( '# Snuffler Markers File Version 0.2\n') fobjrefmarkername.write(( 'phase: %s 0 %s None None None XWStart None False\n' ) % (tw['xcorrstart'].strftime('%Y-%m-%d %H:%M:%S.%f'), name)) fobjrefmarkername.write(( 'phase: %s 0 %s None None None XWEnd None False\n' ) % (tw['xcorrend'].strftime('%Y-%m-%d %H:%M:%S.%f'), name)) fobjrefmarkername.write(( 'phase: %s 1 %s None None None TheoP None False\n' ) % (refp.strftime('%Y-%m-%d %H:%M:%S.%f'), name)) fobjrefmarkername.write(( 'phase: %s 3 %s None None None XTrig None False' ) % (reftriggeronset.strftime('%Y-%m-%d %H:%M:%S.%f'), name)) fobjrefmarkername.close() cmd = 'snuffler %s --markers=%s&' % (os.path.join( self.EventPath, refuntouchname), refmarkername) os.system(cmd) thrOn = float(self.Config['reflta']) # 4 thrOff = float(self.Config['refsta']) # 0.7 plotTrigger(trP, cft, thrOn, thrOff) selection = float( raw_input('Enter self picked phase in seconds: ')) tdiff = selection - self.mintforerun refname = os.path.basename(self.AF) + '-shift.mseed' trP.stats.starttime = trP.stats.starttime - selection trP.write(os.path.join(self.EventPath, refname), format='MSEED') except: selection = 0. refname = os.path.basename(self.AF) + '-shift.mseed' trP.stats.starttime = trP.stats.starttime - selection - self.mintforerun trP.write(os.path.join(self.EventPath, refname), format='MSEED') ''' tdiff = 0 trigger = trP.stats.starttime ''' To = Trigger(name, trigger, os.path.basename(self.AF), tdiff) return tdiff, To
def AutoPick(pickdir='Trigs',outputFormat='HYP',outdir='PickTimes',picker='pkBaer',goodPick='goodpicking', startnum='StartHere.txt',filelist=None): StaKey=pd.read_csv('StationKey.csv') if not os.path.isdir(outdir): os.makedirs(outdir) if not os.path.isdir(goodPick): os.makedirs(goodPick) latmin,latmax,lonmin,lonmax=_getLimits(StaKey) dA,A=_getdA(6371) #calculates symbolically the partial derivatives of the operator for location inversion count=0 if isinstance(filelist,list): files=filelist else: files=glob.glob(os.path.join(pickdir,'*')) try: #Look for startnum txt to see where to begin start=int(np.loadtxt(startnum).tolist()+int(np.random.rand()*10)) except: print 'No progress file, begining at 0' for fil in range(start,len(files)): ST=obspy.core.read(files[fil]) filename=os.path.basename(files[fil]).replace('msd','pha') with open(os.path.join(outdir,filename),'wb') as pik: Stations=StaKey.STATION STR=[0]*len(Stations) pks=[1]*len(Stations) cou=0 Key=StaKey.copy() Key['Ppick']=0.000000000 Key['Spick']=0.000000000 Key['Trace']=object for sta in Key.iterrows(): st=ST.copy() st=st.select(station=sta[1].STATION) if len(st)==0: #If station not found skip iteration continue sr=st[0].stats.sampling_rate STR[cou]=st.copy() cou+=1 for tr in range(len(STR)): if picker=='arPick': Z,N,E=STR[tr].select(channel='*Z').copy(), STR[tr].select(channel='*N').copy(),STR[tr].select(channel='*E').copy() p_pick, s_pick = arPick(Z[0].data, N[0].data,E[0].data, Z[0].stats.sampling_rate,1.0, 15.0, 1.0, 0.1, 4.0, 1.0, 2, 8, 0.1, 0.2) elif picker=='pkBaer': zst=STR[tr].select(channel='*Z') p_pick, phase_info = pkBaer(zst[0].data, sr,20, 60, 1.2, 10.0, 100, 100) if p_pick==1 or p_pick<0: #if baer/arPicker pick failes resort to basic recursive STA/LTA picks cft=recSTALTA(STR[tr].select(channel='*Z')[0].data, int(1 * sr), int(10 * sr)) p_pick=cft.argmax() pks[tr]=p_pick Key['Ppick'][int(tr)]=STR[tr][0].stats.starttime.timestamp+p_pick/float(sr) Key['Trace'][int(tr)]=STR[tr][0] #print (p_pick) for sta in Key.drop_duplicates(cols='Ppick').iterrows(): if outputFormat=='NNL': if picker=='arPick': line1,line2=_makeArPickNLLLine(sta[1].Ppick,s_pick,STR[tr]) pik.write(line1) pik.write(line2) if picker=='pkBaer': line1=_makePkBaerNLLLine(sta[1].Ppick,sta[1].Trace.stats.sampling_rate,sta[1].Trace) pik.write(line1) if outputFormat=='HYP': if picker=='pkBaer': try: line=_makePkBaerHYPLine(sta[1].Ppick,sta[1].Trace.stats.sampling_rate,sta[1].Trace) except: break pik.write(line) m=invertForLocation(Key,dA,A) if outputFormat=='NNL': pass #write this in later if outputFormat=='HYP' and m[0]>-90 and m[0]<90 and m[1]>-180 and m[1]<180: endline=writeEndLine(m,Key) #print np.min(np.min(Key.Ppick.values)) pik.write(endline) pik.write('\n') #Key=_genSynthetics(Key,A) if m[0] < latmin or m[0] > latmax or m[1] < lonmin or m[1] > lonmax: #If rough location is in station peremeter make picks and copy file os.remove(os.path.join(outdir,filename)) else: shutil.copy(files[fil],os.path.join(goodPick,os.path.basename(files[fil]))) print filename count+=1 if count%10==0: _writeProgressFile(count)
from obspy.core import read from obspy.signal.trigger import recSTALTA, plotTrigger trace = read("http://examples.obspy.org/ev0_6.a01.gse2")[0] df = trace.stats.sampling_rate cft = recSTALTA(trace.data, int(5 * df), int(10 * df)) plotTrigger(trace, cft, 1.2, 0.5)