示例#1
0
    def realTimeDrumPlot(self):
        print('start ' + UTCDateTime.now().strftime("%Y%m%d %H%M%S"))
        appTrace = Stream()
        self._rtRunning = True
        for tr in self._traces:
            id = tr.get_id()
            spl = id.split('.')
            network = spl[0]
            station = spl[1]
            channel = spl[3]
            l = int(self._tEnd - tr.stats['endtime'])
            self._status[station] = {}
            self._status[station]["Noise Level"] = "---"
            self._status[station]["Latency"] = str(l) + 's'
            self._status[station]["Voltage"] = "---"
            self._status[station]["Color"] = "#FF0000"

            for b in band:
                fileNameRT = 'RT_' + network + '_' + station + '_' + channel + '_' + str(b) + '.png'
                appTrace = tr.copy()
                bb = band[b]
                appTrace.trim(self._tEnd - self._rTWindow * 60, self._tEnd, pad=True, fill_value=0)
                appTrace.filter('bandpass', freqmin=bb[0], freqmax=bb[1], corners=2, zerophase=True)
                self.plotDrum(appTrace, basePath + 'RT/' + fileNameRT)

        with open(basePath + 'RT/geophone_network_status.json', 'w') as fp:
            json.dump(self._status, fp)
            fp.close()

        print('end ' + UTCDateTime.now().strftime("%Y%m%d %H%M%S"))
        self._rtRunning = False
示例#2
0
    def hystDrumPlot(self):
        print('Hyststart ' + UTCDateTime.now().strftime("%Y%m%d %H%M%S"))
        appTrace = Stream()
        self._hyRunning = True

        for tr in self._traces:
            id = tr.get_id()
            # print('hyst '+id)
            spl = id.split('.')
            network = spl[0]
            station = spl[1]
            channel = spl[3]

            for h in hystType:

                if self._tEnd.hour % int(h / 60) == 0:
                    for b in band:
                        tStart = self._tEnd - h * 60
                        p = network + '/' + station + '/' + channel + '/' + str(self._tEnd.year) + '/' + str(
                            self._tEnd.month) + '/' + str(
                            self._tEnd.day) + '/' + str(h) + '/' + str(b)

                        fileName = p + '/' + tStart.strftime("%Y%m%d%H%M") + '_' + self._tEnd.strftime(
                            "%Y%m%d%H%M") + '.png'

                        appTrace = tr.copy()
                        bb = band[b]
                        appTrace.trim(tStart, self._tEnd, pad=True, fill_value=0)
                        appTrace.filter('bandpass', freqmin=bb[0], freqmax=bb[1], corners=2, zerophase=True)
                        self.plotDrum(appTrace, basePath + fileName)

        print('Hystend ' + UTCDateTime.now().strftime("%Y%m%d %H%M%S"))
        self._hyRunning = False
示例#3
0
def write_st(st: Stream,
             event: Event,
             outfolder: str,
             statxml: Inventory,
             resample: bool = True):
    """
    Write raw waveform data to an asdf file. This includes the corresponding
    (teleseismic) event and the station inventory (i.e., response information).

    :param st: The stream holding the raw waveform data.
    :type st: Stream
    :param event: The seismic event associated to the recorded data.
    :type event: Event
    :param outfolder: Output folder to write the asdf file to.
    :type outfolder: str
    :param statxml: The station inventory
    :type statxml: Inventory
    :param resample: Resample the data to 10Hz sampling rate? Defaults to True.
    :type resample: bool, optional
    """
    fname = '%s.%s.h5' % (st[0].stats.network, st[0].stats.station)
    if resample:
        st.filter('lowpass_cheby_2', freq=4, maxorder=12)
        st = resample_or_decimate(st, 10, filter=False)
    with ASDFDataSet(os.path.join(outfolder, fname)) as ds:
        # Events should not be added because it will read the whole
        # catalogue every single time!
        ds.add_waveforms(st, tag='raw_recording')
        ds.add_stationxml(statxml)  # If there are still problems, we will have
