gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_coinc_extractor_dag
1 #!/usr/bin/env python3
2 '''
3 gstlal_inspiral_coinc_extractor_dag --injection-database=path/to/injection/database --zerolag-database=path/to/zerolag/database --tmp-space=path/to/tmp/space --far-threshold=1e-6 --max-number-inspiral-jobs=max_number_inspiral_jobs
4 '''
5 
6 from optparse import OptionParser
7 import sqlite3
8 import os
9 import glob
10 
11 from ligo.lw import ligolw
12 from ligo.lw import lsctables
13 from ligo.lw import utils as ligolw_utils
14 from ligo.lw.utils import process as ligolw_process
15 from ligo.lw import dbtables
16 from gstlal import dagparts
17 
18 def parse_command_line():
19  parser = OptionParser()
20  parser.add_option("-i", "--injection-database", metavar = "filename", help = "Path to the injection database.")
21  parser.add_option("-z", "--zerolag-database", metavar = "filename", help = "Path to the zerolag database.")
22  parser.add_option("-t", "--tmp-space", metavar = "path", help = "Path to temp space. Defaults to _CONDOR_SCRATCH_DIR .")
23  parser.add_option("-f", "--far-threshold", type = "float", default = 3.86e-7, help = "Threshold for rerunning an injection job to produce the time series.")
24  parser.add_option("-m", "--max-number-inspiral-jobs", type = "int", default = 10000, help = "Maximum number of inspiral jobs to queue. If this option is not provided, the program defaults to the top 10000 that pass the imposed FAR threshold.")
25 
26  options, filenames = parser.parse_args()
27 
28  return options, filenames
29 
30 options, filenames = parse_command_line()
31 
32 if not (options.injection_database or options.zerolag_database):
33  raise ValueError("You must provide a database.")
34 
35 if options.injection_database and options.zerolag_database:
36  raise ValueError("You must provide either an injection or a zerolag a database...just make up your mind!!")
37 
38 if not options.tmp_space:
39  if '_CONDOR_SCRATCH_DIR' in os.environ:
40  options.tmp_space = os.environ['_CONDOR_SCRATCH_DIR']
41  else:
42  options.tmp_space = os.environ['TMPDIR']
43 
44 
45 
46 # copied from gstlal_inspiral_plotsummary
47 def create_sim_coinc_view(connection):
48  """
49  Construct a sim_inspiral --> best matching coinc_event mapping.
50  Only injections that match at least one coinc get an entry in this
51  table.
52  """
53  #
54  # the log likelihood ratio stored in the likelihood column of the
55  # coinc_event table is the ranking statistic. the "best match" is
56  # the coinc with the highest value in this column. although it has
57  # not been true in the past, there is now a one-to-one relationship
58  # between the value of this ranking statistic and false-alarm rate,
59  # therefore it is OK to order by log likelihood ratio and then,
60  # later, impose a "detection" threshold based on false-alarm rate.
61  #
62 
63  connection.cursor().execute("""
64 CREATE TEMPORARY TABLE
65  sim_coinc_map_helper
66 AS
67  SELECT a.event_id as sid,
68  coinc_event.coinc_event_id as cid,
69  coinc_event.likelihood as lr,
70  coinc_event.nevents as nevents,
71  coinc_event.instruments as instruments
72  FROM coinc_event_map as a
73  JOIN coinc_event_map AS b ON (b.coinc_event_id == a.coinc_event_id)
74  JOIN coinc_event ON (coinc_event.coinc_event_id == b.event_id)
75  WHERE a.table_name == "sim_inspiral"
76  AND b.table_name == "coinc_event"
77  AND NOT EXISTS (SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0);
78  """)
79 
80  connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_coinc_map_helper_index ON sim_coinc_map_helper (sid, cid);")
81 
82 #
83 # FIXME NOTE FIXME this selects triple times with no more than two ifos to test the itacac sub threshold stuff
84 #
85 
86  connection.cursor().execute("""
87 CREATE TEMPORARY TABLE
88  sim_coinc_map
89 AS
90  SELECT
91  sim_inspiral.simulation_id AS simulation_id,
92  (
93  SELECT
94  cid
95  FROM
96  sim_coinc_map_helper
97  WHERE
98  sid = simulation_id
99  ORDER BY
100  lr
101  DESC
102  LIMIT 1
103  ) AS coinc_event_id
104  FROM
105  sim_inspiral
106  WHERE
107  coinc_event_id IS NOT NULL;
108 
109  """)
110 
111  connection.cursor().execute("DROP INDEX sim_coinc_map_helper_index;")
112 
113  connection.cursor().execute("""
114 CREATE TEMPORARY TABLE
115  sim_id_combined_far
116 AS
117  SELECT
118  coinc_inspiral.combined_far AS far, sim_coinc_map.simulation_id AS sim_id
119  FROM
120  sim_coinc_map
121  JOIN coinc_inspiral ON ( coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id )
122  """)
123 
124  connection.cursor().execute("""
125 CREATE TEMPORARY TABLE
126  sim_id_sngl_id
127  AS
128  SELECT
129  sim_coinc_map.simulation_id AS sim_id, sngl_inspiral.event_id AS sngl_id
130  FROM
131  sim_coinc_map
132  JOIN coinc_event_map as mapA ON ( mapA.coinc_event_id == sim_coinc_map.coinc_event_id )
133  JOIN sngl_inspiral ON ( sngl_inspiral.event_id == mapA.event_id )
134  """)
135 
136  connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_id_combined_far_index ON sim_id_combined_far (far, sim_id)")
137  connection.cursor().execute("CREATE INDEX IF NOT EXISTS sim_id_sngl_id_index ON sim_id_sngl_id (sim_id, sngl_id)")
138 
139  connection.cursor().execute("""
140 CREATE TEMPORARY TABLE
141  sim_sngl_far
142  AS
143  SELECT
144  sngl_inspiral.process_id AS pid,
145  sngl_inspiral.Gamma1 AS Gamma1,
146  sim_id_combined_far.far AS far,
147  sim_inspiral.simulation_id AS simulation_id,
148  sim_inspiral.*
149  FROM
150  sim_inspiral
151  JOIN sim_id_sngl_id ON (
152  sim_inspiral.simulation_id == sim_id_sngl_id.sim_id
153  )
154  JOIN sngl_inspiral ON (
155  sngl_inspiral.event_id == sim_id_sngl_id.sngl_id
156  )
157  JOIN sim_id_combined_far ON (
158  sim_id_combined_far.sim_id == sim_id_sngl_id.sim_id
159  )
160  """)
161 
162  connection.cursor().execute("DROP INDEX sim_id_combined_far_index")
163  connection.cursor().execute("DROP INDEX sim_id_sngl_id_index")
164 
165 def create_coinc_view(connection, options):
166  connection.cursor().execute("""
167 CREATE TEMPORARY TABLE
168  sngl_far
169 AS
170  SELECT
171  coinc_event.process_id,
172  (SELECT sngl_inspiral.Gamma1 FROM sngl_inspiral WHERE map.event_id == sngl_inspiral.event_id LIMIT 1),
173  combined_far AS far,
174  coinc_inspiral.coinc_event_id,
175  coinc_inspiral.*
176  FROM coinc_inspiral
177  JOIN coinc_event
178  ON coinc_event.coinc_event_id = coinc_inspiral.coinc_event_id
179  JOIN coinc_event_map as map
180  ON map.coinc_event_id == coinc_event.coinc_event_id
181  WHERE
182  map.table_name = "sngl_inspiral"
183  AND combined_far < ?
184  AND NOT EXISTS (SELECT * FROM time_slide WHERE time_slide.time_slide_id == coinc_event.time_slide_id AND time_slide.offset != 0);
185 """, (float(options.far_threshold),))
186 
187 if options.injection_database:
188  db = options.injection_database
189 else:
190  db = options.zerolag_database
191 
192 tmp_space = options.tmp_space
193 num_inspiral_jobs = options.max_number_inspiral_jobs
194 analysis_dir = os.path.dirname(db)
195 
196 working_filename = dbtables.get_connection_filename(db, tmp_path = tmp_space, verbose = True)
197 connection = sqlite3.connect(str(working_filename))
198 
199 if options.injection_database:
200  create_sim_coinc_view(connection)
201  s_row = {}
202  xmldoc = dbtables.get_xml(connection)
203  inspiral_table = lsctables.SimInspiralTable.get_table(xmldoc)
204  for record in connection.cursor().execute("""
205  SELECT
206  *
207  FROM
208  sim_sngl_far
209  WHERE
210  far <= %e
211  ORDER BY
212  far ASC
213  LIMIT ?
214  """ % (options.far_threshold,), (int(num_inspiral_jobs),)):
215  process_id = record[0]
216  bank_id = record[1]
217  far = record[2]
218  sid = record[3]
219  srow = record[4:]
220  s_row[(bank_id, process_id, sid)] = inspiral_table.row_from_cols(srow)
221 
222 elif options.zerolag_database:
223  create_coinc_view(connection, options)
224  s_row = {}
225  xmldoc = dbtables.get_xml(connection)
226  coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(xmldoc)
227  for record in connection.cursor().execute("""
228  SELECT
229  *
230  FROM
231  sngl_far
232  WHERE
233  far <= %e
234  ORDER BY
235  far ASC
236  LIMIT ?
237  """ % (options.far_threshold,), (int(num_inspiral_jobs),)):
238  process_id = record[0]
239  bank_id = record[1]
240  far = record[2]
241  sid = record[3]
242  srow = record[4:]
243  s_row[(bank_id, process_id, sid)] = coinc_inspiral_table.row_from_cols(srow)
244 
245 master_opts_dict = {
246  "gps-start-time":None,
247  "gps-end-time": None,
248  "psd-fft-length": None,
249  "likelihood-snapshot-interval": 100000.0,
250  "track-psd": "",
251  "min-instruments": None,
252  "gracedb-far-threshold": options.far_threshold,
253  "gracedb-service-url": None,
254  "ht-gate-threshold": None,
255  "veto-segments-name": "vetoes",
256  "fir-stride": 0.25,
257  "gracedb-group": "CBC",
258  "coincidence-threshold": 0.005,
259  "control-peak-time": 0,
260  "gracedb-pipeline": "gstlal",
261  "data-source": None,
262  "frame-segments-name": None,
263  "tmp-space": None,
264  "gracedb-search": "AllSky",
265  "channel-name": None,
266  "singles-threshold": "inf",
267  "local-frame-caching":"",
268  "verbose": ""
269 }
270 
271 master_input_dict = {
272  "reference-psd": None,
273  "svd-bank": None, # FIXME THIS ONE IS TRICKY
274  "ranking-stat-pdf": "%s/post_marginalized_likelihood.xml.gz" % analysis_dir,
275  "ranking-stat-input": None, # FIXME THIS ONE IS TRICKY
276  "veto-segments-file": None,
277  "frame-segments-file": None,
278  "frame-cache": None,
279  "time-slide-file": None,
280  "injections": None, # FIXME make this just a single injection with the correct parameters
281  }
282 
283 master_output_dict = {
284  "ranking-stat-output": "not_used.xml.gz",
285  "zerolag-rankingstat-pdf": "notused2.xml.gz",
286  "output": None,
287 }
288 
289 try:
290  os.mkdir("logs")
291 except:
292  pass
293 dag = dagparts.DAG("trigger_pipe")
294 
295 gstlalInspiralInjJob = dagparts.DAGJob("gstlal_inspiral",
296  tag_base="gstlal_inspiral_inj",
297  condor_commands = {"request_memory":"5gb",
298  "request_cpus":"2",
299  "want_graceful_removal":"True",
300  "kill_sig":"15"}
301  )
302 
303 gstlalInspiralJob = dagparts.DAGJob("gstlal_inspiral",
304  tag_base="gstlal_inspiral",
305  condor_commands = {"request_memory":"5gb",
306  "request_cpus":"2",
307  "want_graceful_removal":"True",
308  "kill_sig":"15"}
309  )
310 
311 noIlwdcharJob = dagparts.DAGJob("ligolw_no_ilwdchar")
312 bashJob = dagparts.DAGJob("bash")
313 
314 
315 def updatedict(x, y):
316  for k in x:
317  if x[k] is None:
318  try:
319  x[k] = y[k]
320  except KeyError as e:
321  pass
322 
323 def fixrelpath(x, ys):
324  for y in ys:
325  x[y] = "%s/%s" % (analysis_dir, x[y][0])
326 
327 def new_inj_file(row, output):
328  xmldoc = ligolw.Document()
329  lw = xmldoc.appendChild(ligolw.LIGO_LW())
330  sim_inspiral_table = lsctables.New(lsctables.SimInspiralTable)
331  lw.appendChild(sim_inspiral_table)
332  sim_inspiral_table.append(row)
333  ligolw_utils.write_filename(xmldoc, output)
334 
335 def new_file(row, output):
336  xmldoc = ligolw.Document()
337  lw = xmldoc.appendChild(ligolw.LIGO_LW())
338  inspiral_table = lsctables.New(lsctables.SnglInspiralTable)
339  lw.appendChild(inspiral_table)
340  inspiral_table.append(row)
341  ligolw_utils.write_filename(xmldoc, output)
342 
343 
344 try:
345  os.mkdir("inj_files")
346 except OSError:
347  pass
348 
349 try:
350  os.mkdir("lloid_files")
351 except OSError:
352  pass
353 
354 mass_model = analysis_dir + '/gstlal_inspiral_mass_model'
355 try:
356  os.mkdir("gstlal_inspiral_mass_model")
357  os.system('cp -r %s .' % (mass_model,))
358 except OSError:
359  pass
360 
361 bayesdir = "bayestar_input"
362 try:
363  os.mkdir(bayesdir)
364 except OSError:
365  pass
366 
367 
368 f = open("process.sh", "w")
369 f.write("""#!/usr/bin/bash
370 ID=$1
371 FILE=$(gstlal_inspiral_best_coinc_file lloid_files/${ID}/*CBC_AllSky-*-0.xml)
372 ligolw_no_ilwdchar ${FILE}
373 mkdir -p bayestar_input/${ID}/
374 gstlal_ligolw_add_without_reassign ${FILE} inj_files/${ID}_inj.xml.gz --output bayestar_input/${ID}/${ID}_event.xml.gz
375 lalapps_inspinjfind --time-window 0.9 bayestar_input/${ID}/${ID}_event.xml.gz
376 gstlal_ilwdify bayestar_input/${ID}/${ID}_event.xml.gz
377 """)
378 f.close()
379 
380 for job_id, (bankid, process_id, sid) in enumerate(s_row, start=1):
381  # FIXME Need to add option for dist stats output
382  job_dict = {}
383  ht_gate = []
384  for param, value in connection.cursor().execute("SELECT param, value FROM process_params WHERE process_id == ?", (process_id,)):
385  if param == "--svd-bank-cache":
386  svd_start, svd_stop = os.path.split(value)[1].split("-")[1].split("_")[0:2]
387  # ht gate stuff OMG IS THIS SILLY
388  if param == "--ht-gate-threshold":
389  ht_gate.append(value)
390  job_dict.setdefault(param.replace("--",""), []).append(value)
391  ht_gate_id = int(bankid) - int(svd_start)
392  this_opts_dict = master_opts_dict.copy()
393  updatedict(this_opts_dict, job_dict)
394  this_input_dict = master_input_dict.copy()
395  updatedict(this_input_dict, job_dict)
396  this_output_dict = master_output_dict.copy()
397  updatedict(this_output_dict, job_dict)
398 
399  # ht gate stuff OMG IS THIS SILLY
400  this_input_dict["ht-gate-threshold"] = ht_gate[ht_gate_id]
401 
402  # FIX some stuff
403  fixrelpath(this_input_dict, ("reference-psd", "frame-cache", "time-slide-file", "veto-segments-file", "frame-segments-file"))
404 
405  # make a custom injection file
406  if options.injection_database:
407  inj_file_name = "inj_files/%d_%d_%d_inj.xml.gz" % (job_id, bankid, process_id)
408  new_inj_file(s_row[(bankid, process_id, sid)], inj_file_name)
409  this_input_dict["injections"] = inj_file_name
410  else:
411  coal_time = s_row[(bankid, process_id, sid)].end_time
412  this_input_dict["reconstruction-segment"] = "%d:%d" % (coal_time - 3, coal_time + 3)
413  # FIXME hacks for the svd
414  instruments = [x.split("=")[0] for x in this_opts_dict["channel-name"]]
415  banks = ["%s:%s" % (ifo, glob.glob("%s/gstlal_svd_bank/%s-%04d_SVD*" % (analysis_dir, ifo, bankid))[0]) for ifo in instruments]
416  this_input_dict["svd-bank"] = ",".join(banks)
417 
418  # FIXME don't hardcode H1L1V1
419  ranking_stat_pdf = glob.glob("%s/gstlal_inspiral_marginalize_likelihood/H1L1V1-%04d_MARG_DIST_STATS*" % (analysis_dir, bankid))[0]
420  this_input_dict["ranking-stat-input"] = ranking_stat_pdf
421 
422  # just name the output the same as the input
423  outdir = "lloid_files/%d_%d_%d" % (job_id, bankid, process_id)
424  try:
425  os.mkdir(outdir)
426  except OSError:
427  pass
428 
429  output_file_name = "%s/%d_%d_%d_lloid.xml.gz" % (outdir, job_id, bankid, process_id)
430  this_output_dict["output"] = output_file_name
431 
432  this_opts_dict["gracedb-service-url"] = "file://%s/%s" % (os.getcwd(), outdir)
433 
434  if options.injection_database:
435  node = dagparts.DAGNode(gstlalInspiralInjJob, dag, parent_nodes = [], opts = this_opts_dict, input_files = this_input_dict, output_files = this_output_dict)
436  # all the remaining post processing
437  # FIXME this only works for injections
438  node = dagparts.DAGNode(bashJob, dag, parent_nodes = [node], opts = {"":["process.sh", "%d_%d_%d" % (job_id, bankid, process_id)]})
439  if options.zerolag_database:
440  node = dagparts.DAGNode(gstlalInspiralJob, dag, parent_nodes = [], opts = this_opts_dict, input_files = this_input_dict, output_files = this_output_dict)
441 
442 
443 
444 dag.write_sub_files()
445 dag.write_dag()
446 dag.write_script()