예제 #1
0
 def direct_wave_aftan(self, process_id='', verbose=False):
     """direct wave aftan
     """
     inftan = self.inftan
     if verbose:
         self.print_info(process_id=process_id)
     chan1 = self.channel[0]
     chan2 = self.channel[1]
     staid1 = self.netcode1 + '.' + self.stacode1
     staid2 = self.netcode2 + '.' + self.stacode2
     if not os.path.isdir(self.datadir + '/logs_dw_aftan/' + staid1):
         try:
             os.makedirs(self.datadir + '/logs_dw_aftan/' + staid1)
         except OSError:
             i = 0
             while (i < 10):
                 sleep_time = np.random.random() / 10.
                 time.sleep(sleep_time)
                 if not os.path.isdir(self.datadir + '/logs_dw_aftan/' +
                                      staid1):
                     try:
                         os.makedirs(self.datadir + '/logs_dw_aftan/' +
                                     staid1)
                         break
                     except OSError:
                         pass
                 i += 1
     logfname = self.datadir + '/logs_dw_aftan/' + staid1 + '/' + staid1 + '_' + staid2 + '.log'
     is_continue = False
     if os.path.isfile(logfname):
         with open(logfname, 'r') as fid:
             logflag = fid.readlines()[0].split()[0]
             if logflag == 'RUNNING':
                 is_continue = True
     with open(logfname, 'w') as fid:
         fid.writelines('RUNNING\n')
     if len(glob.glob(self.datadir + '/SYNC_C3/'+staid1+'/C3_'+staid1+'_'+chan1+'_'+staid2+'_'+chan2+'_*ELL.SAC')) > 0 or \
         len(glob.glob(self.datadir + '/SYNC_C3/'+staid1+'/C3_'+staid1+'_'+chan1+'_'+staid2+'_'+chan2+'_*HYP.SAC')) > 0:
         is_sync = True
     elif len(glob.glob(self.datadir + '/ASYNC_C3/'+staid1+'/C3_'+staid1+'_'+chan1+'_'+staid2+'_'+chan2+'_*ELL.SAC')) > 0 or \
         len(glob.glob(self.datadir + '/ASYNC_C3/'+staid1+'/C3_'+staid1+'_'+chan1+'_'+staid2+'_'+chan2+'_*HYP.SAC')) > 0:
         is_sync = False
     else:
         with open(logfname, 'w') as fid:
             fid.writelines('NODATA\n')
         return
     dist0, az0, baz0 = obspy.geodetics.gps2dist_azimuth(
         self.stla1, self.stlo1, self.stla2, self.stlo2)
     dist0 /= 1000.
     if is_sync:
         ellflst = glob.glob(self.datadir + '/SYNC_C3/' + staid1 + '/C3_' +
                             staid1 + '_' + chan1 + '_' + staid2 + '_' +
                             chan2 + '_*ELL.SAC')
         hyplst = glob.glob(self.datadir + '/SYNC_C3/' + staid1 + '/C3_' +
                            staid1 + '_' + chan1 + '_' + staid2 + '_' +
                            chan2 + '_*HYP.SAC')
     else:
         ellflst = glob.glob(self.datadir + '/ASYNC_C3/' + staid1 + '/C3_' +
                             staid1 + '_' + chan1 + '_' + staid2 + '_' +
                             chan2 + '_*ELL.SAC')
         hyplst = glob.glob(self.datadir + '/ASYNC_C3/' + staid1 + '/C3_' +
                            staid1 + '_' + chan1 + '_' + staid2 + '_' +
                            chan2 + '_*HYP.SAC')
     # source station in elliptical stationary phase zone
     ell_piover4 = -2.
     for ellfname in ellflst:
         if is_continue:
             ellnpz = ellfname[:-3] + 'npz'
             if os.path.isfile(ellnpz):
                 continue
             else:
                 is_continue = False
                 print('!!! DELETE DUE TO SEGMENTATION FAULT: ' + ellfname)
                 os.remove(ellfname)
                 continue
         elltr = obspy.read(ellfname)[0]
         ell_atr = pyaftan.aftantrace(elltr.data, elltr.stats)
         ell_atr.stats.sac.dist = dist0 + ell_atr.stats.sac.user0  # distance correction
         phvelname = self.prephdir + "/%s.%s.pre" % (staid1, staid2)
         if not os.path.isfile(phvelname):
             # print ('*** WARNING: '+ phvelname+' not exists!')
             continue
         # aftan analysis
         if self.f77:
             ell_atr.aftanf77(pmf=inftan.pmf,
                              piover4=ell_piover4,
                              vmin=inftan.vmin,
                              vmax=inftan.vmax,
                              tmin=inftan.tmin,
                              tmax=inftan.tmax,
                              tresh=inftan.tresh,
                              ffact=inftan.ffact,
                              taperl=inftan.taperl,
                              snr=inftan.snr,
                              fmatch=inftan.fmatch,
                              nfin=inftan.nfin,
                              npoints=inftan.npoints,
                              perc=inftan.perc,
                              phvelname=phvelname)
         else:
             ell_atr.aftan(pmf=inftan.pmf,
                           piover4=ell_piover4,
                           vmin=inftan.vmin,
                           vmax=inftan.vmax,
                           tmin=inftan.tmin,
                           tmax=inftan.tmax,
                           tresh=inftan.tresh,
                           ffact=inftan.ffact,
                           taperl=inftan.taperl,
                           snr=inftan.snr,
                           fmatch=inftan.fmatch,
                           nfin=inftan.nfin,
                           npoints=inftan.npoints,
                           perc=inftan.perc,
                           phvelname=phvelname)
         # SNR
         ell_atr.get_snr(ffact=inftan.ffact)
         # save aftan
         outdispfname = ellfname[:-4] + '.npz'
         outarr = np.array([dist0, ell_atr.stats.sac.user0])
         ell_atr.ftanparam.write_npz(outfname=outdispfname, outarr=outarr)
     # source station in hypobolic stationary phase zone
     hyp_piover4 = 0.
     for hypfname in hyplst:
         if is_continue:
             hypnpz = hypfname[:-3] + 'npz'
             if os.path.isfile(hypnpz):
                 continue
             else:
                 is_continue = False
                 print('!!! DELETE DUE TO SEGMENTATION FAULT: ' + hypfname)
                 os.remove(hypfname)
                 continue
         hyptr = obspy.read(hypfname)[0]
         hyp_atr = pyaftan.aftantrace(hyptr.data, hyptr.stats)
         hyp_atr.makesym()
         hyp_atr.stats.sac.dist = dist0 + hyp_atr.stats.sac.user0  # distance correction
         phvelname = self.prephdir + "/%s.%s.pre" % (staid1, staid2)
         if not os.path.isfile(phvelname):
             # print ('*** WARNING: '+ phvelname+' not exists!')
             continue
         # aftan analysis
         if self.f77:
             hyp_atr.aftanf77(pmf=inftan.pmf,
                              piover4=hyp_piover4,
                              vmin=inftan.vmin,
                              vmax=inftan.vmax,
                              tmin=inftan.tmin,
                              tmax=inftan.tmax,
                              tresh=inftan.tresh,
                              ffact=inftan.ffact,
                              taperl=inftan.taperl,
                              snr=inftan.snr,
                              fmatch=inftan.fmatch,
                              nfin=inftan.nfin,
                              npoints=inftan.npoints,
                              perc=inftan.perc,
                              phvelname=phvelname)
         else:
             hyp_atr.aftan(pmf=inftan.pmf,
                           piover4=hyp_piover4,
                           vmin=inftan.vmin,
                           vmax=inftan.vmax,
                           tmin=inftan.tmin,
                           tmax=inftan.tmax,
                           tresh=inftan.tresh,
                           ffact=inftan.ffact,
                           taperl=inftan.taperl,
                           snr=inftan.snr,
                           fmatch=inftan.fmatch,
                           nfin=inftan.nfin,
                           npoints=inftan.npoints,
                           perc=inftan.perc,
                           phvelname=phvelname)
         # SNR
         hyp_atr.get_snr(ffact=inftan.ffact)
         # save aftan
         outdispfname = hypfname[:-4] + '.npz'
         outarr = np.array([dist0, hyp_atr.stats.sac.user0])
         hyp_atr.ftanparam.write_npz(outfname=outdispfname, outarr=outarr)
     with open(logfname, 'w') as fid:
         fid.writelines('SUCCESS\n')
     # # # if len(ellflst) > 0 or len(hyplst) > 0:
     # # #     with open(logfname, 'w') as fid:
     # # #         fid.writelines('SUCCESS\n')
     # # # else:
     # # #     with open(logfname, 'w') as fid:
     # # #         fid.writelines('NODATA\n')
     return
