3 # Copyright (C) 2011-2014 Chad Hanna
4 # Copyright (C) 2019 Patrick Godwin
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.
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.
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.
21 ### The offline gstlal inspiral workflow generator; Use to make HTCondor DAGs to rerank triggers
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.
30 This program makes a dag to rerank triggers from offline runs
33 __author__ =
'Chad Hanna <chad.hanna@ligo.org>, Patrick Godwin <patrick.godwin@ligo.org>'
35 #----------------------------------------------------------
38 from collections
import OrderedDict
39 from optparse
import OptionParser
44 from lal.utils
import CacheEntry
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
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
57 #----------------------------------------------------------
58 ### ligolw initialization
60 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
62 lsctables.use_in(LIGOLWContentHandler)
65 #----------------------------------------------------------
66 ### command line options
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")
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")
79 parser.add_option("--dtdphi-file", metavar = "filename", action = "append", help = "dtdphi snr ratio pdfs to read from (hdf5 format)")
82 parser.add_option("--idq-file", metavar = "filename", action = "append", help = "idq glitch file (hdf5 format)")
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).")
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")
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.")
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)")
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)")
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")
115 options, filenames = parser.parse_args()
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"
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")
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)
130 if len(options.dtdphi_file) != len(options.bank_cache):
131 raise ValueError("You must provide as many dtdphi files as banks")
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')
141 return options, filenames
144 #----------------------------------------------------------
147 def set_up_jobs(options):
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)"
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"
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"
169 marg_condor_opts = default_condor_opts.copy()
170 marg_condor_opts['+MemoryUsage'] = "( 2000 ) * 2 / 3"
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"})
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)
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)
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)
218 #----------------------------------------------------------
221 if __name__ == '__main__':
222 options, filenames = parse_command_line()
223 jobs = set_up_jobs(options)
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))
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)
237 if not os.path.exists("logs"):
241 # Set up DAG architecture
244 dag = dagparts.DAG("trigger_rerank_pipe")
246 # generate xml integrity checker (if requested) and pre-script to back up data
247 #inspiral_pipe.set_up_scripts(options)
250 model_node, model_file = inspiral_pipe.
mass_model_layer(dag, jobs, [], instruments, options, boundary_seg, reference_psd)
252 if not options.marginalized_likelihood_file:
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)
257 rankpdf_nodes, rankpdf_zerolag_nodes = inspiral_pipe.calc_rank_pdf_layer(dag, jobs, marg_nodes, options, boundary_seg, instrument_set)
259 # final marginalization step
260 final_marg_nodes, margfiles_to_delete = inspiral_pipe.final_marginalize_layer(dag, jobs, rankpdf_nodes, rankpdf_zerolag_nodes, options)
262 # Create fake marg_nodes and final_marg_nodes objects for the likelihood and compute far layers
263 marg_nodes, final_marg_nodes = [], []
265 margfiles_to_delete = []
268 likelihood_nodes = inspiral_pipe.likelihood_layer(dag, jobs, marg_nodes, lloid_output, lloid_diststats, options, boundary_seg, instrument_set)
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)
275 farnode = inspiral_pipe.
compute_far_layer(dag, jobs, final_marg_nodes, injdbs, noninjdb, final_sqlite_nodes, options)
278 plotnodes = inspiral_pipe.summary_plot_layer(dag, jobs, farnode, options, injdbs, noninjdb, output_dir)
281 inspiral_pipe.
summary_page_layer(dag, jobs, plotnodes, options, boundary_seg, injdbs, output_dir)
283 # rm intermediate merger products
290 dag.write_sub_files()
def clean_merger_products_layer