gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_lvalert_sim_equiv
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2013--2016 Kipp Cannon
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 
19 
20 ### A program to listen to lvalerts, download the candidate data from gstlal
21 ### gracedb events, and upload XML documents containing sim_inspiral entries to
22 ### reproduce simulations of the candidates
23 
24 
25 #
26 # =============================================================================
27 #
28 # Preamble
29 #
30 # =============================================================================
31 #
32 
33 
34 import logging
35 import math
36 import numpy
37 from optparse import OptionParser
38 import sys
39 import json
40 
41 
42 from glue.ligolw import ligolw
43 from glue.ligolw import lsctables
44 from glue.ligolw import utils as ligolw_utils
45 from glue.ligolw.utils import coincs as ligolw_coincs
46 from glue.ligolw.utils import process as ligolw_process
47 from gstlal import lvalert_helper
48 import lal
49 from ligo.gracedb import rest as gracedb
50 from gstlal import spawaveform
51 
52 
53 #
54 # =============================================================================
55 #
56 # Library
57 #
58 # =============================================================================
59 #
60 
61 
62 comment_text = """This document provides injections (sim_inspiral rows) to generate waveforms corresponding to each of the triggers in the candidate. There is one injection per trigger, and each is optimally oriented above its respective instrument. NOTE that this is not an attempt to provide a coherent reconstruction of the signal, the injections are not, in general, consistent with one another; the objective is allow the waveform implied by each trigger to be reconstructed for the purpose of plotting the time series, generating spectrograms, and so on. The injections are linked to their corresponding triggers using coinc_event entries from the 'gstlal_inspiral_lvalert_sim_equiv' search (the name of the program that generated this document)."""
63 
64 
65 def make_sim_xmldoc(xmldoc):
66  xmldoc.childNodes[-1].insertBefore(ligolw.Comment(), xmldoc.childNodes[-1].childNodes[0]).pcdata = comment_text
67  coinc_event_table = lsctables.CoincTable.get_table(xmldoc)
68  coinc_event_table.sync_next_id()
69  if len(coinc_event_table) != 1:
70  raise ValueError("ooops: more than one candidate found in this document, cannot process")
71  coinc_event_map_table = lsctables.CoincMapTable.get_table(xmldoc)
72  sim_inspiral_table = xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.SimInspiralTable, [
73  "process_id",
74  "waveform",
75  "geocent_end_time", "geocent_end_time_ns",
76  "end_time_gmst",
77  "mass1", "mass2",
78  "mchirp", "eta",
79  "distance",
80  "longitude", "latitude",
81  "inclination",
82  "coa_phase",
83  "polarization",
84  "spin1x", "spin1y", "spin1z",
85  "spin2x", "spin2y", "spin2z",
86  "simulation_id"
87  ]))
88 
89  process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral_lvalert_sim_equiv", {}, instruments = lsctables.SnglInspiralTable.get_table(xmldoc).getColumnByName("ifo"))
90  coinc_def_id = ligolw_coincs.get_coinc_def_id(xmldoc, u"gstlal_inspiral_lvalert_sim_equiv", 0, description = u"injections to emulate triggers")
91  time_slide_id = coinc_event_table[0].time_slide_id
92  offsetvector = lsctables.TimeSlideTable.get_table(xmldoc).as_dict()[time_slide_id]
93 
94  for event in lsctables.SnglInspiralTable.get_table(xmldoc):
95  #
96  # some info about the detector
97  #
98 
99  detector = lal.cached_detector_by_prefix[event.ifo]
100  lng = detector.frDetector.vertexLongitudeRadians
101  lat = detector.frDetector.vertexLatitudeRadians
102  r = math.sqrt(numpy.dot(detector.location, detector.location)) / lal.C_SI
103 
104  #
105  # initialize injection
106  #
107 
108  sim = sim_inspiral_table.RowType()
109  sim.process_id = process.process_id
110 
111  #
112  # waveform
113  #
114 
115  sim.mass1, sim.mass2 = event.mass1, event.mass2
116  sim.eta = spawaveform.eta(sim.mass1, sim.mass2)
117  sim.mchirp = (sim.mass1 + sim.mass2) * sim.eta**.6
118  sim.spin1, sim.spin2 = event.spin1, event.spin2
119  # FIXME: hard-coded = bad bad bad
120  if sim.mchirp < 1.73:
121  sim.waveform = u"TaylorF2"
122  else:
123  sim.waveform = u"SEOBNRv4_ROM"
124 
125  #
126  # time and location
127  #
128  # the objective is to construct an injection that will
129  # reproduce this trigger. we want to be able to generate
130  # the waveform using lal and see what it looks like in the
131  # time domain, as a spectrogram, and so on. this is not
132  # the same as reconstructing a description of the best
133  # guess at the signal that passed through the Earth, we are
134  # not attempting to construct something that is consistent
135  # across instruments.
136  #
137  # for each detector we construct an equivalent optimally
138  # oriented source
139  #
140 
141  sim.time_geocent = event.end + offsetvector[event.ifo] + r
142  sim.distance = event.eff_distance * 1000. # kpc / Mpc
143  sim.ra_dec = (-lng - sim.end_time_gmst) % (2. * math.pi), lat
144  sim.inclination = 0.
145  sim.coa_phase = event.coa_phase
146  sim.polarization = 0.
147 
148  #
149  # add to table
150  #
151 
152  sim.simulation_id = sim_inspiral_table.get_next_id()
153  sim_inspiral_table.append(sim)
154 
155  #
156  # link to trigger
157  #
158 
159  coinc = coinc_event_table.RowType()
160  coinc.process_id = process.process_id
161  coinc.coinc_event_id = coinc_event_table.get_next_id()
162  coinc.coinc_def_id = coinc_def_id
163  coinc.insts = event.ifo,
164  coinc.nevents = 1
165  coinc.time_slide_id = time_slide_id
166  coinc.likelihood = None
167  coinc_event_table.append(coinc)
168 
169  coinc_event_map = coinc_event_map_table.RowType()
170  coinc_event_map.table_name = u"sngl_inspiral"
171  coinc_event_map.event_id = event.event_id
172  coinc_event_map.coinc_event_id = coinc.coinc_event_id
173  coinc_event_map_table.append(coinc_event_map)
174 
175  coinc_event_map = coinc_event_map_table.RowType()
176  coinc_event_map.table_name = u"sim_inspiral"
177  coinc_event_map.event_id = sim.simulation_id
178  coinc_event_map.coinc_event_id = coinc.coinc_event_id
179  coinc_event_map_table.append(coinc_event_map)
180 
181  return xmldoc
182 
183 
184 #
185 # =============================================================================
186 #
187 # Command Line
188 #
189 # =============================================================================
190 #
191 
192 
193 def parse_command_line():
194  parser = OptionParser()
195  parser.add_option("--no-upload", action = "store_true", help = "Write plots to disk.")
196  parser.add_option("--skip-404", action = "store_true", help = "Skip events that give 404 (file not found) errors (default is to abort).")
197  parser.add_option("--gracedb-service-url", default="%s" % gracedb.DEFAULT_SERVICE_URL, help = "GraceDb service url to upload to (default: %s)" % gracedb.DEFAULT_SERVICE_URL)
198  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
199  options, graceids = parser.parse_args()
200 
201  if not graceids:
202  # FIXME: lvalert_listen doesn't allow command-line
203  # options, enable logging for online analysis
204  options.verbose = True
205 
206  # can only call basicConfig once (otherwise need to switch to more
207  # complex logging configuration)
208  if options.verbose:
209  logging.basicConfig(format = "%(asctime)s:%(message)s", level = logging.INFO)
210  else:
211  logging.basicConfig(format = "%(asctime)s:%(message)s")
212 
213  return options, graceids
214 
215 
216 #
217 # =============================================================================
218 #
219 # Main
220 #
221 # =============================================================================
222 #
223 
224 
225 options, graceids = parse_command_line()
226 
227 
228 if not graceids:
229  lvalert_data = json.loads(sys.stdin.read())
230  logging.info("%(alert_type)s-type alert for event %(uid)s" % lvalert_data)
231  logging.info("lvalert data: %s" % repr(lvalert_data))
232  if lvalert_data["alert_type"] != "new":
233  logging.info("alert is not new, ignoring")
234  sys.exit()
235  graceids = [str(lvalert_data["uid"])]
236 
237 
238 gracedb_client = gracedb.GraceDb(service_url = options.gracedb_service_url)
239 
240 
241 for graceid in graceids:
242  xmldoc = make_sim_xmldoc(lvalert_helper.get_coinc_xmldoc(gracedb_client, graceid))
243  filename = "%s_sim_equiv.xml.gz" % graceid
244  if options.no_upload:
245  logging.info("writing %s ..." % filename)
246  ligolw_utils.write_filename(xmldoc, filename, compress = "gz", verbose = options.verbose)
247  else:
248  lvalert_helper.upload_xmldoc(gracedb_client, graceid, filename, xmldoc, log_message = "injections to emulate triggers", tagname = "pe")
249  logging.info("finished processing %s" % graceid)