3 # Copyright (C) 2012 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
38 os.environ[
"MPLCONFIGDIR"] =
"/tmp"
41 from glue.ligolw
import lsctables
42 from glue.ligolw
import utils as ligolw_utils
43 from ligo.gracedb
import rest as gracedb
44 from lalinspiral.thinca
import InspiralCoincDef
47 from gstlal
import far
48 from gstlal
import lvalert_helper
49 from gstlal.plots
import far as plotfar
52 matplotlib.rcParams.update({
54 "axes.titlesize": 10.0,
55 "axes.labelsize": 10.0,
56 "xtick.labelsize": 8.0,
57 "ytick.labelsize": 8.0,
58 "legend.fontsize": 8.0,
66 # =============================================================================
70 # =============================================================================
74 def parse_command_line():
75 parser = OptionParser(
76 usage =
"%prog [options] [graceID ...]",
77 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."
79 parser.add_option("--gracedb-service-url", metavar = "URL", default="%s" % gracedb.DEFAULT_SERVICE_URL, help = "GraceDb service url to upload to (default: %s)" % gracedb.DEFAULT_SERVICE_URL)
80 parser.add_option("--max-snr", metavar = "SNR", type = "
float", default = 200., help = "Set the upper bound of the SNR ranges in plots (default = 200).")
81 parser.add_option("--output-path", metavar = "PATH", help = "Write local copies of the plots to this directory (default = don't).")
82 parser.add_option("--no-upload", action = "store_true", help = "Disable upload of plots to gracedb, e.g., for testing new plots.")
83 parser.add_option("--verbose", action = "store_true", help = "Be verbose.")
85 options, gid_list = parser.parse_args()
88 # FIXME: lvalert_listen doesn't allow command-line
89 # options, enable logging for online analysis
90 options.verbose = True
92 # can only call basicConfig once (otherwise need to switch to more
93 # complex logging configuration)
95 logging.basicConfig(format =
"%(asctime)s:%(message)s", level = logging.INFO)
97 logging.basicConfig(format =
"%(asctime)s:%(message)s")
99 if options.no_upload and options.output_path is None:
100 raise ValueError(
"--no-upload without setting --ouput-path disables all output")
102 return options, gid_list
106 # =============================================================================
110 # =============================================================================
114 def get_files(gracedb_client, graceid, ranking_data_filename =
"ranking_data.xml.gz"):
115 coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, graceid)
117 response = lvalert_helper.get_filename(gracedb_client, graceid, filename = ranking_data_filename)
118 ranking_data_xmldoc = ligolw_utils.load_fileobj(response, contenthandler = far.RankingStat.LIGOLWContentHandler)[0]
120 rankingstat, rankingstatpdf = far.parse_likelihood_control_doc(ranking_data_xmldoc)
121 if rankingstat is None:
122 raise ValueError(
"failed to extract CoincParams object from '%s'" % ranking_data_filename)
123 # RankingStat objects are never written to disk .finish()ed
126 # RankingStatPDF objects are never written to disk extincted
127 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
129 return coinc_xmldoc, rankingstat, rankingstatpdf, fapfar
132 def plot_snrchisq(instrument, rankingstat, plot_type, max_snr, snrchisq = None):
133 snr, chisq = snrchisq if snrchisq is not None else (None, None)
134 return plotfar.plot_snr_chi_pdf(rankingstat, instrument, plot_type, max_snr, event_snr = snr, event_chisq = chisq)
138 # =============================================================================
142 # =============================================================================
151 options, gid_list = parse_command_line()
155 lvalert_data = json.loads(sys.stdin.read())
156 logging.info(
"%(alert_type)s-type alert for event %(uid)s" % lvalert_data)
157 logging.info(
"lvalert data: %s" % repr(lvalert_data))
158 if
"filename" in lvalert_data[
"data"]:
159 filename = os.path.split(urlparse.urlparse(lvalert_data[
"data"][
"filename"]).path)[-1]
160 if filename not in (u
"ranking_data.xml.gz",):
161 logging.info(
"filename is not 'ranking_data.xml.gz'. skipping")
163 gid_list = [str(lvalert_data[
"uid"])]
165 logging.info(
"json key filename not in lvalert data, skipping")
169 # connect to gracedb, loop over IDs
173 gracedb_client = gracedb.GraceDb(options.gracedb_service_url)
178 # download candidate
's data
182 coinc_xmldoc, rankingstat, rankingstatpdf, fapfar = get_files(gracedb_client, gid)
183 coinc_event_table = lsctables.CoincTable.get_table(coinc_xmldoc)
184 coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(coinc_xmldoc)
186 coinc_event, = coinc_event_table
187 coinc_inspiral, = coinc_inspiral_table
189 raise ValueError("document does not contain exactly one candidate")
190 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)]:
191 raise ValueError("candidate is not an inspiral<-->inspiral coincidence")
192 offsetvector = lsctables.TimeSlideTable.get_table(coinc_xmldoc).as_dict()[coinc_event.time_slide_id]
193 sngl_inspirals = dict((row.ifo, row) for row in lsctables.SnglInspiralTable.get_table(coinc_xmldoc))
201 for plot_type in ["background_pdf", "injection_pdf", "zero_lag_pdf", "LR"]:
202 for instrument in rankingstat.instruments:
203 if instrument in sngl_inspirals:
204 # place marker on plot
205 fig = plot_snrchisq(instrument, rankingstat, plot_type, options.max_snr, (sngl_inspirals[instrument].snr, sngl_inspirals[instrument].chisq))
207 # no sngl for this instrument
208 fig = plot_snrchisq(instrument, rankingstat, plot_type, options.max_snr)
209 filename = "%s_%s_%s_snrchi.png" % (gid, instrument, plot_type)
210 if not options.no_upload:
211 lvalert_helper.upload_fig(fig, gracedb_client, gid, filename = filename, log_message = "%s SNR, chisq PDF" % instrument, tagname = "background")
212 if options.output_path is not None:
213 filename = os.path.join(options.output_path, filename)
214 logging.info("writing %s ..." % filename)
215 fig.savefig(filename)
218 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,))
219 filename = "%s_likehoodratio_ccdf.png" % gid
220 if not options.no_upload:
221 lvalert_helper.upload_fig(fig, gracedb_client, gid, filename = filename, log_message = "Likelihood Ratio CCDF", tagname = "background")
222 if options.output_path is not None:
223 filename = os.path.join(options.output_path, filename)
224 logging.info("writing %s ..." % filename)
225 fig.savefig(filename)
228 fig = plotfar.plot_horizon_distance_vs_time(rankingstat, (coinc_inspiral.end - 14400., coinc_inspiral.end), tref = coinc_inspiral.end)
229 filename = "%s_horizon_distances.png" % gid
230 if not options.no_upload:
231 lvalert_helper.upload_fig(fig, gracedb_client, gid, filename = filename, log_message = "Horizon Distances", tagname = "psd")
232 if options.output_path is not None:
233 filename = os.path.join(options.output_path, filename)
234 logging.info("writing %s ..." % filename)
235 fig.savefig(filename)
238 fig = plotfar.plot_rates(rankingstat)
239 filename = "%s_rates.png" % gid
240 if not options.no_upload:
241 lvalert_helper.upload_fig(fig, gracedb_client, gid, filename = filename, log_message = "Instrument combo rates", tagname = "background")
242 if options.output_path is not None:
243 filename = os.path.join(options.output_path, filename)
244 logging.info("writing %s ..." % filename)
245 fig.savefig(filename)