示例#4
0
文件: trigger.py 项目: jinwuLi/REDPy
def getData(tstart, tend, opt):

    """
    Download data from files in a folder, from IRIS, or a Earthworm waveserver
    
    A note on SAC/miniSEED files: as this makes no assumptions about the naming scheme of
    your data files, please ensure that your headers contain the correct SCNL information!

    tstart: UTCDateTime of beginning of period of interest
    tend: UTCDateTime of end of period of interest
    opt: Options object describing station/run parameters
    
    Returns ObsPy stream objects, one for cutting and the other for triggering
    """    
    
    nets = opt.network.split(',')
    stas = opt.station.split(',')
    locs = opt.location.split(',')
    chas = opt.channel.split(',')
    
    st = Stream()
    
    if opt.server == 'file':
    
        # Generate list of files
        if opt.server == 'file':
            flist = list(itertools.chain.from_iterable(glob.iglob(os.path.join(
                root,opt.filepattern)) for root, dirs, files in os.walk(opt.searchdir)))
                
        # Determine which subset of files to load based on start and end times and
        # station name; we'll fully deal with stations below
        flist_sub = []
        for f in flist:
            # Load header only
            stmp = obspy.read(f, headonly=True)
            # Check if station is contained in the stas list
            if stmp[0].stats.station in stas:
                # Check if contains either start or end time
                ststart = stmp[0].stats.starttime
                stend = stmp[-1].stats.endtime
                if (ststart<=tstart and tstart<=stend) or (ststart<=tend and
                    tend<=stend) or (tstart<=stend and ststart<=tend):
                    flist_sub.append(f)
        
        # Fully load data from file
        stmp = Stream()
        for f in flist_sub:
            tmp = obspy.read(f, starttime=tstart, endtime=tend+opt.maxdt)
            if len(tmp) > 0:
                stmp = stmp.extend(tmp)
    
        # Filter and merge
        stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax, corners=2,
            zerophase=True)
        stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
        for m in range(len(stmp)):
            if stmp[m].stats.sampling_rate != opt.samprate:
                stmp[m] = stmp[m].resample(opt.samprate)
        stmp = stmp.merge(method=1, fill_value=0)
        
        # Only grab stations/channels that we want and in order
        netlist = []
        stalist = []
        chalist = []
        loclist = []
        for s in stmp:
            stalist.append(s.stats.station)
            chalist.append(s.stats.channel)
            netlist.append(s.stats.network)
            loclist.append(s.stats.location)
            
        # Find match of SCNL in header or fill empty
        for n in range(len(stas)):
            for m in range(len(stalist)):
                if (stas[n] in stalist[m] and chas[n] in chalist[m] and nets[n] in
                    netlist[m] and locs[n] in loclist[m]):
                    st = st.append(stmp[m])
            if len(st) == n:
                print("Couldn't find "+stas[n]+'.'+chas[n]+'.'+nets[n]+'.'+locs[n])
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                st = st.append(trtmp.copy())
    
    else:   
     
        if '.' not in opt.server:
            client = Client(opt.server)
        else:
            client = EWClient(opt.server, opt.port)
        
        for n in range(len(stas)):
            try:
                stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                        tstart, tend+opt.maxdt)
                for m in range(len(stmp)):
                    stmp[m].data = np.where(stmp[m].data == -2**31, 0, stmp[m].data) # replace -2**31 (Winston NaN token) w 0
                stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax,
                    corners=2, zerophase=True)
                stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
                for m in range(len(stmp)):
                    if stmp[m].stats.sampling_rate != opt.samprate:
                        stmp[m] = stmp[m].resample(opt.samprate)
                stmp = stmp.merge(method=1, fill_value=0)
            except (obspy.clients.fdsn.header.FDSNException):
                try: # try again
                    stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                            tstart, tend+opt.maxdt)
                    for m in range(len(stmp)):
                        stmp[m].data = np.where(stmp[m].data == -2**31, 0, stmp[m].data) # replace -2**31 (Winston NaN token) w 0
                    stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax,
                        corners=2, zerophase=True)
                    stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
                    for m in range(len(stmp)):
                        if stmp[m].stats.sampling_rate != opt.samprate:
                            stmp[m] = stmp[m].resample(opt.samprate)
                    stmp = stmp.merge(method=1, fill_value=0)
                except (obspy.clients.fdsn.header.FDSNException):
                    print('No data found for {0}.{1}'.format(stas[n],nets[n]))
                    trtmp = Trace()
                    trtmp.stats.sampling_rate = opt.samprate
                    trtmp.stats.station = stas[n]
                    stmp = Stream().extend([trtmp.copy()])
                                            
            # Last check for length; catches problem with empty waveserver
            if len(stmp) != 1:
                print('No data found for {0}.{1}'.format(stas[n],nets[n]))
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                stmp = Stream().extend([trtmp.copy()])
                
            st.extend(stmp.copy()) 
    
    # Edit 'start' time if using offset option
    if opt.maxdt:
        dts = np.fromstring(opt.offset, sep=',')
        for n, tr in enumerate(st):
            tr.stats.starttime = tr.stats.starttime-dts[n]
    
    st = st.trim(starttime=tstart, endtime=tend, pad=True, fill_value=0)
    stC = st.copy()
    
    return st, stC
    'TOK.2011.328.21.10.54.OKR07.HHN.inv',
    'TOK.2011.328.21.10.54.OKR08.HHN.inv',
    'TOK.2011.328.21.10.54.OKR09.HHN.inv',
    'TOK.2011.328.21.10.54.OKR10.HHN.inv'
]
# Earthquakes' epicenter
eq_lat = 35.565
eq_lon = -96.792

