3 # Copyright (C) 2019 Alexander Pace, Kipp Cannon, Chad Hanna, Drew Keppel
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.
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.
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.
19 ### A program to request some followup data from a running gstlal_inspiral job based on gracedb submissions notified by lvalert
23 # =============================================================================
27 # =============================================================================
32 import urllib.parse as urlparse
34 from optparse
import OptionParser
42 os.environ[
"MPLCONFIGDIR"] =
"/tmp"
44 # Add new LVALert API:
45 from ligo.lvalert
import LVAlertClient
46 from ligo.lvalert
import DEFAULT_SERVER as DEFAULT_LVALERT_URL
48 from glue.ligolw
import lsctables
49 from glue.ligolw
import utils as ligolw_utils
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
56 from lal
import series
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
64 matplotlib.rcParams.update({
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,
78 # =============================================================================
82 # =============================================================================
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."
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.")
102 options, gid_list = parser.parse_args()
105 # FIXME: lvalert_listen doesn't allow command-line
106 # options, enable logging for online analysis
107 options.verbose = True
109 # can only call basicConfig once (otherwise need to switch to more
110 # complex logging configuration)
112 logging.basicConfig(format =
"%(asctime)s:%(message)s", level = logging.INFO)
114 logging.basicConfig(format =
"%(asctime)s:%(message)s")
116 if options.no_upload and options.output_path is None:
117 raise ValueError(
"--no-upload without setting --ouput-path disables all output")
119 return options, gid_list
123 # =============================================================================
127 # =============================================================================
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)
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]
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
143 # RankingStatPDF objects are never written to disk extincted
144 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
146 return coinc_xmldoc, rankingstat, rankingstatpdf, fapfar
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)
153 logging.info(
"No response retrieving psd.xml.gz")
154 return series.read_psd_xmldoc(ligolw_utils.load_fileobj(response, contenthandler = series.PSDContentHandler)[0])
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)
163 # =============================================================================
167 # =============================================================================
171 def main(client=None):
173 # Read in options from the command line:
176 options, gid_list = parse_command_line()
177 logging.info (
"read command line options")
180 # Initiate the LVALert Client, and subscribe to relevant nodes
181 # I
'm hardcoding this to cbc_gstlal_allsky for now.
184 client = LVAlertClient(server=options.lvalert_server_url)
187 # Connect to gracedb:
190 gracedb_client = GraceDb(options.gracedb_service_url)
193 lvnodes = ['test_gstlal_
' + options.search]
195 lvnodes = ['cbc_gstlal_
' + options.search]
197 # start LVAlert listener loop:
200 logging.info("connecting to %s" % options.lvalert_server_url)
202 logging.info("connected to %s" % options.lvalert_server_url)
204 logging.info("could not connect to %s, exiting" % options.lvalert_server_url)
207 plotter = uber_plotter(gracedb_client, options)
208 client.process(block=False)
210 # Subscribe to lvnodes:
214 logging.info("subscribed to node %s" % n)
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)
221 except (KeyboardInterrupt, SystemExit):
222 logging.info("exit signal received, disconnecting from lvalert")
226 # the uber plotter class that responds to alerts:
230 class uber_plotter(object):
232 def __init__(self, gracedb_client, options):
234 self.gracedb = gracedb_client
235 logging.info("uber_plotter class initiated")
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)
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)
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)
260 self.generate_psd_plots(gid)
261 except Exception as err:
262 logging.info(traceback.print_exc())
264 logging.info("filename is not 'ranking_data.xml.gz
' or 'psd.xml.gz
'. skipping")
266 logging.info("json key filename not in lvalert data, skipping")
270 #---- Generate plots from ranking stat file ----#
273 def generate_ranking_plots(self, gid=None):
275 # download candidate's data
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)
281 coinc_event, = coinc_event_table
282 coinc_inspiral, = coinc_inspiral_table
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))
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))
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)
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)
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)
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)
340 #-------- Generate plots from psd file --------#
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)
347 logging.info(
"Could not get_psds, exiting loop")
350 coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(self.gracedb, gid)
356 fig = plotpsd.plot_psds(psds, coinc_xmldoc, plot_width = 800)
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)
364 lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message =
"strain spectral density plot", tagname =
"psd")
367 # Cumulative SNRs plot
370 fig = plotpsd.plot_cumulative_snrs(psds, coinc_xmldoc, plot_width = 800)
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)
378 lvalert_helper.upload_fig(fig, self.gracedb, gid, filename = filename, log_message =
"cumulative SNRs plot", tagname =
"psd")
380 logging.info(
"finished processing psd plot for %s" % gid)
385 if __name__ ==
'__main__':