def main(): """ Demonstrate construction of multiple det data streams with a signal injection """ # # Generate waveform # print 'generating waveoform...' waveform = pmns_utils.Waveform('shen_135135_lessvisc') # Pick some extrinsic parameters ext_params = ExtParams(distance=1, ra=0.0, dec=0.0, polarization=0.0, inclination=0.0, phase=0.0, geocent_peak_time=0.0 + 5.0) # Construct the time series for these params waveform.make_wf_timeseries(theta=ext_params.inclination, phi=ext_params.phase) # # Generate IFO data # det1_data = DetData(waveform=waveform, ext_params=ext_params) from scipy import signal import pylab as pl pl.figure() pl.plot(det1_data.td_response.sample_times, det1_data.td_response.data) pl.plot(det1_data.td_signal.sample_times, det1_data.td_signal.data) pl.figure() f, p = signal.welch(det1_data.td_response.data, fs=1. / det1_data.delta_t, nperseg=512) pl.loglog(f, np.sqrt(p)) f, p = signal.welch(det1_data.td_signal.data, fs=1. / det1_data.delta_t, nperseg=512) pl.loglog(f, np.sqrt(p)) pl.ylim(1e-25, 1e-21) pl.show()
method='nelder-mead') return result_theory # -------------------------------------------------------------------- # Data Generation # # Generate Signal Data # # Signal print '' print '--- %s ---' % sys.argv[1] waveform = pmns_utils.Waveform('%s' % sys.argv[1]) waveform.compute_characteristics() # Extrinsic parameters ext_params = simsig.ExtParams(20.0, ra=0.0, dec=0.0, polarization=0.0, inclination=0.0, phase=0.0, geocent_peak_time=0.25) # Frequency range for SNR around f2 peak - we'll go between 1, 5 kHz for the # actual match calculations, though flow = waveform.fpeak - 150 fupp = waveform.fpeak + 150
###################################################################### # Data Generation print >> sys.stdout, ''' ------------------------------------- Beginning pmns_pca_inference: 1) Generating Data ''' # # Generate Signal Data # print >> sys.stdout, "generating waveform..." waveform = pmns_utils.Waveform('%s_lessvisc'%opts.waveform_name) waveform.compute_characteristics() te=time.time() print >> sys.stdout, "...waveform construction took: %f sec"%(te-ts0) # ------------------------------------------------------------------------------------ # --- Set up timing for injection: inject in center of segment # Need to be careful. The latest, longest template must lie within the data # segment. note also that the noise length needs to be a power of 2. max_sig=100e-3 cbc_delta_t=10e-3 # std of gaussian with cbc timing error time_prior_width=3*cbc_delta_t max_sig_len=int(np.ceil(max_sig*16384))
# # Build Catalogues # fshift_center = 1000 print "building catalogues" (freqaxis, low_cat, high_cat, shift_cat, original_cat, fpeaks, low_sigmas, high_sigmas) = pmns_pca_utils.build_catalogues(waveform_names, fshift_center) delta_f = np.diff(freqaxis)[0] # Convert to magnitude/phase full_mag, full_phase = pmns_pca_utils.complex_to_polar(original_cat) shift_mag, shift_phase = pmns_pca_utils.complex_to_polar(shift_cat) low_mag, low_phase = pmns_pca_utils.complex_to_polar(low_cat) high_mag, high_phase = pmns_pca_utils.complex_to_polar(high_cat) waveform = pmns_utils.Waveform(waveform_names[1]) waveform.reproject_waveform() # Window peakidx = np.argmax(abs(waveform.hplus.data)) win = lal.CreateTukeyREAL8Window(len(waveform.hplus), 0.25) waveform.hplus.data *= win.data.data wavdata = np.zeros(16384) wavdata[:len(waveform.hplus.data)] = np.copy(waveform.hplus.data) waveform_TD = pycbc.types.TimeSeries(wavdata, delta_t=waveform.hplus.delta_t) waveform_FD = waveform_TD.to_frequencyseries() mag = abs(waveform_FD.data) phase = np.unwrap(np.angle(waveform_FD.data))
posterior['bandwidth'].samples) durationPDF = bppu.PosteriorOneDPDF(name='duration', posterior_samples=duration_samps) posterior.append(durationPDF) return posterior # ----------------------------------------------------------------------------------------------------------- # **** MAIN **** # posterior_file = sys.argv[1] bsn_file = sys.argv[2] snr_file = sys.argv[3] waveform = pmns_utils.Waveform("shen_135135_lessvisc") #waveform=pmns_utils.Waveform("apr_135135_lessvisc") waveform.compute_characteristics() waveform.reproject_waveform() H = waveform.hplus.to_frequencyseries() fw, axw = pl.subplots() axw.plot(H.sample_frequencies, abs(H), color='r') oneDMenu, twoDMenu, binSizes = oneD_bin_params() # Get true values: truevals = {} for item in oneDMenu: if item == 'frequency': truevals[item] = waveform.fpeak
def main(): print "running pmns_pp_utils.py doesn't do much (yet)" # Get post-proc dir ppdir = sys.argv[1] waveform_name = sys.argv[2] waveform = pmns_utils.Waveform(waveform_name) waveform.reproject_waveform() waveform.compute_characteristics() outdir = os.path.join(ppdir, "gmmfreqs") try: os.makedirs(outdir) except OSError: print 'e' # Identify posterior files: posfiles, Bfiles, snrsfiles, posparents = find_posterior_files(ppdir) logBs = load_Bfiles(Bfiles) SNRs = load_snrfiles(snrsfiles) # Get the frequency posterior modes freq_mode_means, freq_mode_covars = get_modes(posfiles, plot=True) # Compute the fpeak accuracy, assuming the highest freq mode is the one # which captures fpeak freq_acc = abs(waveform.fpeak - freq_mode_means[:, 0]) # # Summarise the results # freq_acc_summary = measurement_summary('GMMfpeakAccuracy', freq_acc) fmax_mu_summary = measurement_summary('GMMfmax', freq_mode_means[:, 0]) fmid_mu_summary = measurement_summary('GMMfmid', freq_mode_means[:, 1]) fmin_mu_summary = measurement_summary('GMMfmin', freq_mode_means[:, 2]) dump_summary( os.path.join(outdir, 'GMMfreqsSummary.txt'), [freq_acc_summary, fmax_mu_summary, fmid_mu_summary, fmin_mu_summary]) # fmax_sigma_summary = measurement_summary('GMMfmax_sigma', # np.sqrt(freq_mode_covars[:,0])) # fmid_sigma_summary = measurement_summary('GMMfmid_sigma', # np.sqrt(freq_mode_covars[:,1])) # fmin_sigma_summary = measurement_summary('GMMfmin_sigma', # np.sqrt(freq_mode_covars[:,2])) # # # Generate Web Page & Plots # # SNR vs freq acc fig, ax = plot_measurement_vs_statistic(x=SNRs, y=freq_acc, \ yerrs=None, truevals=None, param=None, xlabel=r'Injected SNR', ylabel='GMM Frequency Accuracy [Hz]') ax.set_yscale('log') fig.savefig('{outdir}/GMMfpeakAccuracyvsinjSNR.png'.format(outdir=outdir)) pl.close(fig) # logB vs freq acc fig, ax = plot_measurement_vs_statistic(x=logBs, y=freq_acc, \ yerrs=None, truevals=None, param=None, xlabel=r'BSN', ylabel='GMM Frequency Accuracy [Hz]') ax.set_yscale('log') fig.savefig('{outdir}/GMMfpeakAccuracyvsBSN.png'.format(outdir=outdir)) pl.close(fig) # SNR vs maxfreq fig, ax = plot_measurement_vs_statistic(x=SNRs, y=freq_mode_means[:,0], \ yerrs=None, truevals=None, param=None, xlabel=r'Injected SNR', ylabel='GMM Max Frequency [Hz]') fig.savefig('{outdir}/GMMMaxFreqvsinjSNR.png'.format(outdir=outdir)) pl.close(fig) # logB vs maxfreq fig, ax = plot_measurement_vs_statistic(x=logBs, y=freq_mode_means[:,0], \ yerrs=None, truevals=None, param=None, xlabel=r'BSN', ylabel='GMM Max Frequency [Hz]') fig.savefig('{outdir}/GMMMaxFreqvsBSN.png'.format(outdir=outdir)) pl.close(fig) # SNR vs midfreq fig, ax = plot_measurement_vs_statistic(x=SNRs, y=freq_mode_means[:,1], \ yerrs=None, truevals=None, param=None, xlabel=r'Injected SNR', ylabel='GMM Mid Frequency [Hz]') fig.savefig('{outdir}/GMMMidFreqvsinjSNR.png'.format(outdir=outdir)) pl.close(fig) # logB vs midfreq fig, ax = plot_measurement_vs_statistic(x=logBs, y=freq_mode_means[:,1], \ yerrs=None, truevals=None, param=None, xlabel=r'BSN', ylabel='GMM Mid Frequency [Hz]') fig.savefig('{outdir}/GMMMidFreqvsBSN.png'.format(outdir=outdir)) pl.close(fig) # SNR vs minfreq fig, ax = plot_measurement_vs_statistic(x=SNRs, y=freq_mode_means[:,0], \ yerrs=None, truevals=None, param=None, xlabel=r'Injected SNR', ylabel='GMM Min Frequency [Hz]') fig.savefig('{outdir}/GMMMinFreqvsinjSNR.png'.format(outdir=outdir)) pl.close(fig) # logB vs minfreq fig, ax = plot_measurement_vs_statistic(x=logBs, y=freq_mode_means[:,0], \ yerrs=None, truevals=None, param=None, xlabel=r'BSN', ylabel='GMM Min Frequency[Hz]') fig.savefig('{outdir}/GMMMinFreqvsBSN.png'.format(outdir=outdir)) pl.close(fig)
waveform_names = [ 'apr_135135_lessvisc', 'shen_135135_lessvisc', 'dd2_135135_lessvisc', 'dd2_165165_lessvisc', 'nl3_135135_lessvisc', 'nl3_1919_lessvisc', 'tm1_135135_lessvisc', 'tma_135135_lessvisc', 'sfhx_135135_lessvisc', 'sfho_135135_lessvisc' ] # # Waveform # print '' print '--- %s ---' % sys.argv[1] #waveform = pmns_utils.Waveform('%s_lessvisc'%sys.argv[1]) matches = [] for name in waveform_names: waveform = pmns_utils.Waveform(name) waveform.compute_characteristics() # Get optimal hplus waveform.reproject_waveform() h = apply_taper(waveform.hplus) h_s = pycbc.filter.sigma(h, low_frequency_cutoff=fmin, high_frequency_cutoff=fmax) # # Spectrum # H = abs(h.to_frequencyseries())**2 freqs = h.to_frequencyseries().sample_frequencies.data
#datafiles=sys.argv[2] # XXX: Hardcoding #distances=np.array([5, 7.5, 10, 12.5, 15, 17.5, 20]) distances=np.array([20, 25, 30, 35, 40, 45, 50, 55, 60, 70, 80, 90, 100]) odds2pos = lambda logB: 1.0/(1.0+1.0/np.exp(logB)) #logBthresh=np.interp(0.9, odds2pos(np.arange(0, 10, 1e-4)), np.arange(0, 10, # 1e-4)) found_criterion=sys.argv[2] logBthresh=np.log(float(sys.argv[3])) netSNRthresh=float(sys.argv[3]) wf = pmns_utils.Waveform(waveform_name+'_lessvisc') wf.compute_characteristics() logBs = [] netSNRs = [] freq_pdfs = [] maxfreqs = [] meanfreqs = [] credintvals = [] credintwidths = [] confintvals=[] confintwidths=[] #datafiles=glob.glob('LIB-PMNS_waveform-%s_distance-*.pickle'%waveform_name)
for c in xrange(len(upps)): upps[c] = intervals[1][c] - centers[c] lows[c] = centers[c] - intervals[0][c] return lows, upps # ------------------------------- # Load results #datafiles = sys.argv[1] datafile = sys.argv[1] # XXX: Hardcoding wf = pmns_utils.Waveform('dd2_135135_lessvisc') wf.compute_characteristics() # --- Data extraction print >> sys.stdout, "loading %s..." % datafile freq_axis, freq_pdfs_tmp, freq_estimates, all_sig_evs, all_noise_evs =\ pickle.load(open(datafile)) logBs = all_sig_evs - all_noise_evs #logBthreshs = np.linspace(min(logBs), max(logBs), 100) #logBthresh_range = stats.scoreatpercentile(logBs, [5,95]) #logBthreshs = np.linspace(min(logBthresh_range), max(logBthresh_range), 10) logBthreshs = np.arange(-0.5, 0.5 + 0.05, 0.05) # Preallocation
BSN_threshold=-np.inf # --- end input if not os.path.isdir(outputdirectory): os.makedirs(outputdirectory) else: print >> sys.stdout, \ "warning: %s exists, results will be overwritten"%outputdirectory currentdir=os.path.join(outputdirectory,'summaryfigs') # --- Construct the injected waveform if waveform_name not in ["av15", "av16"]: waveform_name += "_lessvisc" waveform = pmns_utils.Waveform('%s'%waveform_name) waveform.reproject_waveform(0,0) waveform.compute_characteristics() # --- Identify files ifospattern="V1H1L1" engineglobpattern="lalinferencenest" sampglobpattern="posterior" BSNfiles = glob.glob('%s/posterior_samples/%s_%s*.dat_B.txt'%( resultsdir, sampglobpattern, ifospattern ) ) snrfiles = glob.glob('%s/engine/%s*-%s-*_snr.txt'%( resultsdir, engineglobpattern, ifospattern ) )