gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
lloidhandler.py
Go to the documentation of this file.
1 # Copyright (C) 2009--2013 Kipp Cannon, Chad Hanna, Drew Keppel
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the
5 # Free Software Foundation; either version 2 of the License, or (at your
6 # option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11 # Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 
17 ##
18 # @file
19 #
20 # gstlal_inspiral's GStreamer pipeline handler.
21 #
22 #
23 # Review Status
24 #
25 # migrated from lloidparts.py 2018-06-15
26 #
27 # | Names | Hash | Date | Diff to Head of Master |
28 # | ------------------------------------- | ---------------------------------------- | ---------- | --------------------------- |
29 # | Sathya, Duncan Me, Jolien, Kipp, Chad | 2f5f73f15a1903dc7cc4383ef30a4187091797d1 | 2014-05-02 | <a href="@gstlal_inspiral_cgit_diff/python/lloidparts.py?id=HEAD&id2=2f5f73f15a1903dc7cc4383ef30a4187091797d1">lloidparts.py</a> |
30 #
31 #
32 
33 ##
34 # @package lloidparts
35 #
36 # gstlal_inspiral's GStreamer pipeline handler.
37 #
38 
39 
40 #
41 # =============================================================================
42 #
43 # Preamble
44 #
45 # =============================================================================
46 #
47 
48 
49 from collections import defaultdict, deque
50 try:
51  from fpconst import NaN
52  from fpconst import PosInf
53 except ImportError:
54  # fpconst is not part of the standard library and might not be
55  # available
56  NaN = float("nan")
57  PosInf = float("+inf")
58 import itertools
59 import math
60 import numpy
61 import os
62 import resource
63 from scipy.interpolate import interp1d
64 import io
65 import sys
66 import threading
67 import time
68 import shutil
69 import json
70 
71 
72 import gi
73 gi.require_version('Gst', '1.0')
74 from gi.repository import GObject, Gst
75 GObject.threads_init()
76 Gst.init(None)
77 
78 
79 from ligo.lw import ligolw
80 from ligo.lw import utils as ligolw_utils
81 from ligo.lw.utils import process as ligolw_process
82 from ligo.lw.utils import segments as ligolw_segments
83 from gstlal import bottle
84 from gstlal import far
85 from gstlal import inspiral
86 from gstlal import p_astro_gstlal
87 from gstlal import pipeio
88 from gstlal import simplehandler
89 from gstlal import streamthinca
90 from gstlal.snglinspiraltable import GSTLALSnglInspiral as SnglInspiral
91 import lal
92 from lal import LIGOTimeGPS
93 from lal import rate
94 from lal.utils import CacheEntry
95 from ligo import segments
96 from ligo.segments import utils as segmentsUtils
97 
98 
99 #
100 # =============================================================================
101 #
102 # Misc
103 #
104 # =============================================================================
105 #
106 
107 
108 def message_new_checkpoint(src, timestamp = None):
109  s = Gst.Structure.new_empty("CHECKPOINT")
110  message = Gst.Message.new_application(src, s)
111  if timestamp is not None:
112  message.timestamp = timestamp
113  return message
114 
115 
116 def subdir_from_T050017_filename(fname):
117  path = str(CacheEntry.from_T050017(fname).segment[0])[:5]
118  try:
119  os.mkdir(path)
120  except OSError:
121  pass
122  return path
123 
124 
125 #
126 # =============================================================================
127 #
128 # Web Eye Candy
129 #
130 # =============================================================================
131 #
132 
133 
134 class EyeCandy(object):
135  def __init__(self, instruments, kafka_server, tag, pipeline, segmentstracker, latencytracker):
136  self.kafka_server = kafka_server
137  self.tag = tag
138  self.gate_history = segmentstracker.gate_history
139  if latencytracker:
140  self.pipeline_latency_history = latencytracker.pipeline_history
141  else:
142  self.pipeline_latency_history = None
143  self.latency_histogram = rate.BinnedArray(rate.NDBins((rate.LinearPlusOverflowBins(5, 205, 22),)))
144  # NOTE most of this data is collected at 1Hz, thus a 300
145  # element deque should hold about 5 minutes of history.
146  # Keeping the deque short is desirable for efficiency in
147  # downloads, but it could mean that data is lost (though the
148  # snapshot every ~4 hours will contain the information in
149  # general)
150  self.latency_history = deque(maxlen = 300)
151  self.snr_history = deque(maxlen = 300)
152  self.likelihood_history = deque(maxlen = 300)
153  self.far_history = deque(maxlen = 300)
154  self.ram_history = deque(maxlen = 2)
155  self.ifo_snr_history = dict((instrument, deque(maxlen = 300)) for instrument in instruments)
156  self.strain = {}
157  for instrument in instruments:
158  name = "%s_strain_audiorate" % instrument
159  elem = pipeline.get_by_name(name)
160  if elem is not None:
161  self.strain[instrument] = elem
162  self.time_since_last_state = None
163 
164  #
165  # setup bottle routes
166  #
167 
168  bottle.route("/latency_histogram.txt")(self.web_get_latency_histogram)
169  bottle.route("/latency_history.txt")(self.web_get_latency_history)
170  bottle.route("/snr_history.txt")(self.web_get_snr_history)
171  if "H1" in instruments:
172  bottle.route("/H1_snr_history.txt")(self.web_get_H1_snr_history)
173  if "L1" in instruments:
174  bottle.route("/L1_snr_history.txt")(self.web_get_L1_snr_history)
175  if "V1" in instruments:
176  bottle.route("/V1_snr_history.txt")(self.web_get_V1_snr_history)
177  bottle.route("/likelihood_history.txt")(self.web_get_likelihood_history)
178  bottle.route("/far_history.txt")(self.web_get_far_history)
179  bottle.route("/ram_history.txt")(self.web_get_ram_history)
180 
181  #
182  # Setup kafka client
183  #
184 
185  if self.kafka_server is not None:
186  from ligo.scald.io import kafka
187 
188  snr_routes = ["%s_snr_history" % ifo for ifo in instruments]
189  network_routes = ["likelihood_history", "snr_history", "latency_history"]
190  state_routes = ["%s_strain_dropped" % ifo for ifo in instruments]
191  usage_routes = ["ram_history"]
192  gates = ["%ssegments" % gate for gate in ("statevector", "dqvector", "whiteht")]
193  seg_routes = ["%s_%s" % (ifo, gate) for ifo in instruments for gate in gates]
194 
195  instrument_latency_routes = ["%s_%s_latency" % (ifo, stage) for ifo in instruments for stage in ["datasource", "whitening", "snrSlice"]]
196  pipeline_latency_routes = ["all_%s_latency" % stage for stage in ["itacac"]]
197 
198  topics = list(itertools.chain(snr_routes, network_routes, usage_routes, state_routes, seg_routes, instrument_latency_routes, pipeline_latency_routes))
199 
200  self.client = kafka.Client("kafka://{}".format(self.kafka_server))
201  self.client.subscribe(topics)
202  else:
203  self.client = None
204 
205  # FIXME, it is silly to store kafka data like this since we
206  # have all the other data structures, but since we are also
207  # maintaining the bottle route methods, we should keep this a
208  # bit separate for now to not disrupt too much.
209 
210  self.kafka_data = defaultdict(lambda: {'time': [], 'data': []})
211  self.kafka_data["coinc"] = []
212 
213  def update(self, events, last_coincs):
214  self.ram_history.append((float(lal.UTCToGPS(time.gmtime())), (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss) / 1048576.)) # GB
215  if events:
216  maxevents = {}
217  for event in events:
218  if (event.ifo not in maxevents) or (event.snr > maxevents[event.ifo].snr):
219  maxevents[event.ifo] = event
220  for ifo, event in maxevents.items():
221  t, snr = float(event.end), event.snr
222  self.ifo_snr_history[ifo].append((t, snr))
223  if self.client is not None:
224  self.kafka_data["%s_snr_history" % ifo]["time"].append(t)
225  self.kafka_data["%s_snr_history" % ifo]["data"].append(snr)
226  if last_coincs:
227  coinc_inspiral_index = last_coincs.coinc_inspiral_index
228  coinc_event_index = last_coincs.coinc_event_index
229  sngl_inspiral_index = last_coincs.sngl_inspiral_index
230  coinc_dict_list = []
231  for coinc_event_id in coinc_event_index:
232  coinc_dict = {}
233  for attr in ("combined_far", "snr", "false_alarm_rate"):
234  try:
235  coinc_dict[attr] = float(getattr(coinc_inspiral_index[coinc_event_id], attr))
236  except TypeError as e:
237  pass#print >>sys.stderr, e, attr, getattr(coinc_inspiral_index[coinc_event_id], attr)
238  coinc_dict["end"] = float(coinc_inspiral_index[coinc_event_id].end)
239  for attr in ("likelihood",):
240  try:
241  coinc_dict[attr] = float(getattr(coinc_event_index[coinc_event_id], attr))
242  except TypeError as e:
243  pass#print >>sys.stderr, e, attr, getattr(coinc_event_index[coinc_event_id], attr)
244  for sngl_row in sngl_inspiral_index[coinc_event_id]:
245  for attr in ("snr", "chisq", "mass1", "mass2", "spin1z", "spin2z", "coa_phase"):
246  coinc_dict["%s_%s" % (sngl_row.ifo, attr)] = float(getattr(sngl_row, attr))
247  coinc_dict["%s_end" % sngl_row.ifo] = float(sngl_row.end)
248  coinc_dict_list.append(coinc_dict)
249  self.kafka_data["coinc"].extend(coinc_dict_list)
250  for coinc_inspiral in coinc_inspiral_index.values():
251  # latency in .minimum_duration
252  # FIXME: update when a proper column is available
253  self.latency_histogram[coinc_inspiral.minimum_duration,] += 1
254  # latency in .minimum_duration
255  # FIXME: update when a proper column is available
256  max_latency, max_latency_t = max((coinc_inspiral.minimum_duration, float(coinc_inspiral.end)) for coinc_inspiral in coinc_inspiral_index.values())
257  self.latency_history.append((max_latency_t, max_latency))
258 
259  max_snr, max_snr_t = max((coinc_inspiral.snr, float(coinc_inspiral.end)) for coinc_inspiral in coinc_inspiral_index.values())
260  self.snr_history.append((max_snr_t, max_snr))
261 
262  max_likelihood, max_likelihood_t, max_likelihood_far = max((coinc_event_index[coinc_event_id].likelihood, float(coinc_inspiral.end), coinc_inspiral.combined_far) for coinc_event_id, coinc_inspiral in coinc_inspiral_index.items())
263  if max_likelihood is not None:
264  self.likelihood_history.append((max_likelihood_t, max_likelihood))
265  if max_likelihood_far is not None:
266  self.far_history.append((max_likelihood_t, max_likelihood_far))
267 
268  if self.client is not None:
269  for ii, column in enumerate(["time", "data"]):
270  self.kafka_data["latency_history"][column].append(float(self.latency_history[-1][ii]))
271  self.kafka_data["snr_history"][column].append(float(self.snr_history[-1][ii]))
272  if max_likelihood is not None:
273  self.kafka_data["likelihood_history"]["time"].append(float(max_likelihood_t))
274  self.kafka_data["likelihood_history"]["data"].append(float(max_likelihood))
275  if max_likelihood_far is not None:
276  self.kafka_data["far_history"]["time"].append(float(max_likelihood_t))
277  self.kafka_data["far_history"]["data"].append(float(max_likelihood_far))
278 
279  t = inspiral.now()
280  if self.time_since_last_state is None:
281  self.time_since_last_state = t
282 
283  # send state/segment information to kafka every second
284  if self.client is not None and (t - self.time_since_last_state) >= 1:
285  self.time_since_last_state = t
286  for ii, column in enumerate(["time", "data"]):
287  self.kafka_data["ram_history"][column].append(float(self.ram_history[-1][ii]))
288 
289  # collect gate segments
290  for gate in self.gate_history.keys():
291  for instrument, seg_history in self.gate_history[gate].items():
292  if not seg_history:
293  continue
294 
295  # get on/off points, add point at +inf
296  gate_interp_times, gate_interp_onoff = zip(*seg_history)
297  gate_interp_times = list(gate_interp_times)
298  gate_interp_times.append(2000000000)
299  gate_interp_onoff = list(gate_interp_onoff)
300  gate_interp_onoff.append(gate_interp_onoff[-1])
301 
302  # regularly sample from on/off points
303  gate_times = numpy.arange(int(self.time_since_last_state), int(t + 1), 0.25)
304  gate_onoff = interp1d(gate_interp_times, gate_interp_onoff, kind='zero')(gate_times)
305  self.kafka_data["%s_%s" % (instrument, gate)]["time"].extend([t for t in gate_times if t >= self.time_since_last_state])
306  self.kafka_data["%s_%s" % (instrument, gate)]["data"].extend([state for t, state in zip(gate_times, gate_onoff) if t >= self.time_since_last_state])
307 
308  # collect any new latencies
309  if self.pipeline_latency_history:
310  for stage in self.pipeline_latency_history.keys():
311  for instrument in self.pipeline_latency_history[stage].keys():
312  while (self.pipeline_latency_history[stage][instrument]):
313  data = self.pipeline_latency_history[stage][instrument].pop()
314  self.kafka_data["%s_%s_latency" % (instrument, stage)]["time"].append(data[0])
315  self.kafka_data["%s_%s_latency" % (instrument, stage)]["data"].append(data[1])
316 
317  # collect strain dropped samples
318  for instrument, elem in self.strain.items():
319  # I know the name is strain_drop even though it
320  # comes from the "add" property. that is
321  # because audiorate has to "add" samples when
322  # data is dropped.
323  # FIXME don't hard code the rate
324  self.kafka_data["%s_strain_dropped" % instrument]["time"].append(float(t))
325  self.kafka_data["%s_strain_dropped" % instrument]["data"].append(elem.get_property("add") / 16384.)
326 
327  # Send all of the kafka messages and clear the data
328  #self.producer.send(self.tag, self.kafka_data)
329  for route in self.kafka_data.keys():
330  self.client.write(route, self.kafka_data[route], tags=self.tag)
331  # This line forces the send but is blocking!! not the
332  # best idea for production running since we value
333  # latency over getting metric data out
334  #self.producer.flush()
335  for route in self.kafka_data.keys():
336  self.kafka_data[route] = {'time': [], 'data': []}
337  self.kafka_data["coinc"] = []
338 
339  def web_get_latency_histogram(self):
340  with self.lock:
341  for latency, number in zip(self.latency_histogram.centres()[0][1:-1], self.latency_histogram.array[1:-1]):
342  yield "%e %e\n" % (latency, number)
343 
344  def web_get_latency_history(self):
345  with self.lock:
346  # first one in the list is sacrificed for a time stamp
347  for time, latency in self.latency_history:
348  yield "%f %e\n" % (time, latency)
349 
350  def web_get_snr_history(self):
351  with self.lock:
352  # first one in the list is sacrificed for a time stamp
353  for time, snr in self.snr_history:
354  yield "%f %e\n" % (time, snr)
355 
356  def web_get_H1_snr_history(self):
357  with self.lock:
358  # first one in the list is sacrificed for a time stamp
359  for time, snr in self.ifo_snr_history["H1"]:
360  yield "%f %e\n" % (time, snr)
361 
362  def web_get_L1_snr_history(self):
363  with self.lock:
364  # first one in the list is sacrificed for a time stamp
365  for time, snr in self.ifo_snr_history["L1"]:
366  yield "%f %e\n" % (time, snr)
367 
368  def web_get_V1_snr_history(self):
369  with self.lock:
370  # first one in the list is sacrificed for a time stamp
371  for time, snr in self.ifo_snr_history["V1"]:
372  yield "%f %e\n" % (time, snr)
373 
374  def web_get_likelihood_history(self):
375  with self.lock:
376  # first one in the list is sacrificed for a time stamp
377  for time, like in self.likelihood_history:
378  yield "%f %e\n" % (time, like)
379 
380  def web_get_far_history(self):
381  with self.lock:
382  # first one in the list is sacrificed for a time stamp
383  for time, far in self.far_history:
384  yield "%f %e\n" % (time, far)
385 
386  def web_get_ram_history(self):
387  with self.lock:
388  # first one in the list is sacrificed for a time stamp
389  for time, ram in self.ram_history:
390  yield "%f %e\n" % (time, ram)
391 
392 
393 #
394 # =============================================================================
395 #
396 # Segmentlist Tracker
397 #
398 # =============================================================================
399 #
400 
401 
402 class SegmentsTracker(object):
403  def __init__(self, pipeline, instruments, segment_history_duration = LIGOTimeGPS(2592000), verbose = False):
404  self.lock = threading.Lock()
405  self.verbose = verbose
406 
407  # setup segment list collection from gates
408  #
409  # FIXME: knowledge of what gates are present in what
410  # configurations, what they are called, etc., somehow needs to live
411  # with the code that constructs the gates
412  #
413  # FIXME: in the offline pipeline, state vector segments
414  # don't get recorded. however, except for the h(t) gate
415  # segments these are all inputs to the pipeline so it
416  # probably doesn't matter. nevertheless, they maybe should
417  # go into the event database for completeness of that
418  # record, or maybe not because it could result in a lot of
419  # duplication of on-disk data. who knows. think about it.
420  gate_suffix = {
421  # FIXME uncomment the framesegments line once the
422  # online analysis has a frame segments gate
423  #"framesegments": "frame_segments_gate",
424  "statevectorsegments": "state_vector_gate",
425  "dqvectorsegments": "dq_vector_gate",
426  "whitehtsegments": "ht_gate"
427  }
428 
429  # dictionary mapping segtype to segmentlist dictionary
430  # mapping instrument to segment list
431  self.seglistdicts = dict((segtype, segments.segmentlistdict((instrument, segments.segmentlist()) for instrument in instruments)) for segtype in gate_suffix)
432 
433  # create a copy to keep track of recent segment history
434  self.recent_segment_histories = self.seglistdicts.copy()
435  self.segment_history_duration = segment_history_duration
436 
437  # recent gate history encoded in on/off bits
438  self.gate_history = {segtype: {instrument: deque(maxlen = 20) for instrument in instruments} for segtype in gate_suffix}
439 
440  # iterate over segment types and instruments, look for the
441  # gate element that should provide those segments, and
442  # connect handlers to collect the segments
443  if verbose:
444  print(sys.stderr, "connecting segment handlers to gates ...", file=sys.stderr)
445  for segtype, seglistdict in self.seglistdicts.items():
446  for instrument in seglistdict:
447  try:
448  name = "%s_%s" % (instrument, gate_suffix[segtype])
449  except KeyError:
450  # this segtype doesn't come from
451  # gate elements
452  continue
453  elem = pipeline.get_by_name(name)
454  if elem is None:
455  # ignore missing gate elements
456  if verbose:
457  print("\tcould not find %s for %s '%s'" % (name, instrument, segtype), file=sys.stderr)
458  continue
459  if verbose:
460  print("\tfound %s for %s '%s'" % (name, instrument, segtype), file=sys.stderr)
461  elem.connect("start", self.gatehandler, (segtype, instrument, "on"))
462  elem.connect("stop", self.gatehandler, (segtype, instrument, "off"))
463  elem.set_property("emit-signals", True)
464  if verbose:
465  print("... done connecting segment handlers to gates", file=sys.stderr)
466 
467 
468  def __gatehandler(self, elem, timestamp, seg_state_input):
469  """!
470  A handler that intercepts gate state transitions.
471 
472  @param elem A reference to the lal_gate element or None
473  (only used for verbosity)
474  @param timestamp A gstreamer time stamp (integer
475  nanoseconds) that marks the state transition
476  @param segtype the class of segments this gate is defining,
477  e.g., "datasegments", etc..
478  @param instrument the instrument this state transtion is to
479  be attributed to, e.g., "H1", etc..
480  @param new_state the state transition, must be either "on"
481  or "off"
482 
483  Must be called with the lock held.
484  """
485  # convert integer nanoseconds to LIGOTimeGPS
486  timestamp = LIGOTimeGPS(0, timestamp)
487 
488  # unpack argument tuple:
489  segtype, instrument, new_state = seg_state_input
490 
491  if self.verbose:
492  print("%s: %s '%s' state transition: %s @ %s" % ((elem.get_name() if elem is not None else "<internal>"), instrument, segtype, new_state, str(timestamp)), file= sys.stderr)
493 
494  if new_state == "off":
495  # record end of segment
496  self.seglistdicts[segtype][instrument] -= segments.segmentlist((segments.segment(timestamp, segments.PosInfinity),))
497  self.gate_history[segtype][instrument].append((float(timestamp), 0.))
498  elif new_state == "on":
499  # record start of new segment
500  self.seglistdicts[segtype][instrument] += segments.segmentlist((segments.segment(timestamp, segments.PosInfinity),))
501  self.gate_history[segtype][instrument].append((float(timestamp), 1.))
502  else:
503  assert False, "impossible new_state '%s'" % new_state
504 
505 
506  def gatehandler(self, elem, timestamp, seg_state_input):
507  segtype, instrument, new_state = seg_state_input
508  with self.lock:
509  self.__gatehandler(elem, timestamp, (segtype, instrument, new_state))
510 
511 
512  def terminate(self, timestamp):
513  # terminate all segments
514  with self.lock:
515  for segtype, seglistdict in self.seglistdicts.items():
516  for instrument in seglistdict:
517  self.__gatehandler(None, timestamp, (segtype, instrument, "off"))
518 
519 
521  """!
522  A method to output the segment list in a valid ligolw xml
523  format.
524 
525  Must be called with the lock held.
526  """
527  xmldoc = ligolw.Document()
528  xmldoc.appendChild(ligolw.LIGO_LW())
529  process = ligolw_process.register_to_xmldoc(xmldoc, "gstlal_inspiral", {})
530  with ligolw_segments.LigolwSegments(xmldoc, process) as ligolwsegments:
531  for segtype, seglistdict in self.seglistdicts.items():
532  ligolwsegments.insert_from_segmentlistdict(seglistdict, name = segtype, comment = "LLOID snapshot")
533  ligolw_process.set_process_end_time(process)
534  return xmldoc
535 
536 
537  def __T050017_filename(self, description, extension):
538  """!
539  Must be called with the lock held.
540  """
541  # input check
542  if "-" in description:
543  raise ValueError("invalid characters in description '%s'" % description)
544 
545  # determine current extent
546  instruments = set(instrument for seglistdict in self.seglistdicts.values() for instrument in seglistdict)
547  segs = segments.segmentlist(seglistdict.extent_all() for seglistdict in self.seglistdicts.values() if any(seglistdict.values()))
548  if segs:
549  start, end = segs.extent()
550  if math.isinf(end):
551  end = inspiral.now()
552  else:
553  # silence errors at start-up.
554  # FIXME: this is probably dumb. who cares.
555  start = end = inspiral.now()
556 
557  # construct and return filename
558  start, end = int(math.floor(start)), int(math.ceil(end))
559  return "%s-%s-%d-%d.%s" % ("".join(sorted(instruments)), description, start, end - start, extension)
560 
561 
562  def T050017_filename(self, description, extension):
563  with self.lock:
564  return self.__T050017_filename(description, extension)
565 
566 
567  def flush_segments_to_disk(self, tag, timestamp):
568  """!
569  Flush segments to disk, e.g., when checkpointing or
570  shutting down an online pipeline.
571 
572  @param timestamp the LIGOTimeGPS timestamp of the current
573  buffer in order to close off open segment intervals before
574  writing to disk
575  """
576  with self.lock:
577  # make a copy of the current segmentlistdicts
578  seglistdicts = dict((key, value.copy()) for key, value in self.seglistdicts.items())
579 
580  # keep everything before timestamp in the current
581  # segmentlistdicts. keep everything after
582  # timestamp in the copy. we need to apply the cut
583  # this way around so that the T050017 filename
584  # constructed below has the desired start and
585  # duration
586  for seglistdict in self.seglistdicts.values():
587  seglistdict -= seglistdict.fromkeys(seglistdict, segments.segmentlist([segments.segment(timestamp, segments.PosInfinity)]))
588  for seglistdict in seglistdicts.values():
589  seglistdict -= seglistdict.fromkeys(seglistdict, segments.segmentlist([segments.segment(segments.NegInfinity, timestamp)]))
590 
591  # write the current (clipped) segmentlistdicts to
592  # disk
593  fname = self.__T050017_filename("%s_SEGMENTS" % tag, "xml.gz")
594  fname = os.path.join(subdir_from_T050017_filename(fname), fname)
595  ligolw_utils.write_filename(self.gen_segments_xmldoc(), fname, verbose = self.verbose, trap_signals = None)
596 
597  # continue with the (clipped) copy
598  self.seglistdicts = seglistdicts
599 
600 
602  """!
603  provide a bottle route to get segment information via a url
604  """
605  with self.lock:
606  output = io.StringIO()
607  ligolw_utils.write_fileobj(self.gen_segments_xmldoc(), output)
608  outstr = output.getvalue()
609  output.close()
610  return outstr
611 
612 
614  """!
615  A method to update the recent segment histories
616 
617  Must be called with the lock held.
618  """
619  current_gps_time = lal.GPSTimeNow()
620  interval_to_discard = segments.segmentlist((segments.segment(segments.NegInfinity, current_gps_time - self.segment_history_duration),))
621  for segtype, seglistdict in self.recent_segment_histories.items():
622  seglistdict.extend(self.seglistdicts[segtype])
623  seglistdict.coalesce()
624  for seglist in seglistdict.values():
625  seglist -= interval_to_discard
626 
627 
629  """!
630  Construct and return a LIGOLW XML tree containing the
631  recent segment histories.
632 
633  Must be called with the lock held.
634  """
636  xmldoc = ligolw.Document()
637  xmldoc.appendChild(ligolw.LIGO_LW())
638  process = ligolw_process.register_to_xmldoc(xmldoc, "gstlal_inspiral", {})
639  with ligolw_segments.LigolwSegments(xmldoc, process) as ligolwsegments:
640  for segtype, seglistdict in self.recent_segment_histories.items():
641  ligolwsegments.insert_from_segmentlistdict(seglistdict, name = segtype, comment = "LLOID snapshot")
642  ligolw_process.set_process_end_time(process)
643  return xmldoc
644 
645 
647  """!
648  provide a bottle route to get recent segment history
649  information via a url
650  """
651  with self.lock:
652  output = io.StringIO()
653  ligolw_utils.write_fileobj(self.gen_recent_segment_history_xmldoc(), output)
654  outstr = output.getvalue()
655  output.close()
656  return outstr
657 
658 #
659 # =============================================================================
660 #
661 # Pipeline Latency Tracker
662 #
663 # =============================================================================
664 #
665 
666 class LatencyTracker(object):
667  def __init__(self, pipeline, instruments, verbose = False):
668  self.lock = threading.Lock()
669  self.verbose = verbose
670 
671  # recent pipeline stage latencies
672  ifo_pipe_stages = ["datasource", "whitening", "snrSlice"]
673  all_ifo_stages = ["itacac"]
674  self.pipeline_history = {stage: {instrument: deque(maxlen = 20) for instrument in instruments} for stage in ifo_pipe_stages}
675  for stage in all_ifo_stages:
676  self.pipeline_history[stage] = {"all": deque(maxlen = 20)}
677 
678  # iterate over pipeline stages, look for the
679  # stage element that should provide the latencies, and
680  # connect handlers to collect the latencies
681  if verbose:
682  print(sys.stderr, "connecting pipeline latency handlers ...", file=sys.stderr)
683  for stage in self.pipeline_history.keys():
684  for instrument in self.pipeline_history[stage].keys():
685  elem = pipeline.get_by_name("%s_%s_latency" % (instrument, stage))
686  if elem is None:
687  if verbose:
688  print("\tcould not find %s_%s_latency element for pipeline latency monitoring" % (instrument, stage), file=sys.stderr)
689  continue
690  if verbose:
691  print("\tfound %s_%s_latency element for pipeline latency monitoring" % (instrument, stage), file=sys.stderr)
692  elem.connect("notify::current-latency", self.latencyhandler, (stage, instrument, "stop"))
693  if verbose:
694  print("... done connecting pipeline latency handlers", file=sys.stderr)
695 
696 
697  def __latencyhandler(self, elem, timestamp, stage_latency_input):
698  """!
699  A handler that intercepts pipeline latency calls.
700 
701  @param elem A reference to the lal_gate element or None
702  (only used for verbosity)
703  @param timestamp A gstreamer time stamp (integer
704  nanoseconds) that marks the state transition
705  @param stage_latency_input name, instrument and state of the stage
706  from the pipeline
707 
708  Must be called with the lock held.
709  """
710  # parse stage_latency_input
711  stage, instrument, state = stage_latency_input
712 
713  # parse properties from element trigger
714  latency = elem.get_property("current-latency")
715  name = elem.get_property("name") if elem is not None else "<internal>"
716  timestamp = elem.get_property("timestamp")
717 
718  if state == "stop":
719  # record pipeline stage latency
720  self.pipeline_history[stage][instrument].append((float(timestamp), float(latency)))
721  else:
722  assert False, "impossible state '%s'" % state
723 
724 
725  def latencyhandler(self, elem, timestamp, stage_latency_input):
726  with self.lock:
727  self.__latencyhandler(elem, timestamp, stage_latency_input)
728 
729 #
730 # =============================================================================
731 #
732 # Pipeline Handler
733 #
734 # =============================================================================
735 #
736 
737 
738 class Handler(simplehandler.Handler):
739  """!
740  A subclass of simplehandler.Handler to be used with e.g.,
741  gstlal_inspiral
742 
743  Implements additional message handling for dealing with spectrum
744  messages and checkpoints for the online analysis including periodic
745  dumps of segment information, trigger files and background
746  distribution statistics.
747  """
748  def __init__(self, mainloop, pipeline, coincs_document, rankingstat, horizon_distance_func, gracedbwrapper, zerolag_rankingstatpdf_url = None, rankingstatpdf_url = None, ranking_stat_output_url = None, ranking_stat_input_url = None, likelihood_snapshot_interval = None, sngls_snr_threshold = None, tag = "", kafka_server = "10.14.0.112:9092", cluster = False, cap_singles = False, FAR_trialsfactor = 1.0, activation_counts = None, track_latency = False, verbose = False):
749  """!
750  @param mainloop The main application's event loop
751  @param pipeline The gstreamer pipeline that is being
752  controlled by this handler
753  @param dataclass A Data class instance
754  @param tag The tag to use for naming file snapshots, e.g.
755  the description will be "%s_LLOID" % tag
756  @param verbose Be verbose
757  """
758  super(Handler, self).__init__(mainloop, pipeline)
759 
760  #
761  # initialize
762  #
763 
764  self.lock = threading.Lock()
765  self.coincs_document = coincs_document
766  self.pipeline = pipeline
767  self.tag = tag
768  self.verbose = verbose
769  # None to disable periodic snapshots, otherwise seconds
770  self.likelihood_snapshot_interval = likelihood_snapshot_interval
772  self.cluster = cluster
773  self.cap_singles = cap_singles
774  self.FAR_trialsfactor = FAR_trialsfactor
775  self.activation_counts = activation_counts
776 
777  self.gracedbwrapper = gracedbwrapper
778  # FIXME: detangle this
779  self.gracedbwrapper.lock = self.lock
780 
781  #
782  # setup segment list collection from gates
783  #
784 
785  self.segmentstracker = SegmentsTracker(pipeline, rankingstat.instruments, verbose = verbose)
786 
787  #
788  # setup latency collection from pipeline if requested
789  #
790 
791  if track_latency:
792  self.latencytracker = LatencyTracker(pipeline, rankingstat.instruments, verbose = verbose)
793  else:
794  self.latencytracker = None
795 
796  #
797  # set up metric collection
798  #
799 
800  self.eye_candy = EyeCandy(rankingstat.instruments, kafka_server, self.tag, pipeline, self.segmentstracker, self.latencytracker)
801  # FIXME: detangle this
802  self.eye_candy.lock = self.lock
803 
804  #
805  # setup bottle routes (and rahwts)
806  #
807 
808  bottle.route("/cumulative_segments.xml")(self.segmentstracker.web_get_recent_segment_history_xml)
809  bottle.route("/psds.xml")(self.web_get_psd_xml)
810  bottle.route("/rankingstat.xml")(self.web_get_rankingstat)
811  bottle.route("/segments.xml")(self.segmentstracker.web_get_segments_xml)
812  bottle.route("/sngls_snr_threshold.txt", method = "GET")(self.web_get_sngls_snr_threshold)
813  bottle.route("/sngls_snr_threshold.txt", method = "POST")(self.web_set_sngls_snr_threshold)
814  bottle.route("/zerolag_rankingstatpdf.xml")(self.web_get_zerolag_rankingstatpdf)
815 
816  #
817  # attach a StreamThinca instance to ourselves
818  #
819 
821  coincs_document.xmldoc,
822  coincs_document.process_id,
823  delta_t = rankingstat.delta_t,
824  min_instruments = rankingstat.min_instruments,
825  sngls_snr_threshold = sngls_snr_threshold
826  )
827 
828  #
829  # setup likelihood ratio book-keeping.
830  #
831  # in online mode, if ranking_stat_input_url is set then on
832  # each snapshot interval, and before providing stream
833  # thinca with its ranking statistic information, the
834  # current rankingstat object is replaced with the contents
835  # of that file. this is intended to be used by trigger
836  # generator jobs on the injection branch of an online
837  # analysis to import ranking statistic information from
838  # their non-injection cousins instead of using whatever
839  # statistics they've collected internally.
840  # ranking_stat_input_url is not used when running offline.
841  #
842  # ranking_stat_output_url provides the name of the file to
843  # which the internally-collected ranking statistic
844  # information is to be written whenever output is written
845  # to disk. if set to None, then only the trigger file will
846  # be written, no ranking statistic information will be
847  # written. normally it is set to a non-null value, but
848  # injection jobs might be configured to disable ranking
849  # statistic output since they produce nonsense.
850  #
851 
852  self.ranking_stat_input_url = ranking_stat_input_url
853  self.ranking_stat_output_url = ranking_stat_output_url
854  self.rankingstat = rankingstat
855 
856  #
857  # if we have been supplied with external ranking statistic
858  # information then use it to enable ranking statistic
859  # assignment in streamthinca.
860  #
861 
862  if self.ranking_stat_input_url is not None:
863  if self.rankingstat.is_healthy(self.verbose):
864  self.stream_thinca.ln_lr_from_triggers = far.OnlineFrankensteinRankingStat(self.rankingstat, self.rankingstat).finish().ln_lr_from_triggers
865  if self.verbose:
866  print("ranking statistic assignment ENABLED", file=sys.stderr)
867  else:
868  self.stream_thinca.ln_lr_from_triggers = None
869  if self.verbose:
870  print("ranking statistic assignment DISABLED", file=sys.stderr)
871  elif False:
872  # FIXME: move sum-of-SNR^2 cut into this object's
873  # .__call__() and then use as coinc sieve function
874  # instead. left here temporariliy to remember how
875  # to initialize it
876  self.stream_thinca.ln_lr_from_triggers = far.DatalessRankingStat(
877  template_ids = rankingstat.template_ids,
878  instruments = rankingstat.instruments,
879  min_instruments = rankingstat.min_instruments,
880  delta_t = rankingstat.delta_t
881  ).finish().ln_lr_from_triggers
882  if self.verbose:
883  print("ranking statistic assignment ENABLED", file=sys.stderr)
884  else:
885  self.stream_thinca.ln_lr_from_triggers = None
886  if self.verbose:
887  print("ranking statistic assignment DISABLED", file=sys.stderr)
888 
889  #
890  # zero_lag_ranking_stats is a RankingStatPDF object that is
891  # used to accumulate a histogram of the likelihood ratio
892  # values assigned to zero-lag candidates. this is required
893  # to implement the extinction model for low-significance
894  # events during online running but otherwise is optional.
895  #
896  # FIXME: if the file does not exist or is not readable,
897  # the code silently initializes a new, empty, histogram.
898  # it would be better to determine whether or not the file
899  # is required and fail when it is missing
900  #
901 
902  if zerolag_rankingstatpdf_url is not None and os.access(ligolw_utils.local_path_from_url(zerolag_rankingstatpdf_url), os.R_OK):
903  _, self.zerolag_rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_url(zerolag_rankingstatpdf_url, verbose = verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
904  if self.zerolag_rankingstatpdf is None:
905  raise ValueError("\"%s\" does not contain ranking statistic PDF data" % zerolag_rankingstatpdf_url)
906  elif zerolag_rankingstatpdf_url is not None:
907  # initialize an all-zeros set of PDFs
908  self.zerolag_rankingstatpdf = far.RankingStatPDF(rankingstat, nsamples = 0)
909  else:
910  self.zerolag_rankingstatpdf = None
911  self.zerolag_rankingstatpdf_url = zerolag_rankingstatpdf_url
912 
913  #
914  # set horizon distance calculator
915  #
916 
917  self.horizon_distance_func = horizon_distance_func
918 
919  #
920  # rankingstatpdf contains the RankingStatPDF object (loaded
921  # from rankingstatpdf_url) used to initialize the FAPFAR
922  # object for on-the-fly FAP and FAR assignment. except to
923  # initialize the FAPFAR object it is not used for anything,
924  # but is retained so that it can be exposed through the web
925  # interface for diagnostic purposes and uploaded to gracedb
926  # with candidates. the extinction model is applied to
927  # initialize the FAPFAR object but the original is retained
928  # for upload to gracedb, etc.
929  #
930 
931  self.rankingstatpdf_url = rankingstatpdf_url
932  self.load_rankingstat_pdf()
933 
934  #
935  # most recent PSDs
936  #
937 
938  self.psds = {}
939 
940  #
941  # use state vector elements to 0 horizon distances when
942  # instruments are off
943  #
944 
945  if verbose:
946  print("connecting horizon distance handlers to gates ...", file=sys.stderr)
947  self.absent_instruments = set()
948  for instrument in rankingstat.instruments:
949  name = "%s_ht_gate" % instrument
950  elem = pipeline.get_by_name(name)
951  if elem is None:
952  # FIXME: if there is no data for an
953  # instrument for which we have ranking
954  # statistic data then the horizon distance
955  # record needs to indicate that it was off
956  # for the entire segment. should probably
957  # 0 the horizon distance history at start
958  # and stop of each stream, but there is a
959  # statement in the EOS handler that we
960  # don't do that, and I can remember why
961  # that is.
962  self.absent_instruments.add(instrument)
963  continue
964  raise ValueError("cannot find \"%s\" element for %s" % (name, instrument))
965  if verbose:
966  print("\tfound %s for %s" % (name, instrument), file=sys.stderr)
967  elem.connect("start", self.horizgatehandler, (instrument, True))
968  elem.connect("stop", self.horizgatehandler, (instrument, False))
969  elem.set_property("emit-signals", True)
970  if verbose:
971  print("... done connecting horizon distance handlers to gates", file=sys.stderr)
972 
973 
974  def do_on_message(self, bus, message):
975  """!
976  Handle application-specific message types, e.g., spectrum
977  and checkpointing messages.
978 
979  @param bus A reference to the pipeline's bus
980  @param message A reference to the incoming message
981  """
982  #
983  # return value of True tells parent class that we have done
984  # all that is needed in response to the message, and that
985  # it should ignore it. a return value of False means the
986  # parent class should do what it thinks should be done
987  #
988  if message.type == Gst.MessageType.ELEMENT:
989  if message.get_structure().get_name() == "spectrum":
990  # get the instrument, psd, and timestamp.
991  # the "stability" is a measure of the
992  # fraction of the configured averaging
993  # timescale used to obtain this
994  # measurement.
995  # NOTE: epoch is used for the timestamp,
996  # this is the middle of the most recent FFT
997  # interval used to obtain this PSD
998  instrument = message.src.get_name().split("_")[-1]
999  psd = pipeio.parse_spectrum_message(message)
1000  timestamp = psd.epoch
1001  stability = float(message.src.get_property("n-samples")) / message.src.get_property("average-samples")
1002 
1003  # save
1004  self.psds[instrument] = psd
1005 
1006  # update horizon distance history. if the
1007  # whitener's average is not satisfactorily
1008  # converged, claim the horizon distance is
1009  # 0 (equivalent to claiming the instrument
1010  # to be off at this time). this has the
1011  # effect of vetoing candidates from these
1012  # times.
1013  if stability > 0.3:
1014  horizon_distance = self.horizon_distance_func(psd, 8.0)[0]
1015  assert not (math.isnan(horizon_distance) or math.isinf(horizon_distance))
1016  else:
1017  horizon_distance = 0.
1018  self.record_horizon_distance(instrument, float(timestamp), horizon_distance)
1019  return True
1020  elif message.type == Gst.MessageType.APPLICATION:
1021  if message.get_structure().get_name() == "CHECKPOINT":
1022  self.checkpoint(LIGOTimeGPS(0, message.timestamp))
1023  return True
1024  elif message.type == Gst.MessageType.EOS:
1025  with self.lock:
1026  # FIXME: how to choose correct timestamp?
1027  # note that EOS messages' timestamps are
1028  # set to CLOCK_TIME_NONE so they can't be
1029  # used for this.
1030  try:
1031  # seconds
1032  timestamp = self.rankingstat.segmentlists.extent_all()[1]
1033  except ValueError:
1034  # no segments
1035  return False
1036  # convert to integer nanoseconds
1037  timestamp = LIGOTimeGPS(timestamp).ns()
1038  # terminate all segments
1039  self.segmentstracker.terminate(timestamp)
1040  # NOTE: we do not zero the horizon
1041  # distances in the ranking statistic at EOS
1042  # NOTE: never return True from the EOS code-path,
1043  # so as to not stop the parent class from doing
1044  # EOS-related stuff
1045  return False
1046  return False
1047 
1048 
1049  def load_rankingstat_pdf(self):
1050  # FIXME: if the file can't be accessed the code silently
1051  # disables FAP/FAR assignment. need to figure out when
1052  # failure is OK and when it's not OK and put a better check
1053  # here.
1054  if self.rankingstatpdf_url is not None and os.access(ligolw_utils.local_path_from_url(self.rankingstatpdf_url), os.R_OK):
1055  _, self.rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_url(self.rankingstatpdf_url, verbose = self.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
1056  if self.rankingstatpdf is None:
1057  raise ValueError("\"%s\" does not contain ranking statistic PDFs" % url)
1058  if not self.rankingstat.template_ids <= self.rankingstatpdf.template_ids:
1059  raise ValueError("\"%s\" is for the wrong templates")
1060  if self.rankingstatpdf.is_healthy(self.verbose):
1061  self.fapfar = far.FAPFAR(self.rankingstatpdf.new_with_extinction())
1062  if self.verbose:
1063  print("false-alarm probability and rate assignment ENABLED", file=sys.stderr)
1064  else:
1065  self.fapfar = None
1066  if self.verbose:
1067  print("false-alarm probability and rate assignment DISABLED", file=sys.stderr)
1068  else:
1069  self.rankingstatpdf = None
1070  self.fapfar = None
1071 
1072 
1073  def appsink_new_buffer(self, elem):
1074  with self.lock:
1075  # retrieve triggers from appsink element
1076  buf = elem.emit("pull-sample").get_buffer()
1077  events = []
1078  for i in range(buf.n_memory()):
1079  memory = buf.peek_memory(i)
1080  result, mapinfo = memory.map(Gst.MapFlags.READ)
1081  assert result
1082  # NOTE NOTE NOTE NOTE
1083  # It is critical that the correct class'
1084  # .from_buffer() method be used here. This
1085  # code is interpreting the buffer's
1086  # contents as an array of C structures and
1087  # building instances of python wrappers of
1088  # those structures but if the python
1089  # wrappers are for the wrong structure
1090  # declaration then terrible terrible things
1091  # will happen
1092  # NOTE NOTE NOTE NOTE
1093  # FIXME why does mapinfo.data come out as
1094  # an empty list on some occasions???
1095  if mapinfo.data:
1096  events.extend(SnglInspiral.from_buffer(mapinfo.data))
1097  memory.unmap(mapinfo)
1098 
1099  # FIXME: ugly way to get the instrument
1100  instruments = set([event.ifo for event in events])
1101 
1102  # FIXME calculate a chisq weighted SNR and store it in the bank_chisq column
1103  for event in events:
1104  event.bank_chisq = event.snr / ((1 + max(1., event.chisq)**3)/2.0)**(1./5.)
1105 
1106  # extract segment. move the segment's upper
1107  # boundary to include all triggers. ARGH the 1 ns
1108  # offset is needed for the respective trigger to be
1109  # "in" the segment (segments are open from above)
1110  # FIXME: is there another way?
1111  buf_timestamp = LIGOTimeGPS(0, buf.pts)
1112  buf_seg = dict((instrument, segments.segment(buf_timestamp, max(buf_timestamp + LIGOTimeGPS(0, buf.duration), max(event.end for event in events if event.ifo == instrument) + 0.000000001))) for instrument in instruments)
1113  buf_is_gap = bool(buf.mini_object.flags & Gst.BufferFlags.GAP)
1114  # sanity check that gap buffers are empty
1115  assert not (buf_is_gap and events)
1116 
1117  # safety check end times. we cannot allow triggr
1118  # times to go backwards. they cannot precede the
1119  # buffer's start because, below, streamthinca will
1120  # be told the trigger list is complete upto this
1121  # buffer's time stamp. this logic also requires
1122  # this method to be fed buffers in time order: we
1123  # must never receive a buffer whose timestamp
1124  # precedes the timestamp of a buffer we have
1125  # already received. NOTE: the trigger objects'
1126  # comparison operators can be used for this test
1127  # directly, without explicitly retrieving .end
1128  assert all(event >= buf_timestamp for event in events)
1129 
1130  # assign IDs to triggers. set all effective
1131  # distances to NaN. gstlal_inspiral's effective
1132  # distances are incorrect, and the PE codes require
1133  # us to either provide correct effective distances
1134  # or communicate to them that they are incorrect.
1135  # they have explained that setting them to NaN is
1136  # sufficient for the latter.
1137  # FIXME: fix the effective distances
1138  for event in events:
1139  event.process_id = self.coincs_document.process_id
1140  event.event_id = self.coincs_document.get_next_sngl_id()
1141  event.eff_distance = NaN
1142 
1143  # update likelihood snapshot if needed
1144  if self.likelihood_snapshot_interval is not None and (self.likelihood_snapshot_timestamp is None or buf_timestamp - self.likelihood_snapshot_timestamp >= self.likelihood_snapshot_interval):
1145  self.likelihood_snapshot_timestamp = buf_timestamp
1146 
1147  # post a checkpoint message.
1148  # FIXME: make sure this triggers
1149  # self.snapshot_output_url() to be invoked.
1150  # lloidparts takes care of that for now,
1151  # but spreading the program logic around
1152  # like that isn't a good idea, this code
1153  # should be responsible for it somehow, no?
1154  # NOTE: self.snapshot_output_url() writes
1155  # the current rankingstat object to the
1156  # location identified by
1157  # .ranking_stat_output_url, so if that is
1158  # either not set or at least set to a
1159  # different name than
1160  # .ranking_stat_input_url the file that has
1161  # just been loaded above will not be
1162  # overwritten.
1163  self.pipeline.get_bus().post(message_new_checkpoint(self.pipeline, timestamp = buf_timestamp.ns()))
1164 
1165  # if a ranking statistic source url is set
1166  # and is not the same as the file to which
1167  # we are writing our ranking statistic data
1168  # then overwrite rankingstat with its
1169  # contents. the use case is online
1170  # injection jobs that need to periodically
1171  # grab new ranking statistic data from
1172  # their corresponding non-injection partner
1173  if self.ranking_stat_input_url is not None and self.ranking_stat_input_url != self.ranking_stat_output_url:
1174  params_before = self.rankingstat.template_ids, self.rankingstat.instruments, self.rankingstat.min_instruments, self.rankingstat.delta_t
1175  self.rankingstat, _ = far.parse_likelihood_control_doc(ligolw_utils.load_url(self.ranking_stat_input_url, verbose = self.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
1176  if params_before != (self.rankingstat.template_ids, self.rankingstat.instruments, self.rankingstat.min_instruments, self.rankingstat.delta_t):
1177  raise ValueError("'%s' contains incompatible ranking statistic configuration" % self.ranking_stat_input_url)
1178 
1179  # update streamthinca's ranking statistic
1180  # data
1181  if self.rankingstat.is_healthy(self.verbose):
1182  self.stream_thinca.ln_lr_from_triggers = far.OnlineFrankensteinRankingStat(self.rankingstat, self.rankingstat).finish().ln_lr_from_triggers
1183  if self.verbose:
1184  print("ranking statistic assignment ENABLED", file=sys.stderr)
1185  else:
1186  self.stream_thinca.ln_lr_from_triggers = None
1187  if self.verbose:
1188  print("ranking statistic assignment DISABLED", file=sys.stderr)
1189 
1190  # optionally get updated ranking statistic
1191  # PDF data and enable FAP/FAR assignment
1192  self.load_rankingstat_pdf()
1193 
1194  # add triggers to trigger rate record. this needs
1195  # to be done without any cuts on coincidence, etc.,
1196  # so that the total trigger count agrees with the
1197  # total livetime from the SNR buffers. we assume
1198  # the density of real signals is so small that this
1199  # count is not sensitive to their presence. NOTE:
1200  # this is not true locally. a genuine signal, if
1201  # loud, can significantly increase the local
1202  # density of triggers, therefore the trigger rate
1203  # measurement machinery must take care to average
1204  # the rate over a sufficiently long period of time
1205  # that the rate estimates are insensitive to the
1206  # presence of signals. the current implementation
1207  # averages over whole science segments. NOTE: this
1208  # must be done before running stream thinca (below)
1209  # so that the "how many instruments were on test"
1210  # is aware of this buffer.
1211  if not buf_is_gap:
1212  snr_min = self.rankingstat.snr_min
1213  for instrument in instruments:
1214  # FIXME At the moment, empty triggers are added to
1215  # inform the "how many instruments were on test", the
1216  # correct thing to do is probably to add metadata to
1217  # the buffer containing information about which
1218  # instruments were on
1219  self.rankingstat.denominator.triggerrates[instrument].add_ratebin(list(map(float, buf_seg[instrument])), len([event for event in events if event.snr >= snr_min and event.ifo == instrument]))
1220 
1221  # FIXME At the moment, empty triggers are added to
1222  # inform the "how many instruments were on test", the
1223  # correct thing to do is probably to add metadata to
1224  # the buffer containing information about which
1225  # instruments were on
1226  real_events = []
1227  for event in events:
1228  if event.snr >= snr_min:
1229  real_events.append(event)
1230 
1231  events = real_events
1232 
1233  # run stream thinca.
1234  instruments |= self.absent_instruments
1235  instruments |= self.rankingstat.instruments
1236 
1237  for instrument in instruments:
1238  if not self.stream_thinca.push(instrument, [event for event in events if event.ifo == instrument], buf_timestamp):
1239  continue
1240 
1241  flushed_sngls = self.stream_thinca.pull(self.rankingstat, fapfar = self.fapfar, zerolag_rankingstatpdf = self.zerolag_rankingstatpdf, coinc_sieve = self.rankingstat.fast_path_cut_from_triggers, cluster = self.cluster, cap_singles = self.cap_singles, FAR_trialsfactor = self.FAR_trialsfactor)
1242  self.coincs_document.commit()
1243 
1244  # do GraceDB alerts and update eye candy
1245  self.__do_gracedb_alerts(self.stream_thinca.last_coincs)
1246  self.eye_candy.update(events, self.stream_thinca.last_coincs)
1247 
1248  # after doing alerts, no longer need
1249  # per-trigger SNR data for the triggers
1250  # that are too old to be used to form
1251  # candidates.
1252  for event in flushed_sngls:
1253  del event.H1_snr_time_series
1254  del event.L1_snr_time_series
1255  del event.V1_snr_time_series
1256  del event.K1_snr_time_series
1257 
1258 
1259  def _record_horizon_distance(self, instrument, timestamp, horizon_distance):
1260  """
1261  timestamp can be a float or a slice with float boundaries.
1262  """
1263  # retrieve the horizon history for this instrument
1264  horizon_history = self.rankingstat.numerator.horizon_history[instrument]
1265  # NOTE: timestamps are floats here (or float slices), not
1266  # LIGOTimeGPS. whitener should be reporting PSDs with
1267  # integer timestamps so the timestamps are not naturally
1268  # high precision, and, anyway, we don't need nanosecond
1269  # precision for the horizon distance history.
1270  horizon_history[timestamp] = horizon_distance
1271 
1272 
1273  def record_horizon_distance(self, instrument, timestamp, horizon_distance):
1274  """
1275  timestamp can be a float or a slice with float boundaries.
1276  """
1277  with self.lock:
1278  self._record_horizon_distance(instrument, timestamp, horizon_distance)
1279 
1280 
1281  def horizgatehandler(self, elem, timestamp, instrument_tpl):
1282  """!
1283  A handler that intercepts h(t) gate state transitions to 0
1284  horizon distances.
1285 
1286  @param elem A reference to the lal_gate element or None
1287  (only used for verbosity)
1288  @param timestamp A gstreamer time stamp that marks the
1289  state transition (in nanoseconds)
1290  @param instrument the instrument this state transtion is to
1291  be attributed to, e.g., "H1", etc..
1292  @param new_state the state transition, must be either True
1293  or False
1294  """
1295  # essentially we want to set the horizon distance record to
1296  # 0 at both on-to-off and off-to-on transitions so that the
1297  # horizon distance is reported to be 0 at all times within
1298  # the "off" period. the problem is gaps due to glitch
1299  # excision, which is done using a gate that comes after the
1300  # whitener. the whitener sees data flowing during these
1301  # periods and can report PSDs (and thus trigger horizon
1302  # distances to get recorded) but because of the glitch
1303  # excision the real sensitivity of the instrument is 0.
1304  # there's not much we can do to prevent the PSD from being
1305  # reported, but we try to retroactively correct the problem
1306  # when it occurs by using a slice to re-zero the entire
1307  # "off" interval preceding each off-to-on transition. this
1308  # requires access to the segment data to get the timestamp
1309  # for the start of the off interval, but we could also
1310  # record that number in this class here for our own use if
1311  # the entanglement with the segments tracker becomes a
1312  # problem.
1313  #
1314  # FIXME: there is a potential race condition in that we're
1315  # relying on all spurious PSD messages that we are to
1316  # override with 0 to already have been reported when this
1317  # method gets invoked by the whitehtsegments, i.e., we're
1318  # relying on the whitehtsegments gate to report state
1319  # transitions *after* any potential whitener PSD messages
1320  # have been generated. this is normally guaranteed because
1321  # the whitener does not generate PSD messages during gap
1322  # intervals.
1323 
1324  timestamp = float(LIGOTimeGPS(0, timestamp))
1325  instrument, new_state = instrument_tpl
1326 
1327  if self.verbose:
1328  print("%s: %s horizon distance state transition: %s @ %s" % (elem.get_name(), instrument, ("on" if new_state else "off"), str(timestamp)), file=sys.stderr)
1329 
1330  with self.lock:
1331  # retrieve the horizon history for this instrument
1332  horizon_history = self.rankingstat.numerator.horizon_history[instrument]
1333 
1334  if new_state:
1335  # this if statement is checking if
1336  # ~self.seglistdicts[segtype][instrument]
1337  # is empty, and if not then it zeros the
1338  # interval spanned by the last segment in
1339  # that list, but what's done below avoids
1340  # the explicit segment arithmetic
1341  segtype = "whitehtsegments"
1342  if len(self.segmentstracker.seglistdicts[segtype][instrument]) > 1:
1343  self._record_horizon_distance(instrument, slice(float(self.segmentstracker.seglistdicts[segtype][instrument][-2][-1]), timestamp), 0.)
1344  else:
1345  self._record_horizon_distance(instrument, timestamp, 0.)
1346  elif self.rankingstat.numerator.horizon_history[instrument]:
1347  self._record_horizon_distance(instrument, slice(timestamp, None), 0.)
1348  else:
1349  self._record_horizon_distance(instrument, timestamp, 0.)
1350 
1351 
1352  def checkpoint(self, timestamp):
1353  """!
1354  Checkpoint, e.g., flush segments and triggers to disk.
1355 
1356  @param timestamp the LIGOTimeGPS timestamp of the current
1357  buffer in order to close off open segment intervals before
1358  writing to disk
1359  """
1360  try:
1361  self.snapshot_output_url("%s_LLOID" % self.tag, "xml.gz", verbose = self.verbose)
1362  except TypeError as te:
1363  print("Warning: couldn't build output file on checkpoint, probably there aren't any triggers: %s" % te, file=sys.stderr)
1364  # FIXME: the timestamp is used to close off open segments
1365  # and so should *not* be the timestamp of the current
1366  # buffer, necessarily, but rather a GPS time guaranteed to
1367  # precede any future state transitions of any segment list.
1368  # especially if the pipeline is ever run in an "advanced
1369  # warning" configuration using the GPS time of a trigger
1370  # buffer would be an especially bad choice.
1371  self.segmentstracker.flush_segments_to_disk(self.tag, timestamp)
1372 
1373 
1374  def __get_psd_xmldoc(self):
1375  xmldoc = lal.series.make_psd_xmldoc(self.psds)
1376  process = ligolw_process.register_to_xmldoc(xmldoc, "gstlal_inspiral", {}, instruments = self.psds)
1377  ligolw_process.set_process_end_time(process)
1378  return xmldoc
1379 
1380 
1381  def web_get_psd_xml(self):
1382  with self.lock:
1383  output = io.StringIO()
1384  ligolw_utils.write_fileobj(self.__get_psd_xmldoc(), output)
1385  outstr = output.getvalue()
1386  output.close()
1387  return outstr
1388 
1389 
1390  def __get_rankingstat_xmldoc(self, clipped = False):
1391  # generate a ranking statistic output document. NOTE: if
1392  # we are in possession of ranking statistic PDFs then those
1393  # are included in the output. this allows a single
1394  # document to be uploaded to gracedb. in an online
1395  # analysis, those PDFs come from the marginlization process
1396  # and represent the full distribution of ranking statistics
1397  # across the search, and include with them the analysis'
1398  # total observed zero-lag ranking statistic histogram ---
1399  # everything required to re-evaluate the FAP and FAR for an
1400  # uploaded candidate.
1401  xmldoc = ligolw.Document()
1402  xmldoc.appendChild(ligolw.LIGO_LW())
1403  process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral", paramdict = {}, instruments = self.rankingstat.instruments)
1404  # FIXME: don't do this. find a way to reduce the storage
1405  # requirements of the horizon distance history and then go
1406  # back to uploading the full file to gracedb
1407  if clipped:
1408  rankingstat = self.rankingstat.copy()
1409  try:
1410  endtime = rankingstat.numerator.horizon_history.maxkey()
1411  except ValueError:
1412  # empty horizon history
1413  pass
1414  else:
1415  # keep the last hour of history
1416  endtime -= 3600. * 1
1417  for history in rankingstat.numerator.horizon_history.values():
1418  del history[:endtime]
1419  else:
1420  rankingstat = self.rankingstat
1421  far.gen_likelihood_control_doc(xmldoc, rankingstat, self.rankingstatpdf)
1422  ligolw_process.set_process_end_time(process)
1423  return xmldoc
1424 
1425  def __get_p_astro_json(self, lr, m1, m2, snr, far):
1426  return p_astro_gstlal.compute_p_astro(lr, m1, m2, snr, far, self.rankingstatpdf.copy(), activation_counts = self.activation_counts)
1427 
1428  def __get_rankingstat_xmldoc_for_gracedb(self):
1429  # FIXME: remove this wrapper when the horizon history
1430  # encoding is replaced with something that uses less space
1431  return self.__get_rankingstat_xmldoc(clipped = True)
1432 
1433 
1434  def web_get_rankingstat(self):
1435  with self.lock:
1436  output = io.BytesIO()
1437  ligolw_utils.write_fileobj(self.__get_rankingstat_xmldoc(), output)
1438  outstr = output.getvalue()
1439  output.close()
1440  return outstr
1441 
1442 
1443  def __get_zerolag_rankingstatpdf_xmldoc(self):
1444  xmldoc = ligolw.Document()
1445  xmldoc.appendChild(ligolw.LIGO_LW())
1446  process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral", paramdict = {}, instruments = self.rankingstat.instruments)
1448  ligolw_process.set_process_end_time(process)
1449  return xmldoc
1450 
1451 
1452  def web_get_zerolag_rankingstatpdf(self):
1453  with self.lock:
1454  output = io.BytesIO()
1455  ligolw_utils.write_fileobj(self.__get_zerolag_rankingstatpdf_xmldoc(), output)
1456  outstr = output.getvalue()
1457  output.close()
1458  return outstr
1459 
1460 
1461  def __flush(self):
1462  # run StreamThinca in flush mode. forms candidates from
1463  # whatever triggers remain in the queues, and processes
1464  # them
1465 
1466  flushed_sngls = self.stream_thinca.pull(self.rankingstat, fapfar = self.fapfar, zerolag_rankingstatpdf = self.zerolag_rankingstatpdf, coinc_sieve = self.rankingstat.fast_path_cut_from_triggers, flush = True, cluster = self.cluster, cap_singles = self.cap_singles, FAR_trialsfactor = self.FAR_trialsfactor)
1467  self.coincs_document.commit()
1468 
1469  # do GraceDB alerts
1470  self.__do_gracedb_alerts(self.stream_thinca.last_coincs)
1471 
1472  # after doing alerts, no longer need per-trigger SNR data
1473  # for the triggers that are too old to be used to form
1474  # candidates.
1475  for event in flushed_sngls:
1476  del event.H1_snr_time_series
1477  del event.L1_snr_time_series
1478  del event.V1_snr_time_series
1479  del event.K1_snr_time_series
1480 
1481 
1482  def __do_gracedb_alerts(self, last_coincs):
1483  # check for no-op
1484  if self.rankingstatpdf is None or not self.rankingstatpdf.is_healthy():
1485  return
1486  # sanity check. all code paths that result in an
1487  # initialized and healthy rankingstatpdf object also
1488  # initialize a fapfar object from it; this is here to make
1489  # sure that remains true
1490  assert self.fapfar is not None
1491 
1492  # do alerts
1493  self.gracedbwrapper.do_alerts(last_coincs, self.psds, self.__get_rankingstat_xmldoc_for_gracedb, self.segmentstracker.seglistdicts, self.__get_p_astro_json)
1494 
1495 
1496  def web_get_sngls_snr_threshold(self):
1497  with self.lock:
1498  if self.stream_thinca.sngls_snr_threshold is not None:
1499  yield "snr=%.17g\n" % self.stream_thinca.sngls_snr_threshold
1500  else:
1501  yield "snr=\n"
1502 
1503 
1504  def web_set_sngls_snr_threshold(self):
1505  try:
1506  with self.lock:
1507  snr_threshold = bottle.request.forms["snr"]
1508  if snr_threshold:
1509  self.stream_thinca.sngls_snr_threshold = float(snr_threshold)
1510  yield "OK: snr=%.17g\n" % self.stream_thinca.sngls_snr_threshold
1511  else:
1512  self.stream_thinca.sngls_snr_threshold = None
1513  yield "OK: snr=\n"
1514  except:
1515  yield "error\n"
1516 
1517 
1518  def __write_output_url(self, url = None, verbose = False):
1519  self.__flush()
1520  if url is not None:
1521  self.coincs_document.url = url
1522  with self.segmentstracker.lock:
1523  self.coincs_document.write_output_url(seglistdicts = self.segmentstracker.seglistdicts, verbose = verbose)
1524  # can't be used anymore
1525  del self.coincs_document
1526 
1527 
1528  def __write_ranking_stat_url(self, url, description, snapshot = False, verbose = False):
1529  # write the ranking statistic file.
1530  ligolw_utils.write_url(self.__get_rankingstat_xmldoc(), url, verbose = verbose, trap_signals = None)
1531  # Snapshots get their own custom file and path
1532  if snapshot:
1533  fname = self.segmentstracker.T050017_filename(description + '_DISTSTATS', 'xml.gz')
1534  shutil.copy(ligolw_utils.local_path_from_url(url), os.path.join(subdir_from_T050017_filename(fname), fname))
1535 
1536 
1537  def write_output_url(self, url = None, description = "", verbose = False):
1538  with self.lock:
1539  if self.ranking_stat_output_url is not None:
1540  self.__write_ranking_stat_url(self.ranking_stat_output_url, description, verbose = verbose)
1541  self.__write_output_url(url = url, verbose = verbose)
1542 
1543 
1544  def snapshot_output_url(self, description, extension, verbose = False):
1545  with self.lock:
1546  fname = self.segmentstracker.T050017_filename(description, extension)
1547  fname = os.path.join(subdir_from_T050017_filename(fname), fname)
1548  if self.ranking_stat_output_url is not None:
1549  self.__write_ranking_stat_url(self.ranking_stat_output_url, description, snapshot = True, verbose = verbose)
1550  if self.zerolag_rankingstatpdf_url is not None:
1551  ligolw_utils.write_url(self.__get_zerolag_rankingstatpdf_xmldoc(), self.zerolag_rankingstatpdf_url, verbose = verbose, trap_signals = None)
1552  coincs_document = self.coincs_document.get_another()
1553  self.__write_output_url(url = fname, verbose = verbose)
1554  self.coincs_document = coincs_document
1555  # NOTE: this operation requires stream_thinca to
1556  # have been flushed by calling .pull() with flush =
1557  # True. the .__write_output_url() code path does
1558  # that, but there is no check here to ensure that
1559  # remains true so be careful if you are editing
1560  # these methods.
1561  self.stream_thinca.set_xmldoc(self.coincs_document.xmldoc, self.coincs_document.process_id)
def __get_zerolag_rankingstatpdf_xmldoc
def flush_segments_to_disk
Flush segments to disk, e.g., when checkpointing or shutting down an online pipeline.
def web_get_recent_segment_history_xml
provide a bottle route to get recent segment history information via a url
A subclass of simplehandler.Handler to be used with e.g., gstlal_inspiral.
def __get_rankingstat_xmldoc_for_gracedb
def __latencyhandler
A handler that intercepts pipeline latency calls.
def __T050017_filename
Must be called with the lock held.
def web_get_segments_xml
provide a bottle route to get segment information via a url
def __gatehandler
A handler that intercepts gate state transitions.
def horizgatehandler
A handler that intercepts h(t) gate state transitions to 0 horizon distances.
def now
Definition: inspiral.py:116
def update_recent_segment_history
A method to update the recent segment histories.
def do_on_message
Handle application-specific message types, e.g., spectrum and checkpointing messages.
def checkpoint
Checkpoint, e.g., flush segments and triggers to disk.
def gen_recent_segment_history_xmldoc
Construct and return a LIGOLW XML tree containing the recent segment histories.
def parse_likelihood_control_doc
Definition: far.py:1024
def gen_segments_xmldoc
A method to output the segment list in a valid ligolw xml format.
def gen_likelihood_control_doc
Definition: far.py:1010