3 # Copyright (C) 2019 Alexander Pace, Kipp Cannon, Chad Hanna, Drew Keppel
4 # Copyright (C) 2020 Patrick Godwin, Cody Messick
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the
8 # Free Software Foundation; either version 2 of the License, or (at your
9 # option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 # Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 __usage__ =
'gstlal_ll_inspiral_event_plotter [--options]'
21 __description__ =
'an executable to upload auxiliary files and plots for GraceDB events from gstlal_inspiral jobs'
23 #-------------------------------------------------
25 #-------------------------------------------------
27 from collections
import deque, OrderedDict
29 from itertools
import chain
33 from optparse
import OptionParser
40 from ligo.segments
import segment
41 from ligo.gracedb.rest
import GraceDb, HTTPError
42 from ligo.gracedb.rest
import DEFAULT_SERVICE_URL as DEFAULT_GRACEDB_URL
43 from ligo.scald
import utils
45 from lal
import LIGOTimeGPS
46 from lal
import series
48 from gstlal
import events
49 from gstlal
import far
50 from gstlal
import inspiral
51 from gstlal
import lvalert_helper
52 from gstlal.plots
import far as plotfar
53 from gstlal.plots
import psd as plotpsd
55 from ligo.lw
import utils as ligolw_utils
56 from ligo.lw
import lsctables
57 from ligo.lw
import array as ligolw_array
58 from ligo.lw
import param as ligolw_param
59 from ligo.lw
import ligolw
62 matplotlib.rcParams.update({
64 'axes.titlesize': 10.0,
65 'axes.labelsize': 10.0,
66 'xtick.labelsize': 8.0,
67 'ytick.labelsize': 8.0,
68 'legend.fontsize': 8.0,
73 from matplotlib
import figure
74 from matplotlib.backends.backend_agg
import FigureCanvasAgg as FigureCanvas
76 #-------------------------------------------------
78 #-------------------------------------------------
82 class ligolwcontenthandler(ligolw.LIGOLWContentHandler):
85 #-------------------------------------------------
87 #-------------------------------------------------
89 def parse_command_line():
91 parser = OptionParser(usage=__usage__, description=__description__)
92 parser.add_option(
'-v',
'--verbose', default=False, action=
'store_true', help =
'Be verbose.')
93 parser.add_option(
'--tag', metavar =
'string', default =
'test', help =
'Sets the name of the tag used. Default = \'test\'')
94 parser.add_option(
'--max-event-time', type =
'int', default = 7200, help =
'Maximum time to keep around an event. Default = 2 hours.')
95 parser.add_option(
'--processing-cadence', type =
'float', default = 0.1, help =
'Rate at which the event plotter acquires and processes data. Default = 0.1 seconds.')
96 parser.add_option(
'--request-timeout', type =
'float', default = 0.2, help =
'Timeout for requesting messages from a topic. Default = 0.2 seconds.')
97 parser.add_option(
'--kafka-server', metavar =
'string', help =
'Sets the server url that the kafka topic is hosted on. Required.')
98 parser.add_option(
'--gracedb-group', metavar =
'name', default =
'Test', help =
'Gracedb group to which to upload events (default is Test).')
99 parser.add_option(
'--gracedb-pipeline', metavar =
'name', default =
'gstlal', help =
'Name of pipeline to provide in GracedB uploads (default is gstlal).')
100 parser.add_option(
'--gracedb-search', metavar =
'name', default =
'LowMass', help =
'Name of search to provide in GracedB uploads (default is LowMass).')
101 parser.add_option(
'--gracedb-service-url', metavar =
'url', default = DEFAULT_GRACEDB_URL, help =
'Override default GracedB service url (optional, default is {}).'.format(DEFAULT_GRACEDB_URL))
102 parser.add_option(
'--max-snr', metavar =
'SNR', type =
'float', default = 200., help =
'Set the upper bound of the SNR ranges in plots (default = 200).')
103 parser.add_option(
'--format', default =
'png', help =
'Set file format by selecting the extention (default = \'png\').')
104 parser.add_option(
'--output-path', metavar =
'PATH', help =
'Write local copies of the plots to this directory (default = don\'t).')
105 parser.add_option(
'--no-upload', action =
'store_true', help =
'Disable upload of plots to gracedb, e.g., for testing new plots.')
107 options, args = parser.parse_args()
109 if options.no_upload and options.output_path is None:
110 raise ValueError(
'--no-upload without setting --ouput-path disables all output')
114 #-------------------------------------------------
116 #-------------------------------------------------
118 class EventPlotter(events.EventProcessor):
120 manages plotting and file uploading for incoming events.
122 _name =
'event_plotter'
124 def __init__(self, options):
125 logging.info(
'setting up event plotter...')
127 self.upload_topic =
'uploads'
128 self.ranking_stat_topic =
'ranking_stat'
129 events.EventProcessor.__init__(
131 process_cadence=options.processing_cadence,
132 request_timeout=options.request_timeout,
133 kafka_server=options.kafka_server,
134 input_topic=[self.upload_topic, self.ranking_stat_topic],
138 ### initialize timing options
139 self.max_event_time = options.max_event_time
143 ### initialize gracedb client
144 if options.gracedb_service_url.startswith(
'file'):
145 self.client = inspiral.FakeGracedbClient(options.gracedb_service_url)
147 self.client = GraceDb(options.gracedb_service_url)
150 self.gracedb_group = options.gracedb_group
151 self.gracedb_pipeline = options.gracedb_pipeline
152 self.gracedb_search = options.gracedb_search
154 ### initialize event storage
155 self.events = OrderedDict()
157 ### initialize plotting options
158 self.max_snr = options.max_snr
159 self.format = options.format
160 self.output_path = options.output_path
161 self.no_upload = options.no_upload
164 def ingest(self, message):
166 parse a message from a kafka topic
168 payload = json.loads(message.value())
170 time = LIGOTimeGPS(payload[
'time'], payload[
'time_ns'])
171 coinc_fileobj = io.StringIO(payload[
'coinc'])
172 xmldoc = ligolw_utils.load_fileobj(coinc_fileobj, contenthandler=ligolwcontenthandler)
173 coinc_fileobj.close()
174 sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
175 bank_bin =
'{:04}'.format(int(sngl_inspiral_table[0].Gamma1))
176 # No guarantee that the coinc event id will be unique between
177 # bins, so use int(time) and the bank bin as an identifier,
178 # which should be unique as only one event / second / bin may
180 event_key =
'{}_{}'.format(payload[
'time'], bank_bin)
182 if event_key not in self.events:
183 logging.info(
'found new event at {} from bin {}'.format(time, bank_bin))
184 self.events[event_key] = self.new_event(time, bank_bin)
187 if message.topic() == self.ranking_stat_topic:
188 self.events[event_key][
'ranking_data_path'] = payload[
'ranking_data_path']
189 # we
'll just take the xmldoc from the preferred event, which will be identical
193 elif message.topic() == self.upload_topic:
194 self.events[event_key]['gid
'] = payload['gid
']
195 self.events[event_key]['coinc
'] = xmldoc
196 psd_fileobj = io.StringIO(payload['psd
'])
197 self.events[event_key]['psd
'] = ligolw_utils.load_fileobj(psd_fileobj, contenthandler=series.PSDContentHandler)
201 def new_event(self, time, bank_bin):
203 returns the structure that defines an event
211 'ranking_data_path
': None,
212 'uploaded
': {'ranking_data
': False, 'ranking_plots
': False, 'psd_plots
': False, 'snr_plots
': False}
218 handle aux data and plot uploading, clearing out
219 old events as necessary.
221 for event in self.events.values():
223 if not event['uploaded
']['ranking_data
'] and event['ranking_data_path
']:
224 self.upload_ranking_data(event)
225 event['uploaded
']['ranking_data
'] = True
226 elif not event['uploaded
']['ranking_plots
'] and event['ranking_data_path
']:
227 self.upload_ranking_plots(event)
228 event['uploaded
']['ranking_plots
'] = True
229 elif not event['uploaded
']['psd_plots
'] and event['psd
']:
230 self.upload_psd_plots(event)
231 event['uploaded
']['psd_plots
'] = True
232 elif not event['uploaded
']['snr_plots
']:
233 self.upload_snr_plots(event)
234 event['uploaded
']['snr_plots
'] = True
236 # clean out old events
237 current_time = utils.gps_now()
238 for event_key, event in self.events.items():
239 uploaded = event['uploaded
']
240 if uploaded['ranking_data
'] and uploaded['ranking_plots
'] and uploaded['psd_plots
'] and uploaded['snr_plots
']:
241 event['coinc
'].unlink()
242 event['psd
'].unlink()
243 self.events.pop(event_key)
244 if current_time - event['time
'] >= self.max_event_time:
245 logging.info('removing stale event from {} and bin {}
'.format(event['time
'], event['bin
']))
246 if event['coinc
'] is not None:
247 logging.info('Did not receive path of ranking data file associated with
event from {} and bin {}
'.format(event['time
'], event['bin
']))
248 event['coinc
'].unlink()
249 event['psd
'].unlink()
250 self.events.pop(event_key)
252 def upload_file(self, message, filename, tag, contents, graceid):
254 upload a file to gracedb
256 logging.info('posting \
'{}\' to gracedb ID {}'.format(filename, graceid))
257 for attempt in range(1,
self.retries + 1):
259 resp =
self.client.writeLog(
263 filecontents = contents,
266 except HTTPError as resp:
267 logging.warning(resp)
269 if resp.status == http.client.CREATED:
272 'gracedb upload of {} for ID {} '
273 'failed on attempt {:d}/{:d}'.format(filename, graceid, attempt,
self.retries)
275 time.sleep(random.lognormal(math.log(
self.retry_delay), .5))
277 logging.warning(
'gracedb upload of {} for ID {} failed'.format(filename, graceid))
280 def upload_ranking_data(
self, event):
281 ranking_fobj = io.StringIO()
282 ligolw_utils.write_fileobj(ligolw_utils.load_filename(event[
'ranking_data_path'], contenthandler = far.RankingStat.LIGOLWContentHandler), ranking_fobj, compress =
"gz")
283 self.upload_file(
'ranking statistic PDFs',
'ranking_data.xml.gz',
'ranking_statistic', ranking_fobj.getvalue(),
event[
'gid'])
286 def upload_ranking_plots(
self, event):
287 ### load all of the information needed to generate plots
288 sngl_inspirals = dict((row.ifo, row) for row in lsctables.SnglInspiralTable.get_table(event[
'coinc']))
289 coinc_event_table = lsctables.CoincTable.get_table(event[
'coinc'])
291 coinc_event, = coinc_event_table
293 raise ValueError(
'document does not contain exactly one candidate')
295 rankingstat, rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_filename(event[
'ranking_data_path'], contenthandler = far.RankingStat.LIGOLWContentHandler))
297 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
300 ### generate and upload plots
301 for plot_type in [
'background_pdf',
'injection_pdf',
'zero_lag_pdf',
'LR']:
302 for instrument in rankingstat.instruments:
303 if instrument in sngl_inspirals:
304 # place marker on plot
305 if sngl_inspirals[instrument].snr >= 4.:
306 snr = sngl_inspirals[instrument].snr
307 chisq = sngl_inspirals[instrument].chisq
311 fig = plotfar.plot_snr_chi_pdf(rankingstat, instrument, plot_type, self.max_snr, event_snr = snr, event_chisq = chisq)
313 # no sngl for this instrument
314 fig = plotfar.plot_snr_chi_pdf(rankingstat, instrument, plot_type, self.max_snr)
315 filename =
'{}_{}_{}_snrchi.{}'.format(event[
'gid'], instrument, plot_type, self.format)
316 if not self.no_upload:
317 lvalert_helper.upload_fig(fig, self.client, event[
'gid'], filename = filename, log_message =
'%s SNR, chisq PDF' % instrument, tagname =
'background')
318 if self.output_path is not None:
319 filename = os.path.join(self.output_path, filename)
320 logging.info(
'writing {} ...'.format(filename))
321 fig.savefig(filename)
323 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,))
324 filename =
'{}_likehoodratio_ccdf.{}'.format(event[
'gid'], self.format)
325 if not self.no_upload:
326 lvalert_helper.upload_fig(fig, self.client, event[
'gid'], filename = filename, log_message =
'Likelihood Ratio CCDF', tagname =
'background')
327 if self.output_path is not None:
328 filename = os.path.join(self.output_path, filename)
329 logging.info(
'writing {} ...'.format(filename))
330 fig.savefig(filename)
333 fig = plotfar.plot_horizon_distance_vs_time(rankingstat, (event[
'time'] - 14400., event[
'time']), tref = event[
'time'])
334 filename =
'{}_horizon_distances.{}'.format(event[
'gid'], self.format)
335 if not self.no_upload:
336 lvalert_helper.upload_fig(fig, self.client, event[
'gid'], filename = filename, log_message =
'Horizon Distances', tagname =
'psd')
337 if self.output_path is not None:
338 filename = os.path.join(self.output_path, filename)
339 logging.info(
'writing {} ...'.format(filename))
340 fig.savefig(filename)
343 fig = plotfar.plot_rates(rankingstat)
344 filename =
'{}_rates.{}'.format(event[
'gid'], self.format)
345 if not self.no_upload:
346 lvalert_helper.upload_fig(fig, self.client, event[
'gid'], filename = filename, log_message =
'Instrument combo rates', tagname =
'background')
347 if self.output_path is not None:
348 filename = os.path.join(self.output_path, filename)
349 logging.info(
'writing {} ...'.format(filename))
350 fig.savefig(filename)
351 logging.info(
'finished processing ranking data plots for {}'.format(event[
'gid']))
354 def upload_psd_plots(self, event):
355 psds = series.read_psd_xmldoc(event[
'psd'])
357 logging.info(
'Could not get_psds, exiting loop')
364 fig = plotpsd.plot_psds(psds, event[
'coinc'], plot_width = 800)
367 filename =
'{}_psd.{}'.format(event[
'gid'], self.format)
369 logging.info(
'writing {} ...'.format(filename))
370 fig.savefig(filename)
372 lvalert_helper.upload_fig(fig, self.client, event[
'gid'], filename = filename, log_message =
'strain spectral density plot', tagname =
'psd')
375 # Cumulative SNRs plot
378 fig = plotpsd.plot_cumulative_snrs(psds, event[
'coinc'], plot_width = 800)
381 filename =
'{}_cumulative_snrs.{}'.format(event[
'gid'], self.format)
383 logging.info(
'writing {} ...'.format(filename))
384 fig.savefig(filename)
386 lvalert_helper.upload_fig(fig, self.client, event[
'gid'], filename = filename, log_message =
'cumulative SNRs plot', tagname =
'psd')
388 logging.info(
'finished processing psd plot for {}'.format(event[
'gid']))
391 def upload_snr_plots(self, event):
392 # create two dicts keyed by event id: the first dict contains
393 # COMPLEX8TimeSeries which contain the snr time series, the second dict
394 # contains the template row
395 timeseries_ligolw_dict = dict((ligolw_param.get_pyvalue(elem, u
'event_id'), series.parse_COMPLEX8TimeSeries(elem)) for elem in event[
'coinc'].getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u
'Name') and elem.Name == u
'COMPLEX8TimeSeries')
396 eventid_trigger_dict = dict((row.event_id, row) for row in lsctables.SnglInspiralTable.get_table(event[
'coinc']))
398 # Parse the bank files
399 # NOTE This assumes --svd-bank will also be provided once in the ProcessParamsTable
400 banks = inspiral.parse_bank_files(inspiral.parse_svdbank_string([row.value for row in lsctables.ProcessParamsTable.get_table(event[
'coinc']) if row.param ==
'--svd-bank'].pop()), verbose=False)
404 # # Find the template (to retrieve the autocorrelation later)
407 for i, bank in enumerate(banks.values()[0]):
408 for j, row in enumerate(bank.sngl_inspiral_table):
409 # The templates should all have the same template_id, so just grab one
410 if row.Gamma0 == eventid_trigger_dict.values()[0].Gamma0:
414 if banknum is not None:
418 raise ValueError(
'The svd banks in the process params table do not contain the template the event was found with')
422 # # Plot the time series and the expected snr
424 fig = figure.Figure()
427 for i, (eventid, complex8timeseries) in enumerate(timeseries_ligolw_dict.items()):
428 ifo = eventid_trigger_dict[eventid].ifo
429 complex_snr_timeseries = complex8timeseries.data.data
430 autocorr_length = complex8timeseries.data.length
431 time = numpy.linspace(float(complex8timeseries.epoch), float(complex8timeseries.epoch)+(autocorr_length-1)*complex8timeseries.deltaT, autocorr_length)
433 peakoffset = numpy.argmin(abs(time - eventid_trigger_dict[eventid].end))
434 phase = numpy.angle(complex_snr_timeseries[peakoffset])
435 snr = (complex_snr_timeseries * numpy.exp(-1.j * phase)).real
436 snrsigma = numpy.sqrt(2)
437 peaktime = time[peakoffset]
440 auto = banks[ifo][banknum].autocorrelation_bank[tmpltnum]
442 ax = fig.add_subplot(len(timeseries_ligolw_dict.items()),1,i+1)
443 ax.fill_between(time[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)], snr[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)]-snrsigma, snr[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)]+snrsigma, color=
'0.75')
444 #FIXME : This could potentially create an asymmetric plot. Since the peakoffset may not be the
'center' of snr timeseries but could be off by one index from the
'center'.
445 ax.plot(time[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2 + 1)], snr[int(peakoffset-(autocorr_length-1)/2):int(peakoffset+(autocorr_length+1)/2+1)],
'k', label = r
'$\mathrm{Measured}\,\rho(t)$')
446 ax.plot(time[peakoffset-(autocorr_length-1)/2:peakoffset+(autocorr_length+1)/2], auto.real[peakoffset-(autocorr_length-1)/2:peakoffset+(autocorr_length+1)/2]*maxsnr,
'b--', label = r
'$\mathrm{Scaled\,Autocorrelation}$')
447 ax.set_ylabel(r
'$\mathrm{{{}}}\,\rho(t)$'.format(ifo))
448 ax.set_xlabel(r
'$\mathrm{{Time\,from\,{}}}$'.format(peaktime))
449 ax.legend(loc=
'best')
453 filename =
'{}_snrtimeseries.{}'.format(event[
'gid'], self.format)
455 if not self.no_upload:
456 logging.info(
'writing {} ...'.format(filename))
457 lvalert_helper.upload_fig(fig, self.client, event[
'gid'], filename = filename, log_message =
'SNR time series', tagname =
'background')
459 if self.output_path is not None:
460 filename = path.join(self.output_path, filename)
461 logging.info(
'writing {} ...'.format(filename))
462 fig.savefig(filename)
464 logging.info(
'finished processing SNR time series plot for {}'.format(event[
'gid']))
468 upload remaining files/plots before shutting down
473 #-------------------------------------------------
475 #-------------------------------------------------
477 if __name__ ==
'__main__':
479 options, args = parse_command_line()
482 log_level = logging.DEBUG if options.verbose else logging.INFO
483 logging.basicConfig(format =
'%(asctime)s | event_plotter : %(levelname)s : %(message)s')
484 logging.getLogger().setLevel(log_level)
486 # create event plotter instance
487 event_plotter = EventPlotter(options)
490 event_plotter.start()