gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_make_snr_pdf
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2016,2017 Kipp Cannon, Chad Hanna
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 
20 
21 ### Generate an SNR PDF database file.
22 
23 
24 #
25 # =============================================================================
26 #
27 # Preamble
28 #
29 # =============================================================================
30 #
31 
32 
33 import itertools
34 import logging
35 import math
36 from optparse import OptionParser
37 import time
38 
39 
40 from ligo.lw import ligolw
41 from ligo.lw import utils as ligolw_utils
42 from ligo.lw.utils import process as ligolw_process
43 from glue.text_progress_bar import ProgressBar
44 from gstlal import reference_psd
45 from gstlal.stats import inspiral_extrinsics
46 import lal.series
47 from lal.utils import CacheEntry
48 
49 
50 #
51 # =============================================================================
52 #
53 # Command Line
54 #
55 # =============================================================================
56 #
57 
58 
59 def parse_command_line():
60  parser = OptionParser(
61  description = ""
62  )
63 
64  parser.add_option("-f", "--full", action = "store_true", help = "Generate SNR PDFs for all possible horizon distance ratios as defined by the SNR PDF mechanism's internal quantization system. Use --instruments to select the detector network to model (required). A PDF will be constructed for every combination of --min-instruments or more instruments from the set. When --full is enabled, any --horizon-distances options and/or PSD files are ignored. See also --full-fragment for information on parallelization.")
65  parser.add_option("--full-fragment", metavar = "n/m", default = "1/1", help = "Enable parallelization of --full by selecting a fragment of the full SNR PDFs sequence to generate. When --full is enabled, the iteration over SNR PDFs employs a reproducible, deterministic, sequence. That sequence is divided into m (m >= 1) approximately equal-sized intervals, and only the SNR PDFs from the n-th interval (1 <= n <= m) of the sequence will be constructed. Afterwards, the files generated by several jobs can be combined by re-invoking the program using the --seed or --seed-cache options to obtain the complete SNR PDF collection. The format of this option is \"n/m\", and the default is \"1/1\", which causes all SNR PDFs to be constructed.")
66  parser.add_option("--horizon-distance-tolerance", metavar = "ratio", type = "float", default = 0.05, help = "Set the fractional amount by which two horizon distances must differ for them to be considered distinct (optional). The default is 0.05, i.e., when two horizon distances differ by 5\% or more they are considered to be distinct, but less than that and they are considered to be equal.")
67  parser.add_option("--horizon-distances", metavar = "instrument=distance[,instrument=distance,...]", action = "append", help = "Cache SNR PDFs for these instruments and horizon distances. Format is, e.g., H1=120,L1=120,V1=48. Units for distance are irrelevant (PDFs depend only on their ratios). A PDF will be constructed for every combination of --min-instruments or more instruments from the set. All --horizon-distances must list the same instruments (if an instrument is off set its horizon distance to 0).")
68  parser.add_option("--horizon-distance-flow", metavar = "Hz", default = 10., type = "float", help = "When obtaining horizon distances from a collection PSD files, start horizon distance integral at this frequency in Hertz (default = 10 Hz).")
69  parser.add_option("--horizon-distance-masses", metavar = "m1,m2", action = "append", help = "When obtaining horizon distances from a collection of PSD files, compute them for these masses in solar mass units (default = 1.4,1.4). Can be given multiple times.")
70  parser.add_option("--instruments", metavar = "name[,name,...]", help = "Set the instruments to include in the network. If PSD files alone are to be used to provide horizon distances, or --full is selected, then this option is required, otherwise it is optional. If both --instruments and --horizon-distances are given, they must list the same instruments.")
71  parser.add_option("--min-instruments", metavar = "count", action = "append", type = "int", help = "Set the minimum number of instruments required to form a candidate; can be given multiple times (default is 1 and 2). Note that the probability that a recovered signal is recovered by a given set of instruments depends on how many instruments are required to participate. The PDF cache must contain entries for every value of this parameter one will use to conduct searches.")
72  parser.add_option("--output", "-o", metavar = "filename", help = "Write SNR PDF cache to this file (required).")
73  parser.add_option("--seed", metavar = "filename", action = "append", default = [], help = "Seed the SNR PDF cache by loading pre-computed SNR PDFs from this file. Can be given multiple times.")
74  parser.add_option("--seed-cache", metavar = "filename", help = "Seed the SNR PDF cache by loading pre-computed SNR PDFs from the files named in this LAL cache.")
75  parser.add_option("--verbose", "-v", action = "store_true", help = "Be verbose.")
76 
77  options, filenames = parser.parse_args()
78 
79  # defaults that can't be set in OptionParser because they would be
80  # appended to instead of overridden
81  if options.horizon_distance_masses is None:
82  options.horizon_distance_masses = ["1.4,1.4"]
83  if options.min_instruments is None:
84  options.min_instruments = [1, 2]
85 
86  processparams = options.__dict__.copy()
87 
88  if options.verbose:
89  logging.basicConfig(format = "%(message)s", level = logging.INFO)
90  else:
91  logging.basicConfig(format = "%(message)s", level = logging.WARNING)
92 
93  if options.seed_cache:
94  options.seed += [CacheEntry(line).path for line in open(options.seed_cache)]
95 
96  if not options.full and not options.horizon_distances and not options.seed and not filenames:
97  raise ValueError("must either enable --full, or provide one or more --horizon-distances, or one or more --seed and/or a --seed-cache, or provide the names of one or more PSD files")
98 
99  if options.full:
100  if not options.instruments:
101  raise ValueError("must set --instruments with --full enabled")
102 
103  #
104  # disable PSD files and --horizon-distances options. waste
105  # of time if we're already going to generate all possible
106  # PDFs
107  #
108 
109  if filenames:
110  logging.warning("--full enabled, ignoring PSD files")
111  del filenames[:]
112  if options.horizon_distances is not None:
113  logging.warning("--full enabled, ignoring --horizon-distances")
114  options.horizon_distances = None
115 
116  options.full_fragment = map(int, options.full_fragment.split("/"))
117  if len(options.full_fragment) != 2 or options.full_fragment[1] < 1 or not 1 <= options.full_fragment[0] <= options.full_fragment[1]:
118  raise ValueError("invalid --full-fragment")
119 
120  if options.horizon_distance_tolerance <= 0.:
121  raise ValueError("invalid --horizon-distance-tolerance (%g), must be > 0." % options.horizon_distance_tolerance)
122 
123  if options.instruments:
124  options.instruments = set(options.instruments.split(","))
125  if len(options.instruments) < min(options.min_instruments):
126  raise ValueError("--instruments must list at least --min-instruments (%d) instruments" % options.min_instruments)
127 
128  if options.horizon_distances is not None:
129  options.horizon_distances = (items.split(",") for items in options.horizon_distances)
130  options.horizon_distances = ([keyval.split("=") for keyval in items] for items in options.horizon_distances)
131  options.horizon_distances = [dict((instrument, float(distance)) for instrument, distance in items) for items in options.horizon_distances]
132  if not options.horizon_distances or not all(options.horizon_distances):
133  raise ValueError("unknown failure parsing --horizon-distances")
134  instruments = set(options.horizon_distances[0])
135  if any(set(horizon_distances) != instruments for horizon_distances in options.horizon_distances):
136  raise ValueError("all --horizon-distances must list the same instruments (if an instrument is off set its horizon distance to 0)")
137  if not options.instruments:
138  options.instruments = instruments
139  elif instruments != options.instruments:
140  raise ValueError("--instruments does not match --horizon-distances")
141  if any(min(horizon_distances.values()) < 0. for horizon_distances in options.horizon_distances):
142  raise ValueError("all --horizon-distances must be >= 0.")
143  else:
144  # we'll populate this later
145  options.horizon_distances = []
146 
147  # if --full was given it has unset filenames; if any
148  # --horizon-distances were given then .instruments has been
149  # populated from those if it wasn't already set
150  if filenames and not options.instruments:
151  raise ValueError("must set --instruments if PSD files alone are used for horizon distances")
152 
153  options.horizon_distance_masses = [map(float, s.split(",")) for s in options.horizon_distance_masses]
154  if any(len(masses) != 2 for masses in options.horizon_distance_masses):
155  raise ValueError("must provide exactly 2 masses for each --horizon-distance-masses")
156  if any((m1 <= 0. or m2 <= 0.) for m1, m2 in options.horizon_distance_masses):
157  raise ValueError("all --horizon-distances-masses must be > 0")
158 
159  if min(options.min_instruments) < 1:
160  raise ValueError("--min-instruments must be >= 1")
161 
162  if not options.output:
163  raise ValueError("must set --output")
164 
165  return options, processparams, filenames
166 
167 
168 #
169 # =============================================================================
170 #
171 # Main
172 #
173 # =============================================================================
174 #
175 
176 
177 #
178 # parse command line
179 #
180 
181 
182 options, processparams, filenames = parse_command_line()
183 
184 
185 #
186 # initialize empty SNR PDF cache
187 #
188 
189 
190 snrpdf = inspiral_extrinsics.SNRPDF(snr_cutoff = 4., log_distance_tolerance = math.log(1.0 + options.horizon_distance_tolerance))
191 snrpdf.snr_joint_pdf_cache.clear() # just in case
192 
193 
194 #
195 # now load seed files if requested. all SNRPDF instances share a single
196 # global cache of PDFs, so loading one from disk has the effect of
197 # inserting its PDFs into our existing cache
198 #
199 
200 
201 for n, filename in enumerate(options.seed, 1):
202  logging.info("loading seed PDFs %d/%d:" % (n, len(options.seed)))
203  seed_snrpdf = inspiral_extrinsics.SNRPDF.load(open(filename), verbose = options.verbose)
204  if seed_snrpdf.snr_cutoff != snrpdf.snr_cutoff:
205  raise ValueError("incompatible SNR cut-offs")
206  if seed_snrpdf.log_distance_tolerance != snrpdf.log_distance_tolerance:
207  raise ValueError("incompatible horizon distance tolerance, found %g require %g" % (math.exp(seed_snrpdf.log_distance_tolerance) - 1., math.exp(snrpdf.log_distance_tolerance) - 1.))
208  if seed_snrpdf.min_ratio != snrpdf.min_ratio:
209  raise ValueError("incompatible minimum distance ratios")
210 
211 
212 #
213 # obtain horizon distances from PSD files if requested
214 #
215 
216 
217 for n, filename in enumerate(filenames, 1):
218  logging.info("loading PSD %d/%d:" % (n, len(filenames)))
219  psd = lal.series.read_psd_xmldoc(ligolw_utils.load_filename(filename, contenthandler = lal.series.PSDContentHandler, verbose = options.verbose))
220  for m1, m2 in options.horizon_distance_masses:
221  horizon_distances = dict((instrument, (0. if instrument not in psd else reference_psd.HorizonDistance(options.horizon_distance_flow, psd[instrument].f0 + psd[instrument].data.length * psd[instrument].deltaF, psd[instrument].deltaF, m1, m2)(psd[instrument], 8.)[0])) for instrument in options.instruments)
222  logging.info("\t%s" % ", ".join("%s = %.4g Mpc" % x for x in sorted(horizon_distances.items())))
223  options.horizon_distances.append(horizon_distances)
224 
225 
226 #
227 # construct (fragment of) full spectrum of horizon distances if requested
228 #
229 
230 
231 if options.full:
232  # the use of sorted() in both loops ensures the sequence is
233  # reproducible from one job to the next. this is required by the
234  # --full-fragment feature.
235  for loudest in sorted(options.instruments):
236  other_instruments = sorted(options.instruments - set((loudest,)))
237  for other_distances in itertools.product(*([snrpdf.quants] * len(other_instruments))):
238  options.horizon_distances.append(snrpdf.quantized_horizon_distances([(loudest, 0.0)] + zip(other_instruments, other_distances)))
239  options.horizon_distances.append(dict.fromkeys(options.instruments, 0.0))
240  # clip total fragment count to total number of ratios
241  n = len(options.horizon_distances)
242  options.full_fragment[1] = min(options.full_fragment[1], n)
243  # clip fragment index to clipped fragment count
244  options.full_fragment[0] = min(*options.full_fragment)
245  # mean horizon distance ratios per fragment
246  ratios_per_fragment = n / float(options.full_fragment[1])
247  # find start and end of interval to compute
248  start = int(round(ratios_per_fragment * (options.full_fragment[0] - 1)))
249  end = int(round(ratios_per_fragment * options.full_fragment[0]))
250  # clip sequence
251  options.horizon_distances = options.horizon_distances[start : end]
252 
253 
254 #
255 # populate SNR PDF cache
256 #
257 
258 
259 start_time = time.time()
260 for n, horizon_distances in enumerate(options.horizon_distances, 1):
261  logging.info("Horizon distance ratio %d/%d, %g minutes elapsed:" % (n, len(options.horizon_distances), (time.time() - start_time) / 60.))
262  for min_instruments in options.min_instruments:
263  snrpdf.add_to_cache(horizon_distances, min_instruments, verbose = options.verbose)
264 
265 
266 #
267 # write to disk
268 #
269 
270 
271 xmldoc = ligolw.Document()
272 xmldoc.appendChild(ligolw.LIGO_LW())
273 process = ligolw_process.register_to_xmldoc(xmldoc, "gstlal_inspiral_make_snr_pdf", processparams, instruments = options.instruments)
274 xmldoc.childNodes[0].appendChild(snrpdf.to_xml())
275 ligolw_utils.write_filename(xmldoc, options.output, verbose = options.verbose)