gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_rerank_pipe
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2011-2014 Chad Hanna
4 # Copyright (C) 2019 Patrick Godwin
5 #
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the
8 # Free Software Foundation; either version 2 of the License, or (at your
9 # option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 # Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 
20 
21 ### The offline gstlal inspiral workflow generator; Use to make HTCondor DAGs to rerank triggers
22 ###
23 ### Usage:
24 ### ------
25 ###
26 ### It is rare that you would invoke this program in a standalone mode. Usually
27 ### the inputs are complicated and best automated via a Makefile.
28 
29 """
30 This program makes a dag to rerank triggers from offline runs
31 """
32 
33 __author__ = 'Chad Hanna <chad.hanna@ligo.org>, Patrick Godwin <patrick.godwin@ligo.org>'
34 
35 #----------------------------------------------------------
36 ### imports
37 
38 from collections import OrderedDict
39 from optparse import OptionParser
40 import os
41 
42 import numpy
43 
44 from lal.utils import CacheEntry
45 
46 from ligo import segments
47 from ligo.lw import ligolw
48 from ligo.lw import lsctables
49 import ligo.lw.utils as ligolw_utils
50 
51 from gstlal import inspiral_pipe
52 from gstlal import dagparts
53 from gstlal import datasource
54 from gstlal import paths as gstlal_config_paths
55 
56 
57 #----------------------------------------------------------
58 ### ligolw initialization
59 
60 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
61  pass
62 lsctables.use_in(LIGOLWContentHandler)
63 
64 
65 #----------------------------------------------------------
66 ### command line options
67 
68 def parse_command_line():
69  parser = OptionParser(description = __doc__)
70  parser.add_option("--gps-start-time", metavar = "seconds", help = "Set the start time of the segment to analyze in GPS seconds. Required unless --data-source=lvshm")
71  parser.add_option("--gps-end-time", metavar = "seconds", help = "Set the end time of the segment to analyze in GPS seconds. Required unless --data-source=lvshm")
72 
73  # mass model options
74  parser.add_option("--template-bank", metavar = "filename", help = "Set the template bank xml file.")
75  parser.add_option("--mass-model", metavar = "filename", help = "Set the name of the mass model. Options are 'narrow-bns', 'broad-bns', 'bbh', 'ligo', 'detected-logm', 'uniform-template', or 'file'")
76  parser.add_option("--mass-model-file", metavar = "filename", help = "Set the name of the mass model file, e.g., mass_model.h5. Required if --mass-model=file")
77 
78  # dtdphi option
79  parser.add_option("--dtdphi-file", metavar = "filename", action = "append", help = "dtdphi snr ratio pdfs to read from (hdf5 format)")
80 
81  # idq option
82  parser.add_option("--idq-file", metavar = "filename", action = "append", help = "idq glitch file (hdf5 format)")
83 
84  # trigger generation options
85  parser.add_option("--web-dir", metavar = "directory", help = "Set the web directory like /home/USER/public_html")
86  parser.add_option("--coincidence-threshold", metavar = "value", type = "float", default = 0.005, help = "Set the coincidence window in seconds (default = 0.005). The light-travel time between instruments will be added automatically in the coincidence test.")
87  parser.add_option("--min-instruments", metavar = "count", type = "int", default = 2, help = "Set the minimum number of instruments that must contribute triggers to form a candidate (default = 2).")
88  parser.add_option("--reference-likelihood-file", metavar = "file", help = "Set a reference likelihood file to compute initial likelihood ratios. Required")
89  parser.add_option("--verbose", action = "store_true", help = "Be verbose")
90  parser.add_option("--ranking-stat-samples", metavar = "N", default = 2**24, type = "int", help = "Construct ranking statistic histograms by drawing this many samples from the ranking statistic generator (default = 2^24).")
91 
92  # veto options
93  parser.add_option("--vetoes", metavar = "filename", help = "Set the veto xml file.")
94  parser.add_option("--frame-segments-file", metavar = "filename", help = "Set the name of the LIGO light-weight XML file from which to load frame segments. Optional iff --data-source=frames")
95  parser.add_option("--frame-segments-name", metavar = "name", help = "Set the name of the segments to extract from the segment tables. Required iff --frame-segments-file is given")
96 
97  parser.add_option("--injections", action = "append", help = "append injection files to analyze. Must prepend filename with X:Y:, where X and Y are floats, e.g. 1.2:3.1:filename, so that the injections are only searched for in regions of the template bank with X <= chirp mass < Y.")
98  parser.add_option("--analysis-path", metavar = "path", help = "Set the path to the analysis you want to rerank.")
99 
100  # caches
101  parser.add_option("--dist-stats-cache", metavar = "filename", help = "Set the cache file for dist stats")
102  parser.add_option("--lloid-cache", metavar = "filename", help = "Set the cache file for LLOID")
103  parser.add_option("--bank-cache", metavar = "filenames", action = "append", help = "Set the bank cache files in format H1=H1.cache,H2=H2.cache, etc.. (can be given multiple times)")
104 
105  # Data from a zero lag run in the case of an injection-only run.
106  parser.add_option("--svd-bank-cache", metavar = "filename", help = "Set the cache file for svd banks (required iff running injection-only analysis)")
107  # NOTE: delete unless we want db metadata. injection db?
108  parser.add_option("--non-injection-db", metavar = "filename", help = "Set the non injection data base file (required iff running injection-only analysis)")
109  parser.add_option("--marginalized-likelihood-file", metavar = "filename", help = "Set the marginalized likelihood file (required iff running injection-only analysis or performing rerank with the marginalized_likelihood file already computed.)")
110  parser.add_option("--marginalized-likelihood-with-zerolag-file", metavar = "filename", help = "Set the marginalized likelihood with zerolag file (required iff running injection-only analysis)")
111 
112  # Condor commands
113  parser.add_option("--condor-command", action = "append", default = [], metavar = "command=value", help = "set condor commands of the form command=value; can be given multiple times")
114 
115  options, filenames = parser.parse_args()
116 
117  if options.template_bank:
118  bank_xmldoc = ligolw_utils.load_filename(options.template_bank, verbose = options.verbose, contenthandler = LIGOLWContentHandler)
119  sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(bank_xmldoc)
120  assert len(sngl_inspiral_table) == len(set([r.template_id for r in sngl_inspiral_table])), "Template bank ids are not unique"
121 
122  if options.mass_model not in ("narrow-bns", "broad-bns", "bbh", "ligo", "detected-logm", "uniform-template", "file"):
123  raise ValueError("--mass-model must be 'narrow-bns', 'broad-bns', 'bbh', 'ligo', 'detected-logm', 'uniform-template', or 'file'")
124  if options.mass_model == "file" and not options.mass_model_file:
125  raise ValueError("--mass-model-file must be provided if --mass-model=file")
126 
127  if not options.dtdphi_file:
128  options.dtdphi_file = [os.path.join(gstlal_config_paths["pkgdatadir"], "inspiral_dtdphi_pdf.h5")] * len(options.bank_cache)
129 
130  if len(options.dtdphi_file) != len(options.bank_cache):
131  raise ValueError("You must provide as many dtdphi files as banks")
132 
133  #FIXME a hack to find the sql paths
134  share_path = os.path.split(dagparts.which('gstlal_inspiral'))[0].replace('bin', 'share/gstlal')
135  options.cluster_sql_file = os.path.join(share_path, 'simplify_and_cluster.sql')
136  options.snr_cluster_sql_file = os.path.join(share_path, 'snr_simplify_and_cluster.sql')
137  options.injection_snr_cluster_sql_file = os.path.join(share_path, 'inj_snr_simplify_and_cluster.sql')
138  options.injection_sql_file = os.path.join(share_path, 'inj_simplify_and_cluster.sql')
139  options.injection_proc_sql_file = os.path.join(share_path, 'simplify_proc_table_in_inj_file.sql')
140 
141  return options, filenames
142 
143 
144 #----------------------------------------------------------
145 ### DAG utilities
146 
147 def set_up_jobs(options):
148  jobs = {}
149 
150  # default condor options
151  default_condor_opts = OrderedDict()
152  default_condor_opts['want_graceful_removal'] = "True"
153  default_condor_opts['kill_sig'] = "15"
154  default_condor_opts['request_cpus'] = "1"
155  default_condor_opts['+MemoryUsage'] = "( 1000 ) * 2 / 3"
156  default_condor_opts['request_memory'] = "( MemoryUsage ) * 3 / 2"
157  default_condor_opts['periodic_hold'] = "( MemoryUsage >= ( ( RequestMemory ) * 3 / 2 ) )"
158  default_condor_opts['periodic_release'] = "(JobStatus == 5) && ((CurrentTime - EnteredCurrentStatus) > 180) && (HoldReasonCode != 34)"
159 
160  # job-specific condor options
161  calc_rank_pdf_condor_opts = default_condor_opts.copy()
162  calc_rank_pdf_condor_opts['+MemoryUsage'] = "( 3000 ) * 2 / 3"
163  calc_rank_pdf_condor_opts['request_cpus'] = "4"
164 
165  inj_snr_condor_opts = default_condor_opts.copy()
166  inj_snr_condor_opts['+MemoryUsage'] = "( 2000 ) * 2 / 3"
167  inj_snr_condor_opts['request_cpus'] = "2"
168 
169  marg_condor_opts = default_condor_opts.copy()
170  marg_condor_opts['+MemoryUsage'] = "( 2000 ) * 2 / 3"
171 
172  # set condor commands
173  base_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, default_condor_opts)
174  calc_rank_pdf_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, calc_rank_pdf_condor_opts)
175  inj_snr_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, inj_snr_condor_opts)
176  marg_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, marg_condor_opts)
177  sh_condor_commands = dagparts.condor_command_dict_from_opts(options.condor_command, {"want_graceful_removal":"True", "kill_sig":"15"})
178 
179  # jobs only needed to find paths
180  # NOTE: find a better way to do this?
181  jobs['svd'] = dagparts.DAGJob("gstlal_svd_bank", condor_commands = base_condor_commands)
182  jobs['medianPSD'] = dagparts.DAGJob("gstlal_median_of_psds", condor_commands = base_condor_commands)
183 
184  # set up rest of jobs
185  jobs['model'] = dagparts.DAGJob("gstlal_inspiral_mass_model", condor_commands = base_condor_commands)
186  jobs['modelAdd'] = dagparts.DAGJob("gstlal_inspiral_add_mass_models", condor_commands = base_condor_commands)
187  jobs['horizon'] = dagparts.DAGJob("gstlal_plot_psd_horizon", condor_commands = base_condor_commands)
188  jobs['createPriorDistStats'] = dagparts.DAGJob("gstlal_inspiral_create_prior_diststats", condor_commands = base_condor_commands)
189  jobs['calcRankPDFs'] = dagparts.DAGJob("gstlal_inspiral_calc_rank_pdfs", condor_commands = calc_rank_pdf_condor_commands)
190  jobs['calcRankPDFsWithZerolag'] = dagparts.DAGJob("gstlal_inspiral_calc_rank_pdfs", tag_base="gstlal_inspiral_calc_rank_pdfs_with_zerolag", condor_commands=calc_rank_pdf_condor_commands)
191  jobs['calcLikelihood'] = dagparts.DAGJob("gstlal_inspiral_calc_likelihood", condor_commands = base_condor_commands)
192  jobs['marginalize'] = dagparts.DAGJob("gstlal_inspiral_marginalize_likelihood", condor_commands = marg_condor_commands)
193  jobs['marginalizeWithZerolag'] = dagparts.DAGJob("gstlal_inspiral_marginalize_likelihood", tag_base="gstlal_inspiral_marginalize_likelihood_with_zerolag", condor_commands=base_condor_commands)
194 
195  jobs['injSplitter'] = dagparts.DAGJob("gstlal_injsplitter", tag_base="gstlal_injsplitter", condor_commands = base_condor_commands)
196  jobs['gstlalInjSnr'] = dagparts.DAGJob("gstlal_inspiral_injection_snr", condor_commands = inj_snr_condor_commands)
197  jobs['ligolwAdd'] = dagparts.DAGJob("ligolw_add", condor_commands = base_condor_commands)
198  jobs['calcLikelihoodInj'] = dagparts.DAGJob("gstlal_inspiral_calc_likelihood", tag_base='gstlal_inspiral_calc_likelihood_inj', condor_commands=base_condor_commands)
199  jobs['ComputeFarFromSnrChisqHistograms'] = dagparts.DAGJob("gstlal_compute_far_from_snr_chisq_histograms", condor_commands = base_condor_commands)
200  jobs['ligolwInspinjFind'] = dagparts.DAGJob("lalapps_inspinjfind", condor_commands = base_condor_commands)
201  jobs['toSqlite'] = dagparts.DAGJob("ligolw_sqlite", tag_base = "ligolw_sqlite_from_xml", condor_commands = base_condor_commands)
202  jobs['toSqliteNoCache'] = dagparts.DAGJob("ligolw_sqlite", tag_base = "ligolw_sqlite_from_xml_final", condor_commands = base_condor_commands)
203  jobs['toXML'] = dagparts.DAGJob("ligolw_sqlite", tag_base = "ligolw_sqlite_to_xml", condor_commands = base_condor_commands)
204  jobs['lalappsRunSqlite'] = dagparts.DAGJob("lalapps_run_sqlite", condor_commands = base_condor_commands)
205  jobs['plotSummary'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", condor_commands = base_condor_commands)
206  jobs['plotSummaryIsolatePrecession'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", tag_base="gstlal_inspiral_plotsummary_isolated_precession", condor_commands=base_condor_commands)
207  jobs['plotSnglInjSummary'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", tag_base = "gstlal_inspiral_plotsummary_inj", condor_commands=base_condor_commands)
208  jobs['plotSnglInjSummaryIsolatePrecession'] = dagparts.DAGJob("gstlal_inspiral_plotsummary", tag_base="gstlal_inspiral_plotsummary_isolated_precession_inj", condor_commands=base_condor_commands)
209  jobs['plotSensitivity'] = dagparts.DAGJob("gstlal_inspiral_plot_sensitivity", condor_commands = base_condor_commands)
210  jobs['summaryPage'] = dagparts.DAGJob("gstlal_inspiral_summary_page", condor_commands = base_condor_commands)
211  jobs['plotBackground'] = dagparts.DAGJob("gstlal_inspiral_plot_background", condor_commands = base_condor_commands)
212  jobs['cp'] = dagparts.DAGJob("cp", tag_base = "cp", condor_commands = sh_condor_commands)
213  jobs['rm'] = dagparts.DAGJob("rm", tag_base = "rm_intermediate_merger_products", condor_commands = sh_condor_commands)
214 
215  return jobs
216 
217 
218 #----------------------------------------------------------
219 ### main
220 
221 if __name__ == '__main__':
222  options, filenames = parse_command_line()
223  jobs = set_up_jobs(options)
224 
225  # load analysis output from run
226  lloid_output, lloid_diststats, svd_dtdphi_map, instrument_set = inspiral_pipe.load_analysis_output(options)
227  instruments = "".join(sorted(instrument_set))
228 
229  # load reference psd
230  boundary_seg = segments.segment(int(options.gps_start_time), int(options.gps_end_time))
231  gpsmod5 = str(int(boundary_seg[0]))[:5]
232  ref_psd_path = os.path.join(options.analysis_path, inspiral_pipe.subdir_path([jobs['medianPSD'].output_path, gpsmod5]))
233  reference_psd = dagparts.T050017_filename(instruments, "REFERENCE_PSD", boundary_seg, '.xml.gz', path = ref_psd_path)
234 
235  # output directories
236  output_dir = "plots"
237  if not os.path.exists("logs"):
238  os.mkdir("logs")
239 
240  #
241  # Set up DAG architecture
242  #
243 
244  dag = dagparts.DAG("trigger_rerank_pipe")
245 
246  # generate xml integrity checker (if requested) and pre-script to back up data
247  #inspiral_pipe.set_up_scripts(options)
248 
249  # mass model job
250  model_node, model_file = inspiral_pipe.mass_model_layer(dag, jobs, [], instruments, options, boundary_seg, reference_psd)
251 
252  if not options.marginalized_likelihood_file:
253  # marginalize jobs
254  marg_nodes = inspiral_pipe.marginalize_layer(dag, jobs, [], lloid_output, lloid_diststats, options, boundary_seg, instrument_set, model_node, model_file, reference_psd, svd_dtdphi_map, options.idq_file)
255 
256  # calc rank PDF jobs
257  rankpdf_nodes, rankpdf_zerolag_nodes = inspiral_pipe.calc_rank_pdf_layer(dag, jobs, marg_nodes, options, boundary_seg, instrument_set)
258 
259  # final marginalization step
260  final_marg_nodes, margfiles_to_delete = inspiral_pipe.final_marginalize_layer(dag, jobs, rankpdf_nodes, rankpdf_zerolag_nodes, options)
261  else:
262  # Create fake marg_nodes and final_marg_nodes objects for the likelihood and compute far layers
263  marg_nodes, final_marg_nodes = [], []
264 
265  margfiles_to_delete = []
266 
267  # likelihood jobs
268  likelihood_nodes = inspiral_pipe.likelihood_layer(dag, jobs, marg_nodes, lloid_output, lloid_diststats, options, boundary_seg, instrument_set)
269 
270  # Setup clustering and/or merging
271  # after all of the likelihood ranking and preclustering is finished put everything into single databases based on the injection file (or lack thereof)
272  injdbs, noninjdb, final_sqlite_nodes, dbs_to_delete = inspiral_pipe.sql_cluster_and_merge_layer(dag, jobs, likelihood_nodes, [], options, boundary_seg, instruments)
273 
274  # Compute FAR
275  farnode = inspiral_pipe.compute_far_layer(dag, jobs, final_marg_nodes, injdbs, noninjdb, final_sqlite_nodes, options)
276 
277  # make summary plots
278  plotnodes = inspiral_pipe.summary_plot_layer(dag, jobs, farnode, options, injdbs, noninjdb, output_dir)
279 
280  # make a web page
281  inspiral_pipe.summary_page_layer(dag, jobs, plotnodes, options, boundary_seg, injdbs, output_dir)
282 
283  # rm intermediate merger products
284  inspiral_pipe.clean_merger_products_layer(dag, jobs, plotnodes, dbs_to_delete, margfiles_to_delete)
285 
286  #
287  # generate DAG files
288  #
289 
290  dag.write_sub_files()
291  dag.write_dag()
292  dag.write_script()
293  dag.write_cache()
def clean_merger_products_layer