# Reading the waveforms
st = Stream()
for waveform in files:
    st += read(host + waveform)

# Calculating distance from SAC headers lat/lon
# (trace.stats.sac.stla and trace.stats.sac.stlo)
for tr in st:
    tr.stats.distance = gps2DistAzimuth(tr.stats.sac.stla, tr.stats.sac.stlo,
                                        eq_lat, eq_lon)[0]
    # Setting Network name for plot title
    tr.stats.network = 'TOK'

st.filter('bandpass', freqmin=0.1, freqmax=10)
# Plot
st.plot(type='section',
        plot_dx=20e3,
        recordlength=100,
        time_down=True,
        linewidth=.25,
        grid_linewidth=.25)
AC.trim(startaim, endtaim, nearest_sample=True)
RLAS.trim(startaim, endtaim, nearest_sample=True)


# **Resample, Filter and Rotate**

# In[4]:



RLAS.decimate(factor=4)
AC.decimate(factor=4)
f_cutoff = 1.0

RLAS.filter('lowpass', freq=f_cutoff, corners=2, zerophase=True)
AC.filter('lowpass', freq=f_cutoff, corners=2, zerophase=True)

# event location from event info
source_latitude = event.origins[0].latitude
source_longitude = event.origins[0].longitude

# station location (Wettzell)
station_latitude = 49.144001
station_longitude = 12.8782

# theoretical backazimuth and distance
baz = gps2dist_azimuth(source_latitude, source_longitude, station_latitude, station_longitude)

print('Epicentral distance [m]: ',baz[0])
print('Theoretical azimuth [deg]: ', baz[1])
print('Theoretical backazimuth [deg]: ', baz[2])
        end = S_arr + 3 
    
        day_wf = glob.glob(stn + '/' + '*' + str(origin_time.year) + '.' + str(origin_time.julday))
        
        if len(day_wf) == 1:
            fmt_file_name = pwd + '/' + day_wf[0] 
        
        else:
            print('Error finding correct file')
         
        t = read(fmt_file_name)[0]
        traces += read(fmt_file_name,
                       starttime = begin,
                       endtime = end)
        
    st = Stream(traces)
    
    # store prefilter data
    if len(st) > 1:
        st.write('/auto/home/talongi/Cascadia/Code/NC_PI_events/MSEED/' + stn + '.SAC')
    
    st.filter('bandpass', freqmin = 1, freqmax = 10, zerophase = True)
    st.sort(['starttime'])
    
    plot_waveforms(st)
    
    wf_similarity = waveform_similarity(st, vmin = 0.4)

