示例#1
0
 def test_bandpassVsPitsa(self):
     """
     Test Butterworth bandpass filter against Butterworth bandpass filter
     of PITSA. Note that the corners value is twice the value of the filter
     sections in PITSA. The rms of the difference between ObsPy and PITSA
     tends to get bigger with higher order filtering.
     """
     # load test file
     file = os.path.join(self.path, 'rjob_20051006.gz')
     f = gzip.open(file)
     data = np.loadtxt(f)
     f.close()
     # parameters for the test
     samp_rate = 200.0
     freq1 = 5
     freq2 = 10
     corners = 4
     # filter trace
     datcorr = bandpass(data, freq1, freq2, df=samp_rate, corners=corners)
     # load pitsa file
     file = os.path.join(self.path, 'rjob_20051006_bandpass.gz')
     f = gzip.open(file)
     data_pitsa = np.loadtxt(f)
     f.close()
     # calculate normalized rms
     rms = np.sqrt(np.sum((datcorr - data_pitsa) ** 2) /
                   np.sum(data_pitsa ** 2))
     self.assertEqual(rms < 1.0e-05, True)
示例#2
0
 def test_bandpassZPHSHVsPitsa(self):
     """
     Test Butterworth zero-phase bandpass filter against Butterworth
     zero-phase bandpass filter of PITSA. Note that the corners value is
     twice the value of the filter sections in PITSA. The rms of the
     difference between ObsPy and PITSA tends to get bigger with higher
     order filtering.
     Note: The Zero-Phase filters deviate from PITSA's zero-phase filters
     at the end of the trace! The rms for the test is calculated omitting
     the last 200 samples, as this part of the trace is assumed to
     generally be of low interest/importance.
     """
     # load test file
     file = os.path.join(self.path, 'rjob_20051006.gz')
     f = gzip.open(file)
     data = np.loadtxt(f)
     f.close()
     # parameters for the test
     samp_rate = 200.0
     freq1 = 5
     freq2 = 10
     corners = 2
     # filter trace
     datcorr = bandpass(data, freq1, freq2, df=samp_rate,
                        corners=corners, zerophase=True)
     # load pitsa file
     file = os.path.join(self.path, 'rjob_20051006_bandpassZPHSH.gz')
     f = gzip.open(file)
     data_pitsa = np.loadtxt(f)
     f.close()
     # calculate normalized rms
     rms = np.sqrt(np.sum((datcorr[:-200] - data_pitsa[:-200]) ** 2) /
                   np.sum(data_pitsa[:-200] ** 2))
     self.assertEqual(rms < 1.0e-05, True)
示例#3
0
 def test_bandpassVsPitsa(self):
     """
     Test Butterworth bandpass filter against Butterworth bandpass filter
     of PITSA. Note that the corners value is twice the value of the filter
     sections in PITSA. The rms of the difference between ObsPy and PITSA
     tends to get bigger with higher order filtering.
     """
     # load test file
     file = os.path.join(self.path, 'rjob_20051006.gz')
     f = gzip.open(file)
     data = np.loadtxt(f)
     f.close()
     # parameters for the test
     samp_rate = 200.0
     freq1 = 5
     freq2 = 10
     corners = 4
     # filter trace
     datcorr = bandpass(data, freq1, freq2, df=samp_rate, corners=corners)
     # load pitsa file
     file = os.path.join(self.path, 'rjob_20051006_bandpass.gz')
     f = gzip.open(file)
     data_pitsa = np.loadtxt(f)
     f.close()
     # calculate normalized rms
     rms = np.sqrt(np.sum((datcorr - data_pitsa) ** 2) /
                   np.sum(data_pitsa ** 2))
     self.assertEqual(rms < 1.0e-05, True)
示例#4
0
  def filter(self):
    """ Filter data for each band.
    """
    n_bands = self._N_bands()
    LEN = self.tr.stats.npts
    df = self.tr.stats.sampling_rate

    # create zeros 2D array for BF
    BF = np.zeros(shape = (n_bands,LEN))

    for j in range(n_bands):
      octave_high = (self.freqmin + self.freqmin * 2.0) / 2.0 * (2**j)
      octave_low = octave_high / 2.0
      BF[j] = bandpass(self.tr.data, octave_low, octave_high, df, corners = self.cnr, zerophase = False)
      BF[j] = cosTaper(LEN, self.perc_taper) * BF[j]

    return BF
