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
6 from optparse
import OptionParser
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
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.")
26 options, filenames = parser.parse_args()
28 return options, filenames
30 options, filenames = parse_command_line()
32 if not (options.injection_database or options.zerolag_database):
33 raise ValueError(
"You must provide a database.")
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!!")
38 if not options.tmp_space:
39 if
'_CONDOR_SCRATCH_DIR' in os.environ:
40 options.tmp_space = os.environ[
'_CONDOR_SCRATCH_DIR']
42 options.tmp_space = os.environ[
'TMPDIR']
46 # copied from gstlal_inspiral_plotsummary
47 def create_sim_coinc_view(connection):
49 Construct a sim_inspiral --> best matching coinc_event mapping.
50 Only injections that match at least one coinc get an entry in this
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.
63 connection.cursor().execute(
"""
64 CREATE TEMPORARY TABLE
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);
80 connection.cursor().execute(
"CREATE INDEX IF NOT EXISTS sim_coinc_map_helper_index ON sim_coinc_map_helper (sid, cid);")
83 # FIXME NOTE FIXME this selects triple times with no more than two ifos to test the itacac sub threshold stuff
86 connection.cursor().execute(
"""
87 CREATE TEMPORARY TABLE
91 sim_inspiral.simulation_id AS simulation_id,
107 coinc_event_id IS NOT NULL;
111 connection.cursor().execute(
"DROP INDEX sim_coinc_map_helper_index;")
113 connection.cursor().execute(
"""
114 CREATE TEMPORARY TABLE
118 coinc_inspiral.combined_far AS far, sim_coinc_map.simulation_id AS sim_id
121 JOIN coinc_inspiral ON ( coinc_inspiral.coinc_event_id == sim_coinc_map.coinc_event_id )
124 connection.cursor().execute(
"""
125 CREATE TEMPORARY TABLE
129 sim_coinc_map.simulation_id AS sim_id, sngl_inspiral.event_id AS sngl_id
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 )
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)")
139 connection.cursor().execute(
"""
140 CREATE TEMPORARY TABLE
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,
151 JOIN sim_id_sngl_id ON (
152 sim_inspiral.simulation_id == sim_id_sngl_id.sim_id
154 JOIN sngl_inspiral ON (
155 sngl_inspiral.event_id == sim_id_sngl_id.sngl_id
157 JOIN sim_id_combined_far ON (
158 sim_id_combined_far.sim_id == sim_id_sngl_id.sim_id
162 connection.cursor().execute(
"DROP INDEX sim_id_combined_far_index")
163 connection.cursor().execute(
"DROP INDEX sim_id_sngl_id_index")
165 def create_coinc_view(connection, options):
166 connection.cursor().execute(
"""
167 CREATE TEMPORARY TABLE
171 coinc_event.process_id,
172 (SELECT sngl_inspiral.Gamma1 FROM sngl_inspiral WHERE map.event_id == sngl_inspiral.event_id LIMIT 1),
174 coinc_inspiral.coinc_event_id,
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
182 map.table_name = "sngl_inspiral
"
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),))
187 if options.injection_database:
188 db = options.injection_database
190 db = options.zerolag_database
192 tmp_space = options.tmp_space
193 num_inspiral_jobs = options.max_number_inspiral_jobs
194 analysis_dir = os.path.dirname(db)
196 working_filename = dbtables.get_connection_filename(db, tmp_path = tmp_space, verbose = True)
197 connection = sqlite3.connect(str(working_filename))
199 if options.injection_database:
200 create_sim_coinc_view(connection)
202 xmldoc = dbtables.get_xml(connection)
203 inspiral_table = lsctables.SimInspiralTable.get_table(xmldoc)
204 for record in connection.cursor().execute(
"""
214 """ % (options.far_threshold,), (
int(num_inspiral_jobs),)):
215 process_id = record[0]
220 s_row[(bank_id, process_id, sid)] = inspiral_table.row_from_cols(srow)
222 elif options.zerolag_database:
223 create_coinc_view(connection, options)
225 xmldoc = dbtables.get_xml(connection)
226 coinc_inspiral_table = lsctables.CoincInspiralTable.get_table(xmldoc)
227 for record in connection.cursor().execute(
"""
237 """ % (options.far_threshold,), (
int(num_inspiral_jobs),)):
238 process_id = record[0]
243 s_row[(bank_id, process_id, sid)] = coinc_inspiral_table.row_from_cols(srow)
246 "gps-start-time":None,
247 "gps-end-time": None,
248 "psd-fft-length": None,
249 "likelihood-snapshot-interval": 100000.0,
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",
257 "gracedb-group":
"CBC",
258 "coincidence-threshold": 0.005,
259 "control-peak-time": 0,
260 "gracedb-pipeline":
"gstlal",
262 "frame-segments-name": None,
264 "gracedb-search":
"AllSky",
265 "channel-name": None,
266 "singles-threshold":
"inf",
267 "local-frame-caching":
"",
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,
279 "time-slide-file": None,
280 "injections": None, # FIXME make
this just a single injection with the correct parameters
283 master_output_dict = {
284 "ranking-stat-output":
"not_used.xml.gz",
285 "zerolag-rankingstat-pdf":
"notused2.xml.gz",
293 dag = dagparts.DAG(
"trigger_pipe")
295 gstlalInspiralInjJob = dagparts.DAGJob(
"gstlal_inspiral",
296 tag_base=
"gstlal_inspiral_inj",
297 condor_commands = {
"request_memory":
"5gb",
299 "want_graceful_removal":
"True",
303 gstlalInspiralJob = dagparts.DAGJob(
"gstlal_inspiral",
304 tag_base=
"gstlal_inspiral",
305 condor_commands = {
"request_memory":
"5gb",
307 "want_graceful_removal":
"True",
311 noIlwdcharJob = dagparts.DAGJob(
"ligolw_no_ilwdchar")
312 bashJob = dagparts.DAGJob(
"bash")
315 def updatedict(x, y):
320 except KeyError as e:
323 def fixrelpath(x, ys):
325 x[y] =
"%s/%s" % (analysis_dir, x[y][0])
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)
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)
345 os.mkdir(
"inj_files")
350 os.mkdir(
"lloid_files")
354 mass_model = analysis_dir +
'/gstlal_inspiral_mass_model'
356 os.mkdir(
"gstlal_inspiral_mass_model")
357 os.system(
'cp -r %s .' % (mass_model,))
361 bayesdir =
"bayestar_input"
368 f = open(
"process.sh",
"w")
369 f.write(
"""#!/usr/bin/bash
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
380 for job_id, (bankid, process_id, sid) in enumerate(s_row, start=1):
381 # FIXME Need to add option for dist stats output
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)
399 # ht gate stuff OMG IS THIS SILLY
400 this_input_dict[
"ht-gate-threshold"] = ht_gate[ht_gate_id]
403 fixrelpath(this_input_dict, (
"reference-psd",
"frame-cache",
"time-slide-file",
"veto-segments-file",
"frame-segments-file"))
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
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)
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
422 # just name the output the same as the input
423 outdir =
"lloid_files/%d_%d_%d" % (job_id, bankid, process_id)
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
432 this_opts_dict[
"gracedb-service-url"] =
"file://%s/%s" % (os.getcwd(), outdir)
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)
444 dag.write_sub_files()