예제 #2
0
 def direct_wave_interfere(self,
                           process_id='',
                           verbose=False,
                           verbose2=False):
     """direct wave interferometry
     """
     if verbose:
         self.print_info(process_id=process_id)
     chan1 = self.channel[0]
     chan2 = self.channel[1]
     dist0, az0, baz0 = obspy.geodetics.gps2dist_azimuth(
         self.stla1, self.stlo1, self.stla2, self.stlo2)
     dist0 /= 1000.
     staid1 = self.netcode1 + '.' + self.stacode1
     staid2 = self.netcode2 + '.' + self.stacode2
     #=============
     # log file
     #=============
     if not os.path.isdir(self.datadir + '/logs_dw_interfere/' + staid1):
         try:
             os.makedirs(self.datadir + '/logs_dw_interfere/' + staid1)
         except OSError:
             i = 0
             while (i < 10):
                 sleep_time = np.random.random() / 10.
                 time.sleep(sleep_time)
                 if not os.path.isdir(self.datadir + '/logs_dw_interfere/' +
                                      staid1):
                     try:
                         os.makedirs(self.datadir + '/logs_dw_interfere/' +
                                     staid1)
                         break
                     except OSError:
                         pass
                 i += 1
     logfname = self.datadir + '/logs_dw_interfere/' + staid1 + '/' + staid1 + '_' + staid2 + '.log'
     # # # is_continue = False
     # # # if os.path.isfile(logfname):
     # # #     with open(logfname, 'r') as fid:
     # # #         logflag = fid.readlines()[0].split()[0]
     # # #         if logflag == 'RUNNING':
     # # #             is_continue = True
     with open(logfname, 'w') as fid:
         fid.writelines('RUNNING\n')
     xcorrpattern = self.datadir + '/COR/' + staid1 + '/COR_' + staid1 + '_??' + chan1 + '_' + staid2 + '_??' + chan2 + '.SAC'
     if len(glob.glob(xcorrpattern)) > 0:
         outdir = self.outdir + '/SYNC_C3/' + staid1
     else:
         outdir = self.outdir + '/ASYNC_C3/' + staid1
     Ntraces = 0
     # loop over source stations
     for srcnet in self.StationInv:
         for srcsta in srcnet:
             sourceid = srcnet.code + '.' + srcsta.code
             if sourceid == staid1 or sourceid == staid2:
                 continue
             evla = srcsta.latitude
             evlo = srcsta.longitude
             dist1, az1, baz1 = obspy.geodetics.gps2dist_azimuth(
                 evla, evlo, self.stla1, self.stlo1)
             dist2, az2, baz2 = obspy.geodetics.gps2dist_azimuth(
                 evla, evlo, self.stla2, self.stlo2)
             dist1 /= 1000.
             dist2 /= 1000.
             dhyp = dist0 - abs(dist1 - dist2)
             dell = dist1 + dist2 - dist0
             if abs(dhyp - dell) < self.dthresh:
                 if verbose2:
                     print('!!! SKIP c3: %s_%s source: %s' %
                           (staid1, staid2, sourceid))
                 continue
             # not in stationary phase zone
             if min(dhyp, dell) > dist0 * self.alpha:
                 continue
             if dell < dhyp:
                 iellhyp = 1
             else:
                 iellhyp = 2
             # load xcorr data
             # station 1
             if staid1 < sourceid:
                 datadir1 = self.datadir + '/COR/' + staid1
                 fpattern1 = datadir1 + '/COR_' + staid1 + '_??' + chan1 + '_' + sourceid + '_??' + chan1 + '.SAC'
             else:
                 datadir1 = self.datadir + '/COR/' + sourceid
                 fpattern1 = datadir1 + '/COR_' + sourceid + '_??' + chan1 + '_' + staid1 + '_??' + chan1 + '.SAC'
             flst1 = glob.glob(fpattern1)
             if len(flst1) == 0:
                 continue
             fname1 = flst1[0]
             # station 2
             if staid2 < sourceid:
                 datadir2 = self.datadir + '/COR/' + staid2
                 fpattern2 = datadir2 + '/COR_' + staid2 + '_??' + chan2 + '_' + sourceid + '_??' + chan2 + '.SAC'
             else:
                 datadir2 = self.datadir + '/COR/' + sourceid
                 fpattern2 = datadir2 + '/COR_' + sourceid + '_??' + chan2 + '_' + staid2 + '_??' + chan2 + '.SAC'
             flst2 = glob.glob(fpattern2)
             if len(flst2) == 0:
                 continue
             fname2 = flst2[0]
             # load data, get symmetric components
             tr1 = obspy.read(fname1)[0]
             outsactr = obspy.io.sac.SACTrace.from_obspy_trace(tr1.copy())
             tr1 = pyaftan.aftantrace(tr1.data, tr1.stats)
             tr1.makesym()
             tr2 = obspy.read(fname2)[0]
             tr2 = pyaftan.aftantrace(tr2.data, tr2.stats)
             tr2.makesym()
             if abs(tr1.stats.delta - tr2.stats.delta) > min(
                     tr1.stats.delta / 1000., tr2.stats.delta / 1000.):
                 raise AttributeError(
                     '!!! xcorr must have the same sampling rate!')
             if iellhyp == 1:
                 outdata = scipy.signal.convolve(tr1.data,
                                                 tr2.data,
                                                 mode='full',
                                                 method='fft')
             else:
                 outdata = scipy.signal.correlate(tr1.data,
                                                  tr2.data,
                                                  mode='full',
                                                  method='fft')
             # data
             outsactr.data = outdata
             #==================
             # update headers
             #==================
             if iellhyp == 1:
                 outsactr.b += tr1.stats.sac.e
             outsactr.kuser0 = self.netcode1
             outsactr.kevnm = self.stacode1
             outsactr.knetwk = self.netcode2
             outsactr.kstnm = self.stacode2
             outsactr.evla = self.stla1
             outsactr.evlo = self.stlo1
             outsactr.stla = self.stla2
             outsactr.stlo = self.stlo2
             outsactr.dist = dist0
             outsactr.az = az0
             outsactr.baz = baz0
             # source station
             outsactr.kuser1 = srcnet.code
             outsactr.kuser2 = srcsta.code
             if iellhyp == 1:
                 outsactr.user0 = dell
             else:
                 outsactr.user0 = -dhyp
             outsactr.user1 = srcsta.latitude
             outsactr.user2 = srcsta.longitude
             outsactr.kcmpnm = self.channel
             # save data
             if not os.path.isdir(outdir):
                 try:
                     os.makedirs(outdir)
                 except OSError:
                     i = 0
                     while (i < 10):
                         sleep_time = np.random.random() / 10.
                         time.sleep(sleep_time)
                         if not os.path.isdir(outdir):
                             try:
                                 os.makedirs(outdir)
                                 break
                             except OSError:
                                 pass
                         i += 1
             if iellhyp == 1:
                 outfname = outdir + '/C3_' + staid1 + '_' + chan1 + '_' + staid2 + '_' + chan2 + '_' + sourceid + '_ELL.SAC'
             else:
                 outfname = outdir + '/C3_' + staid1 + '_' + chan1 + '_' + staid2 + '_' + chan2 + '_' + sourceid + '_HYP.SAC'
             try:
                 outsactr.write(outfname)
             except Exception:
                 continue
             Ntraces += 1
     # log file
     if Ntraces == 0:
         with open(logfname, 'w') as fid:
             fid.writelines('NODATA\n')
     else:
         with open(logfname, 'w') as fid:
             fid.writelines('SUCCESS\n')
     return Ntraces
