3 # Copyright (C) 2015 Ryan Lang
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 ### Used to assign characteristic SNRs to injections
24 ### Takes an injection xml and a cache of reference PSDs and calculated characteristic SNRs. The values
25 ### will be written to the alpha1 and alpha2 columns in the sim_inspiral table.
29 This program calculates characteristic SNRs given an injection xml and a cache of reference PSDs.
32 __author__ =
'Ryan Lang <ryan.lang@ligo.org>'
38 from optparse
import OptionParser
39 from ligo
import segments
40 from ligo.lw
import ligolw
41 from ligo.lw
import lsctables
42 from glue.lal
import Cache
43 from ligo.lw
import utils as ligolw_utils
45 from lal.series
import *
46 from lal.utils
import CacheEntry
49 import multiprocessing
51 def parse_command_line():
52 parser = OptionParser(description = __doc__)
53 parser.add_option(
"--reference-psd-cache", metavar =
"filename", help =
"Set the reference psd cache file.")
54 parser.add_option(
"--injection-file", metavar =
"filename", help =
"Set the injection xml file.")
55 parser.add_option(
"--flow", metavar =
"value", type =
"float", help =
"Set the low frequency for waveform generation and SNR integral.")
56 parser.add_option(
"--fmax", metavar =
"value", type =
"float",default=1600, help =
"Set the max frequency for waveform generation and SNR integral.Default 1600Hz")
57 parser.add_option(
"--npool", metavar =
"value", type =
"int", default = 2, help =
"Set value for pool. Number of parallel sub-processes")
59 options, filenames = parser.parse_args()
61 if options.reference_psd_cache is None:
62 raise ValueError(
"Must specify --reference-psd-cache")
64 if options.injection_file is None:
65 raise ValueError(
"Must specify --injection-file")
67 if options.flow is None:
68 warnings.warn(
"No --flow specified. Will read from f_lower column of sim_inspiral table.")
70 return options, filenames
73 def calc_expected_snr(inj):
74 # FIXME: don
't hard-code detectors
75 snr = dict.fromkeys(("H1", "L1", "V1"), 0.0)
77 injtime = inj.time_geocent
79 # Determine which PSD files have GPS times covering the injection time.
80 psds = dict((seg, psd) for seg, psd in allPSDs.items() if injtime in seg)
83 # We know no PSD covers the injection.
86 # Only one PSD covers the injection time.
87 seg, chosenPSD = psds.popitem()
89 # More than one PSD covers the injection time. Find the
90 # one whose segment is closest to being centred on the
91 # injection. Compute segment centre using overflow-safe
93 seg, chosenPSD = min(psds.items(), key = lambda x: abs(x[0][0] + abs(x[0]) / 2. - injtime))
95 # FIXME have better scheme for calculating the needed sample_rate
98 approximant = lalsimulation.GetApproximantFromString(str(inj.waveform))
100 if approximant == lalsimulation.NR_hdf5:
101 LALparams = lal.CreateDict()
102 lalsimulation.SimInspiralWaveformParamsInsertNumRelData(LALparams, str(inj.numrel_data))
106 if options.flow is None:
111 h_plus, h_cross = lalsimulation.SimInspiralTD(
112 m1 = inj.mass1*lal.MSUN_SI,
113 m2 = inj.mass2*lal.MSUN_SI,
120 distance = inj.distance*1e6*lal.PC_SI,
121 inclination = inj.inclination,
122 phiRef = inj.coa_phase,
126 deltaT = 1.0 / sample_rate,
129 LALparams = LALparams,
130 approximant = approximant
133 h_plus.epoch += injtime
134 h_cross.epoch += injtime
136 # Compute strain in each detector. If one detector wasn't on, snr will be set to zero.
137 for instrument in snr:
138 if instrument not in chosenPSD:
140 h = lalsimulation.SimDetectorStrainREAL8TimeSeries(h_plus, h_cross, inj.longitude, inj.latitude, inj.polarization, lalsimulation.DetectorPrefixToLALDetector(instrument))
141 snr[instrument] = lalsimulation.MeasureSNR(h, chosenPSD[instrument], options.flow, options.fmax)
146 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
149 ###################################
153 ###################################
155 options, filenames = parse_command_line()
157 # Now we need to read in from the sim_inspiral table
158 xmldoc = ligolw_utils.load_filename(options.injection_file, verbose = True, contenthandler = LIGOLWContentHandler)
159 sim_inspiral_table = lsctables.SimInspiralTable.get_table(xmldoc)
160 if sim_inspiral_table:
161 inj_segment = segments.segment(min(inj.time_geocent for inj in sim_inspiral_table), max(inj.time_geocent for inj in sim_inspiral_table))
165 # Load all PSDs so that they don
't need to be loaded for every injection.
167 (cacheentry.segment, read_psd_xmldoc(ligolw_utils.load_url(cacheentry.url, verbose = True, contenthandler = PSDContentHandler)))
168 for cacheentry in map(CacheEntry, open(options.reference_psd_cache)) if inj_segment is not None and cacheentry.segment.intersects(inj_segment)
171 pool = multiprocessing.Pool(options.npool)
173 #print pool.map(calc_expected_snr,[inj for idx, inj in enumerate(sim_inspiral_table)])
174 for simsnr in pool.map(calc_expected_snr,[inj for idx, inj in enumerate(sim_inspiral_table)]):
179 # FIXME: get proper columns
180 # FIXME: broken for KAGRA
181 for idx, inj in enumerate(sim_inspiral_table):
182 inj.alpha4 = snr[idx]["H1"]
183 inj.alpha5 = snr[idx]["L1"]
184 inj.alpha6 = snr[idx]["V1"]
186 ligolw_utils.write_filename(xmldoc,options.injection_file,verbose = True)