gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_destagger_injections
1 #!/usr/bin/env python3
2 
3 from ligo.lw import dbtables
4 from ligo.lw import lsctables
5 from ligo.lw import utils as ligolw_utils
6 from ligo.lw.ligolw import LIGOLWContentHandler
7 from ligo.lw.utils import process as ligolw_process
8 from ligo.lw.utils import segments as ligolw_segments
9 
10 from optparse import OptionParser
11 from os import path
12 import numpy
13 import sqlite3
14 import sys
15 
16 @lsctables.use_in
17 class ligolwcontenthandler(LIGOLWContentHandler):
18  pass
19 
20 def parse_command_line():
21  parser = OptionParser(usage="%prog [options] database")
22 
23  parser.add_option("--injection-file", "-i", metavar = "filename", action = "append", help = "An original injection file that was used as input to gstlal_inspiral_combine_injection_sets. Option can be provided multiple times. All of the injection files that were combined using gstlal_inspiral_combine_injection_sets must be provided.")
24  parser.add_option("--tmp-space", "-t", metavar = "path", default = None, help = "Path to a directory suitable for use as a work area while manipulating the database file. The database file will be worked on in this directory, and then moved to the final location when complete. This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
25  parser.add_option("--verbose", "-v", action = "store_true", help = "Be verbose.")
26 
27 
28  options, filenames = parser.parse_args()
29  if len(filenames) != 1:
30  raise ValueError("Must provide exactly one database, %d provided (%s)" % (len(filenames), ', '.join(filenames)))
31 
32  return options, filenames[0]
33 
34 def read_inj_files(options):
35  inj_dict = {}
36  for inj in options.injection_file:
37  xmldoc = ligolw_utils.load_filename(inj, contenthandler = ligolwcontenthandler, verbose = options.verbose)
38  start_time = 0
39  dt = 0
40  for processparam in lsctables.ProcessParamsTable.get_table(xmldoc):
41  if processparam.param == "--gps-start-time":
42  if start_time != 0:
43  raise ValueError("injection file %s contains more than one --gps-start-time entry in ProcessParams table" % inj)
44  start_time = int(processparam.value)
45  elif processparam.param == "--time-step":
46  if dt != 0:
47  raise ValueError("injection file %s contains more than one --time-step entry in ProcessParams table" % inj)
48  # Have to call it a float first because int() cant take a string that contains sci notation
49  dt = int(float(processparam.value))
50  if start_time == 0:
51  raise ValueError("injection file %s does not contain --gps-start-time entry in ProcessParams table" % inj)
52  if dt == 0:
53  raise ValueError("injection file %s does not contain --time-step entry in ProcessParams table" % inj)
54  # FIXME Need a standardized naming convention, this could easily fail
55  inj_dict[path.basename(inj).split('.')[0].split('-')[0]] = (start_time, dt)
56  xmldoc.unlink()
57 
58  return inj_dict
59 
60 def set_up(cursor, options):
61  inj_dict = read_inj_files(options)
62  # NOTE NOTE NOTE We only need the integer geocenter time because this
63  # is only used to associate injections with the original injection
64  # files. We need the nanoseconds for the detector times to determine
65  # which injection a coinc_inspiral that hasnt been associated with an
66  # injection already is closest to
67  # FIXME Will need to modify this to include Kagra
68  db_inj_times = set((t for t in cursor.execute('SELECT geocent_end_time, h_end_time+1e-9*h_end_time_ns, l_end_time+1e-9*l_end_time_ns, v_end_time+1e-9*v_end_time_ns, simulation_id FROM sim_inspiral ORDER BY geocent_end_time ASC').fetchall()))
69  sim_id_dict = {}
70 
71  # files we care about have four types of coincidences, these are their descriptions
72  #sngl_inspiral<-->sngl_inspiral coincidences
73  #sim_inspiral<-->sngl_inspiral coincidences
74  #sim_inspiral<-->coinc_event coincidences (exact)
75  #sim_inspiral<-->coinc_event coincidences (nearby)
76  exact_inj_coinc_def_id = cursor.execute('SELECT coinc_def_id FROM coinc_definer WHERE description == "sim_inspiral<-->coinc_event coincidences (exact)"').fetchone()
77  nearby_inj_coinc_def_id = cursor.execute('SELECT coinc_def_id FROM coinc_definer WHERE description == "sim_inspiral<-->coinc_event coincidences (nearby)"').fetchone()
78  inj_trigger_coinc_def_id = cursor.execute('SELECT coinc_def_id FROM coinc_definer WHERE description == "sim_inspiral<-->sngl_inspiral coincidences"').fetchone()
79  coinc_inspiral_coinc_def_id = cursor.execute('SELECT coinc_def_id FROM coinc_definer WHERE description == "sngl_inspiral<-->sngl_inspiral coincidences"').fetchone()
80 
81  # parse the sim_inspiral table into different injection sets
82  for inj_basename, (start_time, dt) in inj_dict.items():
83  for geocent_end_time, h_end_time, l_end_time, v_end_time, sim_id in db_inj_times:
84  tref = geocent_end_time - start_time
85  # Check if this injection is within 2 seconds of where an injection from this injection file would fall if every injection were spaced by dt
86  if tref % dt <= 2 or tref % dt == dt - 2 or tref % dt == dt - 1:
87  sim_id_dict.setdefault(inj_basename, []).append((geocent_end_time, h_end_time, l_end_time, v_end_time, sim_id))
88 
89  if inj_basename in sim_id_dict.keys():
90  db_inj_times -= set(sim_id_dict[inj_basename])
91 
92  return sim_id_dict, exact_inj_coinc_def_id, nearby_inj_coinc_def_id, inj_trigger_coinc_def_id, coinc_inspiral_coinc_def_id
93 
94 
95 options, db = parse_command_line()
96 
97 split_db_name = path.basename(db).split('-')
98 working_filename = dbtables.get_connection_filename(db, tmp_path = options.tmp_space, verbose = options.verbose)
99 connection = sqlite3.connect(str(working_filename))
100 cursor = connection.cursor()
101 original_number_coinc_events = int(cursor.execute('SELECT count(*) FROM coinc_event').fetchone()[0])
102 new_number_coinc_events = 0
103 
104 sim_id_dict, exact_inj_coinc_def_id, nearby_inj_coinc_def_id, inj_trigger_coinc_def_id, coinc_inspiral_coinc_def_id = set_up(cursor, options)
105 
106 for i, sim_key in enumerate(sim_id_dict.keys()):
107  if i != 0:
108  working_filename = dbtables.get_connection_filename(db, tmp_path = options.tmp_space, verbose = True)
109  connection = sqlite3.connect(str(working_filename))
110  cursor = connection.cursor()
111 
112  # register program in process table
113  xmldoc = dbtables.get_xml(connection)
114  # FIXME Make this not ugly
115  process_params_dict = dict(("--injection-file", inj_file) for inj_file in options.injection_file)
116  process_params_dict["--verbose"] = options.verbose
117  process_params_dict["--tmp-space"] = options.tmp_space
118  process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral_destagger_injections", process_params_dict)
119 
120  relevant_sim_ids = [sim_id for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[sim_key]]
121  irrelevant_sim_ids = [sim_id for key in (set(sim_id_dict.keys()) - set((sim_key,))) for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[key]]
122  irrelevant_keys = set(sim_id_dict.keys()) - set((sim_key,))
123 
124  sim_times_relevant_sim_ids = {"H1": numpy.array([h_end_time for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[sim_key]]), "L1": numpy.array([l_end_time for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[sim_key]]), "V1": numpy.array([v_end_time for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[sim_key]])}
125  sim_times_irrelevant_sim_ids = {"H1": numpy.array([h_end_time for key in irrelevant_keys for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[key]]), "L1": numpy.array([l_end_time for key in irrelevant_keys for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[key]]), "V1": numpy.array([v_end_time for key in irrelevant_keys for (g_end_time, h_end_time, l_end_time, v_end_time, sim_id) in sim_id_dict[key]])}
126 
127 
128  if options.verbose:
129  print >>sys.stderr, "Cleaning up exact coincidences"
130 
131 
132  # clean up exact coincidences
133  for coinc_event_id, in cursor.execute('SELECT coinc_event_id FROM coinc_event WHERE coinc_def_id == ?', exact_inj_coinc_def_id).fetchall():
134  # each coinc_event_id is a tuple, so no need to put it in another tuple for the cursor.execute()
135  sim_id = cursor.execute('SELECT event_id FROM coinc_event_map WHERE coinc_event_id == ? AND table_name == "sim_inspiral"', (coinc_event_id,)).fetchall()
136  assert len(sim_id) == 1, "%d sim_ids coincident with coinc" % len(sim_id)
137  # FIXME this needs to be generalized to use all of the files
138  if sim_id[0][0] not in relevant_sim_ids:
139  cursor.execute('DELETE FROM coinc_event WHERE coinc_event_id == ?', (coinc_event_id,))
140 
141  if options.verbose:
142  print >>sys.stderr, "Cleaning up nearby coincidences"
143 
144  # clean up nearby coincidences
145  for coinc_event_id, in cursor.execute('SELECT coinc_event_id FROM coinc_event WHERE coinc_def_id == ?', nearby_inj_coinc_def_id).fetchall():
146  sim_id = cursor.execute('SELECT event_id FROM coinc_event_map WHERE coinc_event_id == ? AND table_name == "sim_inspiral"', (coinc_event_id,)).fetchall()
147  assert len(sim_id) == 1, "multiple sim_ids coincident with coinc"
148  # FIXME this needs to be generalized to use all of the files
149  if sim_id[0][0] not in relevant_sim_ids:
150  cursor.execute('DELETE FROM coinc_event WHERE coinc_event_id == ?', (coinc_event_id,))
151 
152  if options.verbose:
153  print >>sys.stderr, "Cleaning up sim_inspiral sngl_inspiral coincidences"
154 
155  # clean up sim_inspiral sngl_inspiral coincs
156  for coinc_event_id, in cursor.execute('SELECT coinc_event_id FROM coinc_event WHERE coinc_def_id == ?', inj_trigger_coinc_def_id).fetchall():
157  sim_id = cursor.execute('SELECT event_id FROM coinc_event_map WHERE coinc_event_id == ? AND table_name == "sim_inspiral"', (coinc_event_id,)).fetchall()
158  assert len(sim_id) == 1, "%d sim_ids coincident with coinc" % len(sim_id)
159  # FIXME this needs to be generalized to use all of the files
160  if sim_id[0][0] not in relevant_sim_ids:
161  cursor.execute('DELETE FROM coinc_event WHERE coinc_event_id == ?', (coinc_event_id,))
162 
163  if options.verbose:
164  print >>sys.stderr, "Cleaning up sim_inspiral coinc_inspiral coincidences"
165 
166  # clean up coinc_inspirals
167  for coinc_event_id, in cursor.execute('SELECT coinc_event_id FROM coinc_event WHERE coinc_def_id == ?', coinc_inspiral_coinc_def_id).fetchall():
168  # first check if this is coincident with an injection
169  sim_coinc_event_id = cursor.execute('SELECT coinc_event_id FROM coinc_event_map WHERE table_name == "coinc_event" AND event_id == ?', (coinc_event_id,)).fetchall()
170  if len(sim_coinc_event_id) >= 1:
171  sim_ids = []
172  for sim_coinc_event_id in sim_coinc_event_id:
173  sim_ids.extend(cursor.execute('SELECT event_id FROM coinc_event_map WHERE coinc_event_id == ? AND table_name == "sim_inspiral"', sim_coinc_event_id).fetchall())
174  if len(sim_ids) > 1:
175  for sim_id in sim_ids[1:]:
176  # This should always be true, just putting this here to make sure I haven't missed some corner case I don't know about
177  assert sim_ids[0] == sim_id
178  if sim_ids[0][0] not in relevant_sim_ids:
179  cursor.execute('DELETE FROM coinc_event WHERE coinc_event_id == ?', (coinc_event_id,))
180 
181  else:
182  # not coincident with any injections, we need to find the closest time
183  ifos = cursor.execute('SELECT ifos FROM coinc_inspiral WHERE coinc_event_id == ?', (coinc_event_id,)).fetchall()
184  assert len(ifos) == 1
185  # ifos should be a list of involved ifos separated by commas, e.g. H1,L1,V1, which would be returned as [(u"H1,L1,V1")]
186  first_ifo_alphabetically = sorted(ifos[0][0].split(','))[0]
187  end_time = cursor.execute('SELECT end_time+1e-9*end_time_ns FROM sngl_inspiral WHERE ifo == ? and event_id IN (SELECT event_id FROM coinc_event_map WHERE coinc_event_id == ? and table_name = "sngl_inspiral")', (first_ifo_alphabetically, coinc_event_id)).fetchall()
188  assert len(end_time) == 1
189  relevance_test = abs(sim_times_relevant_sim_ids[first_ifo_alphabetically] - end_time[0])
190  irrelevance_test = abs(sim_times_irrelevant_sim_ids[first_ifo_alphabetically] - end_time[0])
191  if min(irrelevance_test) < min(relevance_test):
192  # These coinc triggers are closer to an injection we dont care about than an injection we do care about
193  cursor.execute('DELETE FROM coinc_event WHERE coinc_event_id == ?', (coinc_event_id,))
194 
195  if options.verbose:
196  print >>sys.stderr, "Cleaning up coinc_inspiral table"
197  # now clean up coinc_inspiral and coinc_event_map tables
198  cursor.execute('DELETE FROM coinc_inspiral WHERE coinc_event_id NOT IN (SELECT coinc_event_id FROM coinc_event)')
199  if options.verbose:
200  print >>sys.stderr, "Cleaning up coinc_event_map table"
201  cursor.execute('DELETE FROM coinc_event_map WHERE coinc_event_id NOT IN (SELECT coinc_event_id FROM coinc_event)')
202 
203  if options.verbose:
204  print >>sys.stderr, "Cleaning up sngl_inspiral table"
205  # clean up sngl_inspiral table
206  cursor.execute('DELETE FROM sngl_inspiral WHERE event_id NOT IN (SELECT event_id FROM coinc_event_map WHERE table_name == "sngl_inspiral")')
207 
208  if options.verbose:
209  print >>sys.stderr, "Cleaning up sim_inspiral table"
210  # finally, clean up the sim_inspiral table
211  cursor.executemany('DELETE FROM sim_inspiral WHERE simulation_id == ?', [(sim_id,) for sim_id in irrelevant_sim_ids])
212 
213  if options.verbose:
214  print >>sys.stderr, "Vacuuming"
215  cursor.execute('VACUUM')
216 
217  # Set process end time
218  ligolw_process.set_process_end_time(process)
219  cursor.execute("UPDATE process SET end_time = ? WHERE process_id == ?", (process.end_time, process.process_id))
220 
221  if options.verbose:
222  print >>sys.stderr, "Committing"
223  connection.commit()
224  new_number_coinc_events += int(connection.execute('SELECT count(*) FROM coinc_event').fetchone()[0])
225  connection.close()
226 
227  # Write destaggered db to disk
228  new_db_name = '%s-ALL_LLOID_%s_%s-%s-%s' % (split_db_name[0], sim_key, split_db_name[1].split('_')[-1], split_db_name[2], split_db_name[3])
229  dbtables.put_connection_filename(new_db_name, working_filename, verbose = True)
230 
231 if original_number_coinc_events != new_number_coinc_events:
232  raise RuntimeError("Number of entries in coinc_event table in original document does not match the number of entries in the output coinc_event_tables. There were %d entries originally, and %d were output. Something has gone terribly wrong, and the output documents should not be trusted." % (original_number_coinc_events, new_number_coinc_events))
233 else:
234  print >>sys.stderr, "Confirmed there were %d entries in the original coinc_event table, and %d entries were written to disk in the new coinc_event tables." % (original_number_coinc_events, new_number_coinc_events)