gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_plotsummary
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2009-2013 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 produce a variety of plots from a gstlal inspiral analysis, e.g. IFAR plots, missed found, etc.
20 
21 #
22 # =============================================================================
23 #
24 # Preamble
25 #
26 # =============================================================================
27 #
28 
29 
30 import bisect
31 from functools import reduce
32 import itertools
33 import json
34 import math
35 import operator
36 from optparse import OptionParser
37 import os
38 import sqlite3
39 import sys
40 
41 import numpy
42 import scipy
43 
44 import lal
45 from lal import gpstime
46 from lal import iterutils
47 from lal.utils import CacheEntry
48 
49 from ligo import segments
50 from ligo.lw import dbtables
51 from ligo.lw import lsctables
52 from ligo.lw.utils import segments as ligolw_segments
53 
54 from gstlal import far
55 from gstlal import dagparts
56 from gstlal.plots import summary as plotsumm
57 from gstlal.plots.util import golden_ratio
58 
59 
60 def format_column(column):
61  return column.lower().replace(' ', '_').replace(':', '').replace(';', '')
62 
63 
64 def save_table(fname, fields, rows):
65  ### format data
66  fields = [{'key': format_column(col), 'label': col, 'sortable': True} for col in fields]
67  colnames = [field['key'] for field in fields]
68  items = [{col: val for col, val in zip(colnames, row)} for row in rows]
69 
70  ### write to disk
71  with open(fname, 'w') as f:
72  f.write(json.dumps({'fields': fields, 'items': items}))
73 
74 
75 class SimInspiral(lsctables.SimInspiral):
76  @property
77  def mtotal(self):
78  return self.mass1 + self.mass2
79 
80  @property
81  def chi(self):
82  return (self.mass1 * self.spin1z + self.mass2 * self.spin2z) / self.mtotal
83 
84 
85 class SnglInspiral(lsctables.SnglInspiral):
86  @property
87  def mtotal(self):
88  return self.mass1 + self.mass2
89 
90  @property
91  def eta(self):
92  return self.mass1 * self.mass2 / self.mtotal**2.
93 
94  @property
95  def mchirp(self):
96  return self.mtotal * self.eta**0.6
97 
98  @property
99  def chi(self):
100  return (self.mass1 * self.spin1z + self.mass2 * self.spin2z) / self.mtotal
101 
102 lsctables.SimInspiralTable.RowType = SimInspiral
103 lsctables.SnglInspiralTable.RowType = SnglInspiral
104 
105 
106 __author__ = "Kipp Cannon <kipp.cannon@ligo.org>, Chad Hanna <channa@ligo.caltech.edu>"
107 __version__ = "git id %s" % "FIXME"
108 __date__ = "FIXME"
109 
110 
111 #
112 # =============================================================================
113 #
114 # Command Line
115 #
116 # =============================================================================
117 #
118 
119 
120 def parse_command_line():
121  parser = OptionParser(
122  version = "Name: %%prog\n%s" % "" # FIXME
123  )
124  parser.add_option("","--input-cache", help = "Also get the list of databases to process from this LAL cache.")
125  parser.add_option("--user-tag", metavar = "user-tag", default = "ALL", help = "Set the prefix for output filenames (default = \"ALL\").")
126  parser.add_option("--output-dir", metavar = "output-dir", default = ".", help = "Provide an output directory")
127  parser.add_option("-f", "--format", metavar = "{\"png\",\"pdf\",\"svg\",\"eps\",...}", action = "append", default = [], help = "Set the output image format. Can be given multiple times (default = \"png\").")
128  parser.add_option("--shrink-data-segments", metavar = "float", type = float, help = "Shrink data segments by this much (on each side). e.g. specifying 2 will shrink each datasegment by 4 seconds")
129  parser.add_option("--extend-veto-segments", metavar = "float", type = float, help = "Pad segments by this number of seconds (on both sides)")
130  parser.add_option("--segments-name", metavar = "name", default = "statevectorsegments", help = "Set the name of the segments that were analyzed (default = \"statevectorsegments\").")
131  parser.add_option("--vetoes-name", metavar = "name", default = "vetoes", help = "Set the name of the veto segments (default = \"vetoes\").")
132  parser.add_option("--plot-group", metavar = "number", action = "append", default = None, help = """Generate the given plot group. Can be given multiple times (default = make all plot groups)
133  0. Summary Table (top 10 loudest events globally across all zero lag triggers read in)
134  1. Missed Found (Scatter plots of missed and found injections on several axes)
135  2. Injection Parameter Accuracy Plots
136  3. Background Vs Injection Plots (sngl detector triggers from coincs of snr, chisq, bank chisq, ...)
137  4. Background Vs Injection Plots pairwise (SNR instrument 1 vs. instrument2, ...),
138  5. Rate Vs Threshold (SNR histograms, IFAR histograms, ...)
139  6. Injection Parameter Distribution Plots (The input parameters that went into inspinj, like mass1 vs mass2, ...)
140 """)
141  parser.add_option("--far-threshold", metavar = "Hz", default = 1. / (30 * 86400), type = "float", help = "Set the FAR threshold for found injections (default = 1 / 30 days).")
142  parser.add_option("--likelihood-file", metavar = "filename", help = "Path to the marginalized likelihood file.")
143  # FIXME Add check that plot group 1 being generated if these options are given
144  parser.add_option("--remove-precession", action = "store_true", help = "Ignore precessing injections when generating missed/found plots")
145  parser.add_option("--isolate-precession", action = "store_true", help = "Only make missed/found plots for precessing injections")
146  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.")
147  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
148  options, filenames = parser.parse_args()
149 
150  if options.plot_group is not None:
151  options.plot_group = sorted(list(map(int, options.plot_group)))
152 
153  if (options.plot_group is None or set(options.plot_group) & set((1, 5))) and options.likelihood_file is None:
154  raise ValueError("Must provide --likelihood-file to generate plots in groups 1 and/or 5.")
155 
156  if not options.format:
157  options.format = ["png"]
158 
159  if not filenames:
160  filenames = []
161  if options.input_cache:
162  filenames.extend(c.path for c in map(CacheEntry, open(options.input_cache)))
163 
164  return options, filenames
165 
166 
167 #
168 # =============================================================================
169 #
170 # Database
171 #
172 # =============================================================================
173 #
174 
175 
176 class CoincDatabase(object):
177  def __init__(self, connection, data_segments_name, veto_segments_name = None, verbose = False, plotsummary_json = None, base = None, program_name = "gstlal_inspiral", shrink_data_segments = None, extend_veto_segments = None):
178  """
179  Compute and record some summary information about the
180  database.
181  """
182 
183  self.base = base
184  self.connection = connection
185  xmldoc = dbtables.get_xml(connection)
186  self.all_segs_dict = {}
187 
188  cursor = connection.cursor()
189 
190  # find the tables
191  try:
192  self.sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
193  except ValueError:
194  self.sngl_inspiral_table = None
195  try:
196  self.sim_inspiral_table = lsctables.SimInspiralTable.get_table(xmldoc)
197  except ValueError:
198  self.sim_inspiral_table = None
199  try:
200  self.coinc_def_table = lsctables.CoincDefTable.get_table(xmldoc)
201  self.coinc_table = lsctables.CoincTable.get_table(xmldoc)
202  self.time_slide_table = lsctables.TimeSlideTable.get_table(xmldoc)
203  except ValueError:
204  self.coinc_def_table = None
205  self.coinc_table = None
206  self.time_slide_table = None
207  try:
208  self.coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(xmldoc)
209  except ValueError:
210  self.coinc_inspiral_table = None
211 
212  # determine a few coinc_definer IDs
213  # FIXME: don't hard-code the numbers
214  if self.coinc_def_table is not None:
215  try:
216  self.ii_definer_id = self.coinc_def_table.get_coinc_def_id("inspiral", 0, create_new = False)
217  except KeyError:
218  self.ii_definer_id = None
219  try:
220  self.si_definer_id = self.coinc_def_table.get_coinc_def_id("inspiral", 1, create_new = False)
221  except KeyError:
222  self.si_definer_id = None
223  try:
224  self.sc_definer_id = self.coinc_def_table.get_coinc_def_id("inspiral", 2, create_new = False)
225  except KeyError:
226  self.sc_definer_id = None
227  else:
228  self.ii_definer_id = None
229  self.si_definer_id = None
230  self.sc_definer_id = None
231 
232  # retrieve the distinct on and participating instruments
233  self.on_instruments_combos = [frozenset(lsctables.instrumentsproperty.get(x)) for x, in cursor.execute("SELECT DISTINCT(instruments) FROM coinc_event WHERE coinc_def_id == ?", (self.ii_definer_id,))]
234  self.participating_instruments_combos = [frozenset(lsctables.instrumentsproperty.get(x)) for x, in cursor.execute("SELECT DISTINCT(ifos) FROM coinc_inspiral")]
235 
236  # get the segment lists
237  self.seglists = ligolw_segments.segmenttable_get_by_name(xmldoc, data_segments_name).coalesce()
238  if shrink_data_segments is not None:
239  # Make sure all segments are at least long enough to be
240  # contracted (e.g. if a segment is 32 seconds long but
241  # the user is going to contract it by 17 seconds, then
242  # the end time of the segment would come before the
243  # start time of the segment. This is bad)
244  for seglist in self.seglists.values():
245  iterutils.inplace_filter(lambda s: abs(s) > 2*shrink_data_segments, seglist)
246  self.seglists.contract(shrink_data_segments)
247  self.instruments = set(self.seglists)
248  if veto_segments_name is not None:
249  self.veto_segments = ligolw_segments.segmenttable_get_by_name(xmldoc, veto_segments_name).coalesce()
250  if extend_veto_segments is not None:
251  self.veto_segments.protract(extend_veto_segments)
252  else:
253  self.veto_segments = segments.segmentlistdict()
254  self.seglists -= self.veto_segments
255 
256  # get all the segments in the database to use as a summary
257  for llwsegs in ligolw_segments.LigolwSegments(xmldoc).coalesce():
258  seglists = self.all_segs_dict.setdefault(llwsegs.name, segments.segmentlistdict())
259  # FIXME: should be populating valid segments upstream
260  seglists |= segments.segmentlistdict.fromkeys(llwsegs.instruments, llwsegs.active) #& llwsegs.valid)
261 
262  # get the live time
263  if verbose:
264  print >>sys.stderr, "calculating background livetimes: ",
265  # retrieve background offset vectors
266  self.offset_vectors = [offsetvector for offsetvector in dbtables.TimeSlideTable(connection = connection).as_dict().values() if any(offsetvector.values())]
267 
268  if verbose:
269  print >>sys.stderr
270  self.zerolag_livetime = {}
271  self.background_livetime = {}
272  for on_instruments in self.on_instruments_combos:
273  tmpsegs = self.seglists.intersection(on_instruments) - self.seglists.union(self.instruments - on_instruments)
274  self.zerolag_livetime[on_instruments] = float(abs(sum(abs(seg) for seg in tmpsegs if numpy.isfinite(float(seg[0])) and numpy.isfinite(float(seg[1])))))
275  # FIXME: background livetime hard-coded to be same
276  # as zero-lag livetime. figure out what to do
277  self.background_livetime.update(self.zerolag_livetime)
278 
279  # verbosity
280  if verbose:
281  print >>sys.stderr, "database overview:"
282  for on_instruments in self.on_instruments_combos:
283  print >>sys.stderr, "\tzero-lag livetime for %s: %f s" % ("+".join(sorted(on_instruments)), self.zerolag_livetime[on_instruments])
284  print >>sys.stderr, "\tbackground livetime for %s: %f s" % ("+".join(sorted(on_instruments)), self.background_livetime[on_instruments])
285  if self.sngl_inspiral_table is not None:
286  print >>sys.stderr, "\tinspiral events: %d" % len(self.sngl_inspiral_table)
287  if self.sim_inspiral_table is not None:
288  print >>sys.stderr, "\tinjections: %d" % len(self.sim_inspiral_table)
289  if self.time_slide_table is not None:
290  print >>sys.stderr, "\ttime slides: %d" % cursor.execute("SELECT COUNT(DISTINCT(time_slide_id)) FROM time_slide").fetchone()[0]
291  if self.coinc_def_table is not None:
292  for description, n in cursor.execute("SELECT description, COUNT(*) FROM coinc_definer NATURAL JOIN coinc_event GROUP BY coinc_def_id"):
293  print >>sys.stderr, "\t%s: %d" % (description, n)
294 
295  if plotsummary_json:
296  data = []
297  for on_instruments in self.on_instruments_combos:
298  data.append(["zero-lag livetime for %s" % ("+".join(sorted(on_instruments))), str(self.zerolag_livetime[on_instruments])])
299  data.append(["background livetime for %s" % ("+".join(sorted(on_instruments))), str(self.background_livetime[on_instruments])])
300  if self.sngl_inspiral_table is not None:
301  data.append(["inspiral events", str(len(self.sngl_inspiral_table))])
302  if self.sim_inspiral_table is not None:
303  data.append(["injections", str(len(self.sim_inspiral_table))])
304  if self.time_slide_table is not None:
305  data.append(["time slides", str(cursor.execute("SELECT COUNT(DISTINCT(time_slide_id)) FROM time_slide").fetchone()[0])])
306  if self.coinc_def_table is not None:
307  for description, n in cursor.execute("SELECT description, COUNT(*) FROM coinc_definer NATURAL JOIN coinc_event GROUP BY coinc_def_id"):
308  data.append([description, str(n)])
309  if self.sim_inspiral_table is None:
310  save_table("%s_plot_summary.json" % self.base, ['Summary of database:', plotsummary_json], data)
311 
312 #
313 # =============================================================================
314 #
315 # Utilities
316 #
317 # =============================================================================
318 #
319 
320 def sim_get_chirp_eff_dist(sim, instrument):
321  return getattr(sim, "eff_dist_%s" % instrument[0].lower()) * sim.mchirp**(5./6.) / 1.22**(5./6.)
322 
323 def roman(i, arabics = (1000,900,500,400,100,90,50,40,10,9,5,4,1), romans = ("m","cm","d","cd","c","xc","l","xl","x","ix","v","iv","i")):
324  if not arabics:
325  return ""
326  if i < arabics[0]:
327  return roman(i, arabics[1:], romans[1:])
328  return romans[0] + roman(i - arabics[0], arabics, romans)
329 
330 def truncate(f, digits, si=True):
331  assert digits > 0, 'number of digits must be positive'
332  if si:
333  return float(('%10.' + str(digits) + 'e') % f)
334  else:
335  return float(('%10.' + str(digits) + 'f') % f)
336 
337 
338 def create_sim_coinc_view(connection):
339  """
340  Construct a sim_inspiral --> best matching coinc_event mapping.
341  Only injections that match at least one coinc get an entry in this
342  table.
343  """
344  #
345  # the log likelihood ratio stored in the likelihood column of the
346  # coinc_event table is the ranking statistic. the "best match" is
347  # the coinc with the highest value in this column. although it has
348  # not been true in the past, there is now a one-to-one relationship
349  # between the value of this ranking statistic and false-alarm rate,
350  # therefore it is OK to order by log likelihood ratio and then,
351  # later, impose a "detection" threshold based on false-alarm rate.
352  #
353 
354  connection.cursor().execute("""
355 CREATE TEMPORARY TABLE
356  sim_coinc_map_helper
357 AS
358  SELECT a.event_id as sid,
359  coinc_event.coinc_event_id as cid,
360  coinc_event.likelihood as lr
361  FROM coinc_event_map as a
362  JOIN coinc_event_map AS b ON (b.coinc_event_id == a.coinc_event_id)
363  JOIN coinc_event ON (coinc_event.coinc_event_id == b.event_id)
364  WHERE a.table_name == 'sim_inspiral'
365  AND b.table_name == 'coinc_event'
366  AND NOT EXISTS (SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0);
367  """)
368 
369  connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_coinc_map_helper_index ON sim_coinc_map_helper (sid, cid);")
370 
371  connection.cursor().execute("""
372 CREATE TEMPORARY TABLE
373  sim_coinc_map
374 AS
375  SELECT
376  sim_inspiral.simulation_id AS simulation_id,
377  (
378  SELECT
379  cid
380  FROM
381  sim_coinc_map_helper
382  WHERE
383  sid = simulation_id
384  ORDER BY
385  lr
386  DESC
387  LIMIT 1
388  ) AS coinc_event_id
389  FROM
390  sim_inspiral
391  WHERE
392  coinc_event_id IS NOT NULL;
393 
394  """)
395 
396  connection.cursor().execute("DROP INDEX sim_coinc_map_helper_index;")
397 
398  contents.connection.cursor().execute("""
399 CREATE TEMPORARY TABLE
400  sim_id_combined_far
401 AS
402  SELECT
403  coinc_inspiral.combined_far AS far, sim_coinc_map.simulation_id AS sim_id
404  FROM
405  sim_coinc_map
406  JOIN coinc_inspiral ON ( coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id )
407  """)
408 
409  contents.connection.cursor().execute("""
410 CREATE TEMPORARY TABLE
411  sim_id_sngl_id
412  AS
413  SELECT
414  sim_coinc_map.simulation_id AS sim_id, sngl_inspiral.event_id AS sngl_id
415  FROM
416  sim_coinc_map
417  JOIN coinc_event_map as mapA ON ( mapA.coinc_event_id == sim_coinc_map.coinc_event_id )
418  JOIN sngl_inspiral ON ( sngl_inspiral.event_id == mapA.event_id )
419  """)
420 
421  contents.connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_id_combined_far_index ON sim_id_combined_far (far, sim_id)")
422  contents.connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_id_sngl_id_index ON sim_id_sngl_id (sim_id, sngl_id)")
423 
424  contents.connection.cursor().execute("""
425 CREATE TEMPORARY TABLE
426  sim_sngl_far
427  AS
428  SELECT
429  sim_inspiral.*,
430  sngl_inspiral.*,
431  sim_id_combined_far.far
432  FROM
433  sim_inspiral
434  JOIN sim_id_sngl_id ON (
435  sim_inspiral.simulation_id == sim_id_sngl_id.sim_id
436  )
437  JOIN sngl_inspiral ON (
438  sngl_inspiral.event_id == sim_id_sngl_id.sngl_id
439  )
440  JOIN sim_id_combined_far ON (
441  sim_id_combined_far.sim_id == sim_id_sngl_id.sim_id
442  )
443  """)
444 
445  contents.connection.cursor().execute("DROP INDEX sim_id_combined_far_index")
446  contents.connection.cursor().execute("DROP INDEX sim_id_sngl_id_index")
447 
448 #
449 # =============================================================================
450 #
451 # Summary Table
452 #
453 # =============================================================================
454 #
455 
456 
457 class SummaryTable(object):
458  def __init__(self):
459  self.candidates = []
460  self.bgcandidates = []
461  self.livetime = {}
462  self.num_trigs = {}
463 
464  def add_contents(self, contents):
465  self.base = contents.base
466  if contents.sim_inspiral_table:
467  #For now we only return summary information on non injections
468  return
469  self.candidates += contents.connection.cursor().execute("""
470 SELECT
471  coinc_inspiral.combined_far,
472  coinc_inspiral.false_alarm_rate,
473  coinc_event.likelihood,
474  coinc_inspiral.snr,
475  coinc_inspiral.end_time + coinc_inspiral.end_time_ns * 1e-9,
476  coinc_inspiral.mass,
477  coinc_inspiral.mchirp,
478  coinc_inspiral.ifos,
479  coinc_event.instruments,
480  (SELECT
481  group_concat(sngl_inspiral.ifo || ":" || sngl_inspiral.snr || ":" || sngl_inspiral.chisq || ":" || sngl_inspiral.mass1 || ":" || sngl_inspiral.mass2 || ":" || sngl_inspiral.spin1z || ":" || sngl_inspiral.spin2z, " ")
482  FROM
483  sngl_inspiral
484  JOIN coinc_event_map ON (
485  sngl_inspiral.event_id == coinc_event_map.event_id AND coinc_event_map.table_name == "sngl_inspiral"
486  )
487  WHERE
488  coinc_event_map.coinc_event_id == coinc_inspiral.coinc_event_id
489  )
490 FROM
491  coinc_inspiral
492  JOIN coinc_event ON (
493  coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
494  )
495 WHERE
496  NOT EXISTS(
497  SELECT
498  *
499  FROM
500  time_slide
501  WHERE
502  time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0
503  )
504  AND combined_far IS NOT NULL
505 ORDER BY
506  combined_far
507 LIMIT 100
508  """).fetchall()
509 
510  self.bgcandidates += contents.connection.cursor().execute("""
511 SELECT
512  coinc_inspiral.combined_far,
513  coinc_inspiral.false_alarm_rate,
514  coinc_event.likelihood,
515  coinc_inspiral.snr,
516  coinc_inspiral.end_time + coinc_inspiral.end_time_ns * 1e-9,
517  coinc_inspiral.mass,
518  coinc_inspiral.mchirp,
519  coinc_inspiral.ifos,
520  coinc_event.instruments,
521  (SELECT
522  group_concat(sngl_inspiral.ifo || ":" || sngl_inspiral.snr || ":" || sngl_inspiral.chisq || ":" || sngl_inspiral.mass1 || ":" || sngl_inspiral.mass2 || ":" || sngl_inspiral.spin1z || ":" || sngl_inspiral.spin2z, " ")
523  FROM
524  sngl_inspiral
525  JOIN coinc_event_map ON (
526  sngl_inspiral.event_id == coinc_event_map.event_id AND coinc_event_map.table_name == "sngl_inspiral"
527  )
528  WHERE
529  coinc_event_map.coinc_event_id == coinc_inspiral.coinc_event_id
530  )
531 FROM
532  coinc_inspiral
533  JOIN coinc_event ON (
534  coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
535  )
536 WHERE
537  EXISTS(
538  SELECT
539  *
540  FROM
541  time_slide
542  WHERE
543  time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0
544  )
545  AND combined_far IS NOT NULL
546 ORDER BY
547  combined_far
548 LIMIT 100
549  """).fetchall()
550 
551 
552  contents.connection.cursor().execute("CREATE TEMPORARY TABLE distinct_ifos AS SELECT DISTINCT(ifos) AS ifos FROM coinc_inspiral")
553  for instruments, num in contents.connection.cursor().execute("""
554 SELECT distinct_ifos.ifos, count(*) FROM coinc_inspiral JOIN distinct_ifos ON (distinct_ifos.ifos==coinc_inspiral.ifos) JOIN coinc_event ON (coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id) WHERE coinc_inspiral.ifos==distinct_ifos.ifos AND NOT EXISTS(SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0) GROUP BY distinct_ifos.ifos;
555 """):
556  key = frozenset(lsctables.instrumentsproperty.get(instruments))
557  self.num_trigs.setdefault(key,0)
558  self.num_trigs[key] += num
559 
560  contents.connection.cursor().execute("DROP TABLE distinct_ifos")
561 
562  for on_instruments in set(contents.background_livetime) | set(contents.zerolag_livetime):
563  self.livetime.setdefault(on_instruments, 0.0)
564 
565  for on_instruments, livetime in contents.zerolag_livetime.items():
566  self.livetime[on_instruments] += livetime
567 
568  def write_candidate_json(self, candidates, fname):
569  data = []
570  fields = [
571  "rank",
572  "FAR (Hz)",
573  "FAP",
574  "ln L",
575  "SNR",
576  "GPS time",
577  "UTC time",
578  "M total",
579  "M chirp",
580  "Found IFOs",
581  "On IFOs",
582  "m1",
583  "m2",
584  "S_1z",
585  "S_2z",
586  "H1 SNR",
587  "H1 chisq",
588  "L1 SNR",
589  "L1 chisq",
590  "V1 SNR",
591  "V1 chisq"
592  ]
593  for rank, values in enumerate(candidates, 1):
594  if values[0] is None:
595  # FIXME this probably isn't the correct thing
596  # to do...the issue is that the is_healthy()
597  # conditions for cold booting an analysis go
598  # like this:
599  #
600  # online analysis
601  # starts
602  # |------------------------------------------------->
603  # ^ ^
604  # |--------------| | |
605  # Extra time LRs start to FARs start to
606  # added to be assigned be assigned
607  # livetime
608  # without coincs
609  #
610  # there will be small biases due do the startup
611  # being out of sync.
612  #
613  continue
614  # values[9] is a string that is e.g., H1:4.8993754:1.0139208:2.061641:1.145543 L1:8.2582664:1.1890973:2.061641:1.145543
615  row = [rank] + [truncate(float(v), 3) for v in values[:4]] + [truncate(float(values[4]), 6, si=False)]
616  row.append(gpstime.gps_to_utc(float(values[4])).strftime("%Y-%m-%d %H:%M:%S"))
617  row.extend([truncate(float(v), 3) for v in values[5:7]] + list(values[7:9]))
618 
619  # populate row with trigger data
620  ifodict = {"H1": ['-', '-'], "L1": ['-', '-'], "V1": ['-', '-']}
621  template_params = ['-'] * 4
622  for ifo_row in values[9].split():
623  ifodata = ifo_row.split(":")
624  ifodict[ifodata[0]] = [truncate(float(v), 3) for v in ifodata[1:3]]
625  template_params = [truncate(float(v), 3) for v in ifodata[3:]]
626 
627  # add template params + SNR/chi^2 for all ifos
628  row.extend(template_params)
629  for ifo in sorted(ifodict.keys()):
630  row.extend(ifodict[ifo])
631 
632  # add row to table
633  data.append(row)
634 
635  save_table(fname, fields, data)
636 
637  def finish(self):
638  self.candidates.sort()
639  self.write_candidate_json(self.candidates[:101], self.base+'summary_table.json')
640  self.bgcandidates.sort()
641  self.write_candidate_json(self.bgcandidates[:101], self.base+'bgsummary_table.json')
642  yield None, None, None
643 
644 #
645 # =============================================================================
646 #
647 # Injection Parameter Distributions
648 #
649 # =============================================================================
650 #
651 
652 
653 class InjectionParameterDistributionPlots(object):
654  def __init__(self):
655  self.injections = {}
656 
657  def add_contents(self, contents):
658  if contents.sim_inspiral_table is None:
659  # no injections
660  return
661  for values in contents.connection.cursor().execute("""
662 SELECT
663  *
664 FROM
665  sim_inspiral
666  """):
667  sim = contents.sim_inspiral_table.row_from_cols(values)
668  del sim.process_id, sim.source, sim.simulation_id
669  instruments = frozenset(instrument for instrument, segments in contents.seglists.items() if sim.time_geocent in segments)
670  self.injections.setdefault(sim.waveform, []).append(sim)
671 
672  def finish(self):
673  for waveform, sims in self.injections.items():
674  for col1, col2, ax1, ax2, name, aspect in [
675  ([sim.mass1 for sim in sims], [sim.mass2 for sim in sims], r"$M_{1}$ ($\mathrm{M}_{\odot}$)", r"$M_{2}$ ($\mathrm{M}_{\odot}$)", "sim_dist_m1_m2_%s", None),
676  ([float(sim.time_geocent) for sim in sims], [math.log10(sim.distance) for sim in sims], r"$\textrm{Time (s)}$", r"$\log_{10} (\mathrm{distance} / 1\,\mathrm{Mpc})$", "sim_dist_time_distance_%s", None),
677  ([sim.longitude * 12 / math.pi for sim in sims], [math.sin(sim.latitude) for sim in sims], r"$\textrm{RA (h)}$", r"$\sin \mathrm{dec}$", "sim_dist_ra_dec_%s", None),
678  ([math.cos(sim.inclination) for sim in sims], [sim.polarization for sim in sims], r"$\cos \mathrm{inclination}$", r"$\textrm{Polarization (rad)}$", "sim_dist_inc_pol_%s", None),
679  ([sim.spin1z for sim in sims], [sim.spin2z for sim in sims], r"$s1_z$", r"$s2_z$", "sim_dist_spin1z_spin2z_%s", None)
680  ]:
681  fig = plotsumm.plot_injection_param_dist(col1, col2, ax1, ax2, waveform)
682  yield fig, name % (waveform), False
683 
684 
685 #
686 # =============================================================================
687 #
688 # Missed/Found Plot
689 #
690 # =============================================================================
691 #
692 
693 
694 class MissedFoundPlots(object):
695  class MissedFound(object):
696  def __init__(self, on_instruments, far_thresh, missed_found_plots, remove_precession, isolate_precession, snr_segments):
697  self.on_instruments = on_instruments
698  self.far_thresh = far_thresh
699  self.found_in = {}
700  self.missed_found_plots = missed_found_plots
701  self.remove_precession = remove_precession
702  self.isolate_precession = isolate_precession
703  self.snr_segments = snr_segments
704 
705  def add_contents(self, contents):
706  self.base = contents.base
707  zerolag_segments = contents.seglists.intersection(self.on_instruments) - contents.seglists.union(contents.instruments - self.on_instruments)
708  # why is this intersection being done?
709  # FIXME: why are "found" injections split up by
710  # what instruments recovered them at all? what is
711  # going on? this pipeline hasn't organized results
712  # by instrument combination in at least a decade, I
713  # have no idea why this code was written this way.
714  # OMG I hate found/missed plots! they're *so*
715  # stupid.
716  zerolag_segments &= self.snr_segments
717  for values in contents.connection.cursor().execute("""
718 SELECT
719  sim_inspiral.*,
720  (
721  SELECT
722  coinc_inspiral.ifos
723  FROM
724  sim_coinc_map
725  JOIN coinc_inspiral ON (
726  coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id
727  )
728  WHERE
729  sim_coinc_map.simulation_id == sim_inspiral.simulation_id
730  AND coinc_inspiral.combined_far < ?
731  )
732 FROM
733  sim_inspiral
734  """, (self.far_thresh if self.far_thresh is not None else float("+inf"),)):
735  sim = contents.sim_inspiral_table.row_from_cols(values)
736  del sim.process_id, sim.source, sim.simulation_id
737  if sim.time_geocent in zerolag_segments:
738  # any nonzero nonz spin -> precession_bool=True -> precessing injection
739  # all zero nonz spin -> precession_bool=Fales -> non precesssing injection
740  precession_bool = any(s != 0.0 for s in (sim.spin1x, sim.spin1y, sim.spin2x, sim.spin2y))
741  if self.remove_precession and precession_bool:
742  continue
743  if self.isolate_precession and not precession_bool:
744  continue
745  participating_instruments = lsctables.instrumentsproperty.get(values[-1])
746  if participating_instruments is not None:
747  participating_instruments = frozenset(participating_instruments)
748  self.found_in.setdefault(participating_instruments, []).append(sim)
749 
750  def finish(self):
751  missed = self.found_in.pop(None, [])
752 
753  # Define decisive distance even if there is one instrument
754  # FIXME We have NANs in the eff_distance column now so this
755  # function does not work
756  def decisive_distance(sim, instruments):
757  if len(instruments) > 1:
758  return sorted(sim_get_chirp_eff_dist(sim,instrument) for instrument in instruments)[1]
759  else:
760  return sim_get_chirp_eff_dist(sim,list(instruments)[0])
761  def decisive_chirp_distance(sim, instruments):
762  if len(instruments) > 1:
763  return sorted(sim_get_chirp_eff_dist(sim,instrument) for instrument in instruments)[1]
764  else:
765  return sim_get_chirp_eff_dist(sim,list(instruments)[0])
766 
767  def decisive_charsnr(sim, oninstruments):
768  if len(oninstruments) > 3:
769  raise ValueError("More than 3 instruments not supported for injection snr calculation at this time.")
770  else:
771  alphas = {'H1':sim.alpha4, 'L1':sim.alpha5, 'V1':sim.alpha6}
772  snrlist = []
773  for ifo in oninstruments:
774  snrlist.append(alphas[ifo])
775  if len(snrlist) == 3:
776  # Decisive SNR is second loudest for triple
777  return sorted(snrlist)[1]
778  else:
779  # Decisive SNR for doubles and singles
780  return sorted(snrlist)[0]
781 
782  for cnt, (title, x_label, x_func, y_label, y_func, filename_fragment) in enumerate((
783  (r"$\textrm{Distance vs.\ Chirp Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"$D$ ($\mathrm{Mpc}$)", lambda sim, instruments: sim.distance, "d_vs_mchirp"),
784  (r"$\textrm{Decisive Distance vs.\ Chirp Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_mchirp"),
785  (r"$\textrm{Chirp Decisive Distance vs.\ Chirp Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"$\mathrm{Decisive} D_{\mathrm{chirp, eff}}$ ($\mathrm{Mpc}$)", decisive_chirp_distance, "chirpdist_vs_mchirp"),
786  (r"$\textrm{Chirp Decisive Distance vs.\ Eta (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$\eta$", lambda sim: sim.eta, r"$\mathrm{Decisive} D_{\mathrm{chirp, eff}}$ ($\mathrm{Mpc}$)", decisive_chirp_distance, "chirpdist_vs_eta"),
787  (r"$\textrm{Decisive Distance vs.\ Total Mass (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{total}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mass1 + sim.mass2, r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_mtotal"),
788  (r"$\textrm{Decisive Distance vs.\ Effective Spin (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"$\chi$", lambda sim: (sim.spin1z*sim.mass1 + sim.spin2z*sim.mass2)/(sim.mass1 + sim.mass2), r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_chi"),
789  (r"$\textrm{Decisive Distance vs.\ Time (With %s Operating)}$" % ", ".join(sorted(self.on_instruments)), r"GPS Time (s)", lambda sim: sim.time_geocent, r"$\mathrm{Decisive} D_{\mathrm{eff}}$ ($\mathrm{Mpc}$)", decisive_distance, "deff_vs_t")
790  )):
791  ifo_count_summary = {''.join(sorted(combo)): '---' for num_ifos in range(1, len(self.missed_found_plots.instruments)+1) for combo in sorted(list(itertools.combinations(self.missed_found_plots.instruments, num_ifos)), reverse=True)}
792  ifo_count_summary['missed'] = '---'
793  found_data = {}
794  for participating_instruments, sims in sorted(self.found_in.items(), key = (lambda x: lsctables.instrumentsproperty.set(x[0]))):
795  if cnt == 0:
796  ifo_count_summary["".join(sorted(participating_instruments))] = len(sims)
797  found_data[participating_instruments] = (
798  [x_func(sim) for sim in sims],
799  [y_func(sim, participating_instruments) for sim in sims]
800  )
801  if missed:
802  if cnt == 0:
803  ifo_count_summary["missed"] = len(missed)
804  for rank, sim in enumerate(missed):
805  self.missed_found_plots.missed_summary_data.append(["".join(sorted(self.on_instruments)), sim.waveform, float(sim.time_at_instrument("H1", {"H1": 0.0})), float(sim.time_at_instrument("L1", {"L1": 0.0})), float(sim.time_at_instrument("V1", {"V1": 0.0})), sim.mass1, sim.mass2, sim.spin1x, sim.spin1y, sim.spin1z, sim.spin2x, sim.spin2y, sim.spin2z, sim.distance, decisive_chirp_distance(sim, self.on_instruments), sim.inclination, sim.alpha4, sim.alpha5, sim.alpha6, decisive_charsnr(sim, self.on_instruments)])
806  missed_data = (
807  [x_func(sim) for sim in missed],
808  [y_func(sim, self.on_instruments) for sim in missed]
809  )
810  else:
811  missed_data = None
812  if cnt == 0:
813  total_count = 0
814  for ifos in ifo_count_summary.keys():
815  if ifo_count_summary[ifos] != '---':
816  total_count += ifo_count_summary[ifos]
817  ifo_count_summary['total'] = total_count
818  ifo_columns = sorted([key for key in ifo_count_summary.keys() if 'missed' not in key and 'total' not in key], key=lambda item: (-len(item), item)) + ['missed', 'total']
819  missed_found_row = ["".join(sorted(self.on_instruments))] + [ifo_count_summary[ifo_col] for ifo_col in ifo_columns]
820  self.missed_found_plots.injection_summary_data.append(missed_found_row)
821  fig = plotsumm.plot_missed_found(found_data, missed_data, x_label, y_label, title)
822  yield fig, filename_fragment, False
823 
824  for cnt, (title, x_label, x_func, y_label, filename_fragment) in enumerate((
825  (r"Decisive Characteristic SNR vs.\ Chirp Mass (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mchirp, r"Decisive Characteristic SNR", "dec_expsnr_vs_mchirp"),
826  (r"Decisive Characteristic SNR vs.\ Total Mass (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$M_{\mathrm{total}}$ ($\mathrm{M}_{\odot}$)", lambda sim: sim.mass1 + sim.mass2, r"Decisive Characteristic SNR", "dec_expsnr_vs_mtotal"),
827  (r"Decisive Characteristic SNR vs.\ Eta (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$\eta$", lambda sim: sim.eta, r"Decisive Characteristic SNR", "dec_expsnr_vs_eta"),
828  (r"Decisive Characteristic SNR vs.\ Effective Spin (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"$\chi$", lambda sim: (sim.spin1z*sim.mass1 + sim.spin2z*sim.mass2)/(sim.mass1 + sim.mass2), r"Decisive Characteristic SNR", "dec_expsnr_vs_chi"),
829  (r"Decisive Characteristic SNR vs.\ Time (With %s Operating)" % ", ".join(sorted(self.on_instruments)), r"GPS Time (s)", lambda sim: sim.time_geocent, r"Decisivive Characteristic SNR", "dec_expsnr_vs_t")
830  )):
831  try:
832  found_data = {}
833  for participating_instruments, sims in sorted(self.found_in.items(), key = (lambda x: lsctables.instrumentsproperty.set(x[0]))):
834  found_data[participating_instruments] = (
835  [x_func(sim) for sim in sims],
836  [decisive_charsnr(sim, self.on_instruments) for sim in sims]
837  )
838  if missed:
839  missed_data = (
840  [x_func(sim) for sim in missed],
841  [decisive_charsnr(sim, self.on_instruments) for sim in missed]
842  )
843  else:
844  missed_data = None
845  fig = plotsumm.plot_missed_found(found_data, missed_data, x_label, y_label, title)
846  yield fig, filename_fragment, False
847  except ValueError:
848  print >> sys.stderr, "Cannot create expected SNR plots, no positive values, probably the SNRs are not set"
849 
850  def __init__(self, far_thresh, remove_precession, isolate_precession, snr_segments):
851  self.far_thresh = far_thresh
852  self.plots = {}
853  self.injection_summary_data = []
854  self.missed_summary_data = []
855  self.remove_precession = remove_precession
856  self.isolate_precession = isolate_precession
857  self.snr_segments = snr_segments
858  self.instruments = set()
859 
860  def add_contents(self, contents):
861  self.base = contents.base
862  if contents.sim_inspiral_table is None:
863  # no injections
864  return
865  for on_instruments in contents.on_instruments_combos:
866  self.instruments.update(on_instruments)
867  for on_instruments in contents.on_instruments_combos:
868  if on_instruments not in self.plots:
869  self.plots[on_instruments] = self.MissedFound(on_instruments, self.far_thresh, self, self.remove_precession, self.isolate_precession, self.snr_segments)
870  self.plots[on_instruments].add_contents(contents)
871 
872  def finish(self):
873  for on_instruments in sorted(self.plots.keys(), key=lambda item: (-len(item), item)):
874  plot = self.plots[on_instruments]
875  for fig, filename_fragment, is_open_box in plot.finish():
876  yield fig, "%s_%s" % (filename_fragment, "".join(sorted(on_instruments))), is_open_box
877 
878  ifo_columns = [''.join(sorted(combo)) for num_ifos in range(1, len(self.instruments)+1) for combo in sorted(list(itertools.combinations(self.instruments, num_ifos)), reverse=True)]
879  ifo_columns.sort(key=lambda item: (-len(item), item))
880  save_table(self.base + "_injection_summary.json", ["On Instruments"] + ifo_columns + ['Missed', 'Total'], self.injection_summary_data)
881  save_table(self.base + "_missed_summary.json", ["On Instruments", "Waveform", "H1 time", "L1 time", "V1 time", "m1", "m2", "S_1x", "S_1y", "S_1z", "S_2x", "S_2y", "S_2z", "D (Mpc)", "Decisive D chirp,eff (Mpc)" , "Inclination", "H1 SNR", "L1 SNR", "V1 SNR", "Decisive SNR"], self.missed_summary_data)
882 
883 
884 #
885 # =============================================================================
886 #
887 # Parameter Accuracy
888 #
889 # =============================================================================
890 #
891 
892 
893 class ParameterAccuracyPlots(object):
894  def __init__(self, far_thresh):
895  self.far_thresh = far_thresh
896  self.sim_sngl_pairs = {}
897 
898  @staticmethod
899  def get_inj_snr(sim, instrument):
900  alphas = {'H1':'alpha4', 'L1':'alpha5', 'V1':'alpha6'}
901  return getattr(sim, "%s" % alphas[instrument])
902 
903  def add_contents(self, contents):
904  if contents.sim_inspiral_table is None:
905  # not an injections file
906  return
907  n_simcolumns = len(contents.sim_inspiral_table.columnnames)
908 
909  for values in contents.connection.cursor().execute("SELECT * FROM sim_sngl_far"):
910  if values[-1] <= self.far_thresh:
911  sim = contents.sim_inspiral_table.row_from_cols(values)
912  sngl = contents.sngl_inspiral_table.row_from_cols(values[n_simcolumns:])
913  far = values[-1]
914  del sim.process_id, sim.source, sim.simulation_id
915  del sngl.process_id, sngl.event_id
916  self.sim_sngl_pairs.setdefault((sim.waveform, sngl.ifo), []).append((sim, sngl, far))
917 
918  def finish(self):
919  for (waveform, instrument), pairs in self.sim_sngl_pairs.items():
920  fig = plotsumm.plot_param_accuracy_scatter(
921  [sim.mchirp for sim, sngl, far in pairs],
922  [sngl.mchirp - sim.mchirp for sim, sngl, far in pairs],
923  [far for sim, sngl, far in pairs],
924  r"Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
925  r"Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
926  "FAR (Hz)",
927  r"Absolute $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
928  )
929  yield fig, "mchirp_acc_abs_scatter_%s_%s" % (waveform, instrument), False
930 
931  fig = plotsumm.plot_param_accuracy_histogram(
932  numpy.array([sngl.mchirp - sim.mchirp for sim, sngl, far in pairs]),
933  r"Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
934  r"Absolute $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
935  )
936  yield fig, "mchirp_acc_abs_hist_%s_%s" % (waveform, instrument), False
937 
938  fig = plotsumm.plot_param_accuracy_scatter(
939  [sim.mchirp for sim, sngl, far in pairs],
940  [(sngl.mchirp - sim.mchirp) / sim.mchirp for sim, sngl, far in pairs],
941  [far for sim, sngl, far in pairs],
942  r"Inj. $M_{\mathrm{chirp}}$ ($\mathrm{M}_{\odot}$)",
943  r"(Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$) / Inj. $M_{\mathrm{chirp}}$",
944  "FAR (Hz)",
945  r"Fractional $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
946  )
947  yield fig, "mchirp_acc_frac_scatter_%s_%s" % (waveform, instrument), False
948 
949  fig = plotsumm.plot_param_accuracy_histogram(
950  numpy.array([(sngl.mchirp - sim.mchirp) / sim.mchirp for sim, sngl, far in pairs]),
951  r"(Rec. $M_{\mathrm{chirp}}$ - Inj. $M_{\mathrm{chirp}}$)/ Inj. $M_{\mathrm{chirp}}$",
952  r"Fractional $M_{\mathrm{chirp}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
953  )
954  yield fig, "mchirp_acc_frac_hist_%s_%s" % (waveform, instrument), False
955 
956  fig = plotsumm.plot_param_accuracy_scatter(
957  [sim.mtotal for sim, sngl, far in pairs],
958  [(sngl.mtotal - sim.mtotal) / sim.mtotal for sim, sngl, far in pairs],
959  [far for sim, sngl, far in pairs],
960  r"Inj. $M_{\mathrm{total}}$ ($\mathrm{M}_{\odot}$)",
961  r"(Rec. $M_{\mathrm{total}}$ - Inj. $M_{\mathrm{total}}$) / Inj. $M_{\mathrm{total}}$",
962  "FAR (Hz)",
963  r"Fractional $M_{\mathrm{total}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
964  )
965  yield fig, "mtotal_acc_frac_scatter_%s_%s" % (waveform, instrument), False
966 
967  fig = plotsumm.plot_param_accuracy_histogram(
968  numpy.array([(sngl.mtotal - sim.mtotal) / sim.mtotal for sim, sngl, far in pairs]),
969  r"(Rec. $M_{\mathrm{total}}$ - Inj. $M_{\mathrm{total}}$) / Inj. $M_{\mathrm{total}}$",
970  r"Fractional $M_{\mathrm{total}}$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
971  )
972  yield fig, "mtotal_acc_frac_hist_%s_%s" % (waveform, instrument), False
973 
974  fig = plotsumm.plot_param_accuracy_scatter(
975  [sim.eta for sim, sngl, far in pairs],
976  [sngl.eta - sim.eta for sim, sngl, far in pairs],
977  [far for sim, sngl, far in pairs],
978  r"Inj. $\eta$",
979  r"Rec. $\eta$ - Inj. $\eta$",
980  "FAR (Hz)",
981  r"Absolute $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
982  )
983  yield fig, "eta_acc_abs_scatter_%s_%s" % (waveform, instrument), False
984 
985  fig = plotsumm.plot_param_accuracy_histogram(
986  numpy.array([sngl.eta - sim.eta for sim, sngl, far in pairs]),
987  r"Rec. $\eta$ - Inj. $\eta$",
988  r"Absolute $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
989  )
990  yield fig, "eta_acc_abs_hist_%s_%s" % (waveform, instrument), False
991 
992  fig = plotsumm.plot_param_accuracy_scatter(
993  [sim.eta for sim, sngl, far in pairs],
994  [(sngl.eta - sim.eta) / sim.eta for sim, sngl, far in pairs],
995  [far for sim, sngl, far in pairs],
996  r"Inj. $\eta$",
997  r"(Rec. $\eta$ - Inj. $\eta$) / Inj. $\eta$",
998  "FAR (Hz)",
999  r"Fractional $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1000  )
1001  yield fig, "eta_acc_frac_scatter_%s_%s" % (waveform, instrument), False
1002 
1003  fig = plotsumm.plot_param_accuracy_histogram(
1004  numpy.array([(sngl.eta - sim.eta) / sim.eta for sim, sngl, far in pairs]),
1005  r"(Rec. $\eta$ - Inj. $\eta$) / Inj. $\eta$",
1006  r"Fractional $\eta$ Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1007  )
1008  yield fig, "eta_acc_frac_hist_%s_%s" % (waveform, instrument), False
1009 
1010  fig = plotsumm.plot_param_accuracy(
1011  [sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}) for sim, sngl, far in pairs],
1012  [(sngl.end - sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}))*1000. for sim, sngl, far in pairs],
1013  r"Injection End Time (GPS s)",
1014  r"Rec. End Time - Injection End Time (ms)",
1015  r"End Time Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1016  )
1017  yield fig, "t_acc_scatter_%s_%s" % (waveform, instrument), False
1018 
1019  fig = plotsumm.plot_param_accuracy_histogram(
1020  numpy.array([float(sngl.end - sim.time_at_instrument(sngl.ifo, {sngl.ifo: 0.0}))*1000. for sim, sngl, far in pairs]),
1021  r"Rec. End Time - Injection End Time (ms)",
1022  r"End Time Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1023  )
1024  yield fig, "t_acc_hist_%s_%s" % (waveform, instrument), False
1025 
1026  fig = plotsumm.plot_param_accuracy(
1027  [sim.chi for sim, sngl, far in pairs],
1028  [sngl.chi for sim, sngl, far in pairs],
1029  r"Inj. $\chi$",
1030  r"Rec. $\chi$",
1031  r"Effective Spin Accuracy in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1032  )
1033  yield fig, "chi_acc_scatter_%s_%s" % (waveform, instrument), False
1034 
1035  fig = plotsumm.plot_param_accuracy(
1036  [self.get_inj_snr(sim, instrument) for sim, sngl, far in pairs],
1037  [sngl.snr for sim, sngl, far in pairs],
1038  r"Inj. SNR",
1039  r"Rec. SNR",
1040  r"SNR Recovery in %s (%s Injections)" % (instrument, waveform.replace("_", "\_")),
1041  loglog=max([self.get_inj_snr(sim, instrument) for sim, sngl, far in pairs]) > 20
1042  )
1043  yield fig, "snr_rec_scatter_%s_%s" % (waveform, instrument), False
1044 
1045  fig = plotsumm.plot_param_accuracy_histogram(
1046  numpy.array([(sngl.snr - self.get_inj_snr(sim, instrument)) for sim, sngl, far in pairs]),
1047  r"(Rec. SNR - Inj SNR)",
1048  r"SNR Diff in %s (%s Injections)" % (instrument, waveform.replace("_", "\_"))
1049  )
1050  yield fig, "snr_diff_hist_%s_%s" % (waveform, instrument), False
1051 
1052 #
1053 # =============================================================================
1054 #
1055 # Background vs. Injections --- Single Instrument
1056 #
1057 # =============================================================================
1058 #
1059 
1060 
1061 class BackgroundVsInjectionPlots(object):
1062  class Points(object):
1063  def __init__(self):
1064  self.snr = []
1065  self.chi2 = []
1066  self.bankveto = []
1067  self.mchirp = []
1068  self.eta = []
1069  self.chieff = []
1070  self.spin = []
1071  self.end_time = []
1072 
1073  def __bool__(self):
1074  return bool(self.snr)
1075 
1076  def __init__(self, snr_min):
1077  self.snr_min = snr_min
1078  self.injections = {}
1079  self.background = {}
1080  self.zerolag = {}
1081 
1082  def add_contents(self, contents):
1083  if contents.sim_inspiral_table is None:
1084  # non-injections file
1085  for values in contents.connection.cursor().execute("""
1086 SELECT
1087  sngl_inspiral.*,
1088  EXISTS (
1089  SELECT
1090  *
1091  FROM
1092  time_slide
1093  WHERE
1094  time_slide.time_slide_id == coinc_event.time_slide_id
1095  AND time_slide.offset != 0
1096  )
1097 FROM
1098  coinc_event
1099  JOIN coinc_event_map ON (
1100  coinc_event_map.coinc_event_id == coinc_event.coinc_event_id
1101  )
1102  JOIN sngl_inspiral ON (
1103  coinc_event_map.table_name == 'sngl_inspiral'
1104  AND coinc_event_map.event_id == sngl_inspiral.event_id
1105  )
1106 WHERE
1107  coinc_event.coinc_def_id == ?
1108  """, (contents.ii_definer_id,)):
1109  sngl = contents.sngl_inspiral_table.row_from_cols(values)
1110  eta = sngl.mass1 * sngl.mass2 / (sngl.mass1 + sngl.mass2)**2
1111  mtot = sngl.mass1 + sngl.mass2
1112  chieff = (sngl.mass1 * sngl.spin1z + sngl.mass2 * sngl.spin2z) / mtot
1113  instrument = sngl.ifo
1114  is_background = values[-1]
1115  if is_background:
1116  if instrument not in self.background:
1117  self.background[instrument] = self.Points()
1118  self.background[instrument].snr.append(sngl.snr)
1119  self.background[instrument].chi2.append(sngl.chisq)
1120  self.background[instrument].bankveto.append(sngl.bank_chisq)
1121  self.background[instrument].mchirp.append(mtot * eta**(3. / 5))
1122  self.background[instrument].eta.append(eta)
1123  self.background[instrument].chieff.append(chieff)
1124  self.background[instrument].end_time.append(float(sngl.end))
1125  else:
1126  if instrument not in self.zerolag:
1127  self.zerolag[instrument] = self.Points()
1128  self.zerolag[instrument].snr.append(sngl.snr)
1129  self.zerolag[instrument].chi2.append(sngl.chisq)
1130  self.zerolag[instrument].bankveto.append(sngl.bank_chisq)
1131  self.zerolag[instrument].mchirp.append(mtot * eta**(3. / 5))
1132  self.zerolag[instrument].eta.append(eta)
1133  self.zerolag[instrument].chieff.append(chieff)
1134  self.zerolag[instrument].end_time.append(float(sngl.end))
1135  else:
1136  # injections file
1137  n_simcolumns = len(contents.sim_inspiral_table.columnnames)
1138  for values in contents.connection.cursor().execute("SELECT * FROM sim_sngl_far"):
1139  sim = contents.sim_inspiral_table.row_from_cols(values)
1140  sngl = contents.sngl_inspiral_table.row_from_cols(values[n_simcolumns:])
1141  far = values[-1]
1142  eta = sngl.mass1 * sngl.mass2 / (sngl.mass1 + sngl.mass2)**2
1143  mtot = sngl.mass1 + sngl.mass2
1144  chieff = (sngl.mass1 * sngl.spin1z + sngl.mass2 * sngl.spin2z) / mtot
1145  instrument = sngl.ifo
1146  end_time = sngl.end
1147  # FIXME, what should this be?
1148  spin = (sim.mass1 * (sim.spin1x**2 + sim.spin1y**2 + sim.spin1z**2)**.5 + sim.mass2 * (sim.spin1x**2 + sim.spin1y**2 + sim.spin1**2)**.5 ) / (sim.mass1 + sim.mass2)
1149  if end_time in contents.seglists[instrument]:
1150  if instrument not in self.injections:
1151  self.injections[instrument] = self.Points()
1152  self.injections[instrument].snr.append(sngl.snr)
1153  self.injections[instrument].chi2.append(sngl.chisq)
1154  self.injections[instrument].bankveto.append(sngl.bank_chisq)
1155  self.injections[instrument].mchirp.append(mtot * eta**(3. / 5))
1156  self.injections[instrument].eta.append(eta)
1157  self.injections[instrument].chieff.append(chieff)
1158  self.injections[instrument].spin.append(spin)
1159 
1160  def finish(self):
1161  for instrument in set(self.injections) | set(self.background) | set(self.zerolag):
1162  self.injections.setdefault(instrument, self.Points())
1163  self.background.setdefault(instrument, self.Points())
1164  self.zerolag.setdefault(instrument, self.Points())
1165 
1166  for instrument in self.background:
1167  fig = plotsumm.plot_snr_chi2_background(instrument, self.snr_min, self.injections, self.background)
1168  yield fig, "chi2_vs_rho_%s" % instrument, False
1169 
1170  fig = plotsumm.plot_snr_chi2_background(instrument, self.snr_min, self.injections, self.background, self.zerolag)
1171  yield fig, "chi2_vs_rho_%s" % instrument, True
1172 
1173  # the following plots require background and injections
1174  if self.background[instrument] and self.injections[instrument]:
1175  # for the following plots, sort injections by SNR -- descending
1176  sortable = numpy.array(self.injections[instrument].snr).argsort()[::-1]
1177  inj_mcs = numpy.array(self.injections[instrument].mchirp)[sortable]
1178  inj_etas = numpy.array(self.injections[instrument].eta)[sortable]
1179  inj_snrs = numpy.array(self.injections[instrument].snr)[sortable]
1180  inj_chisq = numpy.array(self.injections[instrument].chi2)[sortable]
1181 
1182  # sort background triggers by SNR -- ascending
1183  sortable = numpy.array(self.background[instrument].snr).argsort()
1184  bg_mcs = numpy.array(self.background[instrument].mchirp)[sortable]
1185  bg_etas = numpy.array(self.background[instrument].eta)[sortable]
1186  bg_snrs = numpy.array(self.background[instrument].snr)[sortable]
1187  bg_chisq = numpy.array(self.background[instrument].chi2)[sortable]
1188  bg_chieffs = numpy.array(self.background[instrument].chieff)[sortable]
1189 
1190  # mass dependence of chisq
1191  fig = plotsumm.plot_mass_chi2_snr2_background(inj_mcs, inj_chisq, inj_snrs, bg_mcs, bg_chisq, bg_snrs, instrument)
1192  yield fig, "chi2_vs_mc_vs_rho_%s" % instrument, False
1193 
1194  # background parameter distributions
1195  fig = plotsumm.plot_background_param_dist(
1196  bg_mcs, bg_etas, numpy.log10(bg_snrs),
1197  r"$M_\mathrm{chirp}$", r"$\eta$", "log(SNR) in %s" % instrument,
1198  r"Background Events in %s (Closed Box)" % instrument
1199  )
1200  yield fig, "bgparams_mchirp_vs_eta_vs_snr_%s" % instrument, False
1201 
1202  # background parameter distributions
1203  flow = 10 # arbitrary choice
1204  a0 = 5. / (256 * (numpy.pi * flow)**(8./3) )
1205  a3 = numpy.pi / (8 * (numpy.pi * flow)**(5./3) )
1206  bg_tau0s = a0 * (lal.MTSUN_SI * bg_mcs)**(-5./3)
1207  bg_tau3s = (a3 / bg_etas) * (bg_etas * bg_tau0s / a0)**(2./5)
1208  fig = plotsumm.plot_background_param_dist(
1209  bg_tau0s, bg_tau3s, numpy.log10(bg_snrs),
1210  r"$\tau_0$ (s)", r"$\tau_3$ (s)", "log(SNR) in %s" % instrument,
1211  r"Background Events in %s (Closed Box)" % instrument
1212  )
1213  yield fig, "bgparams_tau0_vs_tau3_vs_snr_%s" % instrument, False
1214 
1215  # background parameter distributions
1216  fig = plotsumm.plot_background_param_dist(
1217  bg_mcs, bg_chieffs, numpy.log10(bg_snrs),
1218  r"$M_\mathrm{chirp}$", r"$\chi_\mathrm{eff}$", "log(SNR) in %s" % instrument,
1219  r"Background Events in %s (Closed Box)" % instrument
1220  )
1221  yield fig, "bgparams_mchirp_vs_chieff_vs_snr_%s" % instrument, False
1222 
1223 
1224 #
1225 # =============================================================================
1226 #
1227 # Background vs. Injections --- Multi Instrument
1228 #
1229 # =============================================================================
1230 #
1231 
1232 
1233 class BackgroundVsInjectionPlotsMulti(object):
1234  class Points(object):
1235  def __init__(self):
1236  self.background_snr = []
1237  self.injections_snr = []
1238  self.zerolag_snr = []
1239  self.background_deff = []
1240  self.injections_deff = []
1241  self.injections_mchirp = []
1242  self.injections_chieff = []
1243  self.zerolag_deff = []
1244  self.background_mchirp = []
1245  self.background_mtot = []
1246  self.background_eta = []
1247  self.background_chieff = []
1248 
1249  def __init__(self, snr_min):
1250  self.snr_min = snr_min
1251  self.points = {}
1252 
1253  def add_contents(self, contents):
1254  if contents.sim_inspiral_table is None:
1255  # non-injections file
1256  for values in contents.connection.cursor().execute("""
1257 SELECT
1258  sngl_inspiral_x.*,
1259  sngl_inspiral_y.*,
1260  EXISTS (
1261  SELECT
1262  *
1263  FROM
1264  time_slide
1265  WHERE
1266  time_slide.time_slide_id == coinc_event.time_slide_id
1267  AND time_slide.offset != 0
1268  )
1269 FROM
1270  coinc_event
1271  JOIN coinc_event_map AS coinc_event_map_x ON (
1272  coinc_event_map_x.coinc_event_id == coinc_event.coinc_event_id
1273  )
1274  JOIN sngl_inspiral AS sngl_inspiral_x ON (
1275  coinc_event_map_x.table_name == 'sngl_inspiral'
1276  AND coinc_event_map_x.event_id == sngl_inspiral_x.event_id
1277  )
1278  JOIN coinc_event_map AS coinc_event_map_y ON (
1279  coinc_event_map_y.coinc_event_id == coinc_event.coinc_event_id
1280  )
1281  JOIN sngl_inspiral AS sngl_inspiral_y ON (
1282  coinc_event_map_y.table_name == 'sngl_inspiral'
1283  AND coinc_event_map_y.event_id == sngl_inspiral_y.event_id
1284  )
1285  JOIN coinc_inspiral ON (
1286  coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
1287  )
1288 WHERE
1289  coinc_event.coinc_def_id == ?
1290  AND sngl_inspiral_x.ifo > sngl_inspiral_y.ifo
1291  """, (contents.ii_definer_id,)):
1292  x = contents.sngl_inspiral_table.row_from_cols(values)
1293  y = contents.sngl_inspiral_table.row_from_cols(values[len(contents.sngl_inspiral_table.columnnames):])
1294  is_background, = values[-1:]
1295  instrument_pair = (x.ifo, y.ifo)
1296  if instrument_pair not in self.points:
1297  self.points[instrument_pair] = self.Points()
1298  if is_background:
1299  self.points[instrument_pair].background_snr.append((x.snr, y.snr))
1300  eta = x.mass1 * x.mass2 / (x.mass1 + x.mass2)**2
1301  mtot = x.mass1 + x.mass2
1302  self.points[instrument_pair].background_eta.append(eta)
1303  self.points[instrument_pair].background_mtot.append(mtot)
1304  self.points[instrument_pair].background_mchirp.append(mtot * eta**(3./5))
1305  self.points[instrument_pair].background_chieff.append((x.mass1 * x.spin1z + x.mass2 * x.spin2z) / mtot)
1306 
1307  else:
1308  self.points[instrument_pair].zerolag_snr.append((x.snr, y.snr))
1309  else:
1310  # injections file
1311  for values in contents.connection.cursor().execute("""
1312 SELECT
1313  sngl_inspiral_x.*,
1314  sngl_inspiral_y.*
1315 FROM
1316  sngl_inspiral AS sngl_inspiral_x
1317  JOIN sim_id_sngl_id AS sim_id_sngl_id_x ON sim_id_sngl_id_x.sngl_id == sngl_inspiral_x.event_id
1318  JOIN sngl_inspiral AS sngl_inspiral_y JOIN sim_id_sngl_id AS sim_id_sngl_id_y ON sim_id_sngl_id_y.sngl_id == sngl_inspiral_y.event_id
1319 WHERE
1320  sim_id_sngl_id_x.sim_id == sim_id_sngl_id_y.sim_id AND sngl_inspiral_x.ifo > sngl_inspiral_y.ifo;
1321  """):
1322  x = contents.sngl_inspiral_table.row_from_cols(values)
1323  y = contents.sngl_inspiral_table.row_from_cols(values[len(contents.sngl_inspiral_table.columnnames):])
1324  instrument_pair = (x.ifo, y.ifo)
1325  if instrument_pair not in self.points:
1326  self.points[instrument_pair] = self.Points()
1327  self.points[instrument_pair].injections_snr.append((x.snr, y.snr))
1328  eta = x.mass1 * x.mass2 / (x.mass1 + x.mass2)**2
1329  mtot = x.mass1 + x.mass2
1330  self.points[instrument_pair].injections_mchirp.append(mtot * eta**(3./5))
1331  self.points[instrument_pair].injections_chieff.append((x.mass1 * x.spin1z + x.mass2 * x.spin2z) / mtot)
1332 
1333 
1334  def finish(self):
1335  for (x_instrument, y_instrument), points in self.points.items():
1336  fig = plotsumm.plot_param_background_multiifo(
1337  x_instrument, y_instrument, self.snr_min, "SNR", "$\rho$",
1338  points.injections_snr, points.background_snr
1339  )
1340  yield fig, "rho_%s_vs_%s" % (y_instrument, x_instrument), False
1341 
1342  fig = plotsumm.plot_param_background_multiifo(
1343  x_instrument, y_instrument, self.snr_min, "SNR", "$\rho$",
1344  points.injections_snr, points.background_snr, points.zerolag_snr
1345  )
1346  yield fig, "rho_%s_vs_%s" % (y_instrument, x_instrument), True
1347 
1348  fig = plotsumm.plot_param_background_multiifo(
1349  x_instrument, y_instrument, self.snr_min, "Effective Distance", "$D_{\mathrm{eff}}$",
1350  points.injections_deff, points.background_deff
1351  )
1352  yield fig, "deff_%s_vs_%s" % (y_instrument, x_instrument), False
1353 
1354  fig = plotsumm.plot_param_background_multiifo(
1355  x_instrument, y_instrument, self.snr_min, "Effective Distance", "$D_{\mathrm{eff}}$",
1356  points.injections_deff, points.background_deff, points.zerolag_deff
1357  )
1358  yield fig, "deff_%s_vs_%s" % (y_instrument, x_instrument), True
1359 
1360 
1361 #
1362 # =============================================================================
1363 #
1364 # Rate vs. Threshold Plots
1365 #
1366 # =============================================================================
1367 #
1368 
1369 
1370 class RateVsThreshold(object):
1371  def __init__(self, fapfar, snr_min):
1372  self.background_ln_likelihood_ratio = []
1373  self.zerolag_ln_likelihood_ratio = []
1374  self.background_far = []
1375  self.zerolag_far = []
1376  self.background_fap = []
1377  self.zerolag_fap = []
1378  self.background_snr = []
1379  self.zerolag_snr = []
1380  self.fapfar = fapfar
1381  self.snr_min = snr_min
1382 
1383  def add_contents(self, contents):
1384  if contents.sim_inspiral_table is not None:
1385  # skip injection documents
1386  return
1387 
1388  for ln_likelihood_ratio, far, fap, snr, is_background in connection.cursor().execute("""
1389 SELECT
1390  coinc_event.likelihood,
1391  coinc_inspiral.combined_far,
1392  coinc_inspiral.false_alarm_rate,
1393  coinc_inspiral.snr,
1394  EXISTS (
1395  SELECT
1396  *
1397  FROM
1398  time_slide
1399  WHERE
1400  time_slide.time_slide_id == coinc_event.time_slide_id
1401  AND time_slide.offset != 0
1402  )
1403 FROM
1404  coinc_inspiral
1405  JOIN coinc_event ON (
1406  coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
1407  )
1408 WHERE
1409  coinc_event.likelihood >= ?
1410  """, (self.fapfar.minrank,)):
1411  if far is None:
1412  continue
1413  if is_background:
1414  self.background_ln_likelihood_ratio.append(ln_likelihood_ratio)
1415  self.background_far.append(far)
1416  self.background_fap.append(fap)
1417  self.background_snr.append(snr)
1418  else:
1419  self.zerolag_ln_likelihood_ratio.append(ln_likelihood_ratio)
1420  self.zerolag_far.append(far)
1421  self.zerolag_fap.append(fap)
1422  self.zerolag_snr.append(snr)
1423 
1424  def finish(self):
1425  fig = plotsumm.plot_candidate_lnL_vs_snr(self.snr_min, self.background_snr, self.background_ln_likelihood_ratio)
1426  yield fig, "lr_vs_snr", False
1427 
1428  fig = plotsumm.plot_candidate_lnL_vs_snr(
1429  self.snr_min, self.background_snr, self.background_ln_likelihood_ratio,
1430  self.zerolag_snr, self.zerolag_ln_likelihood_ratio
1431  )
1432  yield fig, "lr_vs_snr", True
1433 
1434  for ln_likelihood_ratio, fars, is_open_box in [(self.zerolag_ln_likelihood_ratio, self.zerolag_far, True), (self.background_ln_likelihood_ratio, self.background_far, False)]:
1435  if fars:
1436  # fars in ascending order --> ifars in descending order
1437  zerolag_stats = 1. / numpy.array(sorted(fars))
1438  fig = plotsumm.plot_rate_vs_ifar(zerolag_stats, self.fapfar, is_open_box)
1439  yield fig, "count_vs_ifar", is_open_box
1440 
1441  if ln_likelihood_ratio:
1442  # ln(L) in ascending order
1443  zerolag_stats = numpy.array(sorted(ln_likelihood_ratio, reverse = True))
1444  fig = plotsumm.plot_rate_vs_lnL(zerolag_stats, self.fapfar, is_open_box)
1445  yield fig, "count_vs_lr", is_open_box
1446 
1447  if self.background_ln_likelihood_ratio:
1448  background_stats = numpy.array(sorted(self.background_ln_likelihood_ratio, reverse = True))
1449  zerolag_stats = numpy.array(sorted(self.zerolag_ln_likelihood_ratio, reverse = True))
1450  fig = plotsumm.plot_rate_vs_background_lnL(zerolag_stats, background_stats, self.fapfar)
1451  yield fig, "count_vs_lr_fig3", True
1452 
1453 
1454 class Segments(object):
1455  def __init__(self, base):
1456  self.all_segs_dict = {}
1457  self.data = []
1458  self.table = []
1459  self.base = base
1460 
1461  def add_contents(self, contents):
1462  # only process non-injection documents
1463  if contents.sim_inspiral_table is None:
1464  for name, seglists in contents.all_segs_dict.items():
1465  # need to use operator because Python won't
1466  # allow a function call on the LHS of |=
1467  # for some mystery reason.
1468  operator.ior(self.all_segs_dict.setdefault(name, segments.segmentlistdict()), seglists)
1469 
1470  def finish(self):
1471  segs = reduce(segments.segmentlistdict.__or__, self.all_segs_dict.values(), segments.segmentlistdict())
1472  self.extent = segs.extent_all()
1473 
1474  for name, seglists in self.all_segs_dict.items():
1475  for ifo, seglist in seglists.items():
1476  for seg in seglist:
1477  self.data.append(["%s: %s" % (str(ifo), str(name)), "", "%.2f-%.2f" % (float(seg[0]), float(seg[1])), float(seg[0])*1000 + 315964800000 - 17000, float(seg[1])*1000 + 315964800000 - 17000])
1478 
1479  analyzable_instruments_set = set(segs.keys())
1480  for n in range(1, 1 + len(segs)):
1481  for ifo_combos in itertools.combinations(list(analyzable_instruments_set), n):
1482  this = segs.intersection(ifo_combos) - segs.union(analyzable_instruments_set - set(ifo_combos))
1483  if len(this) > 0:
1484  #FIXME inf is not handled properly
1485  start = float(this.extent()[0])
1486  end = float(this.extent()[1])
1487  if end == float("inf"):
1488  end = 2000000000.
1489  duration = end - start
1490  self.table.append([name, ",".join(ifo_combos), start, end, duration])
1491 
1492  self.table.insert(0, ["all", "all", float(self.extent[0]), float(self.extent[1]), float(abs(self.extent))])
1493  f = open("%s_segments.json" % self.base, "w")
1494  f.write(repr(self.data))
1495  f.close()
1496  save_table("%s_segment_table.json" % self.base, ["name", "ifos", "start", "end", "extent"], self.table)
1497 
1498 
1499 #
1500 # =============================================================================
1501 #
1502 # Main
1503 #
1504 # =============================================================================
1505 #
1506 
1507 
1508 #
1509 # Parse command line
1510 #
1511 
1512 
1513 options, filenames = parse_command_line()
1514 
1515 
1516 #
1517 # Load likelihood input
1518 #
1519 
1520 
1521 if options.likelihood_file is not None:
1522  rankingstatpdf = far.marginalize_pdf_urls([options.likelihood_file], which = "RankingStatPDF", verbose = options.verbose)
1523 else:
1524  rankingstatpdf = None
1525 snr_min = far.inspiral_lr.LnLRDensity.snr_min
1526 if rankingstatpdf is not None:
1527  fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
1528 else:
1529  fapfar = None
1530 
1531 
1532 #
1533 # Initialize plots
1534 #
1535 
1536 
1537 def new_plots(plots, fapfar, far_thresh, remove_precession, isolate_precession, snr_segments):
1538  l = (
1539  SummaryTable(),
1540  MissedFoundPlots(far_thresh, remove_precession, isolate_precession, snr_segments),
1541  ParameterAccuracyPlots(far_thresh = far_thresh),
1542  BackgroundVsInjectionPlots(snr_min = snr_min),
1543  BackgroundVsInjectionPlotsMulti(snr_min = snr_min),
1544  RateVsThreshold(fapfar = fapfar, snr_min = snr_min),
1545  InjectionParameterDistributionPlots(),
1546  )
1547  if plots is None:
1548  plots = range(len(l))
1549  return [(i, l[i]) for i in plots]
1550 
1551 plots = new_plots(options.plot_group, fapfar, options.far_threshold, options.remove_precession, options.isolate_precession, rankingstatpdf.segments if rankingstatpdf is not None else None)
1552 
1553 
1554 #
1555 # Process files
1556 #
1557 
1558 
1559 seg_class = Segments(base = os.path.join(options.output_dir, options.user_tag))
1560 
1561 for n, filename in enumerate(filenames):
1562  if options.verbose:
1563  print >>sys.stderr, "%d/%d: %s" % (n + 1, len(filenames), filename)
1564  with dbtables.workingcopy(filename, tmp_path = options.tmp_space, discard = True, verbose = options.verbose) as working_filename:
1565  connection = sqlite3.connect(str(working_filename))
1566  contents = CoincDatabase(connection, options.segments_name, veto_segments_name = options.vetoes_name, verbose = options.verbose, plotsummary_json = os.path.split(filename)[-1].replace(".sqlite","").replace(".tmp",""), base = os.path.join(options.output_dir, options.user_tag), extend_veto_segments = options.extend_veto_segments, shrink_data_segments = options.shrink_data_segments)
1567  if contents.sim_inspiral_table is not None:
1568  create_sim_coinc_view(connection)
1569  seg_class.add_contents(contents)
1570  for plot_group, plot in plots:
1571  if options.verbose:
1572  print >>sys.stderr, "adding to plot group %d ..." % plot_group
1573  plot.add_contents(contents)
1574  connection.close()
1575 
1576 seg_class.finish()
1577 
1578 
1579 #
1580 # Finish and write plots, deleting them as we go to save memory
1581 #
1582 
1583 
1584 filename_template = dagparts.T050017_filename("H1L1V1", "GSTLAL_INSPIRAL_PLOTSUMMARY_%s_%02d_%s_%s", contents.seglists.extent_all(), "%s", path = options.output_dir)
1585 while len(plots):
1586  plot_group, plot = plots.pop(0)
1587  for fig, filename_fragment, is_open_box in plot.finish():
1588  if fig is not None:
1589  try:
1590  fig.tight_layout(rect=(0.03, 0.02, 0.98, 0.98))
1591  except ValueError:
1592  pass
1593  for fmt in options.format:
1594  if filename_fragment and fig:
1595  filename = filename_template % (options.user_tag, plot_group, filename_fragment, ("openbox" if is_open_box else "closedbox"), fmt)
1596  if options.verbose:
1597  print >>sys.stderr, "writing %s ..." % filename
1598  fig.savefig(filename)
def group
group a list roughly according to the distribution in parts, e.g.