gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_plot_background
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2013 Chad Hanna, Kipp Cannon
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 
19 
20 ### A program to plot the likelihood distributions in noise of a gstlal inspiral analysis
21 
22 
23 #
24 # =============================================================================
25 #
26 # Preamble
27 #
28 # =============================================================================
29 #
30 
31 
32 import itertools
33 import math
34 import matplotlib
35 matplotlib.rcParams.update({
36  "font.size": 10.0,
37  "axes.titlesize": 10.0,
38  "axes.labelsize": 10.0,
39  "xtick.labelsize": 8.0,
40  "ytick.labelsize": 8.0,
41  "legend.fontsize": 8.0,
42  "figure.dpi": 600,
43  "savefig.dpi": 600,
44  "text.usetex": True
45 })
46 from matplotlib import figure
47 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
48 import numpy
49 from optparse import OptionParser
50 import sqlite3
51 import sys
52 
53 
54 from ligo.lw import dbtables
55 from ligo.lw import lsctables
56 from glue.text_progress_bar import ProgressBar
57 from lal.utils import CacheEntry
58 from lalinspiral import thinca
59 from ligo.segments import utils as segmentsUtils
60 
61 
62 from gstlal import far
63 from gstlal import dagparts
64 from gstlal.plots import far as plotfar
65 
66 
67 class SnrChiColourNorm(matplotlib.colors.Normalize):
68  def __call__(self, value, clip = None):
69  value, is_scalar = self.process_value(value)
70  numpy.clip(value, 1e-200, 1e+200, value)
71 
72  self.autoscale_None(value)
73 
74  vmin = math.log(self.vmin)
75  vmax = math.log(self.vmax)
76  xbar = (vmax + vmin) / 2.
77  delta = (vmax - vmin) / 2.
78  pi_2 = math.pi / 2.
79 
80  value = (numpy.arctan((numpy.log(value) - xbar) * pi_2 / delta) + pi_2) / math.pi
81  return value[0] if is_scalar else value
82 
83  def inverse(self, value):
84  vmin = math.log(self.vmin)
85  vmax = math.log(self.vmax)
86  xbar = (vmax + vmin) / 2.
87  delta = (vmax - vmin) / 2.
88  pi_2 = math.pi / 2.
89 
90  value = numpy.exp(numpy.tan(value * math.pi - pi_2) * delta / pi_2 + xbar)
91  numpy.clip(value, 1e-200, 1e+200, value)
92  return value
93 
94  def _autoscale(self, vmin, vmax):
95  vmin = math.log(vmin)
96  vmax = math.log(vmax)
97  xbar = (vmax + vmin) / 2.
98  delta = (vmax - vmin) / 2.
99  xbar += 2. * delta / 3.
100  delta /= 4.
101  vmin = math.exp(xbar - delta)
102  vmax = math.exp(xbar + delta)
103  return vmin, vmax
104 
105  def autoscale(self, A):
106  self.vmin, self.vmax = self._autoscale(numpy.ma.min(A), numpy.ma.max(A))
107 
108  def autoscale_None(self, A):
109  vmin, vmax = self._autoscale(numpy.ma.min(A), numpy.ma.max(A))
110  if self.vmin is None:
111  self.vmin = vmin
112  if self.vmax is None:
113  self.vmax = vmax
114 
115 
116 #
117 # =============================================================================
118 #
119 # Command Line
120 #
121 # =============================================================================
122 #
123 
124 
125 def parse_command_line():
126  parser = OptionParser()
127  parser.add_option("-d", "--database", metavar = "filename", action = "append", help = "Retrieve search results from this database (optional). Can be given multiple times.")
128  parser.add_option("-c", "--database-cache", metavar = "filename", help = "Retrieve search results from all databases in this LAL cache (optional). See lalapps_path2cache.")
129  parser.add_option("--max-snr", metavar = "SNR", default = 200., type = "float", help = "Plot SNR PDFs up to this value of SNR (default = 200).")
130  parser.add_option("--max-log-lambda", metavar = "value", default = 40., type = "float", help = "Plot ranking statistic CCDFs, etc., up to this value of the natural logarithm of the likelihood ratio (default = 40).")
131  parser.add_option("--min-log-lambda", metavar = "value", default = -5., type = "float", help = "Plot ranking statistic CCDFs, etc., down to this value of the natural logarithm of the likelihood ratio (default = -5).")
132  parser.add_option("--scatter-log-lambdas", metavar = "[low]:[high][,[low]:[high]...]", help = "Overlay scatter plots of candidate parameter co-ordinates on various PDF plots, limiting the candidates to those whose log likelihood ratios are in the given range (default = don't overlay scatter plot). Use a range of \":\" to plot all candidates.")
133  parser.add_option("--output-dir", metavar = "output-dir", default = ".", help = "Write output to this directory (default = \".\").")
134  parser.add_option("--output-format", metavar = "extension", default = ".png", help = "Select output format by setting the filename extension (default = \".png\").")
135  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.")
136  parser.add_option("--add-zerolag-to-background", action = "store_true", help = "Add zerolag events to background before populating coincident parameter PDF histograms.")
137  parser.add_option("--user-tag", metavar = "user-tag", default = "ALL", help = "Set the adjustable component of the description fields in the output filenames (default = \"ALL\").")
138  parser.add_option("--plot-snr-snr-pdfs", action = "store_true", help = "Plot the full cache of snr-snr-pdfs.")
139  parser.add_option("--event-snr", metavar = "ifo:snr", action = "append", help = "SNR to plot on snr chisq plots. Pass as ifo:snr, e.g. H1:3.2. Can be passed multiple times, though only once for each ifo. Must also pass --event-chisq for ifo.")
140  parser.add_option("--event-chisq", metavar = "ifo:chisq", action = "append", help = "chisq to plot on snr chisq plots. Pass as ifo:chisq, e.g. H1:1.1. Can be passed multiple times, though only once for each ifo. Must also pass --event-snr for ifo.")
141  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
142  options, filenames = parser.parse_args()
143 
144  if options.database_cache is not None:
145  if options.database is None:
146  options.database = []
147  options.database += [CacheEntry(line).path for line in open(options.database_cache)]
148 
149  valid_formats = (".png", ".pdf", ".svg")
150  if options.output_format not in valid_formats:
151  raise ValueError("invalid --output-format \"%s\", allowed are %s" % (options.output_format, ", ".join("\"%s\"" % fmt for fmt in valid_formats)))
152 
153  if options.scatter_log_lambdas is not None:
154  options.scatter_log_lambdas = segmentsUtils.from_range_strings(options.scatter_log_lambdas.split(","), boundtype = float).coalesce()
155 
156  options.user_tag = options.user_tag.upper()
157 
158  options.event_snr_dict = {}
159  options.event_chisq_dict = {}
160  if options.event_snr or options.event_chisq:
161  for ifo_snr_str in options.event_snr:
162  ifo, snr = ifo_snr_str.split(':')
163  options.event_snr_dict[ifo] = float(snr)
164  for ifo_chisq_str in options.event_chisq:
165  if ifo_chisq_str.split(':')[0] != ifo:
166  continue
167  options.event_chisq_dict[ifo] = float(ifo_chisq_str.split(':')[1])
168 
169  for ifo in options.event_snr_dict.keys():
170  if ifo not in options.event_chisq_dict.keys():
171  print(ifo)
172  raise ValueError("Each ifo provided to --event-snr or --event-chisq must be provided to both options")
173 
174  return options, filenames
175 
176 
177 #
178 # =============================================================================
179 #
180 # Input
181 #
182 # =============================================================================
183 #
184 
185 
186 def load_distributions(filenames, verbose = False):
187  # RankingStat objects go into a dictionary indexed by the template
188  # bank ID set they are for, with RankinStat objects for the same
189  # templates being summed. RankingStatPDF objects are summed (and
190  # therefore are required to be fore the same templates). these
191  # organizational choices reflect the current use cases for this
192  # program
193  rankingstats = {}
194  rankingstatpdf = None
195  for n, filename in enumerate(filenames, 1):
196  if verbose:
197  print("%d/%d:" % (n, len(filenames)), file=sys.stderr)
198  this_rankingstat, this_rankingstatpdf = far.parse_likelihood_control_doc(far.ligolw_utils.load_filename(filename, verbose = verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
199  if this_rankingstat is not None:
200  template_ids = this_rankingstat.template_ids
201  if template_ids in rankingstats:
202  rankingstats[template_ids] += this_rankingstat
203  else:
204  rankingstats[template_ids] = this_rankingstat
205  if this_rankingstatpdf is not None:
206  if rankingstatpdf is None:
207  rankingstatpdf = this_rankingstatpdf
208  else:
209  rankingstatpdf += this_rankingstatpdf
210  progress = ProgressBar(text = "Density estimation", max = len(rankingstats)) if verbose and rankingstats else None
211  for rankingstat in rankingstats.values():
212  if progress is not None:
213  progress.increment()
214  if options.add_zerolag_to_background:
215  rankingstat.denominator.lnzerolagdensity = rankingstat.zerolag
216  rankingstat.finish()
217  del progress
218  # the segment is only used to construct T050017-style filenames, so
219  # just fake one if there's no livetime information
220  seg = (0, 0)
221  if rankingstatpdf is not None:
222  seg = rankingstatpdf.segments.extent()
223  elif rankingstats:
224  rankingstat = list(rankingstats.values())[0]
225  try:
226  seg = rankingstat.segmentlists.extent_all()
227  except ValueError:
228  pass
229  return rankingstats, rankingstatpdf, seg
230 
231 
232 def load_search_results(filenames, tmp_path = None, verbose = False):
233  timeslide_ln_lr = []
234  zerolag_ln_lr = []
235  timeslide_sngls = []
236  zerolag_sngls = []
237 
238  for n, filename in enumerate(filenames, 1):
239  if verbose:
240  print("%d/%d: %s" % (n, len(filenames), filename), file=sys.stderr)
241  with dbtables.workingcopy(filename, tmp_path = tmp_path, discard = True, verbose = verbose) as working_filename:
242  connection = sqlite3.connect(str(working_filename))
243 
244  xmldoc = dbtables.get_xml(connection)
245  definer_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
246 
247  cursor = connection.cursor()
248 
249  # subclass to allow it to carry extra attributes
250  class snglsdict(dict):
251  __slots__ = ("ln_likelihood_ratio", "fap")
252 
253  for coinc_event_id, rows in itertools.groupby(cursor.execute("""
254 SELECT
255  coinc_event_map.coinc_event_id,
256  coinc_event.likelihood,
257  coinc_inspiral.false_alarm_rate,
258  EXISTS (
259  SELECT
260  *
261  FROM
262  time_slide
263  WHERE
264  time_slide.time_slide_id == coinc_event.time_slide_id
265  AND time_slide.offset != 0
266  ),
267  sngl_inspiral.ifo,
268  sngl_inspiral.snr,
269  sngl_inspiral.chisq
270 FROM
271  sngl_inspiral
272  JOIN coinc_event_map ON (
273  coinc_event_map.table_name == 'sngl_inspiral'
274  AND coinc_event_map.event_id == sngl_inspiral.event_id
275  )
276  JOIN coinc_event ON (
277  coinc_event.coinc_event_id == coinc_event_map.coinc_event_id
278  )
279  JOIN coinc_inspiral ON (
280  coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
281  )
282 WHERE
283  coinc_event.coinc_def_id == ?
284 ORDER BY
285  coinc_event_map.coinc_event_id
286  """, (definer_id,)), lambda row: row[0]):
287  rows = list(rows)
288  is_timeslide = rows[0][3]
289  # {instrument: (snr, chisq)} dictionary
290  sngls = snglsdict((row[4], (row[5], row[6])) for row in rows)
291  sngls.ln_likelihood_ratio = rows[0][1]
292  sngls.fap = rows[0][2]
293  if is_timeslide:
294  timeslide_sngls.append(sngls)
295  else:
296  zerolag_sngls.append(sngls)
297 
298  cursor.close()
299  connection.close()
300 
301  timeslide_ln_lr = sorted((sngls.ln_likelihood_ratio, sngls.fap) for sngls in timeslide_sngls)
302  zerolag_ln_lr = sorted((sngls.ln_likelihood_ratio, sngls.fap) for sngls in zerolag_sngls)
303 
304  return timeslide_ln_lr, zerolag_ln_lr, timeslide_sngls, zerolag_sngls
305 
306 
307 #
308 # =============================================================================
309 #
310 # Main
311 #
312 # =============================================================================
313 #
314 
315 
316 #
317 # command line
318 #
319 
320 
321 options, filenames = parse_command_line()
322 
323 
324 #
325 # load input
326 #
327 
328 
329 rankingstats, rankingstatpdf, seg = load_distributions(filenames, verbose = options.verbose)
330 
331 
332 if options.database:
333  timeslide_ln_lr, zerolag_ln_lr, timeslide_sngls, zerolag_sngls = load_search_results(options.database, tmp_path = options.tmp_space, verbose = options.verbose)
334  if options.scatter_log_lambdas is not None:
335  sngls = [sngl for sngl in timeslide_sngls + zerolag_sngls if sngl.ln_likelihood_ratio in options.scatter_log_lambdas]
336  else:
337  sngls = None
338 else:
339  timeslide_ln_lr, zerolag_ln_lr, sngls = None, None, None
340 
341 
342 #
343 # plots
344 #
345 
346 
347 for bin_index, rankingstat in enumerate(sorted(rankingstats.values(), key = lambda rankingstat: sorted(rankingstat.template_ids))):
348  # SNR and \chi^2
349  for instrument in rankingstat.instruments:
350  for snr_chi_type in ("background_pdf", "injection_pdf", "zero_lag_pdf", "LR"):
351  if instrument in options.event_snr_dict.keys():
352  fig = plotfar.plot_snr_chi_pdf(rankingstat, instrument, snr_chi_type, options.max_snr, sngls = sngls, event_snr = options.event_snr_dict[instrument], event_chisq = options.event_chisq_dict[instrument])
353  else:
354  fig = plotfar.plot_snr_chi_pdf(rankingstat, instrument, snr_chi_type, options.max_snr, sngls = sngls)
355  if fig is None:
356  continue
357  plotname = dagparts.T050017_filename(instrument, "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%04d_%s_SNRCHI2" % (options.user_tag, bin_index, snr_chi_type.upper()), seg, options.output_format, path = options.output_dir)
358  if options.verbose:
359  print("writing %s" % plotname, file=sys.stderr)
360  fig.savefig(plotname)
361 
362  # candidate rates
363  fig = plotfar.plot_rates(rankingstat)
364  plotname = dagparts.T050017_filename("H1L1V1", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%04d_RATES" % (options.user_tag, bin_index), seg, options.output_format, path = options.output_dir)
365  if options.verbose:
366  print("writing %s" % plotname, file=sys.stderr)
367  fig.savefig(plotname)
368 
369 
370 # SNR PDFs
371 if options.plot_snr_snr_pdfs:
372  # assume PDFs are identical for all template bank bins, and pick
373  # one set to plot
374  rankingstat = list(rankingstats.values())[0]
375  for (instruments, horizon_distances) in sorted(rankingstat.numerator.SNRPDF.snr_joint_pdf_cache.keys(), key = lambda x: sorted(x[1])):
376  # they're stored as a frozen set of quantized key/value
377  # pairs, need to unquantize them and get a dictionary back
378  horizon_distances = rankingstat.numerator.SNRPDF.quantized_horizon_distances(horizon_distances)
379  fig = plotfar.plot_snr_joint_pdf(rankingstat.numerator.SNRPDF, instruments, horizon_distances, rankingstat.min_instruments, options.max_snr, sngls = sngls)
380  if fig is not None:
381  plotname = dagparts.T050017_filename(instruments, "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_SNR_PDF_%s" % (options.user_tag, "_".join(["%s_%s" % (k, horizon_distances[k]) for k in sorted(horizon_distances)]) ), seg, options.output_format, path = options.output_dir)
382  if options.verbose:
383  print("writing %s" % plotname, file=sys.stderr)
384  fig.savefig(plotname)
385 
386 
387 # ranking statistic PDFs and CCDFs
388 if rankingstatpdf is not None:
389  for Title, which, NAME in (("Noise", "noise", "NOISE"), ("Signal", "signal", "SIGNAL")):
390  fig = plotfar.plot_likelihood_ratio_pdf(rankingstatpdf, (options.min_log_lambda, options.max_log_lambda), Title, which = which)
391  plotname = dagparts.T050017_filename("COMBINED", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%s_LIKELIHOOD_RATIO_PDF" % (options.user_tag, NAME), seg, options.output_format, path = options.output_dir)
392  if options.verbose:
393  print("writing %s" % plotname, file=sys.stderr)
394  fig.savefig(plotname)
395 
396 if rankingstatpdf is not None and rankingstatpdf.zero_lag_lr_lnpdf.array.any():
397  fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
398  if zerolag_ln_lr is not None:
399  xhi = max(zerolag_ln_lr + timeslide_ln_lr)[0]
400  xhi = 5. * math.ceil(xhi / 5.)
401  xhi = max(xhi, options.max_log_lambda)
402  else:
403  xhi = options.max_log_lambda
404  fig = plotfar.plot_likelihood_ratio_ccdf(fapfar, (options.min_log_lambda, xhi), observed_ln_likelihood_ratios = zerolag_ln_lr, is_open_box = True)
405  plotname = dagparts.T050017_filename("COMBINED", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_NOISE_LIKELIHOOD_RATIO_CCDF_openbox" % options.user_tag, seg, options.output_format, path = options.output_dir)
406  if options.verbose:
407  print("writing %s" % plotname, file=sys.stderr)
408  fig.savefig(plotname)
409 
410  fig = plotfar.plot_likelihood_ratio_ccdf(fapfar, (options.min_log_lambda, xhi), observed_ln_likelihood_ratios = timeslide_ln_lr, is_open_box = False)
411  plotname = dagparts.T050017_filename("COMBINED", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_NOISE_LIKELIHOOD_RATIO_CCDF_closedbox" % options.user_tag, seg, options.output_format, path = options.output_dir)
412  if options.verbose:
413  print("writing %s" % plotname, file=sys.stderr)
414  fig.savefig(plotname)