示例#5
0
 def test_bandpassZPHSHVsPitsa(self):
     """
     Test Butterworth zero-phase bandpass filter against Butterworth
     zero-phase bandpass filter of PITSA. Note that the corners value is
     twice the value of the filter sections in PITSA. The rms of the
     difference between ObsPy and PITSA tends to get bigger with higher
     order filtering.
     Note: The Zero-Phase filters deviate from PITSA's zero-phase filters
     at the end of the trace! The rms for the test is calculated omitting
     the last 200 samples, as this part of the trace is assumed to
     generally be of low interest/importance.
     """
     # load test file
     file = os.path.join(self.path, 'rjob_20051006.gz')
     f = gzip.open(file)
     data = np.loadtxt(f)
     f.close()
     # parameters for the test
     samp_rate = 200.0
     freq1 = 5
     freq2 = 10
     corners = 2
     # filter trace
     datcorr = bandpass(data,
                        freq1,
                        freq2,
                        df=samp_rate,
                        corners=corners,
                        zerophase=True)
     # load pitsa file
     file = os.path.join(self.path, 'rjob_20051006_bandpassZPHSH.gz')
     f = gzip.open(file)
     data_pitsa = np.loadtxt(f)
     f.close()
     # calculate normalized rms
     rms = np.sqrt(
         np.sum((datcorr[:-200] - data_pitsa[:-200])**2) /
         np.sum(data_pitsa[:-200]**2))
     self.assertEqual(rms < 1.0e-05, True)
示例#6
0
    def filter(self):
        """ Filter data for each band.
    """
        n_bands = self._N_bands()
        LEN = self.tr.stats.npts
        df = self.tr.stats.sampling_rate

        # create zeros 2D array for BF
        BF = np.zeros(shape=(n_bands, LEN))

        for j in range(n_bands):
            octave_high = (self.freqmin + self.freqmin * 2.0) / 2.0 * (2**j)
            octave_low = octave_high / 2.0
            BF[j] = bandpass(self.tr.data,
                             octave_low,
                             octave_high,
                             df,
                             corners=self.cnr,
                             zerophase=False)
            BF[j] = cosTaper(LEN, self.perc_taper) * BF[j]

        return BF
示例#7
0
                str(stime.julday).zfill(3) + '/' + locs[0] + '_' + sr +
                'H2.512.seed')
    st2 += read('/tr1/telemetry_days/' + stas[1] + '/2016/2016_' +
                str(stime.julday).zfill(3) + '/' + locs[1] + '_' + sr +
                'H2.512.seed')

    st2 += read('/tr1/telemetry_days/' + stas[2] + '/2016/2016_' +
                str(stime.julday).zfill(3) + '/' + locs[2] + '_' + sr +
                'H2.512.seed')

    st2.trim(starttime=stime, endtime=etime)
    st2.detrend('constant')
    for tr in st1:
        #tr.data /= paz['sensitivity']

        tr.data = bandpass(tr.data, 1. / 10., 1., 1. / delta, 4, False)
        tr.taper(0.05)
    for tr in st2:
        #tr.data /= paz['sensitivity']
        tr.data = bandpass(tr.data, 1. / 10., 1., 1. / delta, 4, False)
        tr.taper(0.05)

    #Sensor 1 and 2
    def rot1(theta):
        theta = theta % 360.
        cosd = np.cos(np.deg2rad(theta))
        sind = np.sin(np.deg2rad(theta))
        data1 = cosd * st1[0].data - sind * st2[0].data
        data2 = sind * st1[0].data + cosd * st2[0].data
        resi = abs(
            sum(data1 * st1[1].data) /
示例#8
0
        )[1] != last_id or tr.stats.starttime - last_endtime > 1.0 / df:
            data_buf = np.array([], dtype='float64')
            olap = 0
        while samp < tr.stats.npts:
            data = tr.data[samp:samp + nfft - olap].astype('float64')
            data = np.concatenate((data_buf, data))
            data = detrend(data)
            # Correct for frequency response of instrument
            data = seisSim(data,
                           df,
                           paz_remove=tr.stats.paz,
                           paz_simulate=inst,
                           remove_sensitivity=True)
            # XXX is removed in seisSim... ?!
            # XXX data /= (paz['sensitivity'] / 1e9)  #V/nm/s correct for overall sensitivity
            data = bandpass(data, LOW, HIGH, df)
            data = recStalta(data, s2p(STA, tr), s2p(LTA, tr))
            picked_values = triggerOnset(data, ON, OFF, max_len=overlap)
            #
            for i, j in picked_values:
                begin = tr.stats.starttime + float(i + samp - olap) / df
                end = tr.stats.starttime + float(j + samp - olap) / df
                trigger_list.append(
                    (begin.timestamp, end.timestamp, tr.stats.station))
            olap = overlap  # only needed for first time in loop
            samp += nfft - overlap
            data_buf = data[-overlap:]
        last_endtime, last_id = trId(tr.stats)