#save all figures to a PDF
multipage('/auto/home/talongi/Cascadia/Figures/06_waveforms/waveforms_cc_matrix.pdf')
示例#8
0
文件: trigger.py 项目: jconvers/REDPy
def getData(tstart, tend, opt):
    """
    Download data from files in a folder, from IRIS, or a Earthworm waveserver
    
    A note on SAC/miniSEED files: as this makes no assumptions about the naming scheme of
    your data files, please ensure that your headers contain the correct SCNL information!

    tstart: UTCDateTime of beginning of period of interest
    tend: UTCDateTime of end of period of interest
    opt: Options object describing station/run parameters
    
    Returns ObsPy stream objects, one for cutting and the other for triggering
    """

    nets = opt.network.split(',')
    stas = opt.station.split(',')
    locs = opt.location.split(',')
    chas = opt.channel.split(',')

    st = Stream()

    if opt.server == 'SAC' or opt.server == 'miniSEED':

        # Generate list of files
        if opt.server == 'SAC':
            flist = glob.glob(opt.sacdir + '*.sac') + glob.glob(opt.sacdir +
                                                                '*.SAC')
        elif opt.server == 'miniSEED':
            flist = glob.glob(opt.mseeddir +
                              '*.mseed') + glob.glob(opt.mseeddir + '*.MSEED')

        # Load data from file
        stmp = Stream()
        for f in flist:
            tmp = obspy.read(f, starttime=tstart, endtime=tend)
            if len(tmp) > 0:
                stmp = stmp.extend(tmp)

        # Filter and merge
        stmp = stmp.filter('bandpass',
                           freqmin=opt.fmin,
                           freqmax=opt.fmax,
                           corners=2,
                           zerophase=True)
        stmp = stmp.taper(0.05, type='hann', max_length=opt.mintrig)
        for m in range(len(stmp)):
            if stmp[m].stats.sampling_rate != opt.samprate:
                stmp[m] = stmp[m].resample(opt.samprate)
        stmp = stmp.merge(method=1, fill_value=0)

        # Only grab stations/channels that we want and in order
        netlist = []
        stalist = []
        chalist = []
        loclist = []
        for s in stmp:
            stalist.append(s.stats.station)
            chalist.append(s.stats.channel)
            netlist.append(s.stats.network)
            loclist.append(s.stats.location)

        # Find match of SCNL in header or fill empty
        for n in range(len(stas)):
            for m in range(len(stalist)):
                if (stas[n] in stalist[m] and chas[n] in chalist[m]
                        and nets[n] in netlist[m] and locs[n] in loclist[m]):
                    st = st.append(stmp[m])
            if len(st) == n:
                print("Couldn't find " + stas[n] + '.' + chas[n] + '.' +
                      nets[n] + '.' + locs[n])
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                st = st.append(trtmp.copy())

    else:

        if '.' not in opt.server:
            client = Client(opt.server)
        else:
            client = EWClient(opt.server, opt.port)

        for n in range(len(stas)):
            try:
                stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                                            tstart, tend)
                stmp = stmp.filter('bandpass',
                                   freqmin=opt.fmin,
                                   freqmax=opt.fmax,
                                   corners=2,
                                   zerophase=True)
                stmp = stmp.taper(0.05, type='hann', max_length=opt.mintrig)
                for m in range(len(stmp)):
                    if stmp[m].stats.sampling_rate != opt.samprate:
                        stmp[m] = stmp[m].resample(opt.samprate)
                stmp = stmp.merge(method=1, fill_value=0)
            except (obspy.fdsn.header.FDSNException):
                try:  # try again
                    stmp = client.get_waveforms(nets[n], stas[n], locs[n],
                                                chas[n], tstart, tend)
                    stmp = stmp.filter('bandpass',
                                       freqmin=opt.fmin,
                                       freqmax=opt.fmax,
                                       corners=2,
                                       zerophase=True)
                    stmp = stmp.taper(0.05,
                                      type='hann',
                                      max_length=opt.mintrig)
                    for m in range(len(stmp)):
                        if stmp[m].stats.sampling_rate != opt.samprate:
                            stmp[m] = stmp[m].resample(opt.samprate)
                    stmp = stmp.merge(method=1, fill_value=0)
                except (obspy.fdsn.header.FDSNException):
                    print('No data found for {0}.{1}'.format(stas[n], nets[n]))
                    trtmp = Trace()
                    trtmp.stats.sampling_rate = opt.samprate
                    trtmp.stats.station = stas[n]
                    stmp = Stream().extend([trtmp.copy()])
            st.extend(stmp.copy())

    st = st.trim(starttime=tstart, endtime=tend, pad=True, fill_value=0)
    stC = st.copy()

    return st, stC
