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