def _internal_process(st, lowcut, highcut, filt_order, sampling_rate, first_length, stachan, i=0): tr = st.select(station=stachan[0], channel=stachan[1]) if len(tr) == 0: tr = Trace(np.zeros(int(first_length * sampling_rate))) tr.stats.station = stachan[0] tr.stats.channel = stachan[1] tr.stats.sampling_rate = sampling_rate tr.stats.starttime = st[0].stats.starttime # Do this to make more # sensible plots Logger.warning('Padding stream with zero trace for ' + 'station ' + stachan[0] + '.' + stachan[1]) elif len(tr) == 1: tr = tr[0] tr.detrend('simple') tr = pre_processing.process(tr=tr, lowcut=lowcut, highcut=highcut, filt_order=filt_order, samp_rate=sampling_rate, seisan_chan_names=False) else: raise IOError('Multiple channels for {0}.{1} in a single design ' 'stream.'.format(stachan[0], stachan[1])) return i, tr
def _get_all_motion_types(tr: obspy.Trace, motion_type: str) -> Dict: """Get a dict of all motion types. First detrend""" assert motion_type == "velocity" tr.detrend("linear") # init copies for performing transformations acc = tr.copy() dis = tr.copy() # perform integrations/differentiations dis.integrate() dis.detrend("linear") acc.differentiate() acc.detrend("linear") return dict(displacement=dis, velocity=tr, acceleration=acc)
def test_detrend(self): """ Test detrend method of trace """ t = np.arange(10) data = 0.1 * t + 1. tr = Trace(data=data.copy()) tr.detrend(type='simple') np.testing.assert_array_almost_equal(tr.data, np.zeros(10)) tr.data = data.copy() tr.detrend(type='linear') np.testing.assert_array_almost_equal(tr.data, np.zeros(10)) data = np.zeros(10) data[3:7] = 1. tr.data = data.copy() tr.detrend(type='simple') np.testing.assert_almost_equal(tr.data[0], 0.) np.testing.assert_almost_equal(tr.data[-1], 0.) tr.data = data.copy() tr.detrend(type='linear') np.testing.assert_almost_equal(tr.data[0], -0.4) np.testing.assert_almost_equal(tr.data[-1], -0.4)
def extract_s(taupy_model, pickerlist, event, station_longitude, station_latitude, stn, ste, ba, win_start=-50, win_end=50, resample_hz=20, bp_freqmins=[0.01, 0.01, 0.5], bp_freqmaxs=[1, 2., 5.], margin=None, max_amplitude=1e8, plot_output_folder=None): po = event.preferred_origin if (not po): return None atimes = [] try: atimes = taupy_model.get_travel_times_geo(po.depthkm, po.lat, po.lon, station_latitude, station_longitude, phase_list=('S', )) except: return None # end try if (len(atimes) == 0): return None tat = atimes[0].time # theoretical arrival time buffer_start = -10 buffer_end = 10 snrtr = None try: stn = stn.slice(po.utctime + tat + win_start + buffer_start, po.utctime + tat + win_end + buffer_end) stn = stn.copy() stn.resample(resample_hz) stn.detrend('linear') if (ste): ste = ste.slice(po.utctime + tat + win_start + buffer_start, po.utctime + tat + win_end + buffer_end) ste = ste.copy() ste.resample(resample_hz) ste.detrend('linear') # end if if (ste): if (type(stn[0].data) == np.ndarray and type(ste[0].data) == np.ndarray): rc, tc = rotate_ne_rt(stn[0].data, ste[0].data, ba) snrtr = Trace(data=tc, header=stn[0].stats) snrtr.detrend('linear') # end if else: if (type(stn[0].data) == np.ndarray): snrtr = stn[0] # end if # end if except Exception as e: return None # end try if (type(snrtr.data) == np.ndarray): if (np.max(snrtr.data) > max_amplitude): return None pickslist = [] snrlist = [] residuallist = [] bandindex = -1 pickerindex = -1 taper_percentage = float(buffer_end) / float(win_end) foundpicks = False for i in range(len(bp_freqmins)): trc = snrtr.copy() trc.taper(max_percentage=taper_percentage, type='hann') trc.filter('bandpass', freqmin=bp_freqmins[i], freqmax=bp_freqmaxs[i], corners=4, zerophase=True) trc = trc.slice(po.utctime + tat + win_start, po.utctime + tat + win_end) for ipicker, picker in enumerate(pickerlist): try: scnl, picks, polarity, snr, uncert = picker.picks(trc) for ipick, pick in enumerate(picks): actualArrival = pick - po.utctime residual = actualArrival - tat if ((margin and np.fabs(residual) < margin) or (margin == None)): pickslist.append(pick) plotinfo = None if (plot_output_folder): plotinfo = { 'eventid': event.public_id, 'origintime': po.utctime, 'mag': event.preferred_magnitude.magnitude_value, 'net': trc.stats.network, 'sta': trc.stats.station, 'phase': 's', 'ppsnr': snr[ipick], 'pickid': ipick, 'outputfolder': plot_output_folder } # end if wab = snrtr.slice(pick - 3, pick + 3) wab_filtered = trc.slice(pick - 3, pick + 3) scales = np.logspace(0.5, 4, 30) cwtsnr, dom_freq, slope_ratio = compute_quality_measures( wab, wab_filtered, scales, plotinfo) snrlist.append( [snr[ipick], cwtsnr, dom_freq, slope_ratio]) residuallist.append(residual) bandindex = i pickerindex = ipicker foundpicks = True # end if # end for except: continue # end try if (foundpicks): break # end for if (foundpicks): break # end for if (len(pickslist)): return pickslist, residuallist, \ np.array(snrlist), bandindex, pickerindex # end if # end if return None
str(day), str(tr.stats.station), str(tr.stats.channel), ) if os.path.exists(finpc1) and os.path.getsize(finpc1) > 0: try: st = read(finpc1, starttime=t1, endtime=t2) if len(st) != 0: st.merge(method=1, fill_value=0) tc = st[0] stat = tc.stats.station chan = tc.stats.channel tc.detrend("constant") # 24h continuous trace starts 00 h 00 m 00.0s trim_fill(tc, t1, t2) tc.filter( "bandpass", freqmin=bandpass[0], freqmax=bandpass[1], zerophase=True, ) # store detrended and filtered continuous data # in a Stream stream_df += Stream(traces=[tc]) except IOError: pass
def extract_s(taupy_model, picker, event, station_longitude, station_latitude, stn, ste, ba, win_start=-50, win_end=50, resample_hz=20, bp_freqmins=[0.05, 2], bp_freqmaxs=[0.5, 5], margin=20, max_amplitude=1e8): po = event.preferred_origin if (not po): return None atimes = [] try: atimes = taupy_model.get_travel_times_geo(po.depthkm, po.lat, po.lon, station_latitude, station_longitude, phase_list=('S', )) except: return None # end try if (len(atimes) == 0): return None tat = atimes[0].time # theoretical arrival time tr = None try: stn = stn.slice(po.utctime + tat + win_start, po.utctime + tat + win_end) stn.resample(resample_hz) if (ste): ste = ste.slice(po.utctime + tat + win_start, po.utctime + tat + win_end) ste.resample(resample_hz) # end if if (ste): if (type(stn[0].data) == np.ndarray and type(ste[0].data) == np.ndarray): rc, tc = rotate_ne_rt(stn[0].data, ste[0].data, ba) tr = Trace(data=tc, header=stn[0].stats) #tr = Trace(data=np.sqrt(np.power(rc,2) + np.power(tc,2)), header=stn[0].stats) # end if else: if (type(stn[0].data) == np.ndarray): tr = stn[0] # end if # end if except Exception as e: return None # end try if (tr): if (np.max(tr.data) > max_amplitude): return None pickslist = [] snrlist = [] residuallist = [] tr.detrend('linear') for i in range(len(bp_freqmins)): trc = tr.copy() trc.filter('bandpass', freqmin=bp_freqmins[i], freqmax=bp_freqmaxs[i], corners=4, zerophase=True) try: scnl, picks, polarity, snr, uncert = picker.picks(trc) for ipick, pick in enumerate(picks): actualArrival = pick - po.utctime residual = actualArrival - tat if (np.fabs(residual) < margin): pickslist.append(pick) snrlist.append(snr[ipick]) residuallist.append(residual) #summary = fbpicker.FBSummary(picker, trc) #summary = aicdpicker.AICDSummary(picker, trc) #outputPath = '/home/rakib/work/pst/picking/sarr' #outputPath = '/g/data1a/ha3/rakib/seismic/pst/tests/plots/new' #ofn = '%s/%s.%s_%f_%d.s.png' % (outputPath, scnl, str(po.utctime), snr[0], i) #summary.plot_picks(show=False, savefn=ofn) # end if # end for except: continue # end try # end for if (len(pickslist)): optimal_pick_idx = np.argmax(np.array(snrlist)) return pickslist[optimal_pick_idx], residuallist[optimal_pick_idx], \ snrlist[optimal_pick_idx], optimal_pick_idx # end if # end if return None
def simulate_trace( self, max_amplitude: float = 1e-4, width: float = 0.2, noise: bool = False, ) -> Tuple[Trace, Event, float, float]: """ Make a wood-anderson trace and convolve it with a response. """ from scipy.signal import ricker # Make dummy data in meters on Wood Anderson np.random.seed(42) if noise: data = np.random.randn(int(self.sampling_rate * self.length)) else: data = np.zeros(int(self.sampling_rate * self.length)) wavelet = ricker( int(self.sampling_rate * self.length), a=(width * self.sampling_rate / 4)) wavelet /= wavelet.max() wavelet *= max_amplitude vals = sorted([(val, ind) for ind, val in enumerate(wavelet)], key=lambda x: x[0]) period = abs(vals[0][1] - vals[1][1]) / self.sampling_rate half_max = (wavelet.max() - wavelet.min()) / 2 data += wavelet # Make dummy trace tr = Trace(data=data, header=dict( station=self.inv[0][0].code, network=self.inv[0].code, location=self.inv[0][0][0].location_code, channel=self.inv[0][0][0].code, sampling_rate=self.sampling_rate, starttime=UTCDateTime(2020, 1, 1))) tr = tr.detrend() # Remove Wood-Anderson response and simulate seismometer resp = self.inv[0][0][0].response paz = resp.get_paz() paz = { 'poles': paz.poles, 'zeros': paz.zeros, 'gain': paz.normalization_factor, 'sensitivity': resp.instrument_sensitivity.value, } tr = tr.simulate( paz_remove=PAZ_WA, paz_simulate=paz) # Make an event mid_point = tr.stats.starttime + 0.5 * ( tr.stats.endtime - tr.stats.starttime) event = Event(picks=[ Pick(phase_hint="P", time=mid_point - 3.0, waveform_id=WaveformStreamID( network_code=tr.stats.network, station_code=tr.stats.station, location_code=tr.stats.location, channel_code=tr.stats.channel)), Pick(phase_hint="S", time=mid_point, waveform_id=WaveformStreamID( network_code=tr.stats.network, station_code=tr.stats.station, location_code=tr.stats.location, channel_code=tr.stats.channel))]) return tr, event, period, half_max