gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
inspiral.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 # The python module to implement things needed by gstlal_inspiral
20 #
21 # ### Review Status
22 #
23 # STATUS: reviewed with actions
24 #
25 # | Names | Hash | Date | Diff to Head of Master |
26 # | ------------------------------------------- | ------------------------------------------- | ---------- | -------- |
27 # | 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/inspiral.py?id=HEAD&id2=b8fef70a6bafa52e3e120a495ad0db22007caa20">inspiral.py</a> |
28 # | Kipp Cannon, Chad Hanna, Jolien Creighton, B. Sathyaprakash, Duncan Meacher | 72875f5cb241e8d297cd9b3f9fe309a6cfe3f716 | 2015-11-06 | <a href="@gstlal_inspiral_cgit_diff/python/inspiral.py?id=HEAD&id2=72875f5cb241e8d297cd9b3f9fe309a6cfe3f716">inspiral.py</a> |
29 #
30 # #### Action items
31 # - Document examples of how to get SNR history, etc., to a web browser in an offline search
32 # - Long term goal: Using template duration (rather than chirp mass) should load balance the pipeline and improve statistics
33 # - L651: One thing to sort out is the signal probability while computing coincs
34 # - L640-L647: Get rid of obsolete comments
35 # - L667: Make sure timeslide events are not sent to GRACEDB
36 # - Lxxx: Can normalisation of the tail of the distribution pre-computed using fake data?
37 # - L681: fmin should not be hard-coded to 10 Hz. horizon_distance will be horribly wrong if psd is constructed, e.g. using some high-pass filter. For example, change the default to 40 Hz.
38 # - L817: If gracedb upload failed then it should be possible to identify the failure, the specifics of the trigger that encountered failure and a way of submitting the trigger again to gracedb is important. Think about how to clean-up failures.
39 # - Mimick gracedb upload failures and see if the code crashes
40 
41 
42 ## @package inspiral
43 
44 #
45 # =============================================================================
46 #
47 # Preamble
48 #
49 # =============================================================================
50 #
51 
52 
53 import json
54 import math
55 import numpy
56 from scipy import random
57 import sqlite3
58 import io
59 import sys
60 import time
61 import http.client
62 import tempfile
63 import os
64 from urllib.parse import urlparse
65 
66 from ligo.lw import ligolw
67 from ligo.lw import dbtables
68 from ligo.lw import ilwd
69 from ligo.lw import lsctables
70 from ligo.lw import array as ligolw_array
71 from ligo.lw import param as ligolw_param
72 from ligo.lw import utils as ligolw_utils
73 from ligo.lw.utils import ligolw_sqlite
74 from ligo.lw.utils import ligolw_add
75 from ligo.lw.utils import process as ligolw_process
76 from ligo.lw.utils import segments as ligolw_segments
77 from ligo.lw.utils import time_slide as ligolw_time_slide
78 import lal
79 from lal import iterutils
80 from lal import LIGOTimeGPS
81 from lal import series as lalseries
82 from lalburst.snglcoinc import light_travel_time
83 import ligo.gracedb.rest
84 from ligo import gracedb
85 
86 
87 from gstlal import bottle
88 from gstlal import ilwdify
89 from gstlal import svd_bank
90 
91 
92 #
93 # =============================================================================
94 #
95 # ligo.lw Content Handlers
96 #
97 # =============================================================================
98 #
99 
100 
101 @ligolw_array.use_in
102 @ligolw_param.use_in
103 @lsctables.use_in
104 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
105  pass
106 
107 
108 #
109 # =============================================================================
110 #
111 # Misc
112 #
113 # =============================================================================
114 #
115 
116 
117 def now():
118  return LIGOTimeGPS(lal.UTCToGPS(time.gmtime()))
119 
120 
121 def parse_svdbank_string(bank_string):
122  """
123  parses strings of form
124 
125  H1:bank1.xml,H2:bank2.xml,L1:bank3.xml
126 
127  into a dictionary of lists of bank files.
128  """
129  out = {}
130  if bank_string is None:
131  return out
132  for b in bank_string.split(','):
133  ifo, bank = b.split(':')
134  if ifo in out:
135  raise ValueError("Only one svd bank per instrument should be given")
136  out[ifo] = bank
137  return out
138 
139 
140 def parse_bank_files(svd_banks, verbose, snr_threshold = None):
141  """
142  given a dictionary of lists of svd template bank file names parse them
143  into a dictionary of bank classes
144  """
145 
146  banks = {}
147 
148  for instrument, filename in svd_banks.items():
149  for n, bank in enumerate(svd_bank.read_banks(filename, contenthandler = LIGOLWContentHandler, verbose = verbose)):
150  # Write out sngl inspiral table to temp file for
151  # trigger generator
152  # FIXME teach the trigger generator to get this
153  # information a better way
154  bank.template_bank_filename = tempfile.NamedTemporaryFile(suffix = ".xml.gz", delete = False).name
155  xmldoc = ligolw.Document()
156  # FIXME if this table reference is from a DB this
157  # is a problem (but it almost certainly isn't)
158  xmldoc.appendChild(ligolw.LIGO_LW()).appendChild(bank.sngl_inspiral_table.copy()).extend(bank.sngl_inspiral_table)
159  ligolw_utils.write_filename(xmldoc, bank.template_bank_filename, verbose = verbose)
160  xmldoc.unlink() # help garbage collector
161  bank.logname = "%sbank%d" % (instrument, n)
162  banks.setdefault(instrument, []).append(bank)
163  if snr_threshold is not None:
164  bank.snr_threshold = snr_threshold
165 
166  # FIXME remove when this is no longer an issue
167  if not banks:
168  raise ValueError("Could not parse bank files into valid bank dictionary.\n\t- Perhaps you are using out-of-date svd bank files? Please ensure that they were generated with the same code version as the parsing code")
169  return banks
170 
171 
172 def set_common_snglinspiral_values(sngl_inspiral_table):
173  sngl_inspiral_table[-1].search = sngl_inspiral_table[0].search
174  sngl_inspiral_table[-1].impulse_time = sngl_inspiral_table[0].impulse_time
175  sngl_inspiral_table[-1].impulse_time_ns = sngl_inspiral_table[0].impulse_time_ns
176  sngl_inspiral_table[-1].template_duration = sngl_inspiral_table[0].template_duration
177  sngl_inspiral_table[-1].event_duration = sngl_inspiral_table[0].event_duration
178  sngl_inspiral_table[-1].amplitude = sngl_inspiral_table[0].amplitude
179  sngl_inspiral_table[-1].mass1 = sngl_inspiral_table[0].mass1
180  sngl_inspiral_table[-1].mass2 = sngl_inspiral_table[0].mass2
181  sngl_inspiral_table[-1].mchirp = sngl_inspiral_table[0].mchirp
182  sngl_inspiral_table[-1].mtotal = sngl_inspiral_table[0].mtotal
183  sngl_inspiral_table[-1].eta = sngl_inspiral_table[0].eta
184  sngl_inspiral_table[-1].kappa = sngl_inspiral_table[0].kappa
185  sngl_inspiral_table[-1].chi = sngl_inspiral_table[0].chi
186  sngl_inspiral_table[-1].tau0 = sngl_inspiral_table[0].tau0
187  sngl_inspiral_table[-1].tau2 = sngl_inspiral_table[0].tau2
188  sngl_inspiral_table[-1].tau3 = sngl_inspiral_table[0].tau3
189  sngl_inspiral_table[-1].tau4 = sngl_inspiral_table[0].tau4
190  sngl_inspiral_table[-1].tau5 = sngl_inspiral_table[0].tau5
191  sngl_inspiral_table[-1].ttotal = sngl_inspiral_table[0].ttotal
192  sngl_inspiral_table[-1].psi0 = sngl_inspiral_table[0].psi0
193  sngl_inspiral_table[-1].psi3 = sngl_inspiral_table[0].psi3
194  sngl_inspiral_table[-1].alpha = sngl_inspiral_table[0].alpha
195  sngl_inspiral_table[-1].alpha1 = sngl_inspiral_table[0].alpha1
196  sngl_inspiral_table[-1].alpha2 = sngl_inspiral_table[0].alpha2
197  sngl_inspiral_table[-1].alpha3 = sngl_inspiral_table[0].alpha3
198  sngl_inspiral_table[-1].alpha4 = sngl_inspiral_table[0].alpha4
199  sngl_inspiral_table[-1].alpha5 = sngl_inspiral_table[0].alpha5
200  sngl_inspiral_table[-1].alpha6 = sngl_inspiral_table[0].alpha6
201  sngl_inspiral_table[-1].beta = sngl_inspiral_table[0].beta
202  sngl_inspiral_table[-1].f_final = sngl_inspiral_table[0].f_final
203  sngl_inspiral_table[-1].chisq_dof = sngl_inspiral_table[0].chisq_dof
204  sngl_inspiral_table[-1].bank_chisq = sngl_inspiral_table[0].bank_chisq
205  sngl_inspiral_table[-1].bank_chisq_dof = sngl_inspiral_table[0].bank_chisq_dof
206  sngl_inspiral_table[-1].cont_chisq = sngl_inspiral_table[0].cont_chisq
207  sngl_inspiral_table[-1].cont_chisq_dof = sngl_inspiral_table[0].cont_chisq_dof
208  sngl_inspiral_table[-1].sigmasq = sngl_inspiral_table[0].sigmasq
209  sngl_inspiral_table[-1].rsqveto_duration = sngl_inspiral_table[0].rsqveto_duration
210  sngl_inspiral_table[-1].Gamma0 = sngl_inspiral_table[0].Gamma0
211  sngl_inspiral_table[-1].Gamma1 = sngl_inspiral_table[0].Gamma1
212  sngl_inspiral_table[-1].Gamma2 = sngl_inspiral_table[0].Gamma2
213  sngl_inspiral_table[-1].Gamma3 = sngl_inspiral_table[0].Gamma3
214  sngl_inspiral_table[-1].Gamma4 = sngl_inspiral_table[0].Gamma4
215  sngl_inspiral_table[-1].Gamma5 = sngl_inspiral_table[0].Gamma5
216  sngl_inspiral_table[-1].Gamma6 = sngl_inspiral_table[0].Gamma6
217  sngl_inspiral_table[-1].Gamma7 = sngl_inspiral_table[0].Gamma7
218  sngl_inspiral_table[-1].Gamma8 = sngl_inspiral_table[0].Gamma8
219  sngl_inspiral_table[-1].Gamma9 = sngl_inspiral_table[0].Gamma9
220  sngl_inspiral_table[-1].spin1x = sngl_inspiral_table[0].spin1x
221  sngl_inspiral_table[-1].spin1y = sngl_inspiral_table[0].spin1y
222  sngl_inspiral_table[-1].spin1z = sngl_inspiral_table[0].spin1z
223  sngl_inspiral_table[-1].spin2x = sngl_inspiral_table[0].spin2x
224  sngl_inspiral_table[-1].spin2y = sngl_inspiral_table[0].spin2y
225  sngl_inspiral_table[-1].spin2z = sngl_inspiral_table[0].spin2z
226  sngl_inspiral_table[-1].process_id = sngl_inspiral_table[0].process_id
227 
228 
229 #
230 # =============================================================================
231 #
232 # Parameter Distributions
233 #
234 # =============================================================================
235 #
236 
237 
238 #
239 # Functions to synthesize injections
240 #
241 
242 
243 def snr_distribution(size, startsnr):
244  """
245  This produces a power law distribution in snr of size size starting at startsnr
246  """
247  return startsnr * random.power(3, size)**-1 # 3 here actually means 2 :) according to scipy docs
248 
249 
250 def noncentrality(snrs, prefactor):
251  """
252  This produces a set of noncentrality parameters that scale with snr^2 according to the prefactor
253  """
254  return prefactor * random.rand(len(snrs)) * snrs**2 # FIXME power depends on dimensionality of the bank and the expectation for the mismatch for real signals
255  #return prefactor * random.power(1, len(snrs)) * snrs**2 # FIXME power depends on dimensionality of the bank and the expectation for the mismatch for real signals
256 
257 
258 def chisq_distribution(df, non_centralities, size):
259  """
260  This produces a set of noncentral chisq values of size size, with degrees of freedom given by df
261  """
262  out = numpy.empty((len(non_centralities) * size,))
263  for i, nc in enumerate(non_centralities):
264  out[i*size:(i+1)*size] = random.noncentral_chisquare(df, nc, size)
265  return out
266 
267 
268 #
269 # =============================================================================
270 #
271 # Output Document
272 #
273 # =============================================================================
274 #
275 
276 
277 class CoincsDocument(object):
278  sngl_inspiral_columns = ("process:process_id", "ifo", "end_time", "end_time_ns", "eff_distance", "coa_phase", "mass1", "mass2", "snr", "chisq", "chisq_dof", "bank_chisq", "bank_chisq_dof", "sigmasq", "spin1x", "spin1y", "spin1z", "spin2x", "spin2y", "spin2z", "template_duration", "event_id", "Gamma0", "Gamma1")
279 
280  def __init__(self, url, process_params, process_start_time, comment, instruments, seg, offsetvectors, injection_filename = None, tmp_path = None, replace_file = None, verbose = False):
281  #
282  # how to make another like us
283  #
284 
285  self.get_another = lambda: CoincsDocument(url = url, process_params = process_params, process_start_time = process_start_time, comment = comment, instruments = instruments, seg = seg, offsetvectors = offsetvectors, injection_filename = injection_filename, tmp_path = tmp_path, replace_file = replace_file, verbose = verbose)
286 
287  #
288  # url
289  #
290 
291  self.url = url
292 
293  #
294  # build the XML document
295  #
296 
297  self.xmldoc = ligolw.Document()
298  self.xmldoc.appendChild(ligolw.LIGO_LW())
299  # NOTE FIXME override the process start time. Since gstlal
300  # inspiral can produce several output files from the same
301  # process, this can plot the process metadata by a factor of 50
302  # even though the same process generated the files. It is a
303  # major contributor to the size of merged databases and xml
304  # files. A patch to ligolw_process.register_to_xmldoc would be
305  # welcomed
306  process_params.update(os.environ)
307  self.process = ligolw_process.register_to_xmldoc(self.xmldoc, u"gstlal_inspiral", process_params, comment = comment, instruments = instruments)
308  if process_start_time is not None:
309  self.process.start_time = process_start_time
310  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.SnglInspiralTable, columns = self.sngl_inspiral_columns))
311  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.CoincDefTable))
312  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.CoincTable))
313  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.CoincMapTable))
314  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.TimeSlideTable))
315  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.CoincInspiralTable))
316  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.SegmentDefTable, columns = ligolw_segments.LigolwSegmentList.segment_def_columns))
317  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.SegmentSumTable, columns = ligolw_segments.LigolwSegmentList.segment_sum_columns))
318  self.xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.SegmentTable, columns = ligolw_segments.LigolwSegmentList.segment_columns))
319 
320  #
321  # optionally insert injection list document
322  #
323 
324  if injection_filename is not None:
325  ligolw_add.ligolw_add(self.xmldoc, [injection_filename], contenthandler = LIGOLWContentHandler, verbose = verbose)
326 
327  #
328  # insert time slide offset vectors. remove duplicate
329  # offset vectors when done
330  #
331 
332  time_slide_table = lsctables.TimeSlideTable.get_table(self.xmldoc)
333  for offsetvector in offsetvectors:
334  time_slide_table.append_offsetvector(offsetvector, self.process)
335  time_slide_mapping = ligolw_time_slide.time_slides_vacuum(time_slide_table.as_dict())
336  iterutils.inplace_filter(lambda row: row.time_slide_id not in time_slide_mapping, time_slide_table)
337  for tbl in self.xmldoc.getElementsByTagName(ligolw.Table.tagName):
338  tbl.applyKeyMapping(time_slide_mapping)
339 
340  #
341  # if the output is an sqlite database, build the sqlite
342  # database and convert the in-ram XML document to an
343  # interface to the database file
344  #
345 
346  if url is not None and url.endswith('.sqlite'):
347  self.working_filename = dbtables.workingcopy(ligolw_utils.local_path_from_url(url), tmp_path = tmp_path, replace_file = replace_file, verbose = verbose).__enter__()
348  self.connection = sqlite3.connect(str(self.working_filename), check_same_thread = False)
349  ligolw_sqlite.insert_from_xmldoc(self.connection, self.xmldoc, preserve_ids = False, verbose = verbose)
350 
351  #
352  # convert self.xmldoc into wrapper interface to
353  # database
354  #
355 
356  self.xmldoc.removeChild(self.xmldoc.childNodes[-1]).unlink()
357  self.xmldoc.appendChild(dbtables.get_xml(self.connection))
358 
359  # recover the process_id following the ID remapping
360  # that might have happened when the document was
361  # inserted. hopefully this query is unique enough
362  # to find exactly the one correct entry in the
363  # database
364 
365  (self.process.process_id,), = self.connection.cursor().execute("SELECT process_id FROM process WHERE program == ? AND node == ? AND username == ? AND unix_procid == ? AND start_time == ?", (self.process.program, self.process.node, self.process.username, self.process.unix_procid, self.process.start_time)).fetchall()
366  self.process.process_id = ilwd.ilwdchar(self.process.process_id)
367  else:
368  self.connection = self.working_filename = None
369 
370  #
371  # retrieve references to the table objects, now that we
372  # know if they are database-backed or XML objects
373  #
374 
375  self.sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(self.xmldoc)
376 
377 
378  def commit(self):
379  # update output document
380  if self.connection is not None:
381  self.connection.commit()
382 
383 
384  @property
385  def process_id(self):
386  return self.process.process_id
387 
388 
389  def get_next_sngl_id(self):
390  return self.sngl_inspiral_table.get_next_id()
391 
392 
393  def write_output_url(self, seglistdicts = None, verbose = False):
394  if seglistdicts is not None:
395  with ligolw_segments.LigolwSegments(self.xmldoc, self.process) as llwsegments:
396  for segtype, seglistdict in seglistdicts.items():
397  llwsegments.insert_from_segmentlistdict(seglistdict, name = segtype, comment = "LLOID")
398 
399  ligolw_process.set_process_end_time(self.process)
400 
401  if self.connection is not None:
402  # record the final state of the process row in the
403  # database
404  cursor = self.connection.cursor()
405  cursor.execute("UPDATE process SET end_time = ? WHERE process_id == ?", (self.process.end_time, self.process.process_id))
406  cursor.close()
407  self.connection.commit()
408  dbtables.build_indexes(self.connection, verbose = verbose)
409  self.connection.close()
410  self.connection = None
411  # return working copy to final destination
412  self.working_filename.__exit__(None, None, None)
413  else:
414  self.sngl_inspiral_table.sort(key = lambda row: (row.end, row.ifo))
415  ligolw_utils.write_url(self.xmldoc, self.url, verbose = verbose, trap_signals = None)
416  # can no longer be used
417  self.xmldoc.unlink()
418  del self.xmldoc
419 
420 
421 #
422 # =============================================================================
423 #
424 # GracedB Wrapper
425 #
426 # =============================================================================
427 #
428 
429 
430 class FakeGracedbResp(object):
431  def __init__(self):
432  self.status = http.client.CREATED
433  def json(self):
434  return {"graceid": -1}
435 
436 
437 class FakeGracedbClient(object):
438  def __init__(self, service_url):
439  # Assumes that service url is a directory to write files to
440  self.path = urlparse(service_url).path
441  def createEvent(self, group, pipeline, filename, filecontents, search):
442  with open(os.path.join(self.path, filename), "w") as f:
443  f.write(filecontents)
444  return FakeGracedbResp()
445  def writeLog(self, gracedb_id, message, filename, filecontents, tagname):
446  return FakeGracedbResp()
447  def writeLabel(self, gracedb_id, tagname):
448  return FakeGracedbResp()
449 
450 
451 class GracedBWrapper(object):
452  retries = 5
453  retry_delay = 5.0
454 
455  DEFAULT_SERVICE_URL = gracedb.rest.DEFAULT_SERVICE_URL
456 
457  def __init__(self, instruments, far_threshold = None, min_instruments = None, group = "Test", search = "LowMass", label = None, pipeline = "gstlal", service_url = None, kafka_server = None, delay_uploads = False, upload_auxiliary_data = True, delta_t = 0.005, verbose = False):
458  self.instruments = frozenset(instruments)
459  self.min_instruments = min_instruments
460  self.group = group
461  self.search = search
462  self.label = label
463  self.pipeline = pipeline
464  self.service_url = service_url if service_url is not None else self.DEFAULT_SERVICE_URL
465  self.upload_auxiliary_data = upload_auxiliary_data
466  self.verbose = verbose
467  # must initialize after .service_url because this might
468  # cause the client to be created, which requires
469  # .service_url to have already been set
470  self.far_threshold = far_threshold
471  # store the coincidence threshold to use it later when forming coincidence
472  self.delta_t = delta_t
473 
474  bottle.route("/gracedb_far_threshold.txt", method = "GET")(self.web_get_gracedb_far_threshold)
475  bottle.route("/gracedb_far_threshold.txt", method = "POST")(self.web_set_gracedb_far_threshold)
476  bottle.route("/gracedb_min_instruments.txt", method = "GET")(self.web_get_gracedb_min_instruments)
477  bottle.route("/gracedb_min_instruments.txt", method = "POST")(self.web_set_gracedb_min_instruments)
478 
479  if delay_uploads:
480  assert kafka_server is not None, "if delaying uploads, need to specify a kafka server"
481  self.delay_uploads = delay_uploads
482 
483  # set up kafka producer
484  if kafka_server is not None:
485  from ligo.scald.io import kafka
486  self.client = kafka.Client("kafka://{}".format(kafka_server))
487  self.client.subscribe(["events", "ranking_stat"])
488  else:
489  self.client = None
490 
491  @property
492  def far_threshold(self):
493  return self._far_threshold
494 
495  @far_threshold.setter
496  def far_threshold(self, far_threshold):
497  self._far_threshold = far_threshold
498  if far_threshold is None or far_threshold < 0.:
499  self.gracedb_client = None
500  else:
501  if self.service_url.startswith("file"):
503  else:
504  self.gracedb_client = gracedb.rest.GraceDb(self.service_url)
505 
506  def web_get_gracedb_far_threshold(self):
507  with self.lock:
508  if self.far_threshold is not None:
509  yield "rate=%.17g\n" % self.far_threshold
510  else:
511  yield "rate=\n"
512 
513  def web_set_gracedb_far_threshold(self):
514  try:
515  with self.lock:
516  rate = bottle.request.forms["rate"]
517  if rate:
518  self.far_threshold = float(rate)
519  yield "OK: rate=%.17g\n" % self.far_threshold
520  else:
521  self.far_threshold = None
522  yield "OK: rate=\n"
523  except:
524  yield "error\n"
525 
526  def web_get_gracedb_min_instruments(self):
527  with self.lock:
528  if self.min_instruments is not None:
529  yield "gracedb_min_instruments=%d\n" % self.min_instruments
530  else:
531  yield "gracedb_min_instruments=\n"
532 
533  def web_set_gracedb_min_instruments(self):
534  try:
535  with self.lock:
536  min_instruments = bottle.request.forms["gracedb_min_instruments"]
537  if min_instruments is not None:
538  self.min_instruments = int(min_instruments)
539  yield "OK: gracedb_min_instruments=%d\n" % self.min_instruments
540  else:
541  self.min_instruments = None
542  yield "OK: gracedb_min_instruments=\n"
543  except:
544  yield "error\n"
545 
546  def __upload_aux_data(self, message, filename, tag, contents, gracedb_ids):
547  assert self.gracedb_client is not None, ".gracedb_client is None; did you forget to set .far_threshold?"
548  for gracedb_id in gracedb_ids:
549  if self.verbose:
550  print("posting '%s' to gracedb ID %s ..." % (filename, gracedb_id), file=sys.stderr)
551  for attempt in range(1, self.retries + 1):
552  try:
553  resp = self.gracedb_client.writeLog(gracedb_id, message, filename = filename, filecontents = contents, tagname = tag)
554  except gracedb.rest.HTTPError as resp:
555  pass
556  else:
557  if resp.status == http.client.CREATED:
558  break
559  print("gracedb upload of %s for ID %s failed on attempt %d/%d" % (filename, gracedb_id, attempt, self.retries), file=sys.stderr)
560  time.sleep(random.lognormal(math.log(self.retry_delay), .5))
561  else:
562  print("gracedb upload of %s for ID %s failed" % (filename, gracedb_id), file=sys.stderr)
563 
564  def __upload_aux_xmldoc(self, message, filename, tag, xmldoc, gracedb_ids):
565  # check for no-op
566  if not gracedb_ids:
567  return
568  fobj = io.StringIO()
569  ligolw_utils.write_fileobj(xmldoc, fobj)
570  self.__upload_aux_data(message, filename, tag, fobj.getvalue(), gracedb_ids)
571  del fobj
572 
573  def do_alerts(self, last_coincs, psddict, rankingstat_xmldoc_func, seglistdicts, get_p_astro_func):
574  gracedb_ids = []
575 
576  # no-op short circuit
577  # NOTE the value is tested for less than or equeal to zero so
578  # that people can disable it through the web interface by
579  # setting e.g., -1. None is also less than zero so this works
580  # out.
581  if self.far_threshold <= 0 or not last_coincs:
582  return gracedb_ids
583 
584  coinc_inspiral_index = last_coincs.coinc_inspiral_index
585 
586  # Pick the "best" coinc
587  # FIXME revisit depending on how clustering goes
588  # NOTE if any are None, this becomes None.
589  # best_coinc = [min((coinc_inspiral_index[coinc_event.coinc_event_id].combined_far, coinc_event) for coinc_event in last_coincs.coinc_event_index.values())]
590 
591  # NOTE streamthinca currently records the max LR and max SNR
592  # triggers. Both will be uploaded if they are separate. Many
593  # times they are the same. NOTE NOTE NOTE FIXME FIXME FIXME.
594  # this loop would be a disaster if stream thinca doesn't
595  # cluster!
596  for coinc_event in last_coincs.coinc_event_index.values():
597  # revisit this "best coinc" if clustering is removed from streamthinca
598  #for _, coinc_event in best_coinc:
599  #
600  # continue if the false alarm rate is not low
601  # enough, or is nan, or there aren't enough
602  # instruments participating in this coinc
603  #
604 
605  if coinc_inspiral_index[coinc_event.coinc_event_id].combined_far is None or coinc_inspiral_index[coinc_event.coinc_event_id].combined_far > self.far_threshold or numpy.isnan(coinc_inspiral_index[coinc_event.coinc_event_id].combined_far) or len(last_coincs.sngl_inspirals(coinc_event.coinc_event_id)) < self.min_instruments:
606  continue
607 
608  #
609  # fake a filename for end-user convenience
610  #
611 
612  observatories = "".join(sorted(set(instrument[0] for instrument in self.instruments)))
613  instruments = "".join(sorted(self.instruments))
614  description = "%s_%s_%s_%s" % ("GSTLAL", ("%.4g" % coinc_inspiral_index[coinc_event.coinc_event_id].mass).replace(".", "_").replace("-", "_"), self.group, self.search)
615  end_time = int(coinc_inspiral_index[coinc_event.coinc_event_id].end)
616  filename = "%s-%s-%d-%d.xml" % (instruments, description, end_time, 1)
617 
618  #
619  # make sure the directory where we will write the files to disk exists
620  #
621 
622  gracedb_uploads_gps_dir = os.path.join("gracedb_uploads", str(end_time)[:5])
623  if not os.path.exists(gracedb_uploads_gps_dir):
624  os.makedirs(gracedb_uploads_gps_dir)
625 
626 
627  #
628  # construct message and send to gracedb.
629  # we go through the intermediate step of
630  # first writing the document into a string
631  # buffer incase there is some safety in
632  # doing so in the event of a malformed
633  # document; instead of writing directly
634  # into gracedb's input pipe and crashing
635  # part way through.
636  #
637 
638  print("sending %s to gracedb ..." % filename, file=sys.stderr)
639  message = io.StringIO()
640  xmldoc = last_coincs[coinc_event.coinc_event_id]
641  # give the alert all the standard inspiral
642  # columns (attributes should all be
643  # populated). FIXME: ugly.
644  sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
645  process_params_table = lsctables.ProcessParamsTable.get_table(xmldoc)
646  for standard_column in ("process:process_id", "ifo", "search", "channel", "end_time", "end_time_ns", "end_time_gmst", "impulse_time", "impulse_time_ns", "template_duration", "event_duration", "amplitude", "eff_distance", "coa_phase", "mass1", "mass2", "mchirp", "mtotal", "eta", "kappa", "chi", "tau0", "tau2", "tau3", "tau4", "tau5", "ttotal", "psi0", "psi3", "alpha", "alpha1", "alpha2", "alpha3", "alpha4", "alpha5", "alpha6", "beta", "f_final", "snr", "chisq", "chisq_dof", "bank_chisq", "bank_chisq_dof", "cont_chisq", "cont_chisq_dof", "sigmasq", "rsqveto_duration", "Gamma0", "Gamma1", "Gamma2", "Gamma3", "Gamma4", "Gamma5", "Gamma6", "Gamma7", "Gamma8", "Gamma9", "spin1x", "spin1y", "spin1z", "spin2x", "spin2y", "spin2z", "event_id"):
647  try:
648  sngl_inspiral_table.appendColumn(standard_column)
649  except ValueError:
650  # already has it
651  pass
652  # If we have snr time series for a detector that didn't
653  # produce a peak above threshold, create a trigger here
654  # for the highest peak that is coincident with all
655  # other triggers
656  event_ifos = [event.ifo for event in last_coincs.sngl_inspirals(coinc_event.coinc_event_id)]
657  # FIXME not the best way to do this and also not
658  # gauranteed to work if we change segment names. only
659  # consider ifos that are "on" at this time, i.e., in
660  # seglistdicts["whitehtsegments"][ifo]
661  triggerless_ifos = [ifo for ifo in self.instruments if ifo not in event_ifos and end_time in seglistdicts["whitehtsegments"][ifo]]
662  subthreshold_events = []
663  # FIXME Add logic to take highest network snr set of triggers when more than 1 sub-threshold trigger
664  for ifo in triggerless_ifos:
665  trigger_time_list = sorted([(event.ifo, LIGOTimeGPS(event.end_time, event.end_time_ns), getattr(event, "%s_snr_time_series" % ifo)) for event in last_coincs.sngl_inspirals(coinc_event.coinc_event_id) if getattr(event, "%s_snr_time_series" % ifo) is not None], key = lambda t: t[1])
666  if not trigger_time_list:
667  continue
668  # NOTE NOTE NOTE The coincidence finding algorithm has an extra fudge factor added to the light travel time that isn't used here
669  coinc_segment = ligolw_segments.segments.segment(ligolw_segments.segments.NegInfinity, ligolw_segments.segments.PosInfinity)
670  t0 = trigger_time_list[0][2].epoch
671  # NOTE This assumes all ifos have same sample rate
672  dt = trigger_time_list[0][2].deltaT
673  unit = trigger_time_list[0][2].sampleUnits
674  snr_length = trigger_time_list[0][2].data.length
675  autocorrelation_length = (snr_length - 1) / 2
676  for (trigger_ifo, trigger_time, snr_time_series) in trigger_time_list:
677  coincidence_window = LIGOTimeGPS(light_travel_time(ifo, trigger_ifo)) + self.delta_t
678  coinc_segment &= ligolw_segments.segments.segment(trigger_time - coincidence_window, trigger_time + coincidence_window)
679  if snr_time_series.epoch == t0:
680  snr_time_series_array = snr_time_series.data.data
681  else:
682  idx = int(round((t0 + (len(snr_time_series_array))*dt - snr_time_series.epoch) / dt))
683  snr_time_series_array = numpy.append(snr_time_series_array, snr_time_series.data.data[idx:])
684 
685  if not snr_time_series_array.any():
686  # empty snr time series, detector wasn't on
687  # FIXME Need to fix itacac so that snr time series only created from a detector if there was science mode data, currently it'll just pass zeros
688  continue
689 
690  for (event, snr_time_series) in subthreshold_events:
691  coincidence_window = LIGOTimeGPS(light_travel_time(ifo, event.ifo))
692  trigger_time = LIGOTimeGPS(event.end_time, event.end_time_ns)
693  coinc_segment &= ligolw_segments.segments.segment(trigger_time - coincidence_window, trigger_time + coincidence_window)
694 
695  tfinal = t0 + dt*(snr_time_series_array.shape[0] - 1)
696  # NOTE This will not work if the length of the
697  # snr time series (currently the
698  # autocorrelation length) is not large enough
699  # to cover all possible times that could be
700  # coincident with all of the existing triggers
701  if not ((t0 <= coinc_segment[0]) and (tfinal >= coinc_segment[1])):
702  # NOTE This should probably be an
703  # assert, but it's better to upload a
704  # candidate to gracedb without
705  # subthreshold triggers than to not
706  # upload anything
707  print("something went wrong creating sub-threshold trigger for %s in gracedb upload" % ifo, file=sys.stderr)
708  continue
709  idx0 = int((coinc_segment[0] - t0)/dt)
710  idxf = int(math.ceil((coinc_segment[1] - t0)/dt))
711  peak_snr = 0.
712  for idx in range(idx0, idxf + 1):
713  if abs(snr_time_series_array[idx]) > peak_snr:
714  peak_snr = abs(snr_time_series_array[idx])
715  peak_phase = math.atan2(snr_time_series_array[idx].imag, snr_time_series_array[idx].real)
716  peak_idx = idx
717  peak_t = idx*dt + t0
718 
719  # NOTE Bayestar needs at least 26.3ms on either side of the snr peak, so only provide an snr time series if we have enough samples
720  min_num_samps = int(math.ceil(0.0263 / dt)) + 1
721  if peak_idx < min_num_samps or snr_time_series_array.shape[0] - peak_idx < min_num_samps:
722  print("not enough samples to produce snr time series for sub-threshold trigger in %s" % ifo, file=sys.stderr)
723  continue
724 
725  # snr length guaranteed to be odd
726  if peak_idx > autocorrelation_length:
727  idx0 = peak_idx - autocorrelation_length
728  else:
729  idx0 = 0
730  if peak_idx < snr_time_series_array.shape[0] - autocorrelation_length:
731  idxf = peak_idx + autocorrelation_length + 1
732  else:
733  idxf = snr_time_series_array.shape[0]
734 
735  if idxf - idx0 != snr_length:
736  if idx0 == 0:
737  # We know we don't have enough samples, since we started at the beginning of the available samples the zeros must need to be prepended
738  snr_time_series_array = numpy.concatenate((numpy.zeros(snr_length - (idxf - idx0), dtype=snr_time_series_array.dtype), snr_time_series_array[idx0:idxf]))
739  elif idxf != peak_idx + autocorrelation_length + 1:
740  # We dont have enough samples, we need to append zeros
741  snr_time_series_array = numpy.concatenate((snr_time_series_array[idx0:idxf], numpy.zeros(snr_length - (idxf - idx0), dtype=snr_time_series_array.dtype)))
742  else:
743  print("unexpected conditional while making sub-threshold trigger for %s, skipping. idx0 = %d, idxf = %d" % (ifo, idx0, idxf), file=sys.stderr)
744  continue
745  else:
746  snr_time_series_array = snr_time_series_array[idx0:idxf]
747 
748  sngl_inspiral_table.append(sngl_inspiral_table.RowType())
749 
750  set_common_snglinspiral_values(sngl_inspiral_table)
751  sngl_inspiral_table[-1].ifo = ifo
752  sngl_inspiral_table[-1].end = peak_t
753  sngl_inspiral_table[-1].end_time_gmst = lal.GreenwichMeanSiderealTime(peak_t)
754  sngl_inspiral_table[-1].snr = peak_snr
755  sngl_inspiral_table[-1].coa_phase = peak_phase
756  sngl_inspiral_table[-1].chisq = None
757  sngl_inspiral_table[-1].eff_distance = None
758  sngl_inspiral_table[-1].event_id = sngl_inspiral_table.get_next_id()
759  for row in process_params_table:
760  # FIXME There's probably code in ligolw somewhere to do this
761  if row.param == "--channel-name" and row.value[:2] == ifo:
762  sngl_inspiral_table[-1].channel = row.value[3:]
763  break
764 
765  snr_time_series = lal.CreateCOMPLEX8TimeSeries(
766  name = "snr",
767  epoch = peak_t - autocorrelation_length * dt,
768  f0 = 0.0,
769  deltaT = dt,
770  sampleUnits = unit,
771  length = snr_length
772  )
773  snr_time_series.data.data = snr_time_series_array
774  subthreshold_events.append((sngl_inspiral_table[-1], snr_time_series))
775 
776  if subthreshold_events:
777  sngl_inspiral_table.sort(key = lambda row: row.ifo)
778  coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(xmldoc)
779  setattr(coinc_inspiral_table[0], "ifos", ",".join(sorted([getattr(row, "ifo") for row in sngl_inspiral_table])))
780  setattr(coinc_inspiral_table[0], "snr", sum([getattr(row, "snr")**2. for row in sngl_inspiral_table])**.5)
781 
782  coinc_event_map_table = lsctables.CoincMapTable.get_table(xmldoc)
783  for row in sngl_inspiral_table:
784  if getattr(row, "chisq") is not None:
785  continue
786  coinc_event_map_table.append(coinc_event_map_table.RowType())
787  for column in ("coinc_event_id", "table_name"):
788  setattr(coinc_event_map_table[-1], column, getattr(coinc_event_map_table[0], column))
789  setattr(coinc_event_map_table[-1], "event_id", getattr(row, "event_id"))
790 
791  # add SNR time series if available
792  # FIXME Probably only want one time series for each ifo
793  for event in last_coincs.sngl_inspirals(coinc_event.coinc_event_id):
794  snr_time_series = getattr(event, "%s_snr_time_series" % event.ifo)
795  if snr_time_series is not None:
796  snr_time_series_element = lalseries.build_COMPLEX8TimeSeries(snr_time_series)
797  snr_time_series_element.appendChild(ligolw_param.Param.from_pyvalue(u"event_id", event.event_id))
798  xmldoc.childNodes[-1].appendChild(snr_time_series_element)
799 
800  for (event, snr_time_series) in subthreshold_events:
801  snr_time_series_element = lalseries.build_COMPLEX8TimeSeries(snr_time_series)
802  snr_time_series_element.appendChild(ligolw_param.Param.from_pyvalue(u"event_id", event.event_id))
803  xmldoc.childNodes[-1].appendChild(snr_time_series_element)
804 
805  # get background bin from SnglInspiral objects while they're still available
806  background_bin = int(sngl_inspiral_table[0].Gamma1)
807 
808  # serialize to XML
809  ligolw_utils.write_fileobj(xmldoc, message)
810 
811  # calculate p(astro)
812  p_astro = get_p_astro_func(
813  coinc_event.likelihood,
814  last_coincs.sngl_inspirals(coinc_event.coinc_event_id)[0].mass1,
815  last_coincs.sngl_inspirals(coinc_event.coinc_event_id)[0].mass2,
816  coinc_inspiral_index[coinc_event.coinc_event_id].snr,
817  coinc_inspiral_index[coinc_event.coinc_event_id].combined_far
818  )
819 
820  # send event data to kafka
821  if self.client:
822  psd_fobj = io.StringIO()
823  ligolw_utils.write_fileobj(lalseries.make_psd_xmldoc(psddict), psd_fobj)
824  self.client.write(
825  "events",
826  {
827  "far": coinc_inspiral_index[coinc_event.coinc_event_id].combined_far,
828  "snr": coinc_inspiral_index[coinc_event.coinc_event_id].snr,
829  "time": coinc_inspiral_index[coinc_event.coinc_event_id].end_time,
830  "time_ns": coinc_inspiral_index[coinc_event.coinc_event_id].end_time_ns,
831  "coinc": message.getvalue(),
832  "psd": psd_fobj.getvalue(),
833  "p_astro": p_astro
834  }
835  )
836  del psd_fobj
837  # Write ranking data to disk and send path to kafka
838  rankingstat_filename = os.path.join(gracedb_uploads_gps_dir, "%s-%s_%04d_RankingData-%d-%d.xml.gz" % (instruments, description, background_bin, end_time, 1))
839  with open(rankingstat_filename, "w") as fileobj:
840  ligolw_utils.write_fileobj(rankingstat_xmldoc_func(), fileobj, compress = "gz")
841 
842  self.client.write(
843  "ranking_stat",
844  {
845  "ranking_data_path": os.path.realpath(rankingstat_filename),
846  "time": coinc_inspiral_index[coinc_event.coinc_event_id].end_time,
847  "time_ns": coinc_inspiral_index[coinc_event.coinc_event_id].end_time_ns,
848  "coinc": message.getvalue()
849  }
850  )
851 
852  # upload events
853  if not self.delay_uploads:
854  for attempt in range(1, self.retries + 1):
855  try:
856  resp = self.gracedb_client.createEvent(self.group, self.pipeline, filename, filecontents = message.getvalue(), search = self.search, label = self.label)
857  except gracedb.rest.HTTPError as resp:
858  print(resp)
859  else:
860  resp_json = resp.json()
861  if resp.status == http.client.CREATED:
862  if self.verbose:
863  print("event assigned grace ID %s" % resp_json["graceid"], file=sys.stderr)
864  gracedb_ids.append(resp_json["graceid"])
865  self.__upload_aux_data("GstLAL internally computed p-astro", "p_astro.json", "p_astro", p_astro, [gracedb_ids[-1]])
866  try:
867  resp = self.gracedb_client.writeLabel(gracedb_ids[-1], 'PASTRO_READY')
868  except gracedb.rest.HTTPError as resp:
869  print(resp, file=sys.stderr)
870  break
871  print("gracedb upload of %s failed on attempt %d/%d" % (filename, attempt, self.retries), file=sys.stderr)
872  print(resp_json, file=sys.stderr)
873  time.sleep(random.lognormal(math.log(self.retry_delay), .5))
874  else:
875  print("gracedb upload of %s failed" % filename, file=sys.stderr)
876 
877  # save event to disk
878  message.close()
879  with open(os.path.join(gracedb_uploads_gps_dir, filename), "w") as fileobj:
880  ligolw_utils.write_fileobj(xmldoc, fileobj)
881 
882  xmldoc.unlink()
883 
884  #
885  # upload PSDs and ranking statistic data
886  #
887 
888  if not self.delay_uploads and self.upload_auxiliary_data and len(gracedb_ids) > 0:
889  self.__upload_aux_xmldoc("strain spectral densities", "psd.xml.gz", "psd", lalseries.make_psd_xmldoc(psddict), gracedb_ids)
890  self.__upload_aux_xmldoc("ranking statistic PDFs", "ranking_data.xml.gz", "ranking_statistic", rankingstat_xmldoc_func(), gracedb_ids)
891 
892  #
893  # done
894  #
895 
896  return gracedb_ids
def web_get_gracedb_min_instruments
Definition: inspiral.py:526
def web_set_gracedb_min_instruments
Definition: inspiral.py:533
def read_banks
Definition: svd_bank.py:368