###############################################################################
# start of coincidence part
示例#9
0
def Find_wav_kurt(x,h,g,h1,h2,h3,nlevel,Sc,Fr,opt,Fs=1):
    # [c,Bw,fc,i] = Find_wav_kurt(x,h,g,h1,h2,h3,nlevel,Sc,Fr,opt2)
    # Sc = -log2(Bw)-1 with Bw the bandwidth of the filter
    # Fr is in [0 .5]
    #
    # -------------------
    # J. Antoni : 12/2004
    # -------------------
    level = np.fix((Sc))+ ((Sc%1) >= 0.5) * (np.log2(3)-1)
    Bw = 2**(-level-1)
    freq_w = np.arange(0,2**(level-1)) / 2**(level+1) + Bw/2.
    J = np.argmin(np.abs(freq_w-Fr))
    fc = freq_w[J]
    i = int(np.round(fc/Bw-1./2))
    if level % 1 == 0:
        acoeff = binary(i, level)
        bcoeff = np.array([])
        temp_level = level
    else:
        i2 = np.fix((i/3.))
        temp_level = np.fix((level))-1
        acoeff = binary(i2,temp_level)
        bcoeff = np.array([i-i2*3,])
    acoeff = acoeff[::-1]
    c = K_wpQ_filt(x,h,g,h1,h2,h3,acoeff,bcoeff,temp_level)
    kx = kurt(c,opt)
    
    print "kx", kx
    
    sig = np.median(np.abs(c))/np.sqrt(np.pi/2.)
    print sig
    threshold = sig*raylinv(np.array([.999,]),np.array([1,]))
    print "threshold", threshold
    #~ spec = int(raw_input('	Do you want to see the envelope spectrum (yes = 1 ; no = 0): '))
    spec = 1
    
    t = np.arange(len(x))/Fs
    tc = np.linspace(t[0],t[-1],len(c))
    
    fig = plt.figure()
    ax1 = plt.subplot(2+spec,1,1)
    plt.plot(t,x,'k',label='Original Signal')
    #~ plt.plot(tc,(c/np.max(c))*np.max(np.abs(x)),c='r',label='Filtered Signal')
    
    from obspy.signal import bandpass, envelope
    plt.plot(t,bandpass(x,Fr,Fr+50./32,Fs,corners=2),label='Obspy Filterded Signal')
    
    plt.legend()
    plt.grid(True)
    plt.subplot(2+spec,1,2,sharex=ax1)
    plt.plot(tc,np.abs(c),'k')
    #~ plt.plot(tc,envelope(c),'k')
    #~ plt.plot(tc,threshold*np.ones(len(c)),'--r')
    plt.axhline(threshold,c='r')
    
    
    for ti in tc[ np.where(np.abs(c) >= threshold)[0]]:
        plt.axvline(ti,c='g',zorder=-1)
        ax1.axvline(ti,c='g',zorder=-1)
    
    #~ plt.title('Envlp of the filtr sgl, Bw=Fs/2^{'+(level+1)+'}, fc='+(Fs*fc)+'Hz, Kurt='+(np.round(np.abs(10*kx))/10)+', \alpha=.1%']
    plt.xlabel('time [s]')
    plt.grid(True)
    if spec == 1:
        #~ print nextpow2(len(c))
        nfft = int(nextpow2(len(c)))
        env = np.abs(c)**2
        S = np.abs(np.fft.fft(env.ravel()-np.mean(env)*np.hanning(len(env))/len(env),nfft))
        f = np.linspace(0, 0.5*Fs/2**level,nfft/2)
        plt.subplot(313)
        plt.plot(f,S[:nfft/2],'k')
        plt.title('Fourier transform magnitude of the squared envelope')
        plt.xlabel('frequency [Hz]')
        plt.grid(True)
    plt.show()
    return [c,Bw,fc]
示例#10
0
        overlap = s2p(30.0, tr)
        olap = overlap
        samp = 0
        df = tr.stats.sampling_rate
        if trId(tr.stats)[1] != last_id or tr.stats.starttime - last_endtime > 1.0 / df:
            data_buf = np.array([], dtype='float64')
            olap = 0
        while samp < tr.stats.npts:
            data = tr.data[samp:samp + nfft - olap].astype('float64')
            data = np.concatenate((data_buf, data))
            data = detrend(data)
            # Correct for frequency response of instrument
            data = seisSim(data, df, paz_remove=tr.stats.paz, paz_simulate=inst, remove_sensitivity=True)
            # XXX is removed in seisSim... ?!
            # XXX data /= (paz['sensitivity'] / 1e9)  #V/nm/s correct for overall sensitivity
            data = bandpass(data, LOW, HIGH, df)
            data = recStalta(data, s2p(STA, tr), s2p(LTA, tr))
            picked_values = triggerOnset(data, ON, OFF, max_len=overlap)
            #
            for i, j in picked_values:
                 begin = tr.stats.starttime + float(i + samp - olap) / df
                 end = tr.stats.starttime + float(j + samp - olap) / df
                 trigger_list.append((begin.timestamp, end.timestamp, tr.stats.station))
            olap = overlap # only needed for first time in loop
            samp += nfft - overlap
            data_buf = data[-overlap:]
        last_endtime, last_id = trId(tr.stats)

###############################################################################
# start of coincidence part
###############################################################################