def getChannelScalogram(traceList, channelNo, outfile, imagefolder='scalogram'): tr = traceList[channelNo] dt = tr.stats.delta f_min = 10 f_max = 200 npts = tr.stats.npts t = np.linspace(0, dt * npts, npts) scalogram = cwt(tr.data, dt, 8, f_min, f_max) fig = plt.figure() ax = fig.add_subplot(111) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) ax.set_xlabel("Time after %s [s]" % tr.stats.starttime) ax.set_ylabel("Frequency [Hz]") ax.set_yscale('log') ax.set_ylim(f_min, f_max) plt.savefig('{0}/{1}_scalogram_channel.png'.format(imagefolder, outfile, channelNo))
def _colormap_plot_cwt(cmaps): """ Plot for illustrating colormaps: cwt. :param cmaps: list of :class:`~matplotlib.colors.Colormap` :rtype: None """ import matplotlib.pyplot as plt from obspy import read from obspy.signal.tf_misfit import cwt tr = read()[0] npts = tr.stats.npts dt = tr.stats.delta t = np.linspace(0, dt * npts, npts) f_min = 1 f_max = 50 scalogram = cwt(tr.data, dt, 8, f_min, f_max) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) for cmap in cmaps: fig = plt.figure() ax = fig.add_subplot(111) ax.pcolormesh(x, y, np.abs(scalogram), cmap=cmap) ax.set_xlabel("Time after %s [s]" % tr.stats.starttime) ax.set_ylabel("Frequency [Hz]") ax.set_yscale('log') ax.set_ylim(f_min, f_max) plt.show()
def cwt_obspy(): st = obspy.read() tr = st[0] npts = tr.stats.npts dt = tr.stats.delta t = np.linspace(0, dt * npts, npts) f_min = 1 f_max = 50 scalogram = cwt(tr.data, dt, 8, f_min, f_max) plt.imshow(abs(scalogram), aspect='auto') # fig = plt.figure() # ax = fig.add_subplot(111) # x, y = np.meshgrid(t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) # # ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) # ax.set_xlabel("Time after %s [s]" % tr.stats.starttime) # ax.set_ylabel("Frequency [Hz]") # ax.set_yscale('log') # ax.set_ylim(f_min, f_max) # plt.tight_layout() # frame = plt.gca() # frame.axes.get_xaxis().set_visible(False) # frame.axes.get_yaxis().set_visible(False) plt.savefig('cwt_obspy.png') plt.close()
def plot_wavelet(t, data, dt, scale, fmin, fmax, title): t, data = get_ave_values(t, data) scalogram = cwt(data, dt, scale, fmin, fmax, wl='morlet') fig = plt.figure(num=None, figsize=(15, 10), dpi=80, facecolor='w', edgecolor='k') ax1 = fig.add_axes([0.1, 0.1, 0.7, 0.60]) ax2 = fig.add_axes([0.1, 0.75, 0.75, 0.2]) ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6]) img = ax1.imshow(np.abs(scalogram), extent=[t[0], t[-1], fmin, fmax], aspect='auto', interpolation="nearest") ax1.set_title('Wavelet spectrum_' + title) ax1.set_xlabel("Time (sec)") ax1.set_ylabel("Frequency [Hz]") ax1.set_yscale('linear') ax2.set_title('Vibration signal (Time averaged)_' + title) ax2.plot(t, data, 'k') ax2.set_ylabel('Amplitude') fig.colorbar(img, cax=ax3).set_label('Intensity') plt.show()
def getChannelScalogram(traceList, channelNo, channelStart, outfile, imagefolder='static/Obspy_Plots/diff_plots'): tr = traceList[channelNo] dt = tr.stats.delta f_min = 10 f_max = 150 npts = tr.stats.npts t = np.linspace(0, dt * npts, npts) scalogram = cwt(tr.data, dt, 8, f_min, f_max) fig = plt.figure() ax = fig.add_subplot(111) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) #ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) ax.pcolormesh(x, y, np.abs(scalogram), cmap='jet') ax.set_xlabel("Time after %s [s]" % tr.stats.starttime) ax.set_ylabel("Frequency [Hz]") ax.set_yscale('log') ax.set_ylim(f_min, f_max) image_name = '{0}_scalogram_channel{1}.png'.format( outfile, channelNo + channelStart) print(image_name) plt.savefig('{0}/{1}_scalogram_channel{2}.png'.format( imagefolder, outfile, channelNo + channelStart)) plt.close() return image_name
def generate_morlet_scalogram(self, signal, image_path): axis = signal.ndim - 1 signal_length = signal.shape[axis] t = np.linspace(0, signal_length, signal_length) f_min = 1 f_max = signal_length scalogram = cwt(signal, 0.001, 5, f_min, f_max) fig = plt.figure() ax = fig.add_subplot(111) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax.pcolormesh(x, y, np.abs(scalogram), cmap='hot') ax.set_yscale('log') ax.set_ylim(f_min, f_max) ax.axis('off') ax.set_axis_off() ax.set_yticklabels([]) ax.set_xticklabels([]) plt.savefig(image_path, bbox_inches='tight', format='png', pad_inches=0, transparent=True, dpi=100) plt.clf() plt.cla() plt.close('all')
def _generate_morlet_scalogram(signal): """ Generate morelet scalogram from a numpy signal""" axis = signal.ndim - 1 signal_length = signal.shape[axis] t = np.linspace(0, signal_length, signal_length) f_min = 1 f_max = signal_length scalogram = cwt(signal, 0.001, 5, f_min, f_max) fig = plt.figure() ax = fig.add_subplot(111) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax.pcolormesh(x, y, np.abs(scalogram), cmap='hot') ax.set_yscale('log') ax.set_ylim(f_min, f_max) ax.axis('off') ax.set_axis_off() ax.set_yticklabels([]) ax.set_xticklabels([]) fig.canvas.draw() data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') return data.reshape(fig.canvas.get_width_height()[::-1] + (3, ))
def cwtPlot(self, channelNo): """ Test cwt for a single trace """ tr = self.st[channelNo].copy() npts = tr.stats.npts dt = tr.stats.delta t = np.linspace(0, dt * npts, npts) f_min = 1 f_max = 50 scalogram = cwt(tr.data, dt, 8, f_min, f_max) fig = plt.figure() ax = fig.add_subplot(111) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) ax.set_xlabel("Time after %s [s]" % tr.stats.starttime) ax.set_ylabel("Frequency [Hz]") ax.set_yscale('log') ax.set_ylim(f_min, f_max) img_name = 'cwt{0}_.png'.format(channelNo) plt.savefig('static/Obspy_Plots/test/cwt{0}_.png'.format(channelNo)) return img_name
def cwt_tf_plot(sig, t, f_min=1, f_max=1000, yscale='log', tradeoff=30): """ Time-frequency plot based on continuous wavelet transform. Parameters ---------- sig: ndarray Signal array. t: ndarray Time array f_min: float Minimum frequency. f_max: float Maximun frequency. yscale: str Scale of the y axis; 'log' or 'linear'. tradeoff: float parameter for the wavelet, tradeoff between time and frequency resolution. Returns ------- Z: ndarray Contour array of plot. X: ndarray X grids of plot. Y: ndarray Y grids of plot. """ from obspy.signal.tf_misfit import cwt dt = t[1] - t[0] # Time interval # Wavelet transform W = cwt(sig, dt, tradeoff, f_min, f_max) amp = np.abs(W) # Amplitude power = amp * amp # Power # Plot a figure fig = plt.figure() ax = fig.add_subplot(1, 1, 1) Z = power X, Y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), Z.shape[0])) pcm = ax.pcolormesh(X, Y, Z, cmap='RdBu_r') ax.set_title("Power") ax.set_xlabel("Time (second)") ax.set_ylabel("Frequency (Hz)") ax.set_yscale(yscale) ax.set_ylim(f_min, f_max) # Colorbar fig.colorbar(pcm, ax=ax, extend='both', orientation='vertical') return fig, ax
def peak_frequency(trace, loc, dt, fmin=1, fmax=90, w0=6): if not all(loc>0): return 0.0 else: dsl = int(loc[0] / dt) dsh = int(loc[1] / dt) scalogram = cwt(trace[dsl:dsh], dt, w0, fmin, fmax) nf = np.logspace(np.log10(fmin), np.log10(fmax)) idx = np.argmax(np.abs(scalogram), axis = None) idxmax = np.unravel_index(idx, scalogram.shape) return nf[idxmax[0]//2]
def apply_cwt(self, fmin=1, fmax=90, w0=8): ''' w0: tradeoff between time and frequency resolution ''' from obspy.signal.tf_misfit import cwt self._fmin = fmin self._fmax = fmax self._scalogram = cwt(self._signal, self._dt, w0, self._fmin, self._fmax) self._nfgrid = np.logspace(np.log10(self._fmin), np.log10(self._fmax), \ self._scalogram.shape[0]) self._CWT_flag = True
def plotWaveletTransform(tr, startMin, endMin): print('Calculating Wavelet Transform') N = len(tr.data) # Number of samplepoints dt = tr.stats.delta x0=int(startMin*tr.stats.sampling_rate*60) x1=int(endMin*tr.stats.sampling_rate*60) if (x0 < 0): x0=0 if (x1>N): x1=N-1 subSetLen=x1-x0 t = np.linspace(x0, x1, num=subSetLen) t1 = np.divide(t, (tr.stats.sampling_rate*60)) fig = plt.figure() fig.suptitle('Wavelet Transform ' + str(tr.stats.starttime.date), fontsize=12) fig.canvas.set_window_title('Wavelet Transform ' + str(tr.stats.starttime.date)) #ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60]) ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height] ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1) ax1.plot(t1, tr.data[x0:x1], 'k') ax1.set_ylabel(r'$\Delta$P - Pa') f_min = 0.01 f_max = 15 scalogram = cwt(tr.data[x0:x1], dt, 8, f_min, f_max) x, y = np.meshgrid(t1, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax2.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) ax2.set_xlabel("Time [min]") ax2.set_ylabel("Frequency [Hz]") ax2.set_yscale('log') ax2.set_ylim(f_min, f_max) fig.show()
def wavelet(self, bw_ratio, f_min, f_max): """ Not up-to-date ! """ spectra = list() for st in self.stream: int(st, flush=True) spectra.append(cwt(st.data, st.stats.delta, 20, f_min, f_max).T) self.spectra = np.array(spectra) times = self.stream[0].times() times += float(self.start) times /= 24 * 3600 self.spectral_times = times self.frequencies = [f_min, f_max]
def plot_cwf(tr, ax, t_ref=0, fmin=1. / 50, fmax=1. / 2, w0=6): from obspy.signal.tf_misfit import cwt npts = tr.stats.npts dt = tr.stats.delta t = np.linspace(0, dt * npts, npts) scalogram = abs(cwt(tr.data, dt, w0=w0, fmin=fmin, fmax=fmax, nf=100)) x, y = np.meshgrid( t + t_ref, 1. / np.logspace(np.log10(fmin), np.log10(fmax), scalogram.shape[0])) m = ax.pcolormesh(x, y, np.log10((scalogram)) * 10., cmap='plasma', vmin=-110, vmax=-72)
def plotWaveletTransform(tr1, f_min, f_max): print('Calculating Wavelet Transform') N = len(tr1.data) # Number of samplepoints dt = tr1.stats.delta x0 = 0 x1 = N - 1 t = np.linspace(x0, x1, num=N) t1 = np.divide(t, (tr1.stats.sampling_rate * 60)) fig = plt.figure() fig.suptitle('Wavelet Transform ' + str(tr1.stats.starttime.date), fontsize=12) fig.canvas.set_window_title('Wavelet Transform ' + str(tr1.stats.starttime.date)) # ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60]) ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) # [left bottom width height] ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1) print("x1", x1, "len t", len(t), "len t1", len(t1)) ax1.plot(t1, tr1.data, 'k') ax1.set_ylabel(r'$\Delta$P - Pa') scalogram = cwt(tr1.data[x0:x1], dt, 8, f_min, f_max) x, y = np.meshgrid( t1, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax2.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) ax2.set_xlabel("Time [min]") ax2.set_ylabel("Frequency [Hz]") ax2.set_yscale('log') ax2.set_ylim(f_min, f_max) #fig.savefig("wavelet.png") fig.show() input("Press Enter to continue...")
axs[0].plot(t, st_bp2[1].data, color='b') plt.sca(axs[0]) plt.ylim([-2500., 2500.]) for stn in ['REF', 'DECK']: print('Scalogram working on station: ' + stn + ' and component: ' + component) tr_comb = st_bp.select(station=stn)[0] npts = tr_comb.stats.npts dt = tr_comb.stats.delta t = np.linspace(0, dt * npts, npts) f_min = 1./150. f_max = 5. scalogram = cwt(tr_comb.data, dt, 6, f_min, f_max, nf=100) axnum += 1 ax = axs[axnum] x, y = np.meshgrid(t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) m = ax.pcolormesh(x, y, np.log10((scalogram)), cmap='viridis', vmin=0, vmax=3) ax.set_title(stn) ax.set_ylabel("Frequency [Hz]") ax.set_yscale('log')
#output: graphics [Scalogram plot] import numpy as np import matplotlib.pyplot as plt from obspy.imaging.cm import obspy_sequential from obspy.signal.tf_misfit import cwt npts = len(data.index) dt = 1.0 / sampleRate t = np.linspace(0.0, dt * npts, npts) f_min = 1.0 f_max = sampleRate / 10.0 signal = data[[signal]].values.ravel() scalogram = cwt(signal, dt, w0, f_min, f_max, wl='morlet') if removeDc: signal = signal - np.mean(signal) fig = plt.figure() ax = fig.add_subplot(111) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) ax.set_xlabel("Time, s") ax.set_ylabel("Frequency, Hz") ax.set_yscale('log') ax.set_ylim(f_min, f_max) plt.show()
seisfile = '/raid3/zl382/Data/Synthetics/' + event + '/SYN_' + str( s) + '.PICKLE' seis = read(seisfile, format='PICKLE') seis.resample(10) # Resampling makes things quicker Sdifftime = seis[0].stats['traveltimes'][phase] # find time of phase tr = seis.select(channel=component)[0] w0 = np.argmin(np.abs(tr.times() - Sdifftime + 100)) w1 = np.argmin(np.abs(tr.times() - Sdifftime - 190)) # Copy trace tr1 = tr.copy() #tr1 = tr1.filter('bandpass', freqmin=1/40.,freqmax=1/10.) # Plot reference phase with wide filter # plt.plot(tr.times()[w0:w1]-Sdifftime,tr1.data[w0:w1]/np.max(np.abs(tr1.data[w0:w1])),'k') scalogram = cwt(tr1.data[w0:w1], 0.1, 8, f_min, f_max) x, y = np.meshgrid( tr.times()[w0:w1] - Sdifftime, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) fig, ax = plt.subplots(figsize=(9, 9)) ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) plt.xlabel('time around ' + phase + ' (s)', fontsize=18) plt.xlim([-50, 120]) plt.yticks([1 / 10, 1 / 5, 1 / 3, 1 / 2, 1], ['10', '5', '3', '2', '1']) plt.show()
seislist = glob.glob(data_path + '*PICKLE') for az in az_list: category_az_folder = newfilefolder + 'az_' + str(az) + '/' num_of_trace = len(glob.glob(category_az_folder + '*.npy')) print(str(num_of_trace) + ' found in ' + 'az_' + str(az)) seislist = glob.glob(category_az_folder + '*npy') stack_data = np.zeros(len(sample[1])) # initialize the array for seis in seislist: stack_data = stack_data + 1 / num_of_trace * np.load(seis)[1] if waveform_norm: w_norm = np.max(stack_data) # sigmoid = -np.log(1/(1+np.exp(-num_of_trace/2+0.5))) # plt.plot(sample[0],stack_data/norm + az,color=(sigmoid,0,0)) scalogram = cwt(stack_data / w_norm, 0.1, 8, f_min, f_max) x, y = np.meshgrid( sample[0], np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) plt.figure(figsize=(5, 10)) ax = plt.subplot() if spectrum_norm: s_norm = np.reshape(np.abs(scalogram).max(1), (-1, 1)) ax.pcolormesh(x, y, np.abs(scalogram) / s_norm, cmap=obspy_sequential) else: ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) plt.xlabel('time around ' + 'Sdiff' + ' (s)', fontsize=18) plt.ylabel('Period (s)', fontsize=18) ax.set_yscale('log')
trace = stream[0] # time resolution of the trace is 0.001 second omega = 8 # in the article was this version # spec, scale = mlpy.cwt(trace.data, dt=trace.stats.delta, dj=0.05, # wf='morlet', p=omega0, extmethod='none', # extlength='powerof2') # this is from https://docs.obspy.org/tutorial/code_snippets/continuous_wavelet_transform.html f_min = 1 f_max = 50 npts = trace.stats.npts dt = trace.stats.delta t = np.linspace(0, dt * npts, npts) scalogram = cwt(trace.data, dt, omega, f_min, f_max) print scalogram.shape print scalogram # again from the article - non logarithimc plot tt = np.arange(trace.stats.npts) / trace.stats.sampling_rate plt.imshow(np.abs(scalogram), extent=(t[0], t[-1], 1, 50)) plt.show() fig = plt.figure() ax = fig.add_subplot(111) x, y = np.meshgrid( t, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) print x.shape, y.shape ax.pcolormesh(x, y, np.abs(scalogram)) ax.set_xlabel("Time after %s [s]" % trace.stats.starttime) ax.set_ylabel("Frequency [Hz]")
#!/usr/bin/env python """2d colormap obspy.""" import numpy as np import matplotlib.pyplot as plt from colormap2d import imshow2d import obspy from obspy.signal.tf_misfit import cwt tr = obspy.read()[0] f_min, f_max = 1, 50 scalogram = cwt(tr.data, tr.stats.delta, 8, f_min, f_max) huelight = np.array([np.angle(scalogram), np.abs(scalogram)]) imshow2d(huelight, cmap2d='brightwheel', origin='lower', aspect='auto') plt.show()
import numpy as np import matplotlib.pyplot as plt from obspy.core import read from obspy.signal.tf_misfit import cwt st = read() tr = st[0] npts = tr.stats.npts dt = tr.stats.delta t = np.linspace(0, dt * npts, npts) f_min = 1 f_max = 50 scalogram = cwt(tr.data, dt, 8, f_min, f_max) fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(np.abs(scalogram)[-1::-1], extent=[t[0], t[-1], f_min, f_max], aspect='auto', interpolation="nearest") ax.set_xlabel("Time after %s [s]" % tr.stats.starttime) ax.set_ylabel("Frequency [Hz]") ax.set_yscale('log') plt.show()
def mergeFiles(mainfolder): i = 1 res = [] EEGTMP = pd.read_csv(filepath_or_buffer=mainfolder + "EEG" + str(i) + ".csv", sep=',', usecols=[2], dtype='double', names={"EEG1"}) # EEGTMP = EEGTMP.values.flatten() # frequencies, times, spectrogram = signal.spectrogram(EEGTMP, 200) # plt.pcolormesh(times, frequencies, spectrogram) # plt.imshow(spectrogram) # plt.ylabel('Frequency [Hz]') # plt.xlabel('Time [sec]') # plt.plot(EEGTMP) # plt.ylabel("volts (mV)") # plt.xlabel("time-steps") # plt.show() # plt.close() low = .01 high = .99 quant_df = EEGTMP.quantile([low, high]) filt_df = norm_data( EEGTMP.apply(lambda x: x[(x > quant_df.loc[low, x.name]) & (x < quant_df.loc[high, x.name])], axis=0)) filt_df = filt_df.flatten() # plt.plot(filt_df) # plt.ylabel("volts (mV)") # plt.xlabel("time-steps") # plt.show() # plt.close() f_min = 1 f_max = 100 t = np.linspace(0, 0.005 * len(filt_df), len(filt_df)) scalogram = cwt(filt_df, dt=0.005, w0=8, nf=256, fmin=f_min, fmax=f_max) fig = plt.figure() ax1 = fig.add_axes([0.1, 0.1, 0.7, 0.60]) ax2 = fig.add_axes([0.1, 0.75, 0.75, 0.2]) ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6]) img = ax1.imshow(np.abs(scalogram)[-1::-1], extent=[t[0], t[-1], f_min, f_max], aspect='auto', interpolation="nearest", vmax=0.1, vmin=0) ax1.set_xlabel("Time after [s]") ax1.set_ylabel("Frequency [Hz]") ax1.set_yscale('linear') ax2.plot(t, filt_df, 'k') fig.colorbar(img, cax=ax3) plt.show() plt.close() specgram(filt_df, NFFT=128, Fs=200, noverlap=0.999) plt.show() f, t, Sxx = signal.spectrogram(norm_data(filt_df), fs=200, nfft=128) plt.pcolormesh(t, f, Sxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [sec]') plt.show() ACCTMP = pd.read_csv(filepath_or_buffer=mainfolder + "ACCELEROMETER" + str(i) + ".csv", sep=',', names={"ACC1", "ACC2", "ACC3"}, usecols=[1, 2, 3], dtype='float') HSHTMP = pd.read_csv(filepath_or_buffer=mainfolder + "HORSE_SHOE" + str(i) + ".csv", sep=',', usecols=[2, 3], dtype='float') hshcnt = ceil(len(EEGTMP) / len(HSHTMP)) acccnt = ceil(len(EEGTMP) / len(ACCTMP)) for j in range(len(EEGTMP)): if (j % hshcnt == 0): hsh = HSHTMP.loc[ceil(j / hshcnt)] if (j % acccnt == 0): print(j, " >> ", ceil(j / acccnt), " >> ", ceil(j / hshcnt)) acc = ACCTMP.loc[ceil(j / acccnt)] if (np.array(hsh)[0] == 1 and hsh[1] == 1): res.append(np.concatenate([np.array(EEGTMP.loc[j]), np.array(acc)])) plt.plot(EEGTMP) plt.show() plt.plot(ACCTMP) plt.show() plt.plot(HSHTMP) plt.show() np.savetxt(mainfolder + "EEG-ACC" + str(i) + ".csv", res, delimiter=",", newline="\n") # plt.plot(res) # plt.show() # for j in range(len(EEGTMP)): # newRow = EEGTMP[j] # acc = ACCTMP return training_filepaths # , testing_filepaths
import numpy as np import matplotlib.pyplot as plt from obspy.core import read from obspy.signal.tf_misfit import cwt st = read() tr = st[0] npts = tr.stats.npts dt = tr.stats.delta t = np.linspace(0, dt * npts, npts) f_min = 1 f_max = 50 scalogram = cwt(tr.data, dt, 8, f_min, f_max) fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(np.abs(scalogram)[-1::-1], extent=[t[0], t[-1], f_min, f_max], aspect='auto') ax.set_xlabel("Time after %s [s]" % tr.stats.starttime) ax.set_ylabel("Frequency [Hz]") plt.show()
reftime=seistoplot.stats['eventtime'])[w0:w1] - phase_time data_series = seistoplot.data[w0:w1] # data_series_filter = seistoplot_filter.data[w0:w1] if count == 0: norm = data_series.max() stack_data_series = data_series / norm # stack_data_series_filter = data_series_filter/norm elif per_norm: stack_data_series = stack_data_series + data_series / data_series.max( ) else: stack_data_series = stack_data_series + data_series / norm count = count + 1 scalogram = cwt(stack_data_series, 0.1, 8, fmin, fmax) x, y = np.meshgrid( time_series, np.logspace(np.log10(fmin), np.log10(fmax), scalogram.shape[0])) fig, ax = plt.subplots(figsize=(9, 9)) ax.pcolormesh(x, 1 / y, np.abs(scalogram), cmap=CBname_map) plt.xlabel('Time around ' + 'Sdiff' + ' (s)', fontsize=18) plt.ylabel('Period (s)', fontsize=18) ax.set_yscale('log') # set linear(detail in 1-2-3) or log(even) ax.set_ylim(Tmin, Tmax) majors = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ax.yaxis.set_major_locator(plt.FixedLocator(majors)) # ax.yaxis.set_minor_locator(plt.NullLocator()) ax.yaxis.set_major_formatter(ScalarFormatter()) ax.yaxis.set_minor_formatter(NullFormatter())
w0 = np.argmin(np.abs(tr.timesarray - Sdifftime - time_min)) w1 = np.argmin(np.abs(tr.timesarray - Sdifftime - time_max)) # w0_ref = np.argmin(np.abs(tr.timesarray-Sdifftime-time_min_ref)) # w1_ref = np.argmin(np.abs(tr.timesarray-Sdifftime-time_max_ref)) # Copy trace trf = tr.copy() trf = trf.filter('bandpass', freqmin=1 / 40., freqmax=1 / 10., zerophase=True) # Plot reference phase with wide filter # plt.plot(tr.times()[w0:w1]-Sdifftime,tr1.data[w0:w1]/np.max(np.abs(tr1.data[w0:w1])),'k') scalogram = cwt(tr.data[w0:w1], tr.stats.delta, 8, f_min, f_max) x, y = np.meshgrid( tr.timesarray[w0:w1] - Sdifftime, np.logspace(np.log10(f_min), np.log10(f_max), scalogram.shape[0])) ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential) if if_norm: norm = np.reshape(np.abs(scalogram).max(1), (-1, 1)) ax.pcolormesh(x, y, np.abs(scalogram) / norm, cmap=obspy_sequential) else: ax.pcolormesh(x, y, np.abs(scalogram), cmap=obspy_sequential)
plot_pad = int(plot_pad_time / dt) data = observables["dipole_acceleration_0_1"][1:] padd2 = 2**np.ceil(np.log2(data.shape[0] * 4)) data = np.lib.pad( data, (int(np.floor((padd2 - data.shape[0]) / 2)), int(np.ceil((padd2 - data.shape[0]) / 2))), 'constant', constant_values=(0.0, 0.0)) print w_list for scale_type in ["lin"]: # for scale_type in ["lin", "log"]: for num in w_list[rank::size]: print "rank", rank, "plotting", num scalogram = cwt(data, dt, num, f_min, f_max, nf=400) lower_idx = scalogram.shape[1] / 2 - (time_len / 2 + plot_pad) upper_idx = scalogram.shape[1] / 2 + (time_len / 2 + plot_pad) scalogram = scalogram[:, lower_idx:upper_idx] time = np.linspace(0, dt * scalogram.shape[1], scalogram.shape[1]) - plot_pad_time fig = plt.figure() x, y = np.meshgrid(time, np.logspace( np.log10(f_min), np.log10(f_max), scalogram.shape[0])) y /= f_0 if scale_type == "lin": plt.contourf(x, y, np.abs(scalogram), 15, cmap='viridis') elif scale_type == "log": min_val = 1e-6