gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
streamthinca.py
Go to the documentation of this file.
1 # Copyright (C) 2011--2019 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 ## @file
18 # The python module to implement streaming coincidence
19 #
20 # ### Review Status
21 #
22 # STATUS: reviewed with actions
23 #
24 # | Names | Hash | Date | Diff to Head of Master |
25 # | ------------------------------------------- | ------------------------------------------- | ---------- | --------------------------- |
26 # | Kipp Cannon, Chad Hanna, Jolien Creighton, Florent Robinet, B. Sathyaprakash, Duncan Meacher, T.G.G. Li | b8fef70a6bafa52e3e120a495ad0db22007caa20 | 2014-12-03 | <a href="@gstlal_inspiral_cgit_diff/python/streamthinca.py?id=HEAD&id2=b8fef70a6bafa52e3e120a495ad0db22007caa20">streamthinca.py</a> |
27 # | Kipp Cannon, Chad Hanna, Jolien Creighton, B. Sathyaprakash, Duncan Meacher | 72875f5cb241e8d297cd9b3f9fe309a6cfe3f716 | 2015-11-06 | <a href="@gstlal_inspiral_cgit_diff/python/streamthinca.py?id=HEAD&id2=72875f5cb241e8d297cd9b3f9fe309a6cfe3f716">streamthinca.py</a> |
28 #
29 # #### Action items
30 #
31 # - Question: Is it possible for the offline pipeline to begin producing tiggers after a certain time rather than waiting for all the inspiral jobs to get over? Will be particularly useful if the data length is ~ months or ~ year. Should also avoid producing massive amount of data, right?
32 # - L300+: Please document within the code that the FAR column is used to store FAP so that future developers don't get confused what that column represents
33 
34 
35 #
36 # =============================================================================
37 #
38 # Preamble
39 #
40 # =============================================================================
41 #
42 
43 
44 import time
45 
46 
47 from ligo.lw import ligolw
48 from ligo.lw import lsctables
49 import lal
50 from lalburst import snglcoinc
51 from lalinspiral import thinca
52 from ligo import segments
53 from ligo.segments import utils as segmentsUtils
54 
55 
56 #
57 # =============================================================================
58 #
59 # last_coincs helper
60 #
61 # =============================================================================
62 #
63 
64 
65 #
66 # the last_coincs machine, which is used to construct documents for upload
67 # to gracedb, used to be implemented by a class in thinca.py which was
68 # originally written for this purpose. when the coincidence engine
69 # switched to a native streaming design, that older implementation was no
70 # longer suitable because it indexes the entire document. we have had to
71 # replace that implementation with this, here. the old one is now unused,
72 # but it's potentially useful so it has been left behind and this one put
73 # here instead.
74 #
75 
76 
77 class last_coincs(object):
78  def __init__(self, xmldoc):
79  #
80  # find all tables
81  #
82 
83  self.process_table = lsctables.ProcessTable.get_table(xmldoc)
84  self.process_params_table = lsctables.ProcessParamsTable.get_table(xmldoc)
85  self.sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
86  self.coinc_def_table = lsctables.CoincDefTable.get_table(xmldoc)
87  self.coinc_event_table = lsctables.CoincTable.get_table(xmldoc)
88  self.coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(xmldoc)
89  self.coinc_event_map_table = lsctables.CoincMapTable.get_table(xmldoc)
90  self.time_slide_table = lsctables.TimeSlideTable.get_table(xmldoc)
91 
92  #
93  # index the process, process params, and time_slide tables
94  #
95 
96  self.process_index = dict((row.process_id, row) for row in self.process_table)
97  self.process_params_index = {}
98  for row in self.process_params_table:
99  self.process_params_index.setdefault(row.process_id, []).append(row)
100  self.time_slide_index = {}
101  for row in self.time_slide_table:
102  self.time_slide_index.setdefault(row.time_slide_id, []).append(row)
103 
104  #
105  # find the sngl_inspiral<-->sngl_inspiral coinc_definer
106  #
107 
108  self.coinc_def, = (row for row in self.coinc_def_table if row.search == thinca.InspiralCoincDef.search and row.search_coinc_type == thinca.InspiralCoincDef.search_coinc_type)
109 
110  #
111  # coinc event metadata
112  #
113 
114  self.sngl_inspiral_index = {}
115  self.coinc_event_index = {}
116  self.coinc_event_maps_index = {}
117  self.coinc_inspiral_index = {}
118 
119 
120  def add(self, events, coinc, coincmaps, coinc_inspiral):
121  # FIXME: these checks might be over-doing it. I just
122  # don't want any surprises, but maybe when we are confident
123  # the code works they should be removed
124  assert coinc.coinc_def_id == self.coinc_def.coinc_def_id
125  assert coinc.coinc_event_id == coinc_inspiral.coinc_event_id
126  assert coinc.process_id in self.process_index
127  assert coinc.time_slide_id in self.time_slide_index
128  assert all(event.process_id == coinc.process_id for event in events)
129  assert all(coinc_event_map.coinc_event_id == coinc.coinc_event_id for coinc_event_map in coincmaps)
130  assert set(event.event_id for event in events) == set(coinc_event_map.event_id for coinc_event_map in coincmaps)
131  self.sngl_inspiral_index[coinc.coinc_event_id] = events
132  self.coinc_event_index[coinc.coinc_event_id] = coinc
133  self.coinc_event_maps_index[coinc.coinc_event_id] = coincmaps
134  self.coinc_inspiral_index[coinc.coinc_event_id] = coinc_inspiral
135 
136 
137  def clear(self):
138  self.sngl_inspiral_index.clear()
139  self.coinc_event_index.clear()
140  self.coinc_event_maps_index.clear()
141  self.coinc_inspiral_index.clear()
142 
143 
144  def sngl_inspirals(self, coinc_event_id):
145  return self.sngl_inspiral_index[coinc_event_id]
146 
147 
148  def __iter__(self):
149  return iter(self.coinc_event_index)
150 
151 
152  def __bool__(self):
153  return bool(self.coinc_event_index)
154 
155 
156  def __getitem__(self, coinc_event_id):
157  newxmldoc = ligolw.Document()
158  ligolw_elem = newxmldoc.appendChild(ligolw.LIGO_LW())
159 
160  # when making these, we can't use .copy() method of Table
161  # instances because we need to ensure we have a Table
162  # subclass, not a DBTable subclass
163  new_process_table = ligolw_elem.appendChild(lsctables.New(lsctables.ProcessTable, self.process_table.columnnamesreal))
164  new_process_params_table = ligolw_elem.appendChild(lsctables.New(lsctables.ProcessParamsTable, self.process_params_table.columnnamesreal))
165  new_sngl_inspiral_table = ligolw_elem.appendChild(lsctables.New(lsctables.SnglInspiralTable, self.sngl_inspiral_table.columnnamesreal))
166  new_coinc_def_table = ligolw_elem.appendChild(lsctables.New(lsctables.CoincDefTable, self.coinc_def_table.columnnamesreal))
167  new_coinc_event_table = ligolw_elem.appendChild(lsctables.New(lsctables.CoincTable, self.coinc_event_table.columnnamesreal))
168  new_coinc_inspiral_table = ligolw_elem.appendChild(lsctables.New(lsctables.CoincInspiralTable, self.coinc_inspiral_table.columnnamesreal))
169  new_coinc_event_map_table = ligolw_elem.appendChild(lsctables.New(lsctables.CoincMapTable, self.coinc_event_map_table.columnnamesreal))
170  new_time_slide_table = ligolw_elem.appendChild(lsctables.New(lsctables.TimeSlideTable, self.time_slide_table.columnnamesreal))
171 
172  new_coinc_def_table.append(self.coinc_def)
173  coincevent = self.coinc_event_index[coinc_event_id]
174  new_time_slide_table.extend(self.time_slide_index[coincevent.time_slide_id])
175 
176  new_sngl_inspiral_table.extend(self.sngl_inspiral_index[coinc_event_id])
177  new_coinc_event_table.append(coincevent)
178  new_coinc_event_map_table.extend(self.coinc_event_maps_index[coinc_event_id])
179  new_coinc_inspiral_table.append(self.coinc_inspiral_index[coinc_event_id])
180 
181  for process_id in set(new_sngl_inspiral_table.getColumnByName("process_id")) | set(new_coinc_event_table.getColumnByName("process_id")) | set(new_time_slide_table.getColumnByName("process_id")):
182  # process row is required
183  new_process_table.append(self.process_index[process_id])
184  try:
185  new_process_params_table.extend(self.process_params_index[process_id])
186  except KeyError:
187  # process_params rows are optional
188  pass
189 
190  return newxmldoc
191 
192 
193 #
194 # =============================================================================
195 #
196 # StreamThinca
197 #
198 # =============================================================================
199 #
200 
201 
202 class backgroundcollector(object):
203  def __init__(self):
204  self.zerolag_singles = set()
205  self.timeshifted_coincs = set()
206 
207  def push(self, event_ids, offset_vector):
208  if any(offset_vector.values()):
209  if len(event_ids) > 1:
210  self.timeshifted_coincs.update(event_ids)
211  elif len(event_ids) == 1:
212  self.zerolag_singles.update(event_ids)
213 
214  def pull(self, snr_min, two_or_more_instruments, flushed_events):
215  index = dict((id(event), event) for event in flushed_events)
216  flushed_ids = set(index)
217  background_ids = self.timeshifted_coincs & flushed_ids
218  self.timeshifted_coincs -= flushed_ids
219  background_ids |= set(event_id for event_id in self.zerolag_singles & flushed_ids if float(index[event_id].end) in two_or_more_instruments)
220  self.zerolag_singles -= flushed_ids
221  return [event for event in map(index.__getitem__, background_ids) if event.snr >= snr_min]
222 
223 
224 class StreamThinca(object):
225  def __init__(self, xmldoc, process_id, delta_t, min_instruments = 2, sngls_snr_threshold = None):
226  self.ln_lr_from_triggers = None
227  self.delta_t = delta_t
228  self.min_instruments = min_instruments
229  self.sngls_snr_threshold = sngls_snr_threshold
230  self.set_xmldoc(xmldoc, process_id)
231  self.clustered_sngl_ids = set()
232 
233 
234  def set_xmldoc(self, xmldoc, process_id):
235  self.coinc_tables = thinca.InspiralCoincTables(xmldoc, thinca.InspiralCoincDef)
236  self.sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
237  self.last_coincs = last_coincs(xmldoc)
238  self.process_id = process_id
239  self.time_slide_graph = snglcoinc.TimeSlideGraph(
240  thinca.coincgen_doubles,
241  lsctables.TimeSlideTable.get_table(xmldoc).as_dict(),
242  self.delta_t,
243  min_instruments = self.min_instruments
244  )
246 
247 
248  def push(self, instrument, events, t_complete):
249  """
250  Push new triggers into the coinc engine. Returns True if
251  the coinc engine's internal state has changed in a way that
252  might enable new candidates to be constructed, False if
253  not.
254  """
255  return self.time_slide_graph.push(instrument, events, t_complete)
256 
257 
258  def pull(self, rankingstat, fapfar = None, zerolag_rankingstatpdf = None, coinc_sieve = None, flush = False, cluster = False, cap_singles = False, FAR_trialsfactor = 1.0):
259  # NOTE: rankingstat is not used to compute the ranking
260  # statistic, it supplies the detector livetime segment
261  # lists to determine which triggers are eligible for
262  # inclusion in the background model and is the destination
263  # for triggers identified for inclusion in the background
264  # model. self.ln_lr_from_triggers is the ranking statistic
265  # function (if set).
266 
267  # extract times when instruments were producing SNR. used
268  # to define "on instruments" for coinc tables, as a safety
269  # check for impossible triggers, and to identify triggers
270  # suitable for use in defining the background PDFs. will
271  # only need segment information for the times for which the
272  # queues will yield triggers, so use a bisection search to
273  # clip the lists to reduce subsequent operation count.
274 
275  age = float(self.time_slide_graph.age)
276  snr_segments = segments.segmentlistdict((instrument, ratebinlist[ratebinlist.value_slice_to_index(slice(age, None))].segmentlist()) for instrument, ratebinlist in rankingstat.denominator.triggerrates.items())
277 
278  #
279  # iterate over coincidences
280  #
281 
282  gps_time_now = float(lal.UTCToGPS(time.gmtime()))
283  newly_reported = []
284  flushed = []
285  flushed_unused = []
286  self.last_coincs.clear()
287  max_last_coinc_snr = {}
288  for node, events in self.time_slide_graph.pull(newly_reported = newly_reported, flushed = flushed, flushed_unused = flushed_unused, coinc_sieve = coinc_sieve, event_collector = self.backgroundcollector, flush = flush):
289  # construct row objects for coinc tables.
290 
291  coinc, coincmaps, coinc_inspiral = self.coinc_tables.coinc_rows(self.process_id, node.time_slide_id, events, seglists = snr_segments)
292 
293  # some tasks for zero-lag candidates
294 
295  if node.is_zero_lag:
296  # populate ranking statistic's zero-lag
297  # PDFs with triggers from all zero-lag
298  # candidates
299 
300  for event in events:
301  rankingstat.zerolag.increment(event)
302 
303  # latency goes in minimum_duration column. NOTE:
304  # latency is nonsense unless running live. FIXME:
305  # add a proper column for latency
306 
307  coinc_inspiral.minimum_duration = gps_time_now - float(coinc_inspiral.end)
308 
309  # finally, append coinc to tables
310 
311  if cluster:
312  max_last_coinc_snr.setdefault(node, None)
313  if max_last_coinc_snr[node] is None or coinc_inspiral.snr > max_last_coinc_snr[node][3].snr:
314  max_last_coinc_snr[node] = (events, coinc, coincmaps, coinc_inspiral)
315  else:
316  self.coinc_tables.append_coinc(coinc, coincmaps, coinc_inspiral)
317 
318  # add events to the zero-lag ranking
319  # statistic histogram
320 
321  if zerolag_rankingstatpdf is not None and coinc.likelihood is not None:
322  zerolag_rankingstatpdf.zero_lag_lr_lnpdf.count[coinc.likelihood,] += 1
323 
324  self.last_coincs.add(events, coinc, coincmaps, coinc_inspiral)
325 
326 
327  for node in max_last_coinc_snr:
328  if max_last_coinc_snr[node] is not None:
329  events, coinc, coincmaps, coinc_inspiral = max_last_coinc_snr[node]
330  # assign ranking statistic, FAP and FAR
331  if self.ln_lr_from_triggers is not None:
332  coinc.likelihood = self.ln_lr_from_triggers(events, node.offset_vector)
333  if fapfar is not None:
334  # FIXME: add proper columns to
335  # store these values in
336  coinc_inspiral.combined_far = fapfar.far_from_rank(coinc.likelihood) * FAR_trialsfactor
337  if len(events) == 1 and cap_singles and coinc_inspiral.combined_far < 1. / fapfar.livetime:
338  coinc_inspiral.combined_far = 1. / fapfar.livetime
339  coinc_inspiral.false_alarm_rate = fapfar.fap_from_rank(coinc.likelihood)
340  if zerolag_rankingstatpdf is not None and coinc.likelihood is not None:
341  zerolag_rankingstatpdf.zero_lag_lr_lnpdf.count[coinc.likelihood,] += 1
342 
343  self.coinc_tables.append_coinc(coinc, coincmaps, coinc_inspiral)
344  self.last_coincs.add(events, coinc, coincmaps, coinc_inspiral)
345  self.sngl_inspiral_table.extend([sngl_trigger for sngl_trigger in events if sngl_trigger.event_id not in self.clustered_sngl_ids])
346  self.clustered_sngl_ids |= set(e.event_id for e in events)
347 
348 
349  # add selected singles to the noise model
350 
351  if flushed:
352  # times when at least 2 instruments were generating
353  # SNR. used to select zero-lag singles for
354  # inclusion in the denominator.
355 
356  two_or_more_instruments = segmentsUtils.vote(snr_segments.values(), 2)
357  # FIXME: this is needed to work around rounding
358  # problems in safety checks below, trying to
359  # compare GPS trigger times to float segment
360  # boundaries (the boundaries don't have enough
361  # precision to know if triggers near the edge are
362  # in or out). it would be better not to have to
363  # screw around like this.
364  two_or_more_instruments.protract(1e-3) # 1 ms
365 
366  for event in self.backgroundcollector.pull(rankingstat.snr_min, two_or_more_instruments, flushed):
367  rankingstat.denominator.increment(event)
368 
369  # add any triggers that have been used in coincidences for
370  # the first time to the sngl_inspiral table
371  # FIXME: because this information comes from the
372  # coincidence code, which is not aware of the clustering,
373  # we record a lot of singles that aren't really used for
374  # any (retained) coincs.
375 
376  if not cluster:
377  self.sngl_inspiral_table.extend(newly_reported)
378 
379  # save all sngls above the requested sngls SNR threshold.
380  # all sngls that participated in coincs are already in the
381  # document, so only need to check for ones being flushed
382  # and that were never used.
383 
384  if self.sngls_snr_threshold is not None:
385  self.sngl_inspiral_table.extend(event for event in flushed_unused if event.snr >= self.sngls_snr_threshold)
386 
387  # return the triggers that have been flushed
388  return flushed