gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_ll_inspiral_event_plotter
1 #!/usr/bin/env python3
2 
3 # Copyright (C) 2019 Alexander Pace, Kipp Cannon, Chad Hanna, Drew Keppel
4 # Copyright (C) 2020 Patrick Godwin, Cody Messick
5 #
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.
10 #
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.
15 #
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.
19 
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'
22 
23 #-------------------------------------------------
24 # Preamble
25 #-------------------------------------------------
26 
27 from collections import deque, OrderedDict
28 import http.client
29 from itertools import chain
30 import gzip
31 import json
32 import logging
33 from optparse import OptionParser
34 import io
35 import sys
36 import time
37 
38 import numpy
39 
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
44 
45 from lal import LIGOTimeGPS
46 from lal import series
47 
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
54 
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
60 
61 import matplotlib
62 matplotlib.rcParams.update({
63  'font.size': 10.0,
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,
69  'figure.dpi': 100,
70  'savefig.dpi': 100,
71  'text.usetex': True
72 })
73 from matplotlib import figure
74 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
75 
76 #-------------------------------------------------
77 # Content Handler
78 #-------------------------------------------------
79 @lsctables.use_in
80 @ligolw_array.use_in
81 @ligolw_param.use_in
82 class ligolwcontenthandler(ligolw.LIGOLWContentHandler):
83  pass
84 
85 #-------------------------------------------------
86 # Functions
87 #-------------------------------------------------
88 
89 def parse_command_line():
90 
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.')
106 
107  options, args = parser.parse_args()
108 
109  if options.no_upload and options.output_path is None:
110  raise ValueError('--no-upload without setting --ouput-path disables all output')
111 
112  return options, args
113 
114 #-------------------------------------------------
115 # Classes
116 #-------------------------------------------------
117 
118 class EventPlotter(events.EventProcessor):
119  """
120  manages plotting and file uploading for incoming events.
121  """
122  _name = 'event_plotter'
123 
124  def __init__(self, options):
125  logging.info('setting up event plotter...')
126 
127  self.upload_topic = 'uploads'
128  self.ranking_stat_topic = 'ranking_stat'
129  events.EventProcessor.__init__(
130  self,
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],
135  tag=options.tag
136  )
137 
138  ### initialize timing options
139  self.max_event_time = options.max_event_time
140  self.retries = 5
141  self.retry_delay = 1
142 
143  ### initialize gracedb client
144  if options.gracedb_service_url.startswith('file'):
145  self.client = inspiral.FakeGracedbClient(options.gracedb_service_url)
146  else:
147  self.client = GraceDb(options.gracedb_service_url)
148 
149  ### gracedb settings
150  self.gracedb_group = options.gracedb_group
151  self.gracedb_pipeline = options.gracedb_pipeline
152  self.gracedb_search = options.gracedb_search
153 
154  ### initialize event storage
155  self.events = OrderedDict()
156 
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
162 
163 
164  def ingest(self, message):
165  """
166  parse a message from a kafka topic
167  """
168  payload = json.loads(message.value())
169 
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
179  # be uploaded
180  event_key = '{}_{}'.format(payload['time'], bank_bin)
181 
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)
185 
186  ### ranking stat
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
190  xmldoc.unlink()
191 
192  ### preferred event
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)
198  psd_fileobj.close()
199 
200 
201  def new_event(self, time, bank_bin):
202  """
203  returns the structure that defines an event
204  """
205  return {
206  'time': time,
207  'bin': bank_bin,
208  'coinc': None,
209  'gid': None,
210  'psd': None,
211  'ranking_data_path': None,
212  'uploaded': {'ranking_data': False, 'ranking_plots': False, 'psd_plots': False, 'snr_plots': False}
213  }
214 
215 
216  def handle(self):
217  """
218  handle aux data and plot uploading, clearing out
219  old events as necessary.
220  """
221  for event in self.events.values():
222  if event['gid']:
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
235 
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)
251 
252  def upload_file(self, message, filename, tag, contents, graceid):
253  """
254  upload a file to gracedb
255  """
256  logging.info('posting \'{}\' to gracedb ID {}'.format(filename, graceid))
257  for attempt in range(1, self.retries + 1):
258  try:
259  resp = self.client.writeLog(
260  graceid,
261  message,
262  filename = filename,
263  filecontents = contents,
264  tagname = tag
265  )
266  except HTTPError as resp:
267  logging.warning(resp)
268  else:
269  if resp.status == http.client.CREATED:
270  break
271  logging.info(
272  'gracedb upload of {} for ID {} '
273  'failed on attempt {:d}/{:d}'.format(filename, graceid, attempt, self.retries)
274  )
275  time.sleep(random.lognormal(math.log(self.retry_delay), .5))
276  else:
277  logging.warning('gracedb upload of {} for ID {} failed'.format(filename, graceid))
278  return False
279 
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'])
284  ranking_fobj.close()
285 
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'])
290  try:
291  coinc_event, = coinc_event_table
292  except ValueError:
293  raise ValueError('document does not contain exactly one candidate')
294 
295  rankingstat, rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_filename(event['ranking_data_path'], contenthandler = far.RankingStat.LIGOLWContentHandler))
296  rankingstat.finish()
297  fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
298 
299 
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
308  else:
309  snr = None
310  chisq = None
311  fig = plotfar.plot_snr_chi_pdf(rankingstat, instrument, plot_type, self.max_snr, event_snr = snr, event_chisq = chisq)
312  else:
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)
322 
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)
331 
332 
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)
341 
342 
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']))
352 
353 
354  def upload_psd_plots(self, event):
355  psds = series.read_psd_xmldoc(event['psd'])
356  if psds is None:
357  logging.info('Could not get_psds, exiting loop')
358  return
359 
360  #
361  # PSD plot
362  #
363 
364  fig = plotpsd.plot_psds(psds, event['coinc'], plot_width = 800)
365  fig.tight_layout()
366 
367  filename = '{}_psd.{}'.format(event['gid'], self.format)
368  if self.no_upload:
369  logging.info('writing {} ...'.format(filename))
370  fig.savefig(filename)
371  else:
372  lvalert_helper.upload_fig(fig, self.client, event['gid'], filename = filename, log_message = 'strain spectral density plot', tagname = 'psd')
373 
374  #
375  # Cumulative SNRs plot
376  #
377 
378  fig = plotpsd.plot_cumulative_snrs(psds, event['coinc'], plot_width = 800)
379  fig.tight_layout()
380 
381  filename = '{}_cumulative_snrs.{}'.format(event['gid'], self.format)
382  if self.no_upload:
383  logging.info('writing {} ...'.format(filename))
384  fig.savefig(filename)
385  else:
386  lvalert_helper.upload_fig(fig, self.client, event['gid'], filename = filename, log_message = 'cumulative SNRs plot', tagname = 'psd')
387 
388  logging.info('finished processing psd plot for {}'.format(event['gid']))
389 
390 
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']))
397 
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)
401 
402 
403  #
404  # # Find the template (to retrieve the autocorrelation later)
405  #
406  banknum = None
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:
411  banknum = i
412  tmpltnum = j
413  break
414  if banknum is not None:
415  break
416 
417  if banknum is None:
418  raise ValueError('The svd banks in the process params table do not contain the template the event was found with')
419 
420 
421  #
422  # # Plot the time series and the expected snr
423  #
424  fig = figure.Figure()
425  FigureCanvas(fig)
426 
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)
432 
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]
438  time -= peaktime
439  maxsnr = snr.max()
440  auto = banks[ifo][banknum].autocorrelation_bank[tmpltnum]
441 
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')
450  ax.grid()
451 
452  fig.tight_layout()
453  filename = '{}_snrtimeseries.{}'.format(event['gid'], self.format)
454 
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')
458 
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)
463 
464  logging.info('finished processing SNR time series plot for {}'.format(event['gid']))
465 
466  def finish(self):
467  """
468  upload remaining files/plots before shutting down
469  """
470  self.handle()
471 
472 
473 #-------------------------------------------------
474 # Main
475 #-------------------------------------------------
476 
477 if __name__ == '__main__':
478  # parse arguments
479  options, args = parse_command_line()
480 
481  # set up logging
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)
485 
486  # create event plotter instance
487  event_plotter = EventPlotter(options)
488 
489  # start up
490  event_plotter.start()