예제 #3
0
 def aftan(self, prephdir, ic2c3 = 1, channel = 'ZZ', outdir = None, inftan = pyaftan.InputFtanParam(),\
     basic1 = True, basic2 = True, pmf1 = True, pmf2 = True, verbose = False, f77 = True):
     """ aftan analysis of cross-correlation data 
     =======================================================================================
     ::: input parameters :::
     prephdir    - directory for predicted phase velocity dispersion curve
     ic2c3       - index for xcorr or C3 ( 1 - xcorr; 2 - C3)
     channel     - channel pair for aftan analysis(e.g. 'ZZ', 'TT', 'ZR', 'RZ'...)
     outdir      - directory for output disp txt files (default = None, no txt output)
     inftan      - input aftan parameters
     basic1      - save basic aftan results or not
     basic2      - save basic aftan results(with jump correction) or not
     pmf1        - save pmf aftan results or not
     pmf2        - save pmf aftan results(with jump correction) or not
     f77         - use aftanf77 or not
     ---------------------------------------------------------------------------------------
     ::: output :::
     self.auxiliary_data.DISPbasic1, self.auxiliary_data.DISPbasic2,
     self.auxiliary_data.DISPpmf1, self.auxiliary_data.DISPpmf2
     =======================================================================================
     """
     if ic2c3 == 1:
         pfx     = 'DISP'
     elif ic2c3 == 2:
         pfx     = 'C3DISP'
     else:
         raise ValueError('Unexpected ic2c3 = %d' %ic2c3)
     print ('[%s] [AFTAN] start aftan analysis' %datetime.now().isoformat().split('.')[0])
     staLst                      = self.waveforms.list()
     Nsta                        = len(staLst)
     Ntotal_traces               = int(Nsta*(Nsta-1)/2)
     iaftan                      = 0
     Ntr_one_percent             = int(Ntotal_traces/100.)
     ipercent                    = 0
     for staid1 in staLst:
         netcode1, stacode1      = staid1.split('.')
         for staid2 in staLst:
             netcode2, stacode2  = staid2.split('.')
             if staid1 >= staid2:
                 continue
             # print how many traces has been processed
             iaftan              += 1
             if np.fmod(iaftan, Ntr_one_percent) ==0:
                 ipercent        += 1
                 print ('[%s] [AFTAN] Number of traces finished : ' %datetime.now().isoformat().split('.')[0] \
                        +str(iaftan)+'/'+str(Ntotal_traces)+' '+str(ipercent)+'%')
             # determine channels and get data
             if ic2c3 == 1:
                 try:
                     channels1       = self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2].list()
                     for chan in channels1:
                         if chan[-1] == channel[0]:
                             chan1   = chan
                             break
                     channels2       = self.auxiliary_data.NoiseXcorr[netcode1][stacode1][netcode2][stacode2][chan1].list()
                     for chan in channels2:
                         if chan[-1] == channel[1]:
                             chan2   = chan
                             break
                 except KeyError:
                     continue
                 tr                  = self.get_xcorr_trace(netcode1, stacode1, netcode2, stacode2, chan1, chan2)
             elif ic2c3 == 2:
                 tr                  = self.get_c3_trace(netcode1, stacode1, netcode2, stacode2, channel[0], channel[1])
             if tr is None:
                 # print ('*** WARNING: '+netcode1+'.'+stacode1+'_'+chan1+'_'+netcode2+'.'+stacode2+'_'+chan2+' not exists!')
                 continue
             #================
             # aftan analysis
             #================
             aftanTr             = pyaftan.aftantrace(tr.data, tr.stats)
             if abs(aftanTr.stats.sac.b + aftanTr.stats.sac.e) < aftanTr.stats.delta :
                 aftanTr.makesym()
             phvelname           = prephdir + "/%s.%s.pre" %(netcode1+'.'+stacode1, netcode2+'.'+stacode2)
             if not os.path.isfile(phvelname):
                 print ('*** WARNING: '+ phvelname+' not exists!')
                 continue
             if f77:
                 aftanTr.aftanf77(pmf=inftan.pmf, piover4=inftan.piover4, vmin=inftan.vmin, vmax=inftan.vmax, tmin=inftan.tmin, tmax=inftan.tmax,
                     tresh=inftan.tresh, ffact=inftan.ffact, taperl=inftan.taperl, snr=inftan.snr, fmatch=inftan.fmatch, nfin=inftan.nfin,
                         npoints=inftan.npoints, perc=inftan.perc, phvelname=phvelname)
             else:
                 aftanTr.aftan(pmf=inftan.pmf, piover4=inftan.piover4, vmin=inftan.vmin, vmax=inftan.vmax, tmin=inftan.tmin, tmax=inftan.tmax,
                     tresh=inftan.tresh, ffact=inftan.ffact, taperl=inftan.taperl, snr=inftan.snr, fmatch=inftan.fmatch, nfin=inftan.nfin,
                         npoints=inftan.npoints, perc=inftan.perc, phvelname=phvelname)
             if verbose:
                 print ('--- aftan analysis for: ' + netcode1+'.'+stacode1+'_'+netcode2+'.'+stacode2+'_'+channel)
             # SNR
             aftanTr.get_snr(ffact = inftan.ffact) 
             staid_aux           = netcode1+'/'+stacode1+'/'+netcode2+'/'+stacode2+'/'+channel
             #=====================================
             # save aftan results to ASDF dataset
             #=====================================
             if basic1:
                 parameters      = {'Tc': 0, 'To': 1, 'U': 2, 'C': 3, 'ampdb': 4, 'dis': 5, 'snrdb': 6,\
                                         'mhw': 7, 'amp': 8, 'Np': aftanTr.ftanparam.nfout1_1}
                 self.add_auxiliary_data(data = aftanTr.ftanparam.arr1_1, data_type = pfx + 'basic1',\
                                         path = staid_aux, parameters = parameters)
             if basic2:
                 parameters      = {'Tc': 0, 'To': 1, 'U': 2, 'C': 3, 'ampdb': 4, 'snrdb': 5, 'mhw': 6,\
                                         'amp': 7, 'Np': aftanTr.ftanparam.nfout2_1}
                 self.add_auxiliary_data(data = aftanTr.ftanparam.arr2_1, data_type = pfx + 'basic2',\
                                         path = staid_aux, parameters = parameters)
             if inftan.pmf:
                 if pmf1:
                     parameters  = {'Tc': 0, 'To': 1, 'U': 2, 'C': 3, 'ampdb': 4, 'dis': 5, 'snrdb': 6,\
                                         'mhw': 7, 'amp': 8, 'Np': aftanTr.ftanparam.nfout1_2}
                     self.add_auxiliary_data(data = aftanTr.ftanparam.arr1_2, data_type = pfx + 'pmf1',\
                                         path = staid_aux, parameters = parameters)
                 if pmf2:
                     parameters  = {'Tc': 0, 'To': 1, 'U': 2, 'C': 3, 'ampdb': 4, 'snrdb': 5, 'mhw': 6,\
                                         'amp': 7, 'snr':8, 'Np': aftanTr.ftanparam.nfout2_2}
                     self.add_auxiliary_data(data = aftanTr.ftanparam.arr2_2, data_type = pfx + 'pmf2',\
                                         path = staid_aux, parameters = parameters)
             if outdir is not None:
                 if not os.path.isdir(outdir+'/'+pfx+'/'+staid1):
                     os.makedirs(outdir+'/'+pfx+'/'+staid1)
                 foutPR  = outdir+'/'+pfx+'/'+netcode1+'.'+stacode1+'/'+ \
                             pfx+'_'+netcode1+'.'+stacode1+'_'+chan1+'_'+netcode2+'.'+stacode2+'_'+chan2+'.SAC'
                 aftanTr.ftanparam.writeDISP(foutPR)
     print ('[%s] [AFTAN] aftan analysis done' %datetime.now().isoformat().split('.')[0])
     return
