def v1(): # not used anymore merge = False filelist1 = glob.glob(glob1) filelist2 = glob.glob(file2) N = len(filelist1) assert len(filelist2) == N for i in range(N): file1 = filelist1[i] file2 = filelist2[i] st1 = read(file1) st2 = read(file2) mark1 = st1.getHI('mark') reason1 = st1.getHI('reason') if merge: mark2 = st2.getHI('mark') reason2 = st2.getHI('reason') mark = [mark1[i] or mark2[i] for i in range(N)] reason = reason1.copy() for i in range(N): if mark2[i]: reason[i] = reason2[i] else: st2.setHI('mark', mark1) st2.setHI('reason', reason1) files = os.path.splitext(file2)[0] st2.write(file2 + 'copymark', 'Q')
def read_rf(force=False): global rf_stream try: rf_stream except: rf_stream = read(data.rf_results_dir + '*_mout.QHD') #rf_stream = read(data.rf_results_dir + 'LVC_mout.QHD') #!!! else: if force: rf_stream = read(data.rf_results_dir + '*_mout.QHD') return rf_stream
def calc_ref(): fname = path + "/xcorr/hour_%s_%d.QHD" for year in range(2007, 2012): print year ms2 = read(fname % (station, year)) ms2.trim2(-25, 25, "middle") print "mean" tr = ms2.calculate("mean") print "write" tr.write(path + "/xcorr/hour_%s_ref_%d" % (station, year), "Q") ms = read(path + "/xcorr/hour_%s_ref_*.QHD" % station) tr = ms.calculate("mean") tr.write(path + "/xcorr/hour_%s_ref_2007-2011" % station, "Q")
def test(): from sito import read from obspy.signal.freqattributes import mper #, welch #from mtspec import mtspec ms = read('/home/richter/Data/Parkfield/raw/PKD_1996_296.mseed') #ms.plotTrace() print ms[0].stats # -*- snip -*- data = ms[0].data data = data - np.mean(data) #data -= np.linspace(0,1,len(data))*(data[-1]-data[0])+data[0] N = len(data) df = 1. / (ms[0].stats.endtime - ms[0].stats.starttime) print N // 2 * df spec1 = mper(data, cosTaper(N, 0.05), nextpow2(N))[:N // 2] #spec2 = welch(data, cosTaper(N, 0.05), nextpow2(N), len(data)/10, 0.2)[:N//2] spec1_d = oct_downsample(spec1, df, fac=1.3) freq1 = get_octfreqs(len(spec1_d), df, fac=1.3) ax = plot_psd(spec1, log=True) ax = plot_psd(spec1_d, freq1, log=True, ax=ax) plt.show()
def acorr(in_, out, tw, filter_): print 'acorr events' for fname in ProgressBar()(glob.glob(in_)): st1 = read(fname) st1.setHI('filter', '') st1.filter2(*filter_) for tr in st1: etime = tr.stats.event.etime ptime = tr.stats.event.ptime stime = tr.stats.starttime start_corr = etime + 2.2 * (ptime - etime) end_corr = start_corr + tw data_before = tr.slice(stime + 10, ptime - 10).data rms_before = np.sqrt(np.sum(data_before ** 2) / len(data_before)) data_after = tr.slice(start_corr, end_corr).data rms_after = np.sqrt(np.sum(data_after ** 2) / len(data_after)) #if rms_after < rms_before * 1.5: # continue tr.stats.event.rms_ratio = rms_after / rms_before tr.trim(start_corr, end_corr) tr.timeNorm('runningmean', 20) tr.taper(p=5. / (end_corr - start_corr)) tr.addZeros(tw) tr.acorr(shift=tw) ofname = os.path.splitext(os.path.basename(fname))[0] st1.write(out % ofname, 'Q')
def calc_strong_motion(): files1 = '/media/PBO/archive/20?[7890]/CX/PATCX/B[HL]Z.D/*.???' files2 = '/media/platte/Data/IPOC/raw_PATCX_2011_B-Z/*/*.???' acs = [] vels = [] for fname in glob(files1) + glob(files2): ms = read(fname) for tr in ms: if tr.stats.endtime - tr.stats.starttime < 1000: ms.remove(tr) continue tr.trim(tr.stats.starttime + 10, tr.stats.endtime - 10) tr.stats.filter = '' tr.detrend() tr.filter('highpass', freq=0.2) ms.merge(fill_value=0) if len(ms) == 0: continue tr = ms[0] t = tr.stats.starttime + (tr.stats.endtime - tr.stats.starttime) / 2 maxi = np.max(np.abs(tr.data)) if 'BH' in fname: vels.append((t, maxi)) elif 'BL' in fname: acs.append((t, maxi)) else: print 'wrong filename: ', fname dates_vel, vels = zip(*sorted(vels, key=itemgetter(0))) dates_ac, acs = zip(*sorted(acs, key=itemgetter(0))) np.savez('/home/richter/Results/IPOC/maxima_PATCX_5s.npz', dates_ac=date2num(dates_ac), dates_vel=date2num(dates_vel), vel=vels, ac=acs)
def plot(title=''): ms = read(pp_file + '.QHD') if stack_lon: xlabel = u'longitude of piercing points (°)' else: xlabel = u'latitude of piercing points (°)' plot = ms.plotProfile(start, end, scale=scale, xaxis=header, xlabel=xlabel, figtitle=title, fancy_box=True, box_ax=1, box_fs=5) ax = plot.fig.axes[0] ax.set_xlim(xlim) plot_depth(ax) for ax2 in plt.gcf().axes: ax2.xaxis.labelpad = 1 ax2.yaxis.labelpad = 1 plt.gcf().set_size_inches(fw, fw / 1.61) plt.tight_layout(pad=0.2, h_pad=0.) if len(plt.gcf().axes) == 4: # dirty hack plt.gcf().axes[3].set_visible(False)
def plot(station='*'): start = -5 end = 22 show = False for file_ in glob(azi_path + station + '_azi_stack.QHD'): ms = read(file_) station = ms[0].stats.station ratio = (len(ms) * 0.5 + 1.4 + 0.4 * 2.54) / 15 ratio = min(ratio, 2.) fig = getFig(ratio=ratio) alpha = None num_tr = np.sum(np.array(ms.getHI('count'))) if num_tr >= 100: alpha = ['count', 20, 0, 1., 0.] elif num_tr >= 50: alpha = ['count', 10, 0, 1., 0.] else: alpha = ['count', 5, 0, 1., 0.] plot = ms.plotRF(start, end, yaxis='azi', ylabel=u'azi (°)', show=show, fig=fig, scale=360 / len(ms), plotinfo=('sum',), plotinfowhere=('top',), alpha=alpha) if alpha is not None: #http://matplotlib.sourceforge.net/examples/api/colorbar_only.html ax2 = plot.fig.add_axes([0.94, 0.2, 0.01, 0.6]) norm = colors.Normalize(vmin=0, vmax=alpha[1]) ColorbarBase(ax2, cmap='Greys', norm=norm, extend='max') cosmetic(station, plot.fig) plot.fig.savefig(plotdir + 'rf_azistack_%s_Q.pdf' % station) plt.close(plot.fig)
def profile_pp_binned(stations, bin, header='plon', expr=None, xlim=None): #, scale=0.2 @ReservedAssignment """ PP profile """ log.info('***** Create piercing point binned plot') util.setRootLogger(logdebugfile=data.rf_results_dir + 'a_log_profile_pp.txt') filename = 'profile_pp_%s_%s_dif%s' % (stations, expr, bin[1] - bin[0]) file_ = data.rf_results_dir + filename try: stream = read(file_ + '.QHD') except: stream_all = read_rf() stream = stream_all.select(component='Q', expr=expr).getBinnedStream(bin, header=header) stream.write(file_, 'Q') plot = stream.plotProfile(-2, 21, scale=bin[1] - bin[0], xaxis='plon', xlabel='longitude of piercing points', plotinfo=(), figtitle='profile') ax = plot.fig.axes[0] if xlim: ax.set_xlim(xlim) # second ax with depth ax2 = ax.twinx() h = np.array((0, 50, 100, 150, 200)) h2 = np.arange(20) * 10 t = util.depth2time(h) myLocator = mpl.ticker.FixedLocator(t) myMinorLocator = mpl.ticker.FixedLocator(util.depth2time(h2)) myFormatter = mpl.ticker.FixedFormatter([str(i) for i in h]) ax2.yaxis.set_major_locator(myLocator) ax2.yaxis.set_minor_locator(myMinorLocator) ax2.yaxis.set_major_formatter(myFormatter) ax2.set_ylim(ax.get_ylim()) ax2.set_ylabel('depth (km)') plt.show() #plot.fig.savefig(plotdir + filename + '.eps') #st2.plotProfile(-2, 21, scale=0.05, xaxis = 'plon') #plot.fig.savefig(plotdir + filename + '.png') plt.close(plot.fig)
def test(): from sito import read from obspy.signal.freqattributes import mper # , welch # from mtspec import mtspec ms = read("/home/richter/Data/Parkfield/raw/PKD_1996_296.mseed") # ms.plotTrace() print ms[0].stats # -*- snip -*- data = ms[0].data data = data - np.mean(data) # data -= np.linspace(0,1,len(data))*(data[-1]-data[0])+data[0] N = len(data) df = 1.0 / (ms[0].stats.endtime - ms[0].stats.starttime) print N // 2 * df spec1 = mper(data, cosTaper(N, 0.05), nextpow2(N))[: N // 2] # spec2 = welch(data, cosTaper(N, 0.05), nextpow2(N), len(data)/10, 0.2)[:N//2] spec1_d = oct_downsample(spec1, df, fac=1.3) freq1 = get_octfreqs(len(spec1_d), df, fac=1.3) ax = plot_psd(spec1, log=True) ax = plot_psd(spec1_d, freq1, log=True, ax=ax) plt.show()
def time_binned(station, start, end, dif=0.5, expr=None): log.info('Create time binned plot') util.setRootLogger(logdebugfile=data.rf_results_dir + 'a_log_bin_time.txt') filename = 'bin_time_%s_%s_dif%s' % (station, expr, dif) file_ = data.rf_results_dir + filename try: binned = read(file_ + '.QHD') except: binsx = np.linspace(start, end, int((end - start) / dif + 1)) bins = [ UTCDateTime(int(i // 1), 1, 1) + (i % 1) * 24 * 60 * 60 * (365 + calendar.isleap(int(i // 1))) for i in binsx ] stream = read_rf().select(station=station, component='Q', expr=expr) stream.trim2(-10, 50) binned = stream.getBinnedStream(bins, header='starttime') binned.write(file_, 'Q') fig = binned.plotRF(topcolor=top2, fig=getFig(), botcolor=bot2, plotinfo=['sum', 'starttime'], plotlabel=['time', 'count', 'year'], show=show) fig.savefig(plotdir + filename + '.eps') plt.close(fig)
def plot(station='*'): start = -5 end = 22 show = False components = 'LQT' for file_ in glob(path + station + '_mout.QHD'): ms = read(file_) station = ms[0].stats.station ms = ms.select('not st.mark') ms.sort('azi') ratio = (len(ms) // 3 * 0.1 + 1.4 + 0.4 * 2.54) / 15 ratio = min(ratio, 2.) fig = getFig(ratio=ratio) plot = ms.plotRF(start, end, show=show, fig=fig, scale=1, component=components[1]) cosmetic(station, plot.fig) plot.fig.savefig(plotdir + 'rf_%s_%s.pdf' % (station, components[1])) plt.close(plot.fig) fig2 = getFig(ratio=ratio) plot = ms.plotRF(start, end, show=show, fig=fig2, scale=1, component=components[2]) cosmetic(station, plot.fig) plot.fig.savefig(plotdir + 'rf_%s_%s.pdf' % (station, components[2])) plt.close(plot.fig) fig3 = getFig(ratio=ratio) plot = ms.plotRF(start, end, show=show, fig=fig3, scale=0.9, component=components[0]) cosmetic(station, plot.fig) plot.fig.savefig(plotdir + 'rf_%s_%s.pdf' % (station, components[0])) plt.close(plot.fig)
def acorr(in_, out, tw, filter_): print 'acorr events' for fname in ProgressBar()(glob.glob(in_)): st1 = read(fname) st1.setHI('filter', '') st1.filter2(*filter_) for tr in st1: etime = tr.stats.event.etime ptime = tr.stats.event.ptime stime = tr.stats.starttime start_corr = etime + 2.2 * (ptime - etime) end_corr = start_corr + tw data_before = tr.slice(stime + 10, ptime - 10).data rms_before = np.sqrt(np.sum(data_before**2) / len(data_before)) data_after = tr.slice(start_corr, end_corr).data rms_after = np.sqrt(np.sum(data_after**2) / len(data_after)) #if rms_after < rms_before * 1.5: # continue tr.stats.event.rms_ratio = rms_after / rms_before tr.trim(start_corr, end_corr) tr.timeNorm('runningmean', 20) tr.taper(p=5. / (end_corr - start_corr)) tr.addZeros(tw) tr.acorr(shift=tw) ofname = os.path.splitext(os.path.basename(fname))[0] st1.write(out % ofname, 'Q')
def plot3(): assert (header2 is not None) #colors = 'bgrcmyk' for i in range(len(bins2) - 1): ms = read(pp_file % (bins2[i], bins2[i + 1]) + '.QHD') # if i == len(bins2) - 2: # reverse_y = True if i == 0: plot = ms.plotProfile(start, end, scale=scale, xaxis=header, xlabel=u'longitude of piercing points (°)', plotinfo=(), figtitle='', topcolor='red', botcolor='w', show=False, alpha=0.5) else: ms.plotProfile(start, end, xaxis=header, scale=scale, xlabel=u'longitude of piercing points (°)', plotinfo=(), figtitle=None, show=False, topcolor='green', botcolor='w', ax=plot.ax, ax_info=plot.ax_info, alpha=0.3) ax = plot.fig.axes[0] ax.set_xlim(xlim) plot_depth(ax) poly1 = Rectangle((0, 0), 1, 1, fc="r", alpha=0.5) poly2 = Rectangle((0, 0), 1, 1, fc="g", alpha=0.3) label1 = u'%d° to %d°' % (bins2[0], bins2[1]) label2 = u'%d° to %d°' % (bins2[1], bins2[2]) leg = ax.legend((poly1, poly2), (label1, label2), loc='lower left', fancybox=True, title='latitude') frame = leg.get_frame() frame.set_facecolor('wheat') frame.set_alpha(0.8) # matplotlib.text.Text instances for t in leg.get_texts(): t.set_fontsize('small') for ax2 in plt.gcf().axes: ax2.xaxis.labelpad = 1 ax2.yaxis.labelpad = 1 plt.gcf().set_size_inches(fw, fw / 1.61) plt.tight_layout(pad=0.2, h_pad=0.) plot.fig.savefig(pp_file % ('comparison_' + str(bins2[0]), bins2[-1]) + '.png', dpi=600)
def trim_stream(): fname = path + "/xcorr/hour_%s_2011.QHD" % station ms = read(fname) print ms ms.trim(endtime=UTC("2011-05-01")) ms = ms[:-1] print ms ms.write(path + "/xcorr/hour_%s_2011-01", "Q") % station
def open_files(self): if self.fileo1 is None: from easygui import filesavebox file1 = filesavebox(msg='Choose file with RAW data', default=patho1, filetypes=['*.QHD', '*.*']) else: file1 = self.fileo1 if self.fileo2 is None: file2 = filesavebox(msg='Choose file with RF data', default=patho2, filetypes=['*.QHD', '*.*']) else: file2 = self.fileo2 if file1 is not None and file2 is not None: try: self.st1 = read(file1) self.st2 = read(file2) except ValueError: print("Error while reading file!") return self.st2s = self.st2 if self.select: self.st2s = self.st2.select(expr='not st.mark') event_ids = self.st2s.getHI('event.id') self.st1s = self.st1 if len(self.st1s) != len(self.st2s): for tr in self.st1s: if tr.stats.event.id not in event_ids: self.st1s.remove(tr) if len(self.st1s) != len(self.st2s): raise ValueError('Streams do not have the same lenth') if num_tr is None: self.ind1 = 0 self.ind2 = len(self.st2s) else: self.ind1 = 0 self.ind2 = min(3 * num_tr, len(self.st2s)) if self.bandpass is not None: self.st2s.filter2(*self.bandpass) #self.st2s.select(component='Q').normalize() self.st1s.sort(sort) self.st2s.sort(sort) self.plot_streams()
def produce_event_files(station, year='*'): """ load data and throwed data to produce event files with used and not used events """ log.info('***** Produce event files') stream = read(data.rf_results % (station, year) + 'all_nomout.QHD') events_bad = events.Events.readFromStream(stream.select(expr='st.mark')) events_good = events.Events.readFromStream(stream.select(expr='not st.mark')) events_bad.write('%sevents_bad_%s.txt' % (data.rf_results_dir, station), header=False, format_=events_bad.format_GMT) events_good.write('%sevents_good_%s.txt' % (data.rf_results_dir, station), header=False, format_=events_good.format_GMT)
def calculate_pspier(other_header=False, station='*'): from os.path import splitext for file_ in glob(path + station + '_mout.QHD'): ms = read(file_) if other_header: ms.pspier(pspier_depth, other_header=str(pspier_depth)) else: ms.pspier(pspier_depth) ms.write(splitext(file_)[0], 'Q')
def calculate_profile(): ms = read(path + '*_mout.QHD').select(component='Q', expr='not st.mark') if header2 is None: ms = ms.getBinnedStream(bins1, header=header) ms.write(pp_file, 'Q') else: for i in range(len(bins2) - 1): ms2 = ms.select(expr='%f>=st.%s>%f' % (bins2[i], header2, bins2[i + 1])) ms3 = ms2.getBinnedStream(bins1, header=header) ms3.write(pp_file % (bins2[i], bins2[i + 1]), 'Q')
def stretching2(): fname = path + "/xcorr/hour_%s_%d.QHD" reftr = None # reftr = path + '/xcorr/hour_%s_ref_2008.QHD' if reftr: reftr = read(reftr % station)[0] days1 = 1 days2 = 1 year = 2007 stream = read(fname % (station, year)) stream.trim2(-25, 25, "middle") tws = (((5, 10, 15), 5),) # tws = (((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18), 2),) t = stream[0].stats.starttime t2 = UTC("%d-%d-%d" % (t.year, t.month, t.day)) if t2 < t: t = t2 + 24 * 3600 i = 0 while (t + days2 * 24 * 3600 * 0.5).year != 2012: sel = stream.select(time=(t, t + days2 * 24 * 3600)) if len(sel) > 0.5 * days2 * 48: result = sel.stretch(reftr=reftr, str_range=str_range, nstr=101, time_windows=tws[0], sides="right") dates = [get_ord(time) for time in sel.getHI("starttime")] dates = _correct_dates(dates) np.savez( path + "/stretch/1day/data_stretching2_%s_%05d_5swin" % (station, i), tw_start=tws[0][0], tw_width=tws[0][1], dates=dates, **result ) # tw 5s # np.savez(path + '/stretch/data_stretching_stretching2_%s_%03d_5swin' % (station, i), tw_start=tws[0][0], tw_width=tws[0][1], dates=dates, **result) # np.savez(path + '/stretch/data_stretching_oneref_%s_%03d_5swin' % (station, i), tw_start=tws[0][0], tw_width=tws[0][1], dates=dates, **result) i = i + 1 t = t + days1 * 24 * 3600 if (t + days2 * 24 * 3600 + 20).year != year: year += 1 stream = stream.select(time=(t, None)) if year < 2012: st2 = read(fname % (station, year)) st2.trim2(-25, 25, "middle") stream = stream + st2
def v2(): filelist1 = glob.glob(glob1) for file1 in filelist1: station = file1.split('/')[-1].split('_')[0] print station st1 = read(file1) st2 = read(file2 % station) st1.sort(('event.id', 'channel')) st2.sort(('channel', ), reverse=True) st2.sort(('event.id', )) print len(st1), len(st2) i = 0 while i < len(st1): if st1[i].stats.event.id == st2[i].stats.event.id: i += 1 else: st2.pop(i) st2 = st2[:i] print len(st1), len(st2) st2.write(file3 % station, 'Q')
def v2(): filelist1 = glob.glob(glob1) for file1 in filelist1: station = file1.split('/')[-1].split('_')[0] print station st1 = read(file1) st2 = read(file2 % station) st1.sort(('event.id', 'channel')) st2.sort(('channel',), reverse=True) st2.sort(('event.id',)) print len(st1), len(st2) i = 0 while i < len(st1): if st1[i].stats.event.id == st2[i].stats.event.id: i += 1 else: st2.pop(i) st2 = st2[:i] print len(st1), len(st2) st2.write(file3 % station, 'Q')
def setUp(self): self.stream = read(os.path.join(os.path.dirname(__file__), 'data', 'PKD_1997_246.mseed')) self.stream_down = self.stream.copy() self.stream_down.downsample2(1) N = self.N = 1001 self.data1 = np.sin(np.arange(N) / 100.) self.data1_dem = self.data1.copy() self.data1_dem[:] = self.data1_dem[:] - np.mean(self.data1_dem) self.data2 = np.e ** (-(np.arange(N) - 500) ** 2 / 100.) - np.e ** (-(np.arange(N) - 50) ** 2 / 100.) + 5 * np.e ** (-(np.arange(N) - 950) ** 2 / 100.) self.data2_dem = self.data2.copy() self.data2_dem[:] = self.data2_dem[:] - np.mean(self.data2_dem)
def calculate(station='*'): for file_ in glob(path + station + '_mout.QHD'): ms = read(file_).select(component='Q', expr='not st.mark') station = ms[0].stats.station if len(ms) >= 100: bins = np.arange(19) * 20 elif len(ms) >= 50: bins = np.arange(13) * 30 else: bins = np.arange(7) * 60 ms = ms.getBinnedStream(bins, header='azi') ms.write(azi_path + '%s_azi_stack' % station, 'Q')
def select_rfs_from_region(): """Select rfs from region.""" for file_ in glob(PATH + '*_mout.QHD'): ms = read(file_).select(expr='not st.mark') for region in REGIONS: ms2 = ms.select(around=region) print len(ms2), 'vs', len(ms), file_ station = ms2[0].stats.station num = get_region_number(dist=region[2]) ms2.setHI('eventsfrom', region) ms2.setHI('eventsfromfe', util.feregion(region[0], region[1])) newfile_ = TIMEVARI_PATH + ('rf_%s_R%s' % (station, num)) ms2.write(newfile_, 'Q')
def produce_event_files(station, year='*'): """ load data and throwed data to produce event files with used and not used events """ log.info('***** Produce event files') stream = read(data.rf_results % (station, year) + 'all_nomout.QHD') events_bad = events.Events.readFromStream(stream.select(expr='st.mark')) events_good = events.Events.readFromStream( stream.select(expr='not st.mark')) events_bad.write('%sevents_bad_%s.txt' % (data.rf_results_dir, station), header=False, format_=events_bad.format_GMT) events_good.write('%sevents_good_%s.txt' % (data.rf_results_dir, station), header=False, format_=events_good.format_GMT)
def stack(in_, out): print 'loading files for stacking...' st_sum = Stream() st1 = read(in_) print 'stack traces...' for station in ProgressBar()('PB01 PB02 PB03 PB04 PB05 PB06 PB07 PB08 PB09 PB10 PB11 PB12 PB13 PB14 PB15 HMBCX MNMCX PATCX PSGCX'.split()): #st2 = st1.select(station=station, expr='st.event.rms_ratio > 1.5 and st.sampling_rate>40 and -25<st.event.lat<-18 and -67.8<st.event.lon<-66.0') st2 = st1.select(station=station, expr='st.event.rms_ratio > 1.5 and st.sampling_rate>40') if len(st2) == 0: print 'No traces for station %s' % station continue tr = st2.simpleStack() tr.stats.label = station st_sum += tr st_sum.write(out, 'Q')
def setUp(self): self.stream = read( os.path.join(os.path.dirname(__file__), 'data', 'PKD_1997_246.mseed')) self.stream_down = self.stream.copy() self.stream_down.downsample2(1) N = self.N = 1001 self.data1 = np.sin(np.arange(N) / 100.) self.data1_dem = self.data1.copy() self.data1_dem[:] = self.data1_dem[:] - np.mean(self.data1_dem) self.data2 = np.e**(-(np.arange(N) - 500)**2 / 100.) - np.e**( -(np.arange(N) - 50)**2 / 100.) + 5 * np.e**(-(np.arange(N) - 950)**2 / 100.) self.data2_dem = self.data2.copy() self.data2_dem[:] = self.data2_dem[:] - np.mean(self.data2_dem)
def time_binned(station, start, end, dif=0.5, expr=None): log.info('Create time binned plot') util.setRootLogger(logdebugfile=data.rf_results_dir + 'a_log_bin_time.txt') filename = 'bin_time_%s_%s_dif%s' % (station, expr, dif) file_ = data.rf_results_dir + filename try: binned = read(file_ + '.QHD') except: binsx = np.linspace(start, end, int((end - start) / dif + 1)) bins = [UTCDateTime(int(i // 1), 1, 1) + (i % 1) * 24 * 60 * 60 * (365 + calendar.isleap(int(i // 1))) for i in binsx] stream = read_rf().select(station=station, component='Q', expr=expr) stream.trim2(-10, 50) binned = stream.getBinnedStream(bins, header='starttime') binned.write(file_, 'Q') fig = binned.plotRF(topcolor=top2, fig=getFig(), botcolor=bot2, plotinfo=['sum', 'starttime'], plotlabel=['time', 'count', 'year'], show=show) fig.savefig(plotdir + filename + '.eps') plt.close(fig)
def plot_pspier(): coordfile = pp_path + 'ppcoords%d.npy' % pspier_depth if os.path.isfile(coordfile): coords = np.load(coordfile) else: ms = read(path + '*_mout.QHD').select(component='Q', expr='not st.mark') lat = ms.getHI('plat%d' % pspier_depth) lon = ms.getHI('plon%d' % pspier_depth) coords = np.array([lat, lon]) np.save(coordfile, coords) from sito import map map_dic = dict(figsize=(0.95 * fw, 1.61 * fw * 1.1), margin=(0.1, 0.04, 0.8, 0.92), lw=0.5, station_markersize=3, spines_lw=1, loffset=10000) m = map.createIPOCMap(ll=(-25, -71.5), show=False, trench=None, **map_dic) x, y = m(coords[1, :], coords[0, :]) m.plot(x, y, 'xr', ms=3) print(pp_path + 'map_pp%d.pdf' % pspier_depth) plt.gcf().savefig(pp_path + 'map_pp%d.pdf' % pspier_depth)
def stretching(): fname = path + "/xcorr/hour_%s_2011-01.QHD" % station stream = read(fname) tws = (((5, 10, 15), 5),) # tws = ((range(21), 2),) stream.trim2(-25, 25, "middle") # sel = stream.select(time=(None, UTC('%d-05-01' % year))) sel = stream result = sel.stretch(str_range=str_range, nstr=101, time_windows=tws[0], sides="right") dates = [get_ord(time) for time in sel.getHI("starttime")] dates = _correct_dates(dates) np.savez( path + "/stretch/data_stretching_%s_2011_01-04" % station, tw_start=tws[0][0], tw_width=tws[0][1], dates=dates, **result ) # corr=corr, stretch=stretch)
def calculate_rf(year='*', pp=False, rotateLQT=True, deconvolvef=False): logfile = data.rf_results_dir + 'a_log%s.txt' util.checkDir(logfile) util.setRootLogger(logfile=logfile % '', logdebugfile=logfile % '_debug') log.info('***** Calculate RF') for station in data.stations.keys(): stream = read(data.rf_events % (station, year + '.QHD')) if pp: stream.setPhase('PP') stream.pspier(60, data.stations) log.info('number of events: %s' % (len(stream) // 3)) #stream.filter2(0.033, 2.) stream.trim2(-20, 100, relative='ponset') stream.sort(('event.id', 'station', 'component')) stream.check() stream.setHI('mark', False) if rotateLQT: stream.rotateZNE2LQT(-5, 15, usetheo=True) stream.afarm(signoise=2.0, remove=True) else: #stream.rotateZNE2LQT(-5, 15, usetheo=True) #stream.afarm(signoise=2.0, remove=True) #stream.trim2(-20, 100, relative='ponset') #stream.rotateLQT2ZNE(usetheo=True) stream.rotateNE2RT() #stream.afarm(signoise=2.0, remove=True) #stream.trim2(-25, 100, relative='ponset') # log.info('number of events after first farm: %s' % (len(stream)//3)) # util.ipshell() #stream.receiverf(water=0.005, gauss=5, tshift=20, pad=0, # window='tukey', start=-10, end=30, where='ponset', lenslope=5) if deconvolvef: stream.receiverf() else: stream.receivert() #stream.receiverSH(-10, 80, 1) #stream.afarm('rf', signoise=2., signoiseQ=1., maxL=1 / 1.5, sigQ=False, broad=True, remove=False) #stream.afarm('rf', signoise=False, signoiseQ=False, maxL=False, sigQ=False, broad=False, remove=False) #log.info('number of events after second farm: %s' % (len(stream)//3)) stream.write(data.rf_results % (station, '') + 'nomout', 'Q') #stream.writey(data.rf_results % (station, '%s') + '_nomout', 'Q') print stream.getReasons()
def load_shift_results(compute=False): global RESULTS if not compute: try: with open(RESULTS_FILE) as f: RESULTS = cPickle.load(f) return except IOError: pass RESULTS = collections.OrderedDict() for stareg in WINDOWS: RESULTS[stareg] = {} station, region = stareg.split() ms = read(TIMEVARI_PATH + ('rf_%s_%s.QHD' % (station, region))) ms = ms.select(component='Q') for window in zip(*WINDOWS[stareg]): RESULTS[stareg][window] = shift_and_correlate(ms, T_TOCO, window) with open(RESULTS_FILE, 'w') as f: cPickle.dump(RESULTS, f)
def profile(stations, expr=None): """ plots summation trace for all stations """ log.info('***** Create profile plots') util.setRootLogger(logdebugfile=data.rf_results_dir + 'a_log_profile.txt') filename = 'sum_%s_%s' % (stations, expr) file_ = data.rf_results_dir + filename try: sum_stream = read(file_ + '.QHD') except: stream = read_rf() sum_stream = Stream() for station in stations.split(): temp = stream.select(station=station, component='Q', expr=expr) sum_stream += temp.simpleStack() sum_stream.write(file_, 'Q') plot = sum_stream.plotProfile(-2, 21, scale=5) plot.fig.savefig(plotdir + filename + '.eps') plot.fig.savefig(plotdir + filename + '.png') plt.close(plot.fig)
def mout(station='*', year='*'): log.info('***** Move Out correction') global rf_stream logfile = data.rf_results_dir + 'a_mout_log%s.txt' util.checkDir(logfile) util.setRootLogger(logfile=logfile % '', logdebugfile=logfile % '_debug') rf_stream = read(data.rf_results % (station, year) + 'nomout.QHD') if False: st2 = rf_stream.copy() st2.moveout(phase='Ppps') st2.trim2(-20, 100) st2.write(data.rf_results % '_Ppps', 'Q') st3 = rf_stream.copy() st3.moveout(phase='Ppss') st3.trim2(-20, 100) st3.write(data.rf_results % '_Ppss', 'Q') rf_stream.moveout(phase='Ps') #rf_stream.trim2(-20, 100) rf_stream.writex(data.rf_results % ('%s', '') + 'mout', 'Q', years=False)
def stack(in_, out): print 'loading files for stacking...' st_sum = Stream() st1 = read(in_) print 'stack traces...' for station in ProgressBar( )('PB01 PB02 PB03 PB04 PB05 PB06 PB07 PB08 PB09 PB10 PB11 PB12 PB13 PB14 PB15 HMBCX MNMCX PATCX PSGCX' .split()): #st2 = st1.select(station=station, expr='st.event.rms_ratio > 1.5 and st.sampling_rate>40 and -25<st.event.lat<-18 and -67.8<st.event.lon<-66.0') st2 = st1.select( station=station, expr='st.event.rms_ratio > 1.5 and st.sampling_rate>40') if len(st2) == 0: print 'No traces for station %s' % station continue tr = st2.simpleStack() tr.stats.label = station st_sum += tr st_sum.write(out, 'Q')
def plot3(): assert(header2 is not None) #colors = 'bgrcmyk' for i in range(len(bins2) - 1): ms = read(pp_file % (bins2[i], bins2[i + 1]) + '.QHD') # if i == len(bins2) - 2: # reverse_y = True if i == 0: plot = ms.plotProfile(start, end, scale=scale, xaxis=header, xlabel=u'longitude of piercing points (°)', plotinfo=(), figtitle='', topcolor='red', botcolor='w', show=False, alpha=0.5) else: ms.plotProfile(start, end, xaxis=header, scale=scale, xlabel=u'longitude of piercing points (°)', plotinfo=(), figtitle=None, show=False, topcolor='green', botcolor='w', ax=plot.ax, ax_info=plot.ax_info, alpha=0.3) ax = plot.fig.axes[0] ax.set_xlim(xlim) plot_depth(ax) poly1 = Rectangle((0, 0), 1, 1, fc="r", alpha=0.5) poly2 = Rectangle((0, 0), 1, 1, fc="g", alpha=0.3) label1 = u'%d° to %d°' % (bins2[0], bins2[1]) label2 = u'%d° to %d°' % (bins2[1], bins2[2]) leg = ax.legend((poly1, poly2), (label1, label2), loc='lower left', fancybox=True, title='latitude') frame = leg.get_frame() frame.set_facecolor('wheat') frame.set_alpha(0.8) # matplotlib.text.Text instances for t in leg.get_texts(): t.set_fontsize('small') for ax2 in plt.gcf().axes: ax2.xaxis.labelpad = 1 ax2.yaxis.labelpad = 1 plt.gcf().set_size_inches(fw, fw / 1.61) plt.tight_layout(pad=0.2, h_pad=0.) plot.fig.savefig(pp_file % ('comparison_' + str(bins2[0]), bins2[-1]) + '.png', dpi=600)
def open_data(self, file=None): #@ReservedAssignment if file == None: file = easygui.fileopenbox(default=def_open, filetypes=['*.QHD', '*.*']) #@ReservedAssignment if file != None: try: self.st_all = read(file) except: exceptionbox("Error while reading file!") if self.st_all[0].stats.event.get('id') == None: for tr in self.st_all: tr.stats.event['id'] = str(tr.stats.event.eventno) self.handmarked = [] self.handunmarked = [] self.st_all.downsample2(self.ui.spin_downsample.value()) self.st_all.trim2(-50, 300) self.st_all.sort(self.sort_after.split(',')) self.st_all.check() self.st_all.setHI('mark', False) #self.slice_changed(self.ui.edit_slice.text()) #self.update_raw() self.st_all_old = self.st_all self.update_rf()
def plot(station='*'): start = -5 end = 22 show = False for file_ in glob(azi_path + station + '_azi_stack.QHD'): ms = read(file_) station = ms[0].stats.station ratio = (len(ms) * 0.5 + 1.4 + 0.4 * 2.54) / 15 ratio = min(ratio, 2.) fig = getFig(ratio=ratio) alpha = None num_tr = np.sum(np.array(ms.getHI('count'))) if num_tr >= 100: alpha = ['count', 20, 0, 1., 0.] elif num_tr >= 50: alpha = ['count', 10, 0, 1., 0.] else: alpha = ['count', 5, 0, 1., 0.] plot = ms.plotRF(start, end, yaxis='azi', ylabel=u'azi (°)', show=show, fig=fig, scale=360 / len(ms), plotinfo=('sum', ), plotinfowhere=('top', ), alpha=alpha) if alpha is not None: #http://matplotlib.sourceforge.net/examples/api/colorbar_only.html ax2 = plot.fig.add_axes([0.94, 0.2, 0.01, 0.6]) norm = colors.Normalize(vmin=0, vmax=alpha[1]) ColorbarBase(ax2, cmap='Greys', norm=norm, extend='max') cosmetic(station, plot.fig) plot.fig.savefig(plotdir + 'rf_azistack_%s_Q.pdf' % station) plt.close(plot.fig)
def create_rf_plots_years(station, years): global rf_stream for year in years: read(data.rf_results % (station, year)) create_rf_plots()
def create_event_files(station='*'): for file_ in glob(path + station + '_mout.QHD'): ms = read(file_).select(component='Q', expr='not st.mark') station = ms[0].stats.station events = ms.getEvents() events.write(em_path + 'events_%s.txt' % station)
import argparse import logging from sito import read from sito.util.main import isint, isfloat logging.basicConfig() parser = argparse.ArgumentParser( description='Get header entry of traces in files. Sea sito.Stream.g(s)etHI' ) parser.add_argument('header', help='header e.g. dist') parser.add_argument('files', nargs='*', help='files') parser.add_argument('-w', '--write', help='write entry into header') args = parser.parse_args() header = args.header if not args.write: entries = [] for f in args.files: ms = read(f) entries.extend(ms.getHI(header)) print ' '.join([str(entry) for entry in entries]) else: entry = args.write entry = int(entry) if isint(entry) else float(entry) if isfloat( entry) else entry for f in args.files: print 'loading file' + f ms = read(f) ms.setHI(header, entry) print 'write file...' ms.write(f, ms[0].stats._format)
l.set_dash_capstyle('round') ax.set_xlim([2, 20]) if i == 2 or i == 0: ax.set_ylim([0, 1.3]) elif i == 4: ax.set_ylim([0, 1]) elif i == 3: ax.set_ylim([0, 4]) ax.set_yticks(range(5)) #ax.annotate('phase of temperature', (14, 36), va='top', ha='center') #ax.axhline(31, color='k', zorder=-100, lw=1) #ax.set_ylim([20, 120]) else: ax.set_xlabel('lag time (s)') for j, (freq, tws) in enumerate(freq_tws.items()): stream = read(path_stack % (freq - 1, freq + 1)) stream.trim2(0, 20, relative='middle') tr = stream[0] lt = np.linspace(0, 20, len(tr)) data = tr.data clip = 0.02 data[data > clip] = clip data[data < -clip] = -clip l, = ax.plot(lt, data / clip / 2 + 3 + j, lw=0.5, color=colors[j]) ddxx = 0.7 * ((freq >= 9) + (freq >= 11)) ddyy = 0.1 * (freq >= 11) ax.annotate('%d-%dHz' % (freq - 1, freq + 1), (19.5, 3 + j - ddyy), va='bottom', ha='right', color=colors[j], size=7) print freq, ddxx l, = ax.plot((14.6 - ddxx, 16.3 - ddxx), 2 * [3.25 - ddyy + j], lw=1, ls=lss[j], color=colors[j]) if steps[j]: