def detectEvent(self, channelNo, methodName='z_detect'): tr = self.st[channelNo].copy() if methodName == 'z_detect': df = tr.stats.sampling_rate cft = z_detect(tr.data, int(10 * df)) plot_trigger(tr, cft, -0.4, -0.3, show=False) plt.title('Channel No.' + str(channelNo)) plot_name = 'trigger_detection_' + str(channelNo) + '.png' path = 'static/Obspy_Plots/test/' + plot_name plt.savefig(path) return plot_name
def return_trigger_index(wiggle, channel_name, class_type): global triggers_verified trace = wiggle.copy() trigger_indices = [] index_depth = 0.3 # how far into max indices to return possible trigger # (avoids returning triggers at very beginning) on = 1 off = 1 if "PDB" in channel_name: # Hydrophone if (class_type == -1): trigger_indices, ctf = standard_trigger_finder(trace, channel_name) on = std_on off = std_off elif "OT" in channel_name: # Accelerometer if (class_type == -1): trigger_indices, ctf = standard_trigger_finder(trace, channel_name) on = std_on off = std_off trigger_data = np.zeros(1, dtype=np.int32) # Single integer depth_threshold = 0.05 # triggers at indices sooner than this will not be used trigger_index = floor( index_depth * len(trigger_indices)) # just in case all triggers are very early for trigger_pair in trigger_indices: if not ((trigger_pair[0] / len(ctf)) < depth_threshold) and ( trigger_pair[0] / len(ctf) < 0.7 ): # dont return triggers too close to the edge to min. padding trigger_index = trigger_pair[0] break # return first best trigger ? trigger_data[0] = trigger_index trigger_stream = Stream([Trace(data=trigger_data)]) # Visualize detected triggers if (triggers_verified < trigger_verif_amt): t = trace.copy() t.data = t.data[300:] plot_trigger(t, ctf, on, off) triggers_verified += 1 return trigger_stream
def pick_arrival(trace, nsta_seconds, nlta_seconds, df, origin_time, pick_threshold, plot_flag=False): """ P wave arrival is picked using a recursive sta/lta algorithm. Parameters ---------- trace: obspy trace Seimic data. nsta_seconds, nlta_seconds, pick_threshold: float parameters for sta/lta df: int, float Data sampling rate origin_time: obspy UTCDateTime Earthquake occurrence time . Returns ------- P_pick: array-like Picked arrivals in samples. Reference: Withers, M., Aster, R., Young, C., Beiriger, J., Harris, M., Moore, S., and Trujillo, J. (1998), A comparison of select trigger algorithms for automated global seismic phase and event detection, Bulletin of the Seismological Society of America, 88 (1), 95-106. """ cft = recursive_sta_lta(trace, int(nsta_seconds * df), int(nlta_seconds * df)) arrivals = trigger_onset(cft, pick_threshold, 0.5) if plot_flag: plot_trigger(trace, cft, pick_threshold, 0.5, show=True) P_pick = check_arrival_time(arrivals, trace.stats.starttime, origin_time, df) return P_pick
def pick_arrival(trace, nsta_seconds, nlta_seconds, df, origin_time, pick_threshold, plot_flag=False): """ P wave arrival is picked using a recursive sta/lta algorithm. """ cft = recursive_sta_lta(trace, int(nsta_seconds * df), int(nlta_seconds * df)) arrivals = trigger_onset(cft, pick_threshold, 0.5) if plot_flag: plot_trigger(trace, cft, pick_threshold, 0.5, show=True) P_pick = check_arrival_time(arrivals, trace.stats.starttime, origin_time, df) return P_pick
st[0].copy().taper(0.05).filter("bandpass", freqmin=freq_bounds[0], freqmax=freq_bounds[1]).plot() # + {"deletable": true, "editable": true} tr = st[0].filter("bandpass", freqmin=freq_bounds[0], freqmax=freq_bounds[1]) sps = int(tr.stats.sampling_rate) onthresh = 2.0 offthresh = 0.5 shortwin = 5 # sec longwin = 20 # sec cft = trg.classic_sta_lta(tr.data, shortwin * sps, longwin * sps) trg.plot_trigger(tr, cft, onthresh, offthresh) # + {"deletable": true, "editable": true, "cell_type": "markdown"} # In multiple studies (Qamar, 1988; O'Neel, 2007; Bartholomaus, 2015; Kohler 2016), the duration of calving icequakes has been shown to be an important predictor of iceberg size and/or calving flux. Below, calculate and record the cumulative duration of calving events on randomly selected days during the Yahtse seismic experiment. I recommend choosing some fixed amount of time on the first of each month. Choose the longest fixed amount of time that you can bear to wait for the data to be retrieved and the analysis to run. I recommend trying 12 hrs on the first of each month. # + {"deletable": true, "editable": true} trigs = trg.trigger_onset(cft, onthresh, offthresh) # the array of trigger on and off indices event_times = np.array(starttime) + trigs / sps # Detection "on" times # del durs # remove the durs variable, so that old time runs don't contaminate new runs. durs = np.diff(trigs, axis=1) / sps # s duration of events durs = durs[:, 0] print(starttime)
import obspy from obspy.signal.trigger import classic_STALTA, plot_trigger trace = obspy.read("http://examples.obspy.org/ev0_6.a01.gse2")[0] df = trace.stats.sampling_rate cft = classic_STALTA(trace.data, int(5. * df), int(10. * df)) plot_trigger(trace, cft, 1.5, 0.5)
trs_all = trace_all.slice(starttime=start, endtime=end) trs_low = trace_low.slice(starttime=start, endtime=end) #trs.filter("bandpass", freqmin=fmin,freqmax=fmax) #trs_e = obspy.signal.filter.envelope(trs.data) #print('reference waveform') trs_high.plot(type='relative', color='b') #, starttime=start , endtime=end) sr = trace_all.stats.sampling_rate nsta = int(0.5 * sr) nlta = int(25 * sr) stream = trs_high.data cft = recursive_sta_lta(stream, nsta, nlta) trig_on = 15 trig_off = 0.5 plot_trigger(trs_high, cft, trig_on, trig_off) on_off = trigger_onset(cft, trig_on, trig_off) #print("here 2") #%% catalogue = np.zeros(shape=(0, 1)) num = 0 shift2 = 200 shift = 10 for x in range(0, len(on_off)): event_h = trs_high[on_off[x, 0] - 2000:on_off[x, 1] + 2000] event_h2 = trs_high[on_off[x, 0] - 1000:on_off[x, 1] + 1000] event_a = trs_all[on_off[x, 0] - 2000:on_off[x, 1] + 2000] event_l = trs_low[on_off[x, 0] - 2000:on_off[x, 1] + 2000]
import obspy from obspy.signal.trigger import plot_trigger, z_detect trace = obspy.read("http://examples.obspy.org/ev0_6.a01.gse2")[0] df = trace.stats.sampling_rate cft = z_detect(trace.data, int(10. * df)) plot_trigger(trace, cft, -0.4, -0.3)
def stalta_pick(stream, stalen, ltalen, trig_on, trig_off, freqmin=False, freqmax=False, debug=0, show=False): """ Basic sta/lta picker, suggest using alternative in obspy. Simple sta-lta (short-term average/long-term average) picker, using \ obspy's stalta routine to generate the characteristic function. Currently very basic quick wrapper, there are many other (better) options \ in obspy, found \ `here <http://docs.obspy.org/packages/autogen/obspy.signal.trigger.html>`_. :type stream: obspy.Stream :param stream: The stream to pick on, can be any number of channels. :type stalen: float :param stalen: Length of the short-term average window in seconds. :type ltalen: float :param ltalen: Length of the long-term average window in seconds. :type trig_on: float :param trig_on: sta/lta ratio to trigger a detection/pick :type trig_off: float :param trig_off: sta/lta ratio to turn the trigger off - no further picks\ will be made between exceeding trig_on until trig_off is reached. :type freqmin: float :param freqmin: Low-cut frequency in Hz for bandpass filter :type freqmax: float :param freqmax: High-cut frequency in Hz for bandpass filter :type debug: int :param debug: Debug output level from 0-5. :type show: bool :param show: Show picks on waveform. :returns: obspy.core.event.Event .. rubric:: Example >>> from obspy import read >>> from eqcorrscan.utils.picker import stalta_pick >>> st = read() >>> event = stalta_pick(st, stalen=0.2, ltalen=4, trig_on=10, ... trig_off=1, freqmin=3.0, freqmax=20.0) >>> event.creation_info.author 'EQcorrscan' """ from obspy.signal.trigger import classic_sta_lta, trigger_onset from obspy.signal.trigger import plot_trigger from obspy import UTCDateTime from obspy.core.event import Event, Pick, WaveformStreamID from obspy.core.event import CreationInfo, Comment, Origin import eqcorrscan.utils.plotting as plotting event = Event() event.origins.append(Origin()) event.creation_info = CreationInfo(author='EQcorrscan', creation_time=UTCDateTime()) event.comments.append(Comment(text='stalta')) picks = [] for tr in stream: # We are going to assume, for now, that if the pick is made on the # horizontal channel then it is an S, otherwise we will assume it is # a P-phase: obviously a bad assumption... if tr.stats.channel[-1] == 'Z': phase = 'P' else: phase = 'S' if freqmin and freqmax: tr.detrend('simple') tr.filter('bandpass', freqmin=freqmin, freqmax=freqmax, corners=3, zerophase=True) df = tr.stats.sampling_rate cft = classic_sta_lta(tr.data, int(stalen * df), int(ltalen * df)) if debug > 3: plot_trigger(tr, cft, trig_on, trig_off) triggers = trigger_onset(cft, trig_on, trig_off) for trigger in triggers: on = tr.stats.starttime + (trigger[0] / df) # off = tr.stats.starttime + (trigger[1] / df) wav_id = WaveformStreamID(station_code=tr.stats.station, channel_code=tr.stats.channel, network_code=tr.stats.network) pick = Pick(waveform_id=wav_id, phase_hint=phase, time=on) if debug > 2: print('Pick made:') print(pick) picks.append(pick) # QC picks del pick pick_stations = list(set([pick.waveform_id.station_code for pick in picks])) for pick_station in pick_stations: station_picks = [ pick for pick in picks if pick.waveform_id.station_code == pick_station ] # If P-pick is after S-picks, remove it. p_time = [ pick.time for pick in station_picks if pick.phase_hint == 'P' ] s_time = [ pick.time for pick in station_picks if pick.phase_hint == 'S' ] if p_time > s_time: p_pick = [pick for pick in station_picks if pick.phase_hint == 'P'] for pick in p_pick: print('P pick after S pick, removing P pick') picks.remove(pick) if show: plotting.pretty_template_plot(stream, picks=picks, title='Autopicks', size=(8, 9)) event.picks = picks event.origins[0].time = min([pick.time for pick in event.picks]) - 1 event.origins[0].latitude = float('nan') event.origins[0].longitude = float('nan') # Set arbitrary origin time return event
import obspy from obspy.signal.trigger import delayed_sta_lta, plot_trigger trace = obspy.read("https://examples.obspy.org/ev0_6.a01.gse2")[0] df = trace.stats.sampling_rate cft = delayed_sta_lta(trace.data, int(5 * df), int(10 * df)) plot_trigger(trace, cft, 5, 10)
def stalta_pick(stream, stalen, ltalen, trig_on, trig_off, freqmin=False, freqmax=False, debug=0, show=False): """ Basic sta/lta picker, suggest using alternative in obspy. Simple sta-lta (short-term average/long-term average) picker, using \ obspy's stalta routine to generate the characteristic function. Currently very basic quick wrapper, there are many other (better) options \ in obspy, found \ `here <http://docs.obspy.org/packages/autogen/obspy.signal.trigger.html>`_. :type stream: obspy.Stream :param stream: The stream to pick on, can be any number of channels. :type stalen: float :param stalen: Length of the short-term average window in seconds. :type ltalen: float :param ltalen: Length of the long-term average window in seconds. :type trig_on: float :param trig_on: sta/lta ratio to trigger a detection/pick :type trig_off: float :param trig_off: sta/lta ratio to turn the trigger off - no further picks\ will be made between exceeding trig_on until trig_off is reached. :type freqmin: float :param freqmin: Low-cut frequency in Hz for bandpass filter :type freqmax: float :param freqmax: High-cut frequency in Hz for bandpass filter :type debug: int :param debug: Debug output level from 0-5. :type show: bool :param show: Show picks on waveform. :returns: obspy.core.event.Event .. rubric:: Example >>> from obspy import read >>> from eqcorrscan.utils.picker import stalta_pick >>> st = read() >>> event = stalta_pick(st, stalen=0.2, ltalen=4, trig_on=10, ... trig_off=1, freqmin=3.0, freqmax=20.0) >>> event.creation_info.author 'EQcorrscan' """ from obspy.signal.trigger import classic_sta_lta, trigger_onset from obspy.signal.trigger import plot_trigger from obspy import UTCDateTime from obspy.core.event import Event, Pick, WaveformStreamID from obspy.core.event import CreationInfo, Comment, Origin import eqcorrscan.utils.plotting as plotting event = Event() event.origins.append(Origin()) event.creation_info = CreationInfo(author='EQcorrscan', creation_time=UTCDateTime()) event.comments.append(Comment(text='stalta')) picks = [] for tr in stream: # We are going to assume, for now, that if the pick is made on the # horizontal channel then it is an S, otherwise we will assume it is # a P-phase: obviously a bad assumption... if tr.stats.channel[-1] == 'Z': phase = 'P' else: phase = 'S' if freqmin and freqmax: tr.detrend('simple') tr.filter('bandpass', freqmin=freqmin, freqmax=freqmax, corners=3, zerophase=True) df = tr.stats.sampling_rate cft = classic_sta_lta(tr.data, int(stalen * df), int(ltalen * df)) if debug > 3: plot_trigger(tr, cft, trig_on, trig_off) triggers = trigger_onset(cft, trig_on, trig_off) for trigger in triggers: on = tr.stats.starttime + (trigger[0] / df) # off = tr.stats.starttime + (trigger[1] / df) wav_id = WaveformStreamID(station_code=tr.stats.station, channel_code=tr.stats.channel, network_code=tr.stats.network) pick = Pick(waveform_id=wav_id, phase_hint=phase, time=on) if debug > 2: print('Pick made:') print(pick) picks.append(pick) # QC picks del pick pick_stations = list(set([pick.waveform_id.station_code for pick in picks])) for pick_station in pick_stations: station_picks = [pick for pick in picks if pick.waveform_id.station_code == pick_station] # If P-pick is after S-picks, remove it. p_time = [pick.time for pick in station_picks if pick.phase_hint == 'P'] s_time = [pick.time for pick in station_picks if pick.phase_hint == 'S'] if p_time > s_time: p_pick = [pick for pick in station_picks if pick.phase_hint == 'P'] for pick in p_pick: print('P pick after S pick, removing P pick') picks.remove(pick) if show: plotting.pretty_template_plot(stream, picks=picks, title='Autopicks', size=(8, 9)) event.picks = picks event.origins[0].time = min([pick.time for pick in event.picks]) - 1 event.origins[0].latitude = float('nan') event.origins[0].longitude = float('nan') # Set arbitrary origin time return event
def trigger_events(self, ftmin, ftmax, nsta, nlta, thrsh1, thrsh2, num_trig, plot=True): """ Function to trigger events from continuous data. :param ftmin: lower corner frequency used for filtering prior to triggering :param ftmax: upper corner frequency used for filtering prior to triggering :param nsta: number of samples short term average :param nlta: number of samples long term average :param thrsh1: nsta/nlta threshold to trigger :param thrsh2: nsta/nlta threshold to stop trigger :param num_trig: number of stations required to eventually trigger an event :param plot: if true, gives an overview of triggered events """ print("TRIGGER EVENTS ...") print("STA: %i samples" % nsta) print("LTA: %i samples" % nlta) print("-------------------------------------------------") # trigger on continuous data from all array stations trig_times = {} dict_env_maxs = {} # read data for stn in self.stnlist: try: st = read(self.path2mseed + "%s/%s.D/4D.%s..%s.D.2016.%i" % (stn, self.chn, stn, self.chn, self.jday)) except: print("%s: no data!!!" % stn) print("skip this day!") sys.exit(1) # adjust sampling rate for tr in st: if tr.stats.sampling_rate != self.fs: tr.resample(self.fs) if self.decfact > 1: st.decimate(self.decfact) # trim and filter t1 = UTCDateTime(2016, 1, 1) t1.julday = self.jday t2 = t1 + 24. * 60. * 60. st.trim(t1, t2) dt = st[0].stats.delta st.filter("bandpass", freqmin=ftmin, freqmax=ftmax, zerophase=True) # for station, trigger all traces and count number of events n_ev = 0 for tr in st: cft = classic_sta_lta(tr.data, nsta, nlta) on_off = trigger_onset(cft, thrsh1, thrsh2) if plot: plot_trigger(tr, cft, thrsh1, thrsh2) if len(on_off) > 0: n_ev += on_off.shape[0] # trigger again and convert trigger time to timestring format ons = np.zeros(n_ev) offs = np.zeros(n_ev) ind = 0 for i, tr in enumerate(st): cft = classic_sta_lta(tr.data, nsta, nlta) trig = trigger_onset(cft, thrsh1, thrsh2) if len(trig) > 0: ons[ind:ind + trig.shape[0]] = trig.astype( float)[:, 0] * dt + tr.stats.starttime.timestamp offs[ind:ind + trig.shape[0]] = trig.astype( float)[:, 1] * dt + tr.stats.starttime.timestamp ind += trig.shape[0] # remove events which are triggered within one second after an event tt = 3. ind_del = [] for i in range(len(ons) - 1): print(ons[i + 1] - ons[i]) if (ons[i + 1] - ons[i]) < tt: ind_del.append(i + 1) ons = np.delete(ons, ind_del) offs = np.delete(offs, ind_del) print("%s: %i events detected!" % (stn, len(ons))) # recalculate on/off times (defined as the interval where the envelope is greater than 0.2 times its max) n = 0.4 p = 0.6 env_maxs = np.zeros(len(ons)) for i in range(len(ons)): ts = UTCDateTime(ons[i]) - n te = UTCDateTime(offs[i]) + p st_ = read(self.path2mseed + "%s/%s.D/4D.%s..%s.D.2016.%i" % (stn, self.chn, stn, self.chn, self.jday), starttime=ts - 5, endtime=te + 5) # adjust sampling rate for tr in st_: if tr.stats.sampling_rate != self.fs: tr.resample(self.fs) st_.filter("bandpass", freqmin=self.fmin, freqmax=self.fmax, zerophase=True) st_.trim(ts, te) # calc envelope env = obspy.signal.filter.envelope(st_[0].data) env_max = np.max(env) env_maxs[i] = ts.timestamp + np.argmax(env) * dt ind_greater = np.where(env >= 0.2 * env_max)[0] ediff = np.ediff1d(ind_greater) ind_greater = np.split(ind_greater, np.where(ediff != 1)[0] + 1) for j in range(len(ind_greater)): if np.argmax(env) in ind_greater[j]: ons[i] = ts.timestamp + ind_greater[j][0] * dt offs[i] = ts.timestamp + ind_greater[j][-1] * dt #plt.plot(st_[0].data) #plt.plot(env, "k:") #plt.plot(ind_greater[j], env[ind_greater[j]], "r") #plt.show() on_off_ = np.zeros((len(ons), 2)) on_off_[:, 0] = ons on_off_[:, 1] = offs trig_times[stn] = on_off_ dict_env_maxs[stn] = env_maxs # take only events which are triggered on at least num_trig stations (take travel time for very slow velocities # across the array radius as limit) tt = self.r / 1000. self.stnlist.sort() cstn = self.stnlist[4] on_off_ = [] env_max_PMx5 = dict_env_maxs[cstn] for i in range(len(env_max_PMx5)): env_PMx5 = env_max_PMx5[i] count = 0 for j in range(len(self.stnlist) - 1): stn = self.stnlist[j] ind = np.where(((dict_env_maxs[stn] - tt) < env_PMx5) & (env_PMx5 < (dict_env_maxs[stn] + tt)))[0] if len(ind) == 1: count += 1 if count >= (num_trig - 1): add = np.array(trig_times[cstn][i]) on_off_.append(add) print("--> %i events detected on >= %i stations!" % (len(on_off_), num_trig)) print("------------------------------------------") # convert to numpy array on_off = np.zeros((len(on_off_), 2)) for i in range(len(on_off_)): on_off[i, :] = on_off_[i] return on_off
import obspy from obspy.signal.trigger import carl_sta_trig, plot_trigger trace = obspy.read("http://examples.obspy.org/ev0_6.a01.gse2")[0] df = trace.stats.sampling_rate cft = carl_sta_trig(trace.data, int(5 * df), int(10 * df), 0.8, 0.8) plot_trigger(trace, cft, 20.0, -20.0)
#plot_trigger(event_trace[0], cft, 12, 5) trig = trigger_onset(cft,np.max(cft)*2/4, np.max(cft)*1/3) #pick = event_trace[0].stats.starttime + event_trace[0].stats.delta*trig[0,0] fig = plt.figure() fig.set_size_inches(15, 2) plt.xlim([t[trig[0,0]]-1,t[trig[0,0]]+1]) plt.plot(t,event_trace[i].data,'k') plt.axvline(t[trig[0,0]]) pick[0,i] = trig[0,0] # look at all the shots for station 1 and pick them shotpick_trace = read('/Volumes/research/users/mbodmer/TwoTowers_data/Two_Towers/SAC_Data/1/20160621*Z*', starttime=dt+35, endtime=dt+68) shotpick_trace.plot() df = shotpick_trace[0].stats.sampling_rate # sta lta picker cft = recursive_sta_lta(shotpick_trace[0].data, 5, 200) plot_trigger(shotpick_trace[0], cft, 25, 5) trig_picks = trigger_onset(cft,np.max(cft)*3/4, np.max(cft)*1/3) npts = shotpick_trace[0].stats.npts t = np.arange(npts, dtype=np.float32) / df print(t[trig_picks[:,0]])
S._cleanup() #ZNALAZLAM TO W METODZIE MERGE, ALE NIE ROZUMIEM PO CO TU TO JEST #Tego na razie nie robimy - to zrobimy potem #S.trim(ST-3600,ET+3600) print(S) print() Z = S.select(component="Z") print(Z) df = Z[0].stats.sampling_rate print("df=", df) Z.filter('lowpass', freq=1.0, corners=2, zerophase=True) cft = classic_sta_lta(Z[0].data, int(60 * df), int(180 * df)) print(cft) plot_trigger(Z[0], cft, 1.5, 0.5) #nie rozumiem skad 1.5 #Lista triggerow w zapisie True/False, czestosc zapisu - 100 Hz trig2 = [] num = [] for i in range(len(cft)): if cft[i] > 1.5: trig2.append(True) num.append(i) else: trig2.append(False) #zmniejszenie czestosci zapisu trig = [] for i in range(int(len(trig2) / 100)): if trig2[3 * i] == True or trig2[(3 * i) + 1] == True or trig2[(3 * i) +
def _channel_loop(tr, parameters, max_trigger_length=60, despike=False, debug=0): """ Internal loop for parellel processing. :type tr: obspy.core.trace :param tr: Trace to look for triggers in. :type parameters: list :param parameters: List of TriggerParameter class for trace. :type max_trigger_length: float :type despike: bool :type debug: int :return: trigger :rtype: list """ from eqcorrscan.utils.despike import median_filter from obspy.signal.trigger import trigger_onset, plot_trigger from obspy.signal.trigger import recursive_sta_lta import warnings for par in parameters: if par['station'] == tr.stats.station and \ par['channel'] == tr.stats.channel: parameter = par break else: msg = 'No parameters set for station ' + str(tr.stats.station) warnings.warn(msg) return [] triggers = [] if debug > 0: print(tr) tr.detrend('simple') if despike: median_filter(tr) if parameter['lowcut'] and parameter['highcut']: tr.filter('bandpass', freqmin=parameter['lowcut'], freqmax=parameter['highcut']) elif parameter['lowcut']: tr.filter('highpass', freq=parameter['lowcut']) elif parameter['highcut']: tr.filter('lowpass', freq=parameter['highcut']) # find triggers for each channel using recursive_sta_lta df = tr.stats.sampling_rate cft = recursive_sta_lta(tr.data, int(parameter['sta_len'] * df), int(parameter['lta_len'] * df)) if max_trigger_length: trig_args = {'max_len_delete': True} trig_args['max_len'] = int(max_trigger_length * df + 0.5) if debug > 3: plot_trigger(tr, cft, parameter['thr_on'], parameter['thr_off']) tmp_trigs = trigger_onset(cft, float(parameter['thr_on']), float(parameter['thr_off']), **trig_args) for on, off in tmp_trigs: cft_peak = tr.data[on:off].max() cft_std = tr.data[on:off].std() on = tr.stats.starttime + \ float(on) / tr.stats.sampling_rate off = tr.stats.starttime + \ float(off) / tr.stats.sampling_rate triggers.append( (on.timestamp, off.timestamp, tr.id, cft_peak, cft_std)) return triggers
trs_all = trace_all.slice(starttime=start, endtime=end) trs_low = trace_low.slice(starttime=start, endtime=end) #trs.filter("bandpass", freqmin=fmin,freqmax=fmax) #trs_e = obspy.signal.filter.envelope(trs.data) #print('reference waveform') trs_high.plot(type='relative', color='b') #, starttime=start , endtime=end) sr = trace_all.stats.sampling_rate nsta = int(8 * sr) nlta = int(60 * sr) stream = trs_all.data cft = recursive_sta_lta(stream, nsta, nlta) trig_on = 2 trig_off = 0.5 plot_trigger(trs_all, cft, trig_on, trig_off) on_off = trigger_onset(cft, trig_on, trig_off) #print("here 2") #%% catalogue = np.zeros(shape=(0, 1)) num = 0 shift2 = 200 shift = 10 for x in range(0, len(on_off)): event_h = trs_high[on_off[x, 0] - 2000:on_off[x, 1] + 2000] event_h2 = trs_high[on_off[x, 0] - 1000:on_off[x, 1] + 1000] event_a = trs_all[on_off[x, 0] - 2000:on_off[x, 1] + 2000] event_l = trs_low[on_off[x, 0] - 2000:on_off[x, 1] + 2000]
import obspy from obspy.signal.trigger import classic_STALTA, plot_trigger trace = obspy.read("http://examples.obspy.org/ev0_6.a01.gse2")[0] df = trace.stats.sampling_rate cft = classic_STALTA(trace.data, int(5.0 * df), int(10.0 * df)) plot_trigger(trace, cft, 1.5, 0.5)
def _channel_loop(tr, parameters, max_trigger_length=60, despike=False, debug=0): """ Internal loop for parellel processing. :type tr: obspy.core.trace :param tr: Trace to look for triggers in. :type parameters: list :param parameters: List of TriggerParameter class for trace. :type max_trigger_length: float :type despike: bool :type debug: int :return: trigger :rtype: list """ from eqcorrscan.utils.despike import median_filter from obspy.signal.trigger import trigger_onset, plot_trigger from obspy.signal.trigger import recursive_sta_lta import warnings for par in parameters: if par['station'] == tr.stats.station and \ par['channel'] == tr.stats.channel: parameter = par break else: msg = 'No parameters set for station ' + str(tr.stats.station) warnings.warn(msg) return [] triggers = [] if debug > 0: print(tr) tr.detrend('simple') if despike: median_filter(tr) if parameter['lowcut'] and parameter['highcut']: tr.filter('bandpass', freqmin=parameter['lowcut'], freqmax=parameter['highcut']) elif parameter['lowcut']: tr.filter('highpass', freq=parameter['lowcut']) elif parameter['highcut']: tr.filter('lowpass', freq=parameter['highcut']) # find triggers for each channel using recursive_sta_lta df = tr.stats.sampling_rate cft = recursive_sta_lta(tr.data, int(parameter['sta_len'] * df), int(parameter['lta_len'] * df)) if max_trigger_length: trig_args = {'max_len_delete': True} trig_args['max_len'] = int(max_trigger_length * df + 0.5) if debug > 3: plot_trigger(tr, cft, parameter['thr_on'], parameter['thr_off']) tmp_trigs = trigger_onset(cft, float(parameter['thr_on']), float(parameter['thr_off']), **trig_args) for on, off in tmp_trigs: cft_peak = tr.data[on:off].max() cft_std = tr.data[on:off].std() on = tr.stats.starttime + \ float(on) / tr.stats.sampling_rate off = tr.stats.starttime + \ float(off) / tr.stats.sampling_rate triggers.append((on.timestamp, off.timestamp, tr.id, cft_peak, cft_std)) return triggers
import obspy from obspy.signal.trigger import delayed_sta_lta, plot_trigger trace = obspy.read("http://examples.obspy.org/ev0_6.a01.gse2")[0] df = trace.stats.sampling_rate cft = delayed_sta_lta(trace.data, int(5 * df), int(10 * df)) plot_trigger(trace, cft, 5, 10)
trs = trace.slice( starttime=start, endtime=end ) #cut out sample waveform with same window length as chosen event #trs_e = obspy.signal.filter.envelope(trs.data) #print('reference waveform') trs.plot(type='relative', color='b') #, starttime=start , endtime=end) sr = trace.stats.sampling_rate nsta = int(2 * sr) #2 nlta = int(10 * sr) #20 stream = trs.data cft = recursive_sta_lta(stream, nsta, nlta) trig_on = 6 #8 trig_off = 0.2 #0.2 plot_trigger(trs, cft, trig_on, trig_off) on_off = trigger_onset(cft, trig_on, trig_off) for x in range(0, len(on_off)): tr = trace.slice(starttime=start + (on_off[x, 0] / sr) - 10, endtime=start + (on_off[x, 1] / sr) + 10) tr_e = obspy.signal.filter.envelope(tr.data) #%% frequency info tr_data = tr.data m = np.mean(tr_data) tr_data = tr_data - m famp = abs(np.fft.fft(tr_data)) # peak f
from obspy.signal.trigger import plot_trigger # Retrieve waveforms via ArcLink client = Client(host="erde.geophysik.uni-muenchen.de", port=18001, user="******") t = obspy.UTCDateTime("2009-08-24 00:19:45") st = client.get_waveforms('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 = recursive_sta_lta(tr.data, int(2.5 * df), int(10. * df)) on_of = trigger_onset(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() plot_trigger(tr, cft, 3.5, 0.5, show=True)