예제 #4
0
 def aftan(self, prephdir, sps = 1., channel = 'Z', outdir = None, inftan = pyaftan.InputFtanParam(),\
         basic1 = True, basic2 = True, pmf1 = True, pmf2 = True, verbose = False, f77 = True, pfx = 'DISP',
         walltimeinhours = None, walltimetol = 2000., startind = 1):
     """ aftan analysis of earthquake data 
     =======================================================================================
     ::: input parameters :::
     prephdir    - directory for predicted phase velocity dispersion curve
     sps         - target sampling rate
     channel     - channel pair for aftan analysis('Z', 'R', 'T')
     outdir      - directory for output disp txt files (default = None, no txt output)
     inftan      - input aftan parameters
     basic1      - save basic aftan results or not
     basic2      - save basic aftan results(with jump correction) or not
     pmf1        - save pmf aftan results or not
     pmf2        - save pmf aftan results(with jump correction) or not
     f77         - use aftanf77 or not
     pfx         - prefix for output txt DISP files
     ---------------------------------------------------------------------------------------
     ::: output :::
     self.auxiliary_data.DISPbasic1, self.auxiliary_data.DISPbasic2,
     self.auxiliary_data.DISPpmf1, self.auxiliary_data.DISPpmf2
     =======================================================================================
     """
     print('[%s] [AFTAN] start aftan analysis' %
           datetime.now().isoformat().split('.')[0])
     if walltimeinhours != None:
         walltime = walltimeinhours * 3600.
     else:
         walltime = 1e10
     stime4compute = timeit.default_timer()
     try:
         print(self.cat)
     except AttributeError:
         self.copy_catalog()
     if len(self.cat) >= 10000:
         raise ValueError('number of events is larger than 10000')
     # Loop over stations
     Nsta = len(self.waveforms.list())
     ista = startind - 1
     for staid in (self.waveforms.list())[(startind - 1):]:
         etime4compute = timeit.default_timer()
         if etime4compute - stime4compute > walltime - walltimetol:
             print(
                 '================================== End computation due to walltime ======================================'
             )
             print('start from ' + str(ista + 1) + ' next run!')
             break
         netcode, stacode = staid.split('.')
         ista += 1
         print ('[%s] [AFTAN] Station ID: %s %d/%d' %(datetime.now().isoformat().split('.')[0], \
                        staid, ista, Nsta))
         issucess = False
         with warnings.catch_warnings():
             warnings.simplefilter("ignore")
             for i in range(10):
                 try:
                     tmppos = self.waveforms[staid].coordinates
                     issucess = True
                     break
                 except Exception:
                     pass
         if not issucess:
             print('ERROR: station: %s' % staid)
             continue
         stla = tmppos['latitude']
         stlo = tmppos['longitude']
         stz = tmppos['elevation_in_m']
         outstr = ''
         issucess = False
         for i in range(10):
             try:
                 taglst = self.waveforms[staid].get_waveform_tags()
                 issucess = True
                 break
             except Exception:
                 pass
         if not issucess:
             print('ERROR: station: %s' % staid)
             continue
         # # # # try:
         # # # #     taglst      = self.waveforms[staid].get_waveform_tags()
         # # # # except Exception:
         # # # #     print ('ERROR: station: %s' %staid)
         # # # #     continue
         if len(taglst) == 0:
             print('!!! No data for station: ' + staid)
             continue
         # Loop over tags(events)
         ievent = 0
         Ndata = 0
         for event in self.cat:
             ievent += 1
             evid = 'E%04d' % (ievent)  # evid,
             pmag = event.preferred_magnitude()
             magnitude = pmag.mag
             Mtype = pmag.magnitude_type
             event_descrip = event.event_descriptions[
                 0].text + ', ' + event.event_descriptions[0].type
             porigin = event.preferred_origin()
             otime = porigin.time
             timestr = otime.isoformat()
             evlo = porigin.longitude
             evla = porigin.latitude
             try:
                 evdp = porigin.depth / 1000.
             except:
                 continue
             event_id = event.resource_id.id.split('=')[-1]
             timestr = otime.isoformat()
             oyear = otime.year
             omonth = otime.month
             oday = otime.day
             ohour = otime.hour
             omin = otime.minute
             osec = otime.second
             label = '%d_%d_%d_%d_%d_%d' % (oyear, omonth, oday, ohour,
                                            omin, osec)
             tag = 'surf_' + label
             if not tag in taglst:
                 continue
             staid_aux = netcode + '_' + stacode + '_' + channel
             try:
                 if tag in self.auxiliary_data['DISPbasic1'].list():
                     if staid_aux in self.auxiliary_data['DISPbasic1'][
                             tag].list():
                         continue
             except:
                 pass
             dist, az, baz = obspy.geodetics.gps2dist_azimuth(
                 evla, evlo, stla, stlo)  # distance is in m
             dist = dist / 1000.
             if baz < 0:
                 baz += 360.
             #-------------------
             # get waveform data
             #-------------------
             try:
                 inST = self.waveforms[staid][tag].select(component=channel)
             except:
                 continue
             if len(inST) == 0:
                 continue
             else:
                 if len(inST) > 1:
                     print('!!! WARNING: more traces stored: ' + tag +
                           ' station: ' + staid)
                 tr = inST[0]
             # resample
             target_dt = 1. / sps
             dt = tr.stats.delta
             if abs(dt - target_dt) > (min(dt, target_dt)) / 100.:
                 factor = np.round(target_dt / dt)
                 if abs(factor * dt - target_dt) < min(
                         dt, target_dt / 1000.):
                     dt = target_dt / factor
                     tr.stats.delta = dt
                 else:
                     print(target_dt, dt)
                     raise ValueError('CHECK!' + staid)
                 tr.filter(type='lowpass', freq=sps / 2.,
                           zerophase=True)  # prefilter
                 tr.decimate(factor=int(factor), no_filter=True)
                 # # # try:
                 # # #     tr.filter(type = 'lowpass', freq = sps/2., zerophase = True) # prefilter
                 # # #     tr.decimate(factor = int(factor), no_filter = True)
                 # # # except:
                 # # #     continue
             else:
                 tr.stats.delta = target_dt
             stime = tr.stats.starttime
             etime = tr.stats.endtime
             tr.stats.sac = {}
             tr.stats.sac['dist'] = dist
             tr.stats.sac['b'] = stime - otime
             tr.stats.sac['e'] = etime - otime
             aftanTr = pyaftan.aftantrace(tr.data, tr.stats)
             phvelname = prephdir + "/%s.%s.pre" % (evid, staid)
             if not os.path.isfile(phvelname):
                 print('*** WARNING: ' + phvelname + ' not exists!')
                 continue
             if f77:
                 aftanTr.aftanf77(pmf=inftan.pmf,
                                  piover4=inftan.piover4,
                                  vmin=inftan.vmin,
                                  vmax=inftan.vmax,
                                  tmin=inftan.tmin,
                                  tmax=inftan.tmax,
                                  tresh=inftan.tresh,
                                  ffact=inftan.ffact,
                                  taperl=inftan.taperl,
                                  snr=inftan.snr,
                                  fmatch=inftan.fmatch,
                                  nfin=inftan.nfin,
                                  npoints=inftan.npoints,
                                  perc=inftan.perc,
                                  phvelname=phvelname)
             else:
                 aftanTr.aftan(pmf=inftan.pmf,
                               piover4=inftan.piover4,
                               vmin=inftan.vmin,
                               vmax=inftan.vmax,
                               tmin=inftan.tmin,
                               tmax=inftan.tmax,
                               tresh=inftan.tresh,
                               ffact=inftan.ffact,
                               taperl=inftan.taperl,
                               snr=inftan.snr,
                               fmatch=inftan.fmatch,
                               nfin=inftan.nfin,
                               npoints=inftan.npoints,
                               perc=inftan.perc,
                               phvelname=phvelname)
             aftanTr.get_snr(ffact=inftan.ffact)  # SNR analysis
             staid_aux = tag + '/' + netcode + '_' + stacode + '_' + channel
             #-----------------------------------
             # save aftan results to ASDF dataset
             #-----------------------------------
             if basic1:
                 parameters = {
                     'Tc': 0,
                     'To': 1,
                     'U': 2,
                     'C': 3,
                     'ampdb': 4,
                     'dis': 5,
                     'snrdb': 6,
                     'mhw': 7,
                     'amp': 8,
                     'Np': aftanTr.ftanparam.nfout1_1
                 }
                 self.add_auxiliary_data(data = aftanTr.ftanparam.arr1_1, data_type = 'DISPbasic1',\
                         path = staid_aux, parameters = parameters)
             if basic2:
                 parameters = {
                     'Tc': 0,
                     'To': 1,
                     'U': 2,
                     'C': 3,
                     'ampdb': 4,
                     'snrdb': 5,
                     'mhw': 6,
                     'amp': 7,
                     'Np': aftanTr.ftanparam.nfout2_1
                 }
                 self.add_auxiliary_data(data = aftanTr.ftanparam.arr2_1, data_type = 'DISPbasic2',\
                         path = staid_aux, parameters = parameters)
             if inftan.pmf:
                 if pmf1:
                     parameters = {
                         'Tc': 0,
                         'To': 1,
                         'U': 2,
                         'C': 3,
                         'ampdb': 4,
                         'dis': 5,
                         'snrdb': 6,
                         'mhw': 7,
                         'amp': 8,
                         'Np': aftanTr.ftanparam.nfout1_2
                     }
                     self.add_auxiliary_data(data = aftanTr.ftanparam.arr1_2, data_type = 'DISPpmf1',\
                         path = staid_aux, parameters = parameters)
                 if pmf2:
                     parameters = {
                         'Tc': 0,
                         'To': 1,
                         'U': 2,
                         'C': 3,
                         'ampdb': 4,
                         'snrdb': 5,
                         'mhw': 6,
                         'amp': 7,
                         'snr': 8,
                         'Np': aftanTr.ftanparam.nfout2_2
                     }
                     self.add_auxiliary_data(data = aftanTr.ftanparam.arr2_2, data_type = 'DISPpmf2',\
                         path = staid_aux, parameters = parameters)
             if outdir is not None:
                 if not os.path.isdir(outdir + '/' + pfx + '/' + tag):
                     os.makedirs(outdir + '/' + pfx + '/' + tag)
                 foutPR = outdir + '/' + pfx + '/' + tag + '/' + staid + '_' + channel + '.SAC'
                 aftanTr.ftanparam.writeDISP(foutPR)
             Ndata += 1
             outstr += otime.date.isoformat()
             outstr += ' '
         print('--- %4d traces processed' % Ndata)
         if verbose:
             print('EVENT DATE: ' + outstr)
         print(
             '-----------------------------------------------------------------------------------------------------------'
         )
     print('[%s] [AFTAN] all done' %
           datetime.now().isoformat().split('.')[0])
     return
