gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_plot_sensitivity
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2012-2014 Stephen Privitera, Kipp Cannon, Chad Hanna, Drew Keppel
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 ### A program to plot the sensitivity of a gstlal inspiral search, e.g., VT
20 
21 import itertools
22 import math
23 from optparse import OptionParser
24 import os
25 import sqlite3
26 import sys
27 
28 import numpy
29 
30 from ligo.lw import ligolw
31 from ligo.lw import lsctables
32 from ligo.lw import dbtables
33 from ligo.lw import utils as ligolw_utils
34 from ligo.lw import array as ligolw_array
35 from ligo import segments
36 
37 import lal
38 from lal import rate
39 from lal.utils import CacheEntry
40 
41 from gstlal import imr_utils
42 from gstlal import dagparts
43 from gstlal.plots import sensitivity as plotsens
44 from matplotlib import pyplot
45 
46 
47 __author__ = "Stephen Privitera <sprivite@caltech.edu>, Chad Hanna <channa@perimeterinstitute.ca>, Kipp Cannon <kipp.cannon@ligo.org>"
48 __version__ = "git id %s" % "" # FIXME
49 __date__ = "" # FIXME
50 
51 
52 def source_type_distance_chirp_mass_bins_from_sims(sims, distbins = 200):
53  """
54  Given a list of the injections, guess at the chirp mass and distance
55  bins.
56  """
57  dist_mchirp_vals = map(imr_utils.sim_to_distance_chirp_mass_bins_function, sims)
58 
59  distances = [tup[0] for tup in dist_mchirp_vals]
60 
61  if min(distances) == max(distances):
62  return rate.NDBins([rate.LinearBins(min(distances)-1.0, max(distances)+1.0, 1), rate.IrregularBins([0.5, 2.0, 4.5, 45., 450])])
63  else:
64  return rate.NDBins([rate.LinearBins(min(distances), max(distances), distbins), rate.IrregularBins([0.5, 2.0, 4.5, 45., 450])])
65  #return rate.NDBins([rate.LinearBins(min(distances), max(distances), distbins), rate.IrregularBins([0.8, 1.74, 8.07, 14.92, 21.77, 100.0, 218.00, 450.0])])
66 
67 def source_type_distance_duration_bins_from_sims(sims, distbins = 200):
68  """
69  Given a list of the injections, guess at the template duration and
70  distance bins.
71  """
72  dist_mchirp_vals = map(imr_utils.sim_to_distance_chirp_mass_bins_function, sims)
73 
74  distances = [tup[0] for tup in dist_mchirp_vals]
75 
76  if min(distances) == max(distances):
77  return rate.NDBins([rate.LinearBins(min(distances)-1.0, max(distances)+1.0, 1), rate.IrregularBins([0., 2., 10., numpy.inf])])
78  else:
79  return rate.NDBins([rate.LinearBins(min(distances), max(distances), distbins), rate.IrregularBins([0., 2., 10., numpy.inf])])
80 
81 def chirp_mass(m1,m2):
82  m1 = numpy.array(m1)
83  m2 = numpy.array(m2)
84  mu = (m1*m2)/(m1+m2)
85  mtotal = m1+m2
86  return mu**(3./5) *mtotal**(2./5)
87 
88 class upper_limit(object):
89  """
90  The upper_limit class organizes the calculation of the sensitive search volume
91  for a search described by the input database.
92  """
93  def __init__(self, opts):
94  ## Instance variables ######################################
95  self.opts = opts
96  self.instrument_combos = []
97  self.segments = segments.segmentlistdict()
98  self.zero_lag_segments = segments.segmentlistdict()
99  self.start_time = None
100  self.end_time = None
101  self.searched_instruments = None
102  ############################################################
103 
104  # read the zero lag databases first
105  for f in self.opts.zero_lag_database:
106  if opts.verbose:
107  print(f"Gathering search data from zero-lag database: {f}....", file=sys.stderr)
108  with dbtables.workingcopy(f, tmp_path=opts.tmp_space, discard = True, verbose = opts.verbose) as working_filename:
109  connection = sqlite3.connect(str(working_filename))
110 
111  # find out which instruments were on and when
112  self.get_segments(connection) #get single ifo segments with vetoes applied
113  self.get_searched_instruments(connection)
114 
115  # done with zl database
116  connection.commit()
117 
118  # derived quantities
119  self.get_instrument_combos()
120  self.get_zero_lag_segments() #make coincident ifo segments from single ifo segments
121  self.get_livetime() #get the livetime for the chosen set of instruments
122 
123  # open up injection databases
124  self.found_injections_fars = {}
125  self.found_injections_snrs = {}
126  self.total_injections = {}
127  for f in self.opts.injection_database:
128  if opts.verbose:
129  print(f"Reading results of injection analysis from {f} ...", file=sys.stderr)
130  with dbtables.workingcopy(f, tmp_path=opts.tmp_space, discard = True, verbose = opts.verbose) as working_filename:
131  connection = sqlite3.connect(str(working_filename))
132  for inst in self.instrument_combos:
133  self.found_injections_fars.setdefault(inst,[])
134  self.found_injections_snrs.setdefault(inst,[])
135  self.total_injections.setdefault(inst,[])
136 
137  # get sim-far relationships
138  found, total, missed = imr_utils.get_min_far_inspiral_injections(connection, segments = self.zero_lag_segments[inst], table_name="coinc_inspiral")
139  self.found_injections_fars[inst] += found
140  self.total_injections[inst] += total
141 
142  # get sim-snr relationships
143  found, total, missed = imr_utils.get_max_snr_inspiral_injections(connection, segments = self.zero_lag_segments[inst], table_name="coinc_inspiral")
144  self.found_injections_snrs[inst] += found
145 
146  # remove injections that violate user-imposed constraints and
147  # symmetrize between m1-m2
148  for instr in self.instrument_combos:
149  self.total_injections[instr] = imr_utils.symmetrize_sims(self.total_injections[instr], "mass1", "mass2")
150  self.total_injections[instr] = self.filter_injections(self.total_injections[instr])
151  self.found_injections_fars[instr] = self.filter_injections(self.found_injections_fars[instr])
152  self.found_injections_snrs[instr] = self.filter_injections(self.found_injections_snrs[instr])
153 
154  if self.opts.verbose:
155  print("\nInstruments: %s" % instr, file=sys.stdout)
156  print("Number of found injections: %d" % len(self.found_injections_fars[instr]), file=sys.stdout)
157  print("Number of total injections: %d" % len(self.total_injections[instr]), file=sys.stdout)
158 
159 
160  def get_searched_instruments(self,connection):
161  '''
162  Retrieve the sets of instruments which were on during the search.
163  '''
164  for inst in connection.cursor().execute("""SELECT DISTINCT(ifos) FROM process WHERE ifos NOTNULL""").fetchall():
165  if self.searched_instruments is None:
166  self.searched_instruments = inst[0].replace(",","")
167  else:
168  if self.searched_instruments != inst[0].replace(",",""):
169  raise ValueError("Detected different searched instruments between databases")
170 
171 
172  def get_instrument_combos(self, min_instruments = 1):
173  instruments = self.segments.keys()
174  combos = set()
175  for i in range(min_instruments, len(instruments,) + 1):
176  for choice in itertools.combinations(instruments, i):
177  # NOTE the reference IFO is always the first in
178  # alphabetical order for any given combination,
179  # hence the sort here
180  combos.add(frozenset(sorted(choice)))
181  # NOTE add an "ALL" key which will be used to provide a summary plot of the entire analysis not broken down by livetime
182  combos.add(frozenset(("ALL",)))
183  self.instrument_combos = tuple(sorted(list(combos)))
184  return self.instrument_combos
185 
186 
187  def get_segments(self,connection):
188  '''
189  Retrieve raw single IFO segments from the database and
190  subtract vetoes.
191  '''
192  #
193  # get start and end times of the analysis, used for output
194  # naming. these may extend beyond the actual analyzed
195  # segments because of vetoes.
196  #
197  start_time = int( connection.cursor().execute('SELECT MIN(start_time + 1e-9 * start_time_ns) FROM segment').fetchone()[0] )
198  end_time = int( connection.cursor().execute('SELECT MAX(end_time + 1e-9 * end_time_ns) FROM segment').fetchone()[0] )
199  if not self.start_time or start_time < self.start_time:
200  self.start_time = start_time
201  if not self.end_time or end_time < self.end_time:
202  self.end_time = end_time
203 
204  # retrieve single-ifo segments
205  self.segments += imr_utils.get_segments( connection, dbtables.get_xml(connection), opts.coinc_table_name, opts.live_time_program, opts.veto_segments_name, opts.data_segments_name)
206 
207  return self.segments
208 
209 
210  def get_zero_lag_segments(self):
211  '''
212  Compute multi-ifo (coincident) segment list from single ifo segments.
213  '''
214  if self.opts.verbose:
215  print("\nForming coincident segments from single IFO segments...", file=sys.stdout)
216 
217  for inst in self.instrument_combos[:]:
218  # intersect single ifo segments
219  self.zero_lag_segments.setdefault(inst,segments.segmentlist())
220  if inst == frozenset(("ALL",)):
221  self.zero_lag_segments[inst] = self.segments.union(self.segments.keys())
222  else:
223  self.zero_lag_segments[inst] = self.segments.intersection(inst) - self.segments.union(set(self.segments.keys()) - inst)
224  if self.opts.verbose:
225  print("\t%s were on for %d seconds (after vetoes)" % (','.join(sorted(list(inst))),abs(self.zero_lag_segments[inst])), file=sys.stdout)
226 
227  return self.zero_lag_segments
228 
229 
230  def get_livetime(self):
231  '''Compute the instrument livetimes from the search segments.'''
232  self.livetime = {}
233  for inst in self.zero_lag_segments.keys():
234  self.livetime[inst] = float(abs(self.zero_lag_segments[inst]))/lal.YRJUL_SI
235 
236  return True
237 
238 
239  def set_bins(self, bin_type, inst):
240  if bin_type == "Total_Mass":
241  self.bins = imr_utils.guess_distance_total_mass_bins_from_sims(self.total_injections[inst], nbins = opts.mass_bins, distbins = opts.dist_bins)
242  self.sim_to_bins = imr_utils.sim_to_distance_total_mass_bins_function
243  if bin_type == "Chirp_Mass":
244  self.bins = imr_utils.guess_distance_chirp_mass_bins_from_sims(self.total_injections[inst], mbins = opts.mass_bins, distbins = opts.dist_bins)
245  self.sim_to_bins = imr_utils.sim_to_distance_chirp_mass_bins_function
246  if bin_type == "Mass1_Mass2":
247  self.bins = imr_utils.guess_distance_mass1_mass2_bins_from_sims(self.total_injections[inst], mass1bins = opts.mass_bins, mass2bins = opts.mass_bins, distbins = opts.dist_bins)
248  self.sim_to_bins = imr_utils.sim_to_distance_mass1_mass2_bins_function
249  if bin_type == "Aligned_Spin":
250  self.bins = imr_utils.guess_distance_effective_spin_parameter_bins_from_sims(self.total_injections[inst], chibins = opts.spin_bins, distbins = opts.dist_bins)
251  self.sim_to_bins = imr_utils.sim_to_distance_effective_spin_parameter_bins_function
252  if bin_type == "Mass_Ratio":
253  self.bins = imr_utils.guess_distance_mass_ratio_bins_from_sims(self.total_injections[inst], qbins = opts.mass_bins, distbins = opts.dist_bins)
254  self.sim_to_bins = imr_utils.sim_to_distance_mass_ratio_bins_function
255  if bin_type == "Source_Type":
256  self.bins = source_type_distance_chirp_mass_bins_from_sims(self.total_injections[inst], distbins = opts.dist_bins)
257  self.sim_to_bins = imr_utils.sim_to_distance_chirp_mass_bins_function
258  if bin_type == "Duration":
259  self.bins = source_type_distance_duration_bins_from_sims(self.total_injections[inst], distbins = opts.dist_bins)
260  self.sim_to_bins = imr_utils.sim_to_distance_duration_bins_function
261 
262  return self.bins, self.sim_to_bins
263 
264 
265  def filter_injections(self, sims):
266  '''
267  Remove injections from those found in the database based on
268  user-imposed restrictions.
269  '''
270  for inst in self.instrument_combos:
271  newinjs = []
272  for sim_params in sims:
273 
274  if type(sim_params) == tuple:
275  far, sim = sim_params
276  else:
277  sim = sim_params
278 
279  # exclude simulations from certain waveform families
280  if sim.waveform in self.opts.exclude_sim_type:
281  continue
282 
283  if not self.opts.min_mtotal < sim.mass1 + sim.mass2 < self.opts.max_mtotal:
284  continue
285 
286  if self.opts.max_mass_ratio and not (1.0/self.opts.max_mass_ratio <= sim.mass1/sim.mass2 <= self.opts.max_mass_ratio):
287  continue
288 
289  # Exclude precessing waveforms if requested
290  if self.opts.remove_precession:
291  if any(s != 0.0 for s in (sim.spin1x, sim.spin1y, sim.spin2x, sim.spin2y)):
292  continue
293 
294  # symmetrize in m1-m2
295  if sim.mass1 > sim.mass2:
296  m1 = sim.mass1
297  m2 = sim.mass2
298  sim.mass1 = m2
299  sim.mass2 = m1
300 
301  # passed all constraint tests, we can use it
302  if type(sim_params) == tuple:
303  newinjs.append((far,sim))
304  else:
305  newinjs.append(sim)
306 
307  return newinjs
308 
309 
310 def parse_command_line():
311 
312  description = '''
313  description:
314 
315 The program gstlal_inspiral_plot_sensitivity computes the sensitive volume of a CBC search from input databases containing triggers from simulation experiments. These triggers need to be ranked by false alarm rate, the detection statistic used in S6 searches. Then injections which register a trigger louder than the loudest event, by false alarm rate, are considered found. All others are considered missed. The efficiency of detecting an event depends on the source parameters, such as its component masses, distance, spin, inclination, sky position, etc. However, lalapps_cbc_svim only considers the dependency of the efficiency on distance and mass, marginalizing over the other parameters. Injections are binned in distance and mass and the estimated efficiency is integrated over distance to convert the efficiency into a physical volume.
316 '''
317 
318  parser = OptionParser(version = __version__, usage = description)
319 
320  # FAR range and resolution
321  parser.add_option("--xaxis-points", default = 50, type = "int", help = "Specify the number of FARs/SNRs for which to compute the search volume.")
322  parser.add_option("--min-far", default = 1.0e-6/lal.YRJUL_SI, type = "float", help = "Specify the minimum FAR (Hz)") # one per million years is probably detection worthy
323  parser.add_option("--max-far", default = 12.0/lal.YRJUL_SI, type = "float", help = "Specify the maximum FAR (Hz)") # one per month is possibly EM-followup worthy
324  parser.add_option("--fiducial-far", default = 1.0e-2/lal.YRJUL_SI, type = "float", help = "Specify a fiducial FAR (Hz) for plotting efficiency")
325  parser.add_option("--min-snr", default = 7, type = "float", help = "Specify the minimum SNR for volume calculation.")
326  parser.add_option("--max-snr", default = 15, type = "float", help = "Specify the maximum SNR for volume calculation.")
327 
328  # Input data options
329  parser.add_option("--zero-lag-database", default = [], action = "append", help = "Name of database containing the zero lag segments and triggers.")
330  parser.add_option("--injection-database", default = [], action = "append", help = "Name of database containing injection parameters and triggers.")
331  parser.add_option("--live-time-program", default = "gstlal_inspiral", metavar = "name", help = "Set the name of the program whose rings will be extracted from the search_summary table. Default = \"gstlal_inspiral\".")
332  parser.add_option("--veto-segments-name", default = "vetoes", help = "Set the name of the veto segments to use from the XML document.")
333  parser.add_option("--data-segments-name", default = "whitehtsegments", help = "Set the name of the data segments. Default = \"whitehtsegments\".")
334  parser.add_option("--coinc-table-name", default = "coinc_inspiral", metavar = "name", help = "Set the name of the table containing coincident triggers. Default = \"coinc_inspiral\".")
335 
336  # Output data options
337  parser.add_option("--user-tag", default = "SEARCH", metavar = "name", help = "Add a descriptive tag to the names of output files.")
338  parser.add_option("--output-dir", default = "./", metavar = "name", help = "Select a directory to place output files.")
339  parser.add_option("-t", "--tmp-space", metavar = "path", help = "Path to a directory suitable for use as a work area while manipulating the database file. The database file will be worked on in this directory, and then moved to the final location when complete. This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
340  parser.add_option("--output-path", default = "./", action = "store", help="Choose directory to save output files.")
341  parser.add_option("--output-cache", default = None, help = "Name of output cache file. If not specified, then no cache file will be written.")
342  parser.add_option("--verbose", action = "store_true", help = "Be verbose.")
343 
344  #
345  # Binning options
346  #
347  parser.add_option("--mass-bins", default = 3, metavar = "integer", type = "int", help = "Number of mass bins (per dimension), if mass bin boundaries are not explicitly set.")
348  parser.add_option("--spin-bins", default = 3, metavar = "integer", type = "int", help = "Number of spin bins (per dimension), if spin bin boundaries are not explicitly set.")
349  parser.add_option("--dist-bins", default = 50, metavar = "integer", type = "int", help = "Space distance bins evenly and specify the number of distance bins to use.")
350 
351  # injection filters
352  parser.add_option("--min-mtotal", metavar = "m", type = 'float', default = 0.0, help = "Specify the minimum total mass to consider among the injections found in the DB. This filters all injections outside this total mass range.")
353  parser.add_option("--max-mtotal", metavar = "m", type = 'float', default = float("Inf"), help = "Specify the maximum total mass to consider among the injections found in the DB. This filters all injections outside this total mass range.")
354  parser.add_option("--min-mass", metavar = "MM", type = 'float', default = 0.0, help = "Specify the minimum component mass to consider among the injections found in the DB. This filters all injectionswith any component lighter than MM.")
355  parser.add_option("--max-mass", metavar = "MM", type = 'float', default = float("Inf"), help = "Specify the maximum mass to consider among the injections found in the DB. This filters all injections with any component heavier than MM.")
356  parser.add_option("--max-mass-ratio", metavar = "q", type = 'float', default = None, help = "Specify the maximum allowed mass ratio. Should be >= 1.")
357  parser.add_option("--exclude-sim-type", default = [], action = "append", metavar = "SIM", help = "When computing the search volume, exclude injections made using the SIM waveform family. Example: SpinTaylorthreePointFivePN. Use this option multiple times to exclude more than one injection type.")
358  parser.add_option("--remove-precession", action = "store_true", help = "Exclude precessing injections when plotting sensitivity.")
359 
360  # binning options
361  parser.add_option("--bin-by-mass1-mass2", default = False, action = "store_true", help = "Bin injections by component mass in two dimensions when estimating the search efficiency.")
362  parser.add_option("--bin-by-total-mass", default = False, action = "store_true", help = "Bin injections by total mass when estimating the search efficiency.")
363  parser.add_option("--bin-by-chirp-mass", default = False, action = "store_true", help = "Bin injections by chirp mass when estimating the search efficiency.")
364  parser.add_option("--bin-by-aligned-spin", default = False, action = "store_true", help = "Bin injections by aligned spin parameter when estimating the search efficiency.")
365  parser.add_option("--bin-by-mass-ratio", default = False, action = "store_true", help = "Bin injections by mass ratio when estimating the search efficiency.")
366  parser.add_option("--bin-by-source-type", default = False, action = "store_true", help = "Bin injections by source type: BNS mchirp between 0.8 and 2, NSBH between 2 and 4.5, BBH between 4.5 and 45.0, IMBH between 45.0 and 450.0")
367  parser.add_option("--bin-by-duration", default = False, action = "store_true", help = "Bin injections by template duration when estimating the search efficiency.")
368 
369  opts, filenames = parser.parse_args()
370  opts.injection_database.extend(filenames)
371 
372  opts.bin_types = []
373  if opts.bin_by_total_mass:
374  opts.bin_types.append("Total_Mass")
375  if opts.bin_by_chirp_mass:
376  opts.bin_types.append("Chirp_Mass")
377  if opts.bin_by_mass1_mass2:
378  opts.bin_types.append("Mass1_Mass2")
379  if opts.bin_by_aligned_spin:
380  opts.bin_types.append("Aligned_Spin")
381  if opts.bin_by_mass_ratio:
382  opts.bin_types.append("Mass_Ratio")
383  if opts.bin_by_source_type:
384  opts.bin_types.append("Source_Type")
385  if opts.bin_by_duration:
386  opts.bin_types.append("Duration")
387 
388  if opts.max_mass_ratio and (opts.max_mass_ratio < 1):
389  raise ValueError("The maximum mass ratio must be >=1!")
390 
391  return opts, filenames
392 
393 
394 ############################ MAIN PROGRAM #####################################
395 ###############################################################################
396 ###############################################################################
397 
398 #create an empty cache which will store the output files/metadata
399 cache_list = []
400 
401 
402 def write_cache(cache_list, fileout):
403  # write cache file
404  if opts.output_cache is not None:
405  fd = open( fileout, "w" )
406  for l in cache_list:
407  fd.write( str(l) + "\n")
408  fd.close()
409  return
410 
411 #
412 # MAIN
413 #
414 
415 
416 # read in command line opts
417 opts, database = parse_command_line()
418 
419 # read in data from input database, store in upper limit object
420 if opts.verbose: print("\n\nSetting up the search volume calculations...\n")
421 UL = upper_limit(opts)
422 
423 # get the range of xaxis values to use
424 fars = numpy.logspace(numpy.log10(opts.min_far), numpy.log10(opts.max_far), opts.xaxis_points)
425 snrs = numpy.logspace(numpy.log10(opts.min_snr), numpy.log10(opts.max_snr), opts.xaxis_points)
426 
427 
428 #
429 # loop over the requested instruments and mass bin types, compute the
430 # search volume as a function of FAR and SNR threshold
431 #
432 for bin_type in opts.bin_types:
433 
434  for instr in UL.instrument_combos:
435 
436  if opts.verbose:
437  print("\n\nComputing sensitive volume for %s observation time binning by %s...\n" % ("".join(sorted(list(instr))),bin_type))
438  # check for empty injection sets. these tend to crash
439  # set_bins, so we just catch it here
440  if not UL.total_injections[instr]:
441  print("No injections performed in %s time. Skipping..." % "".join(sorted(list(instr))), file=sys.stderr)
442  continue
443 
444  # get bins
445  bins, s2b = UL.set_bins(bin_type,instr)
446 
447  # check for sufficient number of injection sets
448  nbins = 1.0
449  for bin in bins:
450  nbins *= len(bin)
451 
452  if len(UL.total_injections[instr]) / nbins <= 1:
453  print("Insufficient injections (%d) performed in %s time to compute sensitivity. Perform more injections or request fewer bins." % (len(UL.total_injections[instr]), "".join(sorted(list(instr)))), file=sys.stderr)
454  print("Skipping ...", file=sys.stderr)
455  continue
456 
457  if opts.verbose:
458  print("\tInjections performed: %d\n" % (len(UL.total_injections[instr])))
459 
460 
461  #
462  # compute efficiency at some fiducial far
463  #
464  found_by_far = [s for f, s in UL.found_injections_fars[instr] if f < opts.fiducial_far]
465  eff_fid_lo, eff_fid, eff_fid_hi = imr_utils.compute_search_efficiency_in_bins(found_by_far, UL.total_injections[instr], bins, s2b)
466 
467  #
468  # prepare output XML file. record mass bins, fars, snrs and
469  # livetime
470  #
471  xmldoc = ligolw.Document()
472  child = xmldoc.appendChild(ligolw.LIGO_LW())
473 
474  # write out mass bins
475  for j in range(len(bins[1:])):
476  xml = ligolw.LIGO_LW({u"Name": u"mass%d_bins:%s" % (j+1,bin_type)})
477  edges = tuple( numpy.concatenate((l,u[-1:])) for l,u in zip(bins.lower(), bins.upper()) )
478  xml.appendChild(ligolw_array.Array.build(u"array", edges[j+1]))
479  child.appendChild(xml)
480 
481  # write out fars/snrs/livetime
482  xml = ligolw.LIGO_LW({u"Name": u"far_bins:%s" % (bin_type,)})
483  xml.appendChild(ligolw_array.Array.build(u"array", fars))
484  child.appendChild(xml)
485 
486  xml = ligolw.LIGO_LW({u"Name": u"snr_bins:%s" % (bin_type,)})
487  xml.appendChild(ligolw_array.Array.build(u"array", snrs))
488  child.appendChild(xml)
489 
490  xml = ligolw.LIGO_LW({u"Name": u"livetime:%s" % (bin_type,)})
491  xml.appendChild(ligolw_array.Array.build(u"array", numpy.array([UL.livetime[instr]])))
492  child.appendChild(xml)
493 
494  #
495  # compute volume by far and snr for all mass bins
496  #
497  vols_lo_far, vols_far, vols_hi_far = [], [], []
498  vols_lo_snr, vols_snr, vols_hi_snr = [], [], []
499  for k, far, snr in zip(range(opts.xaxis_points), fars, snrs):
500 
501  #
502  # get found/missed injections
503  #
504  found_by_far = [s for f, s in UL.found_injections_fars[instr] if f < far]
505  found_by_snr = [s for rho, s in UL.found_injections_snrs[instr] if rho > snr]
506 
507  #
508  # compute volume vs far
509  #
510  eff_lo, eff, eff_hi = imr_utils.compute_search_efficiency_in_bins(found_by_far, UL.total_injections[instr], bins, s2b)
511  vol_lo = imr_utils.compute_search_volume(eff_lo)
512  vol_lo.array *= UL.livetime[instr] #preferred unit is Mpc^3*yr
513  vols_lo_far.append(vol_lo)
514 
515  vol = imr_utils.compute_search_volume(eff)
516  vol.array *= UL.livetime[instr] #preferred unit is Mpc^3*yr
517  vols_far.append(vol)
518 
519  vol_hi = imr_utils.compute_search_volume(eff_hi)
520  vol_hi.array *= UL.livetime[instr] #preferred unit is Mpc^3*yr
521  vols_hi_far.append(vol_hi)
522 
523  #
524  # write volume and volume errors array to xml
525  #
526  xml = ligolw.LIGO_LW({u"Name": u"volume_lo_by_far_%d:%s" % (k, bin_type,)})
527  xml.appendChild(ligolw_array.Array.build(u"array", vol_lo.array))
528  child.appendChild(xml)
529 
530  xml = ligolw.LIGO_LW({u"Name": u"volume_by_far_%d:%s" % (k, bin_type,)})
531  xml.appendChild(ligolw_array.Array.build(u"array", vol.array))
532  child.appendChild(xml)
533 
534  xml = ligolw.LIGO_LW({u"Name": u"volume_hi_by_far_%d:%s" % (k, bin_type,)})
535  xml.appendChild(ligolw_array.Array.build(u"array", vol_hi.array))
536  child.appendChild(xml)
537 
538  #
539  # compute volume vs snr
540  #
541  eff_lo, eff, eff_hi = imr_utils.compute_search_efficiency_in_bins(found_by_snr, UL.total_injections[instr], bins, s2b)
542  vol_lo = imr_utils.compute_search_volume(eff_lo)
543  vol_lo.array *= UL.livetime[instr] #preferred unit is Mpc^3*yr
544  vols_lo_snr.append(vol_lo)
545 
546  vol = imr_utils.compute_search_volume(eff)
547  vol.array *= UL.livetime[instr] #preferred unit is Mpc^3*yr
548  vols_snr.append(vol)
549 
550  vol_hi = imr_utils.compute_search_volume(eff_hi)
551  vol_hi.array *= UL.livetime[instr] #preferred unit is Mpc^3*yr
552  vols_hi_snr.append(vol_hi)
553 
554  #
555  # write volume and volume errors array to xml
556  #
557  xml = ligolw.LIGO_LW({u"Name": u"volume_lo_by_snr_%d:%s" % (k, bin_type,)})
558  xml.appendChild(ligolw_array.Array.build(u"array", vol_lo.array))
559  child.appendChild(xml)
560 
561  xml = ligolw.LIGO_LW({u"Name": u"volume_by_snr_%d:%s" % (k, bin_type,)})
562  xml.appendChild(ligolw_array.Array.build(u"array", vol.array))
563  child.appendChild(xml)
564 
565  xml = ligolw.LIGO_LW({u"Name": u"volume_hi_by_snr_%d:%s" % (k, bin_type,)})
566  xml.appendChild(ligolw_array.Array.build(u"array", vol_hi.array))
567  child.appendChild(xml)
568 
569  #
570  # finish xml document
571  #
572  output_filename = "%s_%s-SEARCH_VOLUME_BINNED_BY_%s_%s-%d-%d.xml" % (UL.searched_instruments, "".join(sorted(list(instr))), bin_type.upper(), opts.user_tag, UL.start_time, UL.end_time-UL.start_time)
573  ligolw_utils.write_filename(xmldoc, output_filename)
574  cache_list.append( CacheEntry( "".join(sorted(list(instr))), bin_type,segments.segment(UL.start_time, UL.end_time), "file://localhost%s/%s" % (os.getcwd(), output_filename)) )
575 
576  #
577  # plot the volume/range versus far/snr for each bin
578  # FIXME: since we are now writing the data to disk,
579  # it may make more sense to carry out the plotting
580  # in a separate code
581  #
582 
583  far_vols = (vols_lo_far, vols_far, vols_hi_far)
584  snr_vols = (vols_lo_snr, vols_snr, vols_hi_snr)
585  eff_fids = (eff_fid_lo, eff_fid, eff_fid_hi)
586 
587  fig_far = plotsens.plot_sensitivity_vs_far(far_vols, fars, UL.livetime, instr, bins, bin_type)
588  fig_far_range = plotsens.plot_range_vs_far(far_vols, fars, UL.livetime, instr, bins, bin_type)
589  fig_snr = plotsens.plot_sensitivity_vs_far(snr_vols, snrs, UL.livetime, instr, bins, bin_type)
590  fig_eff = plotsens.plot_fiducial_efficiency(eff_fids, opts.fiducial_far, instr, bins, bin_type)
591 
592  # save and close figures
593  ifostr = "%s_%s" % (UL.searched_instruments, "".join(sorted(instr)))
594  for fig, plot_type in zip((fig_far, fig_far_range, fig_snr, fig_eff), ("VOLUME_VS_FAR", "RANGE_VS_FAR", "VOLUME_VS_SNR", "EFFICIENCY")):
595  plot_desc = f"GSTLAL_INSPIRAL_PLOT_SENSITIVITY_{plot_type}_{opts.user_tag}_BINNED_BY_{bin_type.upper()}"
596  tag = dagparts.T050017_filename(ifostr, plot_desc, (UL.start_time, UL.end_time), ".png", path = opts.output_dir)
597  fig.savefig(tag)
598  pyplot.close(fig)
599 
600 
601 # write a cache file describing the files generated during by this program
602 if opts.output_cache:
603  write_cache(cache_list, opts.output_cache)