gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_injection_snr
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2015 Ryan Lang
4 #
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.
9 #
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.
14 #
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.
18 
19 ### Used to assign characteristic SNRs to injections
20 ###
21 ### Usage:
22 ### ------
23 ###
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.
26 ###
27 
28 """
29 This program calculates characteristic SNRs given an injection xml and a cache of reference PSDs.
30 """
31 
32 __author__ = 'Ryan Lang <ryan.lang@ligo.org>'
33 
34 import math
35 import numpy
36 import warnings
37 
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
44 import lal
45 from lal.series import *
46 from lal.utils import CacheEntry
47 import lalsimulation
48 
49 import multiprocessing
50 
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")
58 
59  options, filenames = parser.parse_args()
60 
61  if options.reference_psd_cache is None:
62  raise ValueError("Must specify --reference-psd-cache")
63 
64  if options.injection_file is None:
65  raise ValueError("Must specify --injection-file")
66 
67  if options.flow is None:
68  warnings.warn("No --flow specified. Will read from f_lower column of sim_inspiral table.")
69 
70  return options, filenames
71 
72 
73 def calc_expected_snr(inj):
74  # FIXME: don't hard-code detectors
75  snr = dict.fromkeys(("H1", "L1", "V1"), 0.0)
76 
77  injtime = inj.time_geocent
78 
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)
81 
82  if len(psds) < 1:
83  # We know no PSD covers the injection.
84  return snr
85  elif len(psds) == 1:
86  # Only one PSD covers the injection time.
87  seg, chosenPSD = psds.popitem()
88  else:
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
92  # arithmetic.
93  seg, chosenPSD = min(psds.items(), key = lambda x: abs(x[0][0] + abs(x[0]) / 2. - injtime))
94 
95  # FIXME have better scheme for calculating the needed sample_rate
96  sample_rate = 16384.0
97 
98  approximant = lalsimulation.GetApproximantFromString(str(inj.waveform))
99 
100  if approximant == lalsimulation.NR_hdf5:
101  LALparams = lal.CreateDict()
102  lalsimulation.SimInspiralWaveformParamsInsertNumRelData(LALparams, str(inj.numrel_data))
103  f_min = inj.f_lower
104  else:
105  LALparams = None
106  if options.flow is None:
107  f_min = inj.f_lower
108  else:
109  f_min = options.flow
110 
111  h_plus, h_cross = lalsimulation.SimInspiralTD(
112  m1 = inj.mass1*lal.MSUN_SI,
113  m2 = inj.mass2*lal.MSUN_SI,
114  S1x = inj.spin1x,
115  S1y = inj.spin1y,
116  S1z = inj.spin1z,
117  S2x = inj.spin2x,
118  S2y = inj.spin2y,
119  S2z = inj.spin2z,
120  distance = inj.distance*1e6*lal.PC_SI,
121  inclination = inj.inclination,
122  phiRef = inj.coa_phase,
123  longAscNodes = 0.0,
124  eccentricity = 0.0,
125  meanPerAno = 0.0,
126  deltaT = 1.0 / sample_rate,
127  f_min = f_min,
128  f_ref = 0.0,
129  LALparams = LALparams,
130  approximant = approximant
131  )
132 
133  h_plus.epoch += injtime
134  h_cross.epoch += injtime
135 
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:
139  continue
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)
142 
143  return snr
144 
145 @lsctables.use_in
146 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
147  pass
148 
149 ###################################
150 #
151 # Main
152 #
153 ###################################
154 
155 options, filenames = parse_command_line()
156 
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))
162 else:
163  inj_segment = None
164 
165 # Load all PSDs so that they don't need to be loaded for every injection.
166 allPSDs = dict(
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)
169 )
170 
171 pool = multiprocessing.Pool(options.npool)
172 snr = []
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)]):
175  snr.append(simsnr)
176 pool.close()
177 pool.join()
178 
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"]
185 
186 ligolw_utils.write_filename(xmldoc,options.injection_file,verbose = True)