def main_compare_gif_gotic2(): start = tconvert('Oct 15 2018 00:00:00') end = tconvert('Oct 21 2018 00:00:00') # gif data pfx = '/Users/miyo/Dropbox/KagraData/gif/' segments = GifData.findfiles(start, end, 'CALC_STRAIN', prefix=pfx) allfiles = [path for files in segments for path in files] strain = TimeSeries.read(source=allfiles, name='CALC_STRAIN', format='gif', pad=numpy.nan, nproc=2) strain = strain.detrend('linear') # gotic data source = '201805010000_201811010000.gotic' gifx = KagraGoticStrain.read(source, start=start, end=end).x gifx = gifx.detrend('linear') gifx = gifx * 0.9 # plot plot = Plot(gifx, strain, xscale='auto-gps') plot.legend() plot.subplots_adjust(right=.86) plot.savefig('result.png') plot.close()
def spectral_comparison(gps, qspecgram, fringe, output, thresh=15, multipliers=(1, 2, 4, 8), colormap='viridis', figsize=[12, 8]): """Compare a high-resolution spectrogram with projected fringe frequencies Parameters ---------- gps : `float` reference GPS time (in seconds) to serve as the origin qspecgram : `~gwpy.spectrogram.Spectrogram` an interpolated high-resolution spectrogram fringe : `~gwpy.timeseries.TimeSeries` projected fringe frequencies (in Hz) output : `str` name of the output file thresh : `float`, optional frequency threshold (Hz) for scattering fringes, default: 15 multipliers : `tuple`, optional collection of fringe harmonic numbers to plot, can be given in any order, default: `(1, 2, 4, 8)` colormap : `str`, optional matplotlib colormap to use, default: viridis figsize : `tuple`, optional size (width x height) of the final figure, default: `(12, 8)` """ plot = Plot(figsize=figsize) # format spectral plot ax1 = plot.add_subplot(211) ax1.set_title('{0} at {1:.2f} with $Q$ of {2:.1f}'.format( qspecgram.name, gps, qspecgram.q)) _format_spectrogram(ax1, qspecgram, colormap=colormap) ax1.set_xlabel(None) # format fringe frequency plot ax2 = plot.add_subplot(212, sharex=ax1) ax2.set_title('{} scattering fringes'.format(fringe.name)) _format_timeseries(ax2, gps, fringe, multipliers=multipliers, thresh=thresh) # format timeseries axes ax2.set_ylim([-1, 60]) ax2.set_ylabel('Projected Frequency [Hz]') # save plot and close plot.savefig(output, bbox_inches='tight') plot.close()
def make_omegascan(ifo, t0, durs): """Helper function to create a single omegascan image, with multiple durations. Parameters ---------- ifo : str 'H1', 'L1', or 'V1' t0 : int or float Central time of the omegascan. durs : list of floats/ints List of three durations which will be scanned symmetrically about t0. Example: [0.5, 2, 10] Returns ------- bytes or None bytes of png of the omegascan, or None if no omegascan created. """ # Explicitly use a non-interactive Matplotlib backend. plt.switch_backend('agg') # Collect data longest = max(durs) long_start, long_end = t0 - longest, t0 + longest cache = create_cache(ifo, long_start, long_end) strain_name = app.conf['strain_channel_names'][ifo] try: ts = TimeSeries.read(cache, strain_name, start=long_start, end=long_end).astype('float64') # Do q_transforms for the different durations qgrams = [ts.q_transform( frange=(20, 4096), gps=t0, outseg=(t0 - dur, t0 + dur), logf=True) for dur in durs] except (IndexError, FloatingPointError, ValueError): # data from cache can't be properly read, or data is weird fig = plt.figure() plt.axis("off") plt.text(0.1, 0.45, f"Failed to create {ifo} omegascan", fontsize=17) else: fig = Plot(*qgrams, figsize=(10 * len(durs), 5), geometry=(1, len(durs)), yscale='log', method='pcolormesh') for ax in fig.axes: fig.colorbar(ax=ax, label='Normalized energy', clim=(0, 30)) ax.set_epoch(t0) fig.suptitle(f'Omegascans of {strain_name} at {t0}', fontweight="bold") outfile = io.BytesIO() fig.savefig(outfile, format='png', dpi=300) return outfile.getvalue()
def plot_timeseries(*data, **kwargs): title = kwargs.pop('title', None) ylim = kwargs.pop('ylim', None) fname = kwargs.pop('fname', 'TimeSeries.png') plot = Plot(figsize=(15, 10)) ax0 = plot.gca() ax0.plot(*data) ax0.legend([text.to_string(_data.name) for _data in data], fontsize=20) ax0.set_xscale('auto-gps') ax0.set_ylabel(text.to_string(data[0].unit)) plot.add_state_segments(segments_daq_iy0_ok, label='IY0 DAQ State') plot.add_state_segments(segments_daq_ix1_ok, label='IX1 DAQ State') plot.suptitle(title, fontsize=40) if ylim: ax0.set_ylim(ylim[0], ylim[1]) plot.savefig(fname) plot.close()
def spectral_overlay(gps, qspecgram, fringe, output, multipliers=(1, 2, 4, 8), figsize=[12, 4]): """Overlay scattering fringe projections on top of a high-resolution spectrogram Parameters ---------- gps : `float` reference GPS time (in seconds) to serve as the origin qspecgram : `~gwpy.spectrogram.Spectrogram` an interpolated high-resolution spectrogram fringe : `~gwpy.timeseries.TimeSeries` projected fringe frequencies (in Hz) output : `str` name of the output file multipliers : `tuple`, optional collection of fringe harmonic numbers to plot, can be given in any order, default: `(1, 2, 4, 8)` figsize : `tuple`, optional size (width x height) of the final figure, default: `(12, 4)` """ plot = Plot(figsize=figsize) ax = plot.gca() # format spectrogram plot ax.set_title('Fringes: {0}, Spectrogram: {1}'.format( fringe.name, qspecgram.name)) _format_spectrogram(ax, qspecgram, colormap='binary') # overlay fringe frequencies _format_timeseries(ax, gps, fringe, multipliers=multipliers, linewidth=1.5) ax.set_ylim([ qspecgram.f0.to('Hz').value, qspecgram.frequencies.max().to('Hz').value ]) # save plot and close plot.savefig(output, bbox_inches='tight') plot.close()
def plot_asd(data,replot=False,fftlength=2**7,show=False,**kwargs): if isinstance(data,TimeSeries): chname = data.name psd_specgram = data.spectrogram2(fftlength=fftlength, overlap=fftlength/2.0, window='hanning') elif isinstance(data,Spectrogram): chname = data.name specgram = data pngfname = to_pngfname(chname,ftype='ASD',**kwargs) if not replot and os.path.exists(pngfname): print('Skip plot {0}'.format(pngfname)) return None median = specgram.percentile(50) low = specgram.percentile(5) high = specgram.percentile(95) median = vel2vel(median) low = vel2vel(low) high = vel2vel(high) _f, _selfnoise = trillium.selfnoise(trillium='120QA',psd='ASD',unit='velo') _selfnoise = _selfnoise*1e6 plot = Plot() ax = plot.gca(xscale='log', xlim=(1e-3, 3e2), xlabel='Frequency [Hz]', #yscale='log', ylim=(1e-11, 3e-6), yscale='log', ylim=(1e-5, 3e-0), ylabel=r'Velocity [m/sec/\rtHz]') ax.plot(_f,_selfnoise,'-',linewidth=1,color='gray') ax.plot_mmm(median, low, high, color='gwpy:ligo-livingston') ax.set_title(chname.replace('_',' '),fontsize=16) ax.legend(labels=['Selfnoise','Measurement']) plot.savefig(pngfname) print('plot in ',pngfname) return plot
def spectral_overlay(gps, qspecgram, fringe, output, multipliers=(1, 2, 4, 8), figsize=[12, 4]): """Overlay scattering fringe projections on top of a high-resolution spectrogram Parameters ---------- gps : `float` reference GPS time (in seconds) to serve as the origin qspecgram : `~gwpy.spectrogram.Spectrogram` an interpolated high-resolution spectrogram fringe : `~gwpy.timeseries.TimeSeries` projected fringe frequencies (in Hz) output : `str` name of the output file multipliers : `tuple`, optional collection of fringe harmonic numbers to plot, can be given in any order, default: `(1, 2, 4, 8)` figsize : `tuple`, optional size (width x height) of the final figure, default: `(12, 4)` """ plot = Plot(figsize=figsize) ax = plot.gca() # format spectrogram plot ax.set_title('Fringes: {0}, Spectrogram: {1}'.format( fringe.name, qspecgram.name)) _format_spectrogram(ax, qspecgram, colormap='binary') # overlay fringe frequencies _format_timeseries(ax, gps, fringe, multipliers=multipliers, linewidth=1.5) ax.set_ylim([qspecgram.f0.to('Hz').value, qspecgram.frequencies.max().to('Hz').value]) # save plot and close plot.savefig(output, bbox_inches='tight') plot.close()
def significance_drop(outfile, old, new, show_channel_names=None, **kwargs): """Plot the signifiance drop for each channel """ channels = sorted(old.keys()) if show_channel_names is None: show_channel_names = len(channels) <= 50 plot = Plot(figsize=(18, 6)) plot.subplots_adjust(left=.07, right=.93) ax = plot.gca() if show_channel_names: plot.subplots_adjust(bottom=.4) winner = sorted(old.items(), key=lambda x: x[1])[-1][0] for i, c in enumerate(channels): if c == winner: color = 'orange' elif old[c] > new[c]: color = 'dodgerblue' else: color = 'red' ax.plot([i, i], [old[c], new[c]], color=color, linestyle='-', marker='o', markeredgecolor='k', markeredgewidth=.5, markersize=10, label=c, zorder=old[c]) ax.set_xlim(-1, len(channels)) ax.set_ybound(lower=0) # set xticks to show channel names if show_channel_names: ax.set_xticks(range(len(channels))) ax.set_xticklabels([c.replace('_','\_') for c in channels]) for i, t in enumerate(ax.get_xticklabels()): t.set_rotation(270) t.set_verticalalignment('top') t.set_horizontalalignment('center') t.set_fontsize(8) # or just show systems of channels else: plot.canvas.draw() systems = {} for i, c in enumerate(channels): sys = c.split(':', 1)[1].split('-')[0].split('_')[0] try: systems[sys][1] += 1 except KeyError: systems[sys] = [i, 1] systems = sorted(systems.items(), key=lambda x: x[1][0]) labels, counts = zip(*systems) xticks, xmticks = zip(*[(a, a+b/2.) for (a, b) in counts]) # show ticks at the edge of each group ax.set_xticks(xticks, minor=False) ax.set_xticklabels([], minor=False) # show label in the centre of each group ax.set_xticks(xmticks, minor=True) for t in ax.set_xticklabels(labels, minor=True): t.set_rotation(270) kwargs.setdefault('ylabel', 'Significance') # create interactivity if outfile.endswith('.svg'): _finalize_plot(plot, ax, outfile.replace('.svg', '.png'), close=False, **kwargs) tooltips = [] ylim = ax.get_ylim() yoffset = (ylim[1] - ylim[0]) * 0.061 bbox = {'fc': 'w', 'ec': '.5', 'alpha': .9, 'boxstyle': 'round'} xthresh = len(channels) / 10. for i, l in enumerate(ax.lines): x = l.get_xdata()[1] if x < xthresh: ha = 'left' elif x > (len(channels) - xthresh): ha ='right' else: ha = 'center' y = l.get_ydata()[0] + yoffset c = l.get_label() tooltips.append(ax.annotate(c.replace('_', r'\_'), (x, y), ha=ha, zorder=ylim[1], bbox=bbox)) l.set_gid('line-%d' % i) tooltips[-1].set_gid('tooltip-%d' % i) f = BytesIO() plot.savefig(f, format='svg') tree, xmlid = etree.XMLID(f.getvalue()) tree.set('onload', 'init(evt)') for i in range(len(tooltips)): try: e = xmlid['tooltip-%d' % i] except KeyError: warnings.warn("Failed to recover tooltip %d" % i) continue e.set('visibility', 'hidden') for i, l in enumerate(ax.lines): e = xmlid['line-%d' % i] e.set('onmouseover', 'ShowTooltip(this)') e.set('onmouseout', 'HideTooltip(this)') tree.insert(0, etree.XML(SHOW_HIDE_JAVASCRIPT)) etree.ElementTree(tree).write(outfile) plot.close() else: _finalize_plot(plot, ax, outfile, **kwargs)
def inject_signal_into_gwpy_timeseries(data, waveform_generator, parameters, det, power_spectral_density=None, outdir=None, label=None): """ Inject a signal into a gwpy timeseries Parameters ========== data: gwpy.timeseries.TimeSeries The time-series data into which we want to inject the signal waveform_generator: bilby.gw.waveform_generator.WaveformGenerator An initialised waveform_generator parameters: dict A dictionary of the signal-parameters to inject det: bilby.gw.detector.Interferometer The interferometer for which the data refers too power_spectral_density: bilby.gw.detector.PowerSpectralDensity Power spectral density determining the sensitivity of the detector. outdir, label: str If given, the outdir and label used to generate a plot Returns ======= data_and_signal: gwpy.timeseries.TimeSeries The data with the time-domain signal added meta_data: dict A dictionary of meta data about the injection """ from gwpy.timeseries import TimeSeries from gwpy.plot import Plot ifo = get_empty_interferometer(det) if isinstance(power_spectral_density, PowerSpectralDensity): ifo.power_spectral_density = power_spectral_density elif power_spectral_density is not None: raise TypeError( "Input power_spectral_density should be bilby.gw.detector.psd.PowerSpectralDensity " "object or None, received {}.".format( type(power_spectral_density))) ifo.strain_data.set_from_gwpy_timeseries(data) parameters_check, _ = convert_to_lal_binary_black_hole_parameters( parameters) parameters_check = { key: parameters_check[key] for key in ['mass_1', 'mass_2', 'a_1', 'a_2', 'tilt_1', 'tilt_2'] } safe_time = get_safe_signal_duration(**parameters_check) if data.duration.value < safe_time: ValueError( "Injecting a signal with safe-duration {} longer than the data {}". format(safe_time, data.duration.value)) waveform_polarizations = waveform_generator.time_domain_strain(parameters) signal = np.zeros(len(data)) for mode in waveform_polarizations.keys(): det_response = ifo.antenna_response(parameters['ra'], parameters['dec'], parameters['geocent_time'], parameters['psi'], mode) signal += waveform_polarizations[mode] * det_response time_shift = ifo.time_delay_from_geocenter(parameters['ra'], parameters['dec'], parameters['geocent_time']) dt = parameters['geocent_time'] + time_shift - data.times[0].value n_roll = dt * data.sample_rate.value n_roll = int(np.round(n_roll)) signal_shifted = TimeSeries(data=np.roll(signal, n_roll), times=data.times, unit=data.unit) signal_and_data = data.inject(signal_shifted) if outdir is not None and label is not None: fig = Plot(signal_shifted) fig.savefig('{}/{}_{}_time_domain_injected_signal'.format( outdir, ifo.name, label)) meta_data = dict() frequency_domain_signal, _ = utils.nfft( signal, waveform_generator.sampling_frequency) meta_data['optimal_SNR'] = (np.sqrt( ifo.optimal_snr_squared(signal=frequency_domain_signal)).real) meta_data['matched_filter_SNR'] = (ifo.matched_filter_snr( signal=frequency_domain_signal)) meta_data['parameters'] = parameters logger.info("Injected signal in {}:".format(ifo.name)) logger.info(" optimal SNR = {:.2f}".format(meta_data['optimal_SNR'])) logger.info(" matched filter SNR = {:.2f}".format( meta_data['matched_filter_SNR'])) for key in parameters: logger.info(' {} = {}'.format(key, parameters[key])) return signal_and_data, meta_data
#ax.loglog(aanoise,'b--',label='AA Noise',linewidth=1,alpha=0.7) ax.loglog(exv_x, 'k-', label='EXV') ax.loglog(ixv_x, label='IXV1') ax.set_xlim(1e-2, 10) ax.set_ylim(1e-12, 5e-5) #ax.loglog(ixv2,label='IXV2') #ax.loglog(d12,label='IXV1-IXV2') #ax.loglog(strain,label='StrainMeter') ax.legend(fontsize=8, loc='lower left') ax.set_title( 'Seismometer, {dname}'.format(dname=dataname.replace('_', '')), fontsize=16) if not os.path.exists('./results/{dname}'.format(dname=dataname)): os.mkdir('./results/{dname}'.format(dname=dataname)) plot.savefig(fname_img_asd.format(dname=dataname)) plot.close() print(fname_img_asd.format(dname=dataname)) # # # # f = np.logspace(-3, 2, 1e4) w = 2.0 * np.pi * f L = 3000.0 # m c_p = 5500.0 # m/sec c_r = 5500.0 # m/sec cdmr_p = lambda w, c: np.sqrt((1.0 + np.cos(L * w / c)) / (1.0 - np.cos(L * w / c))) #cdmr_r = lambda w,c: np.sqrt((1.0+jv(0,2*L*w/c))/(1.0-jv(0,2*L*w/c))) cdmr_r = lambda w, c: np.sqrt((1.0 + jv(0, L * w / c)) /
alpha=0.7) ax.loglog(adcnoise, 'r--', label='ADC Noise', linewidth=1, alpha=0.7) ax.loglog(ampnoise, 'g--', label='Amp Noise', linewidth=1, alpha=0.7) ax.loglog(aanoise, 'b--', label='AA Noise', linewidth=1, alpha=0.7) ax.loglog(exv0, 'k-', label='EXV') ax.loglog(ixv1, label='IXV1') #ax.loglog(ixv2,label='IXV2') #ax.loglog(d12,label='IXV1-IXV2') #ax.loglog(strain,label='StrainMeter') #ImportError: No module named gwpy.plot ax.legend(fontsize=8, loc='lower left') ax.set_title( 'Seismometer, {dname}'.format(dname=dataname.replace('_', '')), fontsize=16) plot.savefig('./{dname}/ASD_{dname}_X.png'.format(dname=dataname)) plot.close() print('save ./{dname}/ASD_{dname}_X.png'.format(dname=dataname)) # f = np.logspace(-3, 2, 1e4) w = 2.0 * np.pi * f L = 3000.0 # m c_p = 5500.0 # m/sec cdmr_p = lambda w, c: np.sqrt((1.0 + np.cos(L * w / c)) / (1.0 - np.cos(L * w / c))) cdmr_ps = lambda w, c: np.sqrt((1.0 + jv(0, 2 * L * w / c)) / (1.0 - jv(0, 2 * L * w / c))) if True: from gwpy.plot import Plot
pdp_m = pdp.percentile(50) pdp_l = pdp.percentile(5) pdp_h = pdp.percentile(95) pds = spol.spectrogram2(fftlength=2, overlap=1, window='hanning')**(1 / 2.) pds_m = pds.percentile(50) pds_l = pds.percentile(5) pds_h = pds.percentile(95) # Plot asd graph from gwpy.plot import Plot plot = Plot() ax = plot.gca( xscale='log', xlim=(1, 50000), xlabel='Frequency [Hz]', yscale='log', #ylim=(3e-24, 2e-20), ylabel=r'Voltage [V/\rtHz]') ax.plot_mmm(pdp_m, pdp_l, pdp_h, color='gwpy:ligo-hanford', label='P-polarized signal') ax.plot_mmm(pds_m, pds_l, pds_h, color='gwpy:ligo-livingston', label='S-polarized signal') ax.set_title('PD voltage', fontsize=16) ax.legend() plot.savefig('asd.png')
xlabel='Frequency [Hz]', yscale='log', ylim=(1e-5, 3e-0), ylabel=r'Velocity [um/sec/\rtHz]') ax.plot(_f, _selfnoise, '-', linewidth=1, color='gray') ax.plot(asd1, label='1', color='black', linewidth=3) #ax.plot(asd2,label='2',color='red',linewidth=1) #ax.plot(asd3,label='3',color='blue',linewidth=1) #ax.plot(adc,label='adc',color='green',linewidth=1) #ax.plot(noise13,'o',label='Noise13 : IXV*(1-coh13) ',markersize=1) #ax.plot(noise12,'o',label='Noise12 : IXV*(1-coh12) ',markersize=1) ax.plot(signal13, label='Signal13 : IXV*coh13 ', markersize=1) ax.plot(signal12, label='Signal12 : IXV*coh12 ', markersize=1) #ax.plot(signal_local,label='Local Signal') ax.legend() plot.savefig('ASD.png') print 'plot in ASD.png' exit() plot_asd(specgram1, replot=True, **kwargs) plot_asd(specgram2, replot=True, **kwargs) plot_spectrogram(specgram1, replot=True, **kwargs) plot_spectrogram(specgram2, replot=True, **kwargs) plot_spectrogram(coherence_mag_specgram, replot=True, normlog=False, **kwargs) plot_coherence(csd_specgram, specgram1, specgram2, fftlength=fftlength, **kwargs)
def significance_drop(outfile, old, new, show_channel_names=None, **kwargs): """Plot the signifiance drop for each channel """ channels = sorted(old.keys()) if show_channel_names is None: show_channel_names = len(channels) <= 50 plot = Plot(figsize=(20, 5)) plot.subplots_adjust(left=.07, right=.93) ax = plot.gca() if show_channel_names: plot.subplots_adjust(bottom=.4) winner = sorted(old.items(), key=lambda x: x[1])[-1][0] for i, c in enumerate(channels): if c == winner: color = 'orange' elif old[c] > new[c]: color = 'dodgerblue' else: color = 'red' ax.plot([i, i], [old[c], new[c]], color=color, linestyle='-', marker='o', markeredgecolor='k', markeredgewidth=.5, markersize=10, label=c, zorder=old[c]) ax.set_xlim(-1, len(channels)) ax.set_ybound(lower=0) # set xticks to show channel names if show_channel_names: ax.set_xticks(range(len(channels))) ax.set_xticklabels([texify(c) for c in channels]) for i, t in enumerate(ax.get_xticklabels()): t.set_rotation(270) t.set_verticalalignment('top') t.set_horizontalalignment('center') t.set_fontsize(8) # or just show systems of channels else: plot.canvas.draw() systems = {} for i, c in enumerate(channels): sys = c.split(':', 1)[1].split('-')[0].split('_')[0] try: systems[sys][1] += 1 except KeyError: systems[sys] = [i, 1] systems = sorted(systems.items(), key=lambda x: x[1][0]) labels, counts = zip(*systems) xticks, xmticks = zip(*[(a, a + b / 2.) for (a, b) in counts]) # show ticks at the edge of each group ax.set_xticks(xticks, minor=False) ax.set_xticklabels([], minor=False) # show label in the centre of each group ax.set_xticks(xmticks, minor=True) for t in ax.set_xticklabels(labels, minor=True): t.set_rotation(270) kwargs.setdefault('ylabel', 'Significance') # create interactivity if outfile.endswith('.svg'): _finalize_plot(plot, ax, outfile.replace('.svg', '.png'), close=False, **kwargs) tooltips = [] ylim = ax.get_ylim() yoffset = (ylim[1] - ylim[0]) * 0.061 bbox = {'fc': 'w', 'ec': '.5', 'alpha': .9, 'boxstyle': 'round'} xthresh = len(channels) / 10. for i, l in enumerate(ax.lines): x = l.get_xdata()[1] if x < xthresh: ha = 'left' elif x > (len(channels) - xthresh): ha = 'right' else: ha = 'center' y = l.get_ydata()[0] + yoffset c = l.get_label() tooltips.append( ax.annotate(texify(c), (x, y), ha=ha, zorder=ylim[1], bbox=bbox)) l.set_gid('line-%d' % i) tooltips[-1].set_gid('tooltip-%d' % i) f = BytesIO() plot.savefig(f, format='svg') tree, xmlid = etree.XMLID(f.getvalue()) tree.set('onload', 'init(evt)') for i in range(len(tooltips)): try: e = xmlid['tooltip-%d' % i] except KeyError: warnings.warn("Failed to recover tooltip %d" % i) continue e.set('visibility', 'hidden') for i, l in enumerate(ax.lines): e = xmlid['line-%d' % i] e.set('onmouseover', 'ShowTooltip(this)') e.set('onmouseout', 'HideTooltip(this)') tree.insert(0, etree.XML(SHOW_HIDE_JAVASCRIPT)) etree.ElementTree(tree).write(outfile) plot.close() else: _finalize_plot(plot, ax, outfile, **kwargs)
nproc=2, window='hanning')**(1 / 2.) print('fft done') # percentile median = sg.percentile(50) low = sg.percentile(5) high = sg.percentile(95) print('percentile done') # plot TimeSeries plot = data.plot() plot.savefig('./img_timeseries.png') plot.close() # plot Spectrum plot = Plot() ax = plot.gca( xscale='log', xlim=(1e-3, 200), xlabel='Frequency [Hz]', yscale='log', # ylim=(3e-24, 2e-20), ylabel=r'Ground Velocity [um/sec/\rtHz]') ax.plot_mmm(median, low, high, color='gwpy:ligo-hanford') ax.set_title('No title', fontsize=16) plot.savefig('./img_asd.png') # write data low.write('data1_exv_x_5pct.hdf5', format='hdf5', overwrite=True) median.write('data1_exv_x_50pct.hdf5', format='hdf5', overwrite=True) high.write('data1_exv_x_95pct.hdf5', format='hdf5', overwrite=True)
ax.set_title('Trillium120QA Noise Investigation', fontsize=20) ax.text(110, 1e-7, 'START : {0}'.format(start), rotation=90, ha='left', va='bottom') ax.text(150, 1e-7, 'BW : {0:3.2e}, Window : {1}, AVE : {2:3d}'.format( df, window, ave), rotation=90, ha='left', va='bottom') ax.legend(fontsize=12) plot.savefig('img_comparison_ixv1_diff12.png') # ----------------------------------------------- # DIFF12 DIFF13 # ----------------------------------------------- if comparison_diff12_diff13: from gwpy.plot import Plot plot = Plot() ax = plot.gca(xscale='log', xlim=(1e-3, 100), yscale='log', ylim=(1e-7, 1e2)) ax.plot(diff13, color='k', label=r'(IXV1 - EXV)/$\sqrt{2}$') ax.plot(diff12, color='r', label=r'(IXV1 - IXV2)/$\sqrt{2}$') ax.plot(tr120_selfnoise, color='k', label='selfnoise', linestyle='--') ax.set_xlabel('Frequency [Hz]', fontsize=15)
if len(pks) > 0: try: Max_Amp = 10**np.max(x[pks[(pks > 1200) & (pks < 4800)]]) Max_Amp_Loc = pks[np.argmax(x[pks[(pks > 1200) & (pks < 4800)]])] except: print("An exception occured, peak likely to be out of range") print("Max_Amp = {} nm/s, Max_Amp_Loc = {}".format(Max_Amp,Max_Amp_Loc)) print(' ') ########################### SAVE RESULTS ############################# if saveData: np.savetxt(fileName,dataX) print('Data saved to {}'.format(fileName) ) if saveImage: plot = Plot(DATA, figsize=(12, 6), sharex=True, yscale='log') ax1 = plot.axes for ifo, ax in zip(('Livingston'), (ax1)): ax.legend(['ITMY-X', 'ITMY-Y', 'ITMY-Z','ETMY-X', 'ETMY-Y', 'ETMY-Z','ETMX-X', 'ETMX-Y', 'ETMX-Z']) #ax.text(1.01, 0.5, ifo, ha='left', va='center', transform=ax.transAxes,fontsize=18) ax.set_ylabel('Ground motion [$ nm/s $]') ax.set_title('Magnitude {} earthquake: Impact on {}'.format(MAG,IFO)) plot.savefig(figName) print('Figure saved to {}'.format(figName) ) if saveResult: np.savetxt(resultName, (Max_Amp,Max_Amp_Loc)) print('Result saved to {}'.format(resultName) ) print("#########################################################")
Max_Amp_Loc = pks[np.argmax(x[pks[(pks > 1200) & (pks < 4800)]])] except: print("An exception occured, peak likely to be out of range") print("Max_Amp = {} nm/s, Max_Amp_Loc = {}".format(Max_Amp, Max_Amp_Loc)) print(' ') ########################### SAVE RESULTS ############################# if saveData: np.savetxt(fileName, dataX) print('Data saved to {}'.format(fileName)) if saveImage: plot = Plot(DATA, figsize=(12, 6), sharex=True, yscale='log') ax1 = plot.axes for ifo, ax in zip(('Livingston'), (ax1)): ax.legend([ 'ITMY-X', 'ITMY-Y', 'ITMY-Z', 'ETMY-X', 'ETMY-Y', 'ETMY-Z', 'ETMX-X', 'ETMX-Y', 'ETMX-Z' ]) #ax.text(1.01, 0.5, ifo, ha='left', va='center', transform=ax.transAxes,fontsize=18) ax.set_ylabel('Ground motion [$ nm/s $]') ax.set_title('Magnitude {} earthquake: Impact on {}'.format(MAG, IFO)) plot.savefig(figName) print('Figure saved to {}'.format(figName)) if saveResult: np.savetxt(resultName, (Max_Amp, Max_Amp_Loc)) print('Result saved to {}'.format(resultName)) print("#########################################################")
'''Read timeseriese from gwffile. ''' __author__ = "Koseki Miyo" from gwpy.timeseries import TimeSeries from gwpy.plot import Plot start = '2019 Jan 10 05:36:46' end = '2019 Jan 10 06:07:18' chname = 'K1:PEM-IXV_GND_TR120Q_X_OUT_DQ' data = TimeSeries.fetch(chname,start,end,host='k1nds0',port=8088) sg = data.spectrogram2(fftlength=2**7, overlap=2**6, window='hanning') ** (1/2.) median = sg.percentile(50) low = sg.percentile(5) high = sg.percentile(95) plot = Plot() ax = plot.gca(xscale='log', xlim=(0.01, 100), xlabel='Frequency [Hz]', yscale='log', #ylim=(3e-24, 2e-20), ylabel=r'Strain noise [1/\rtHz]') ax.plot_mmm(median, low, high, color='gwpy:ligo-hanford') ax.set_title('LIGO-Hanford strain noise variation around GW170817', fontsize=16) plot.savefig('result_asd.png')