예제 #5
0
# netcode, stacode= staid.split('.')
#                 tmppos          = self.waveforms[staid1].coordinates
#                 lat             = tmppos['latitude']
#                 lon             = tmppos['longitude']

#
import surfpy.aftan.pyaftan as pyaftan
import glob
import matplotlib.pyplot as plt
import obspy
import numpy as np
f = '/home/lili/data_threestation/COR/AZ.MONP/COR_AZ.MONP_LHZ_TA.R12A_LHZ.SAC'

st = obspy.read(f)
tr = st[0]
tr = pyaftan.aftantrace(tr.data, tr.stats)

tr.makesym()
tr.aftanf77(piover4=-1., pmf=True, vmin=1.5, vmax=5.0, ffact=1. , tmin=4.0, tmax=70.0,\
            phvelname = '/home/lili/data_wus/prep_ph_vel/ph_vel_R/AZ.MONP.TA.R12A.pre')
tr.get_snr()

pers = np.append(np.arange(18.) * 2. + 6., np.arange(4.) * 5. + 45.)
c0 = np.interp(pers, tr.ftanparam.arr2_2[1, :tr.ftanparam.nfout2_2],
               tr.ftanparam.arr2_2[3, :tr.ftanparam.nfout2_2])

fpattern = '/home/lili/data_threestation/SYNC_C3/AZ.MONP/C3_AZ.MONP_Z_TA.R12A_Z_*.npz'
fnamelst = glob.glob(fpattern)
for fname in fnamelst:
    fparam = pyaftan.ftanParam()
    fparam.load_npy(fname)