示例#9
0
文件: trigger.py 项目: ahotovec/REDPy
def getData(tstart, tend, opt):

    """
    Download data from files in a folder, from IRIS, or a Earthworm waveserver
    
    A note on SAC/miniSEED files: as this makes no assumptions about the naming scheme of
    your data files, please ensure that your headers contain the correct SCNL information!

    tstart: UTCDateTime of beginning of period of interest
    tend: UTCDateTime of end of period of interest
    opt: Options object describing station/run parameters
    
    Returns ObsPy stream objects, one for cutting and the other for triggering
    """    
    
    nets = opt.network.split(',')
    stas = opt.station.split(',')
    locs = opt.location.split(',')
    chas = opt.channel.split(',')
    
    st = Stream()
    
    if opt.server == 'SAC' or opt.server == 'miniSEED':
    
        # Generate list of files
        if opt.server == 'SAC':
            flist = list(itertools.chain.from_iterable(glob.iglob(os.path.join(
                root,'*.sac')) for root, dirs, files in os.walk(opt.sacdir)))+list(
                itertools.chain.from_iterable(glob.iglob(os.path.join(
                root,'*.SAC')) for root, dirs, files in os.walk(opt.sacdir)))
        elif opt.server == 'miniSEED':
            flist = list(itertools.chain.from_iterable(glob.iglob(os.path.join(
                root,'*.mseed')) for root, dirs, files in os.walk(opt.mseeddir)))+list(
                itertools.chain.from_iterable(glob.iglob(os.path.join(
                root,'*.MSEED')) for root, dirs, files in os.walk(opt.mseeddir)))
                
        # Determine which subset of files to load based on start and end times and
        # station name; we'll fully deal with stations below
        flist_sub = []
        for f in flist:
            # Load header only
            stmp = obspy.read(f, headonly=True)
            # Check if station is contained in the stas list
            if stmp[0].stats.station in stas:
                # Check if contains either start or end time
                ststart = stmp[0].stats.starttime
                stend = stmp[0].stats.endtime
                if (ststart<=tstart and tstart<=stend) or (ststart<=tend and
                    tend<=stend) or (tstart<=stend and ststart<=tend):
                    flist_sub.append(f)
        
        # Fully load data from file
        stmp = Stream()
        for f in flist_sub:
            tmp = obspy.read(f, starttime=tstart, endtime=tend+opt.maxdt)
            if len(tmp) > 0:
                stmp = stmp.extend(tmp)
    
        # Filter and merge
        stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax, corners=2,
            zerophase=True)
        stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
        for m in range(len(stmp)):
            if stmp[m].stats.sampling_rate != opt.samprate:
                stmp[m] = stmp[m].resample(opt.samprate)
        stmp = stmp.merge(method=1, fill_value=0)
        
        # Only grab stations/channels that we want and in order
        netlist = []
        stalist = []
        chalist = []
        loclist = []
        for s in stmp:
            stalist.append(s.stats.station)
            chalist.append(s.stats.channel)
            netlist.append(s.stats.network)
            loclist.append(s.stats.location)
            
        # Find match of SCNL in header or fill empty
        for n in range(len(stas)):
            for m in range(len(stalist)):
                if (stas[n] in stalist[m] and chas[n] in chalist[m] and nets[n] in
                    netlist[m] and locs[n] in loclist[m]):
                    st = st.append(stmp[m])
            if len(st) == n:
                print("Couldn't find "+stas[n]+'.'+chas[n]+'.'+nets[n]+'.'+locs[n])
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                st = st.append(trtmp.copy())
    
    else:   
     
        if '.' not in opt.server:
            client = Client(opt.server)
        else:
            client = EWClient(opt.server, opt.port)
        
        for n in range(len(stas)):
            try:
                stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                        tstart, tend+opt.maxdt)
                stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax,
                    corners=2, zerophase=True)
                stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
                for m in range(len(stmp)):
                    if stmp[m].stats.sampling_rate != opt.samprate:
                        stmp[m] = stmp[m].resample(opt.samprate)
                stmp = stmp.merge(method=1, fill_value=0)
            except (obspy.clients.fdsn.header.FDSNException):
                try: # try again
                    stmp = client.get_waveforms(nets[n], stas[n], locs[n], chas[n],
                            tstart, tend+opt.maxdt)
                    stmp = stmp.filter('bandpass', freqmin=opt.fmin, freqmax=opt.fmax,
                        corners=2, zerophase=True)
                    stmp = stmp.taper(0.05,type='hann',max_length=opt.mintrig)
                    for m in range(len(stmp)):
                        if stmp[m].stats.sampling_rate != opt.samprate:
                            stmp[m] = stmp[m].resample(opt.samprate)
                    stmp = stmp.merge(method=1, fill_value=0)
                except (obspy.clients.fdsn.header.FDSNException):
                    print('No data found for {0}.{1}'.format(stas[n],nets[n]))
                    trtmp = Trace()
                    trtmp.stats.sampling_rate = opt.samprate
                    trtmp.stats.station = stas[n]
                    stmp = Stream().extend([trtmp.copy()])
                                            
            # Last check for length; catches problem with empty waveserver
            if len(stmp) != 1:
                print('No data found for {0}.{1}'.format(stas[n],nets[n]))
                trtmp = Trace()
                trtmp.stats.sampling_rate = opt.samprate
                trtmp.stats.station = stas[n]
                stmp = Stream().extend([trtmp.copy()])
                
            st.extend(stmp.copy()) 
    
    # Edit 'start' time if using offset option
    if opt.maxdt:
        dts = np.fromstring(opt.offset, sep=',')
        for n, tr in enumerate(st):
            tr.stats.starttime = tr.stats.starttime-dts[n]
    
    st = st.trim(starttime=tstart, endtime=tend, pad=True, fill_value=0)
    stC = st.copy()
    
    return st, stC
fig.tight_layout()
plt.show()
# -

# ### Resample, Filter and Rotate
# Resample seismograms using **decimate** in order to reduce the size of the arrays (speeds up processing).
# The seismograms are high-cut and low-cut filtered, depending on the frequency range of interest and the resolution of the instruments.

# +
RLAS.decimate(factor=4)
AC.decimate(factor=4)
high_cut = 1.0
low_cut = 0.005

RLAS.filter('bandpass', freqmax=high_cut, freqmin=low_cut, corners=2, zerophase=True)
AC.filter('bandpass', freqmax=high_cut, freqmin=low_cut, corners=2, zerophase=True)
# -

# In order to align the seismometer recordings with the event direction, we need to rotate the horizontal components<br>
# of the acceleration to transverse and radial.<br>
# <br>
# We can determine the theoretical rotation/direction angle (= backazimuth) from station and event location using **gps2dist_azimuth**.<br>
# This function also yields the epicentral distance and the azimuth angle.

# +
from obspy.geodetics.base import gps2dist_azimuth

# event location from event info
source_latitude = event.origins[0].latitude
source_longitude = event.origins[0].longitude
from obspy.core.util import gps2DistAzimuth

host = 'http://examples.obspy.org/'
# Files (fmt: SAC)
files = ['TOK.2011.328.21.10.54.OKR01.HHN.inv',
'TOK.2011.328.21.10.54.OKR02.HHN.inv', 'TOK.2011.328.21.10.54.OKR03.HHN.inv',
'TOK.2011.328.21.10.54.OKR04.HHN.inv', 'TOK.2011.328.21.10.54.OKR05.HHN.inv',
'TOK.2011.328.21.10.54.OKR06.HHN.inv', 'TOK.2011.328.21.10.54.OKR07.HHN.inv',
'TOK.2011.328.21.10.54.OKR08.HHN.inv', 'TOK.2011.328.21.10.54.OKR09.HHN.inv',
'TOK.2011.328.21.10.54.OKR10.HHN.inv']
# Earthquakes' epicenter
eq_lat = 35.565
eq_lon = -96.792

# Reading the waveforms
st = Stream()
for waveform in files:
	st += read(host + waveform)

# Calculating distance from SAC headers lat/lon
# (trace.stats.sac.stla and trace.stats.sac.stlo)
for tr in st:
	tr.stats.distance = gps2DistAzimuth(tr.stats.sac.stla,
									tr.stats.sac.stlo, eq_lat, eq_lon)[0]
	# Setting Network name for plot title
	tr.stats.network = 'TOK'

st.filter('bandpass', freqmin=0.1, freqmax=10)
# Plot
st.plot(type='section', plot_dx=20e3, recordlength=100,
			time_down=True, linewidth=.25, grid_linewidth=.25)
示例#12
0
def calculate_rf(data,
                 filter_config=config.FILTER_FREQ,
                 time_from=config.RF_TIME_FROM,
                 time_to=config.RF_TIME_TO,
                 zero_shift=0.):
    """
        input:
        [data] - obspy.core.stream.Stream object with event in LQT format.
            After function input [data] may be changed.
        [filter_config] (optional) - Python dictionary with keys 'FREQMIN' and 'FREQMAX',
            used in ObsPy 'boundpass' filter function.
        [time_from, time_to] (floats, optional)- result will contain data between
            [time_from] and [time_to] seconds. Time is measured from time 0.
        [zero_shift] (float, optional) - time 0 is set [zero_shift] seconds after theoretical
            time 0 (maximum in deconvolved L trace).
            Default value is 0. (float)
        [zero_date] (obspy.core.utcdatetime.UTCDateTime or convertable, optional)
            - time 0 is represented as [zero_date] time
        
        output: obspy.core.stream.Stream object containing
            calculated reveival function
    """
    assert time_from < time_to
    zero_date = _get_zero_date(data)

    # filtering
    data = data.filter('bandpass',
                       freqmin=filter_config['FREQMIN'],
                       freqmax=filter_config['FREQMAX'])

    # normalization
    if config.NORMALIZE_BEFORE:
        mx = max([np.max(t.data) for t in data.traces])
        mn = min([np.min(t.data) for t in data.traces])
        for tr in data.traces:
            tr.data /= mx - mn

    # counting receival function
    stL = data.select(component='L')
    stQ = data.select(component='Q')
    stT = data.select(component='T')

    rfQ, rfT, rfL = deconvolve(
        [stQ.traces[0].data, stT.traces[0].data, stL.traces[0].data],
        stL.traces[0].data)
    if config.REVERSE_QRF: rfQ = -rfQ
    if config.REVERSE_TRF: rfT = -rfT

    # setting "zero" moment
    freq = int(1 / stL.traces[0].stats['delta'])
    zero_pos = np.argmax(rfL) + int(freq * zero_shift)
    from_pos = zero_pos + int(time_from * freq)
    to_pos = zero_pos + int(time_to * freq)
    if from_pos < 0:
        rfQ = np.concatenate((np.zeros(-from_pos), rfQ))
        rfT = np.concatenate((np.zeros(-from_pos), rfT))
        to_pos += -from_pos
        from_pos = 0
    if to_pos > len(rfQ):
        rfQ = np.concatenate((rfQ, np.zeros(to_pos - len(rfQ))))
        rfT = np.concatenate((rfT, np.zeros(to_pos - len(rfT))))

    stQ.traces[0].data = rfQ[from_pos:to_pos]
    stT.traces[0].data = rfT[from_pos:to_pos]

    stQ.traces[0].stats.starttime = zero_date + time_from
    stT.traces[0].stats.starttime = zero_date + time_from

    stQ.traces[0].stats.channel = 'RFQ'
    stT.traces[0].stats.channel = 'RFT'

    data = Stream(stQ.traces + stT.traces)

    # filtering
    data = data.filter('bandpass',
                       freqmin=filter_config['FREQMIN'],
                       freqmax=filter_config['FREQMAX'])

    # normalization
    if config.NORMALIZE_AFTER:
        mx = max([np.max(t.data) for t in data.traces])
        mn = min([np.min(t.data) for t in data.traces])
        for tr in data.traces:
            tr.data /= mx - mn

    return data