gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_lvalert_uberplotter
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2019 Alexander Pace, 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 request some followup data from a running gstlal_inspiral job based on gracedb submissions notified by lvalert
20 
21 
22 #
23 # =============================================================================
24 #
25 # Preamble
26 #
27 # =============================================================================
28 #
29 
30 
31 import json
32 import urllib.parse as urlparse
33 import logging
34 from optparse import OptionParser
35 import os
36 import sys
37 import time
38 
39 # Error catching:
40 import traceback
41 
42 os.environ["MPLCONFIGDIR"] = "/tmp"
43 
44 # Add new LVALert API:
45 from ligo.lvalert import LVAlertClient
46 from ligo.lvalert import DEFAULT_SERVER as DEFAULT_LVALERT_URL
47 
48 from glue.ligolw import lsctables
49 from glue.ligolw import utils as ligolw_utils
50 
51 #from ligo.gracedb import rest as gracedb
52 from ligo.gracedb.rest import GraceDb
53 from ligo.gracedb.rest import DEFAULT_SERVICE_URL as DEFAULT_GRACEDB_URL
54 from lalinspiral.thinca import InspiralCoincDef
55 
56 from lal import series
57 
58 from gstlal import far
59 from gstlal import lvalert_helper
60 from gstlal.plots import far as plotfar
61 from gstlal.plots import psd as plotpsd
62 
63 import matplotlib
64 matplotlib.rcParams.update({
65  "font.size": 10.0,
66  "axes.titlesize": 10.0,
67  "axes.labelsize": 10.0,
68  "xtick.labelsize": 8.0,
69  "ytick.labelsize": 8.0,
70  "legend.fontsize": 8.0,
71  "figure.dpi": 100,
72  "savefig.dpi": 100,
73  "text.usetex": True
74 })
75 
76 
77 #
78 # =============================================================================
79 #
80 # Command Line
81 #
82 # =============================================================================
83 #
84 
85 
86 def parse_command_line():
87  parser = OptionParser(
88  usage = "%prog [options] [graceID ...]",
89  description = "%prog generates a suite of plots displaying the data used to assess the significance of a candidate event in gracedb. This program can be run manually with one more more gracedb IDs provided on the command line. If no gracedb IDs are given on the command line, the tool assumes it is being run as an lvalert_listen client, and retrieves the candidate ID to process from a json blob ingested from stdin."
90  )
91  parser.add_option("--gracedb-service-url", metavar = "URL", default="%s" % DEFAULT_GRACEDB_URL, help = "GraceDb service url to upload to (default: %s)" % DEFAULT_GRACEDB_URL)
92  parser.add_option("--lvalert-server-url", metavar = "LVURL", default=DEFAULT_LVALERT_URL, help = "LVAlert Sever to listen to (default: %s)" % DEFAULT_LVALERT_URL)
93  parser.add_option("--search", metavar = "gdbsearch", default="allsky", help = "Search specification of GraceDB uploads (default: %s)" % "allsky")
94  parser.add_option("--max-snr", metavar = "SNR", type = "float", default = 200., help = "Set the upper bound of the SNR ranges in plots (default = 200).")
95  parser.add_option("--format", default = "png", help = "Set file format by selecting the extention (default = \"png\").")
96  parser.add_option("--output-path", metavar = "PATH", help = "Write local copies of the plots to this directory (default = don't).")
97  parser.add_option("--no-upload", action = "store_true", help = "Disable upload of plots to gracedb, e.g., for testing new plots.")
98  parser.add_option("--skip-404", action = "store_true", help = "Skip events that give 404 (file not found) errors (default is to abort).")
99  parser.add_option("--testenv", action = "store_true", help = "Listen to test nodes")
100  parser.add_option("--verbose", action = "store_true", help = "Be verbose.")
101 
102  options, gid_list = parser.parse_args()
103 
104  if not gid_list:
105  # FIXME: lvalert_listen doesn't allow command-line
106  # options, enable logging for online analysis
107  options.verbose = True
108 
109  # can only call basicConfig once (otherwise need to switch to more
110  # complex logging configuration)
111  if options.verbose:
112  logging.basicConfig(format = "%(asctime)s:%(message)s", level = logging.INFO)
113  else:
114  logging.basicConfig(format = "%(asctime)s:%(message)s")
115 
116  if options.no_upload and options.output_path is None:
117  raise ValueError("--no-upload without setting --ouput-path disables all output")
118 
119  return options, gid_list
120 
121 
122 #
123 # =============================================================================
124 #
125 # Local Library
126 #
127 # =============================================================================
128 #
129 
130 
131 def get_files(gracedb_client, graceid, ranking_data_filename = "ranking_data.xml.gz"):
132  coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, graceid)
133 
134  response = lvalert_helper.get_filename(gracedb_client, graceid, filename = ranking_data_filename)
135  ranking_data_xmldoc = ligolw_utils.load_fileobj(response, contenthandler = far.RankingStat.LIGOLWContentHandler)[0]
136 
137  rankingstat, rankingstatpdf = far.parse_likelihood_control_doc(ranking_data_xmldoc)
138  if rankingstat is None:
139  raise ValueError("failed to extract CoincParams object from '%s'" % ranking_data_filename)
140  # RankingStat objects are never written to disk .finish()ed
141  rankingstat.finish()
142 
143  # RankingStatPDF objects are never written to disk extincted
144  fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
145 
146  return coinc_xmldoc, rankingstat, rankingstatpdf, fapfar
147 
148 
149 
150 def get_psds(gracedb_client, graceid, filename = "psd.xml.gz", ignore_404 = False):
151  response = lvalert_helper.get_filename(gracedb_client, graceid, filename = filename, ignore_404 = ignore_404)
152  if response is None:
153  logging.info("No response retrieving psd.xml.gz")
154  return series.read_psd_xmldoc(ligolw_utils.load_fileobj(response, contenthandler = series.PSDContentHandler)[0])
155 
156 
157 def plot_snrchisq(instrument, rankingstat, plot_type, max_snr, snrchisq = None):
158  snr, chisq = snrchisq if snrchisq is not None else (None, None)
159  return plotfar.plot_snr_chi_pdf(rankingstat, instrument, plot_type, max_snr, event_snr = snr, event_chisq = chisq)
160 
161 
162 #
163 # =============================================================================
164 #
165 # Main
166 #
167 # =============================================================================
168 #
169 
170 
171 def main(client=None):
172  #
173  # Read in options from the command line:
174  #
175 
176  options, gid_list = parse_command_line()
177  logging.info ("read command line options")
178 
179  #
180  # Initiate the LVALert Client, and subscribe to relevant nodes
181  # I'm hardcoding this to cbc_gstlal_allsky for now.
182  #
183 
184  client = LVAlertClient(server=options.lvalert_server_url)
185 
186  #
187  # Connect to gracedb:
188  #
189 
190  gracedb_client = GraceDb(options.gracedb_service_url)
191 
192  if options.testenv:
193  lvnodes = ['test_gstlal_' + options.search]
194  else:
195  lvnodes = ['cbc_gstlal_' + options.search]
196  #
197  # start LVAlert listener loop:
198  #
199  try:
200  logging.info("connecting to %s" % options.lvalert_server_url)
201  if client.connect():
202  logging.info("connected to %s" % options.lvalert_server_url)
203  else:
204  logging.info("could not connect to %s, exiting" % options.lvalert_server_url)
205  exit()
206 
207  plotter = uber_plotter(gracedb_client, options)
208  client.process(block=False)
209 
210  # Subscribe to lvnodes:
211  for n in lvnodes:
212  try:
213  client.subscribe(n)
214  logging.info("subscribed to node %s" % n)
215  except:
216  logging.info("Could not subscribe to node %s" % n)
217  logging.info("Listening for lvalerts.")
218  client.listen(plotter.process_alert)
219  while True: time.sleep(5)
220 
221  except (KeyboardInterrupt, SystemExit):
222  logging.info("exit signal received, disconnecting from lvalert")
223  client.abort()
224 
225 #
226 # the uber plotter class that responds to alerts:
227 #
228 
229 
230 class uber_plotter(object):
231  # initiate:
232  def __init__(self, gracedb_client, options):
233  self.opts = options
234  self.gracedb = gracedb_client
235  logging.info("uber_plotter class initiated")
236 
237  # respond to an alert:
238  def process_alert(self, node=None, payload=None):
239  lvalert_data = json.loads(payload)
240  logging.info("Recieved LVAlert from node %s" % node)
241  logging.info("Alert Contents: %s" % lvalert_data)
242 
243  gid = None
244 
245  # check for the right filenames:
246  if "filename" in lvalert_data["data"]:
247  filename = os.path.split(urlparse.urlparse(lvalert_data["data"]["filename"]).path)[-1]
248  gid = str(lvalert_data["uid"])
249  if filename in (u"ranking_data.xml.gz",):
250  logging.info("ranking_data.xml.gz available for %s" % gid)
251  logging.info("generating ranking plots for %s" % gid)
252  try:
253  self.generate_ranking_plots(gid)
254  except Exception as err:
255  logging.info(traceback.print_exc())
256  elif filename in (u"psd.xml.gz",):
257  logging.info("psd.xml.gz available for %s" % gid)
258  logging.info("generating psd plots for %s" % gid)
259  try:
260  self.generate_psd_plots(gid)
261  except Exception as err:
262  logging.info(traceback.print_exc())
263  else:
264  logging.info("filename is not 'ranking_data.xml.gz' or 'psd.xml.gz'. skipping")
265  else:
266  logging.info("json key filename not in lvalert data, skipping")
267 
268 
269  # #
270  #---- Generate plots from ranking stat file ----#
271  # #
272 
273  def generate_ranking_plots(self, gid=None):
274  #
275  # download candidate's data
276  #
277  coinc_xmldoc, rankingstat, rankingstatpdf, fapfar = get_files(gracedb_client=self.gracedb, graceid=gid)
278  coinc_event_table = lsctables.CoincTable.get_table(coinc_xmldoc)
279  coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(coinc_xmldoc)
280  try:
281  coinc_event, = coinc_event_table
282  coinc_inspiral, = coinc_inspiral_table
283  except ValueError:
284  raise ValueError("document does not contain exactly one candidate")
285  if [(row.search, row.search_coinc_type) for row in lsctables.CoincDefTable.get_table(coinc_xmldoc) if row.coinc_def_id == coinc_event.coinc_def_id] != [(InspiralCoincDef.search, InspiralCoincDef.search_coinc_type)]:
286  raise ValueError("candidate is not an inspiral<-->inspiral coincidence")
287  offsetvector = lsctables.TimeSlideTable.get_table(coinc_xmldoc).as_dict()[coinc_event.time_slide_id]
288  sngl_inspirals = dict((row.ifo, row) for row in lsctables.SnglInspiralTable.get_table(coinc_xmldoc))
289 
290 
291 
292  for plot_type in ["background_pdf", "injection_pdf", "zero_lag_pdf", "LR"]:
293  for instrument in rankingstat.instruments:
294  if instrument in sngl_inspirals:
295  # place marker on plot
296  fig = plot_snrchisq(instrument, rankingstat, plot_type, self.opts.max_snr, (sngl_inspirals[instrument].snr, sngl_inspirals[instrument].chisq))
297  else:
298  # no sngl for this instrument
299  fig = plot_snrchisq(instrument, rankingstat, plot_type, self.opts.max_snr)
300  filename = "%s_%s_%s_snrchi.png" % (gid, instrument, plot_type)
301  if not self.opts.no_upload:
302  lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message = "%s SNR, chisq PDF" % instrument, tagname = "background")
303  if self.opts.output_path is not None:
304  filename = os.path.join(self.opts.output_path, filename)
305  logging.info("writing %s ..." % filename)
306  fig.savefig(filename)
307 
308 
309  fig = plotfar.plot_likelihood_ratio_ccdf(fapfar, (0., max(40., coinc_event.likelihood - coinc_event.likelihood % 5. + 5.)), ln_likelihood_ratio_markers = (coinc_event.likelihood,))
310  filename = "%s_likehoodratio_ccdf.png" % gid
311  if not self.opts.no_upload:
312  lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message = "Likelihood Ratio CCDF", tagname = "background")
313  if self.opts.output_path is not None:
314  filename = os.path.join(self.opts.output_path, filename)
315  logging.info("writing %s ..." % filename)
316  fig.savefig(filename)
317 
318 
319  fig = plotfar.plot_horizon_distance_vs_time(rankingstat, (coinc_inspiral.end - 14400., coinc_inspiral.end), tref = coinc_inspiral.end)
320  filename = "%s_horizon_distances.png" % gid
321  if not self.opts.no_upload:
322  lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message = "Horizon Distances", tagname = "psd")
323  if self.opts.output_path is not None:
324  filename = os.path.join(self.opts.output_path, filename)
325  logging.info("writing %s ..." % filename)
326  fig.savefig(filename)
327 
328 
329  fig = plotfar.plot_rates(rankingstat)
330  filename = "%s_rates.png" % gid
331  if not self.opts.no_upload:
332  lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message = "Instrument combo rates", tagname = "background")
333  if self.opts.output_path is not None:
334  filename = os.path.join(self.opts.output_path, filename)
335  logging.info("writing %s ..." % filename)
336  fig.savefig(filename)
337 
338 
339  # #
340  #-------- Generate plots from psd file --------#
341  # #
342 
343  def generate_psd_plots(self, gid=None):
344  psds = get_psds(gracedb_client=self.gracedb,
345  graceid=gid, ignore_404 = self.opts.skip_404)
346  if psds is None:
347  logging.info("Could not get_psds, exiting loop")
348  return
349 
350  coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(self.gracedb, gid)
351 
352  #
353  # PSD plot
354  #
355 
356  fig = plotpsd.plot_psds(psds, coinc_xmldoc, plot_width = 800)
357  fig.tight_layout()
358 
359  filename = "%s_psd.%s" % (gid, self.opts.format)
360  if self.opts.no_upload:
361  logging.info("writing %s ..." % filename)
362  fig.savefig(filename)
363  else:
364  lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message = "strain spectral density plot", tagname = "psd")
365 
366  #
367  # Cumulative SNRs plot
368  #
369 
370  fig = plotpsd.plot_cumulative_snrs(psds, coinc_xmldoc, plot_width = 800)
371  fig.tight_layout()
372 
373  filename = "%s_cumulative_snrs.%s" % (gid, self.opts.format)
374  if self.opts.no_upload:
375  logging.info("writing %s ..." % filename)
376  fig.savefig(filename)
377  else:
378  lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message = "cumulative SNRs plot", tagname = "psd")
379 
380  logging.info("finished processing psd plot for %s" % gid)
381 
382 
383 
384 
385 if __name__ == '__main__':
386  main(client=None)
387