3 # Copyright (C) 2011--2013 Kipp Cannon, Chad Hanna, Drew Keppel
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 ### Compute FAR and FAP distributions from the likelihood CCDFs.
22 # =============================================================================
26 # =============================================================================
30 from optparse
import OptionParser
35 from pysqlite2
import dbapi2 as sqlite3
36 sqlite3.enable_callback_tracebacks(True)
40 from ligo.lw
import ligolw
41 from ligo.lw
import dbtables
42 from ligo.lw
import lsctables
43 from ligo.lw
import utils as ligolw_utils
44 from ligo.lw.utils
import process as ligolw_process
45 from lalinspiral
import thinca
46 from gstlal
import far
50 # =============================================================================
54 # =============================================================================
58 def parse_command_line():
59 parser = OptionParser()
60 parser.add_option(
"--background-bins-file", metavar =
"filename", help =
"Set the name of the xml file containing the marginalized likelihood (required).")
61 parser.add_option(
"--tmp-space", metavar =
"dir", help =
"Set the name of the tmp space if working with sqlite.")
62 parser.add_option(
"--non-injection-db", metavar =
"filename", default = [], action =
"append", help =
"Provide the name of a database from a non-injection run. Can be given multiple times.")
63 parser.add_option(
"--injection-db", metavar =
"filename", default = [], action =
"append", help =
"Provide the name of a database from an injection run. Can be given multiple times. Databases are assumed to be over the same time period as the non injection databases using the same templates. If not the results will be nonsense.")
64 parser.add_option(
"--force",
"-f", action =
"store_true", help =
"Force script to reevaluate FARs and FAPs.")
65 parser.add_option(
"--verbose",
"-v", action =
"store_true", help =
"Be verbose.")
66 options, filenames = parser.parse_args()
68 process_params = options.__dict__.copy()
70 if options.background_bins_file is None:
71 raise ValueError(
"must set --background-bins-file")
73 if not options.non_injection_db + options.injection_db:
74 raise ValueError(
"must provide at least one database file to process")
77 raise ValueError(
"unrecognized trailing arguments")
79 return options, process_params, filenames
83 # =============================================================================
87 # =============================================================================
96 options, process_params, filenames = parse_command_line()
100 # Retrieve distribution data
104 _, rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_filename(options.background_bins_file, contenthandler = far.RankingStat.LIGOLWContentHandler, verbose = options.verbose))
105 if rankingstatpdf is None:
106 raise ValueError(
"\"%s\" does not contain likelihood ratio PDFs" % options.background_bins_file)
110 # Histogram zero-lag likelihood ratios to construct extinction model.
111 # FIXME: don
't do this here. write stand-alone tool to collect zero-lag
112 # counts and have this program require that as input data. also, below,
113 # don't write any ranking statistic output file from this program.
118 print(
"beginning count of above-threshold events", file=sys.stderr)
120 rankingstatpdf.zero_lag_lr_lnpdf.array[:] = 0.
122 for n, filename in enumerate(options.non_injection_db, start = 1):
124 # get working copy of database. do not use scratch space for this,
129 print(
"%d/%d: %s" % (n, len(options.non_injection_db), filename), file=sys.stderr)
130 with dbtables.workingcopy(filename, discard = True, verbose = options.verbose) as working_filename:
131 connection = sqlite3.connect(str(working_filename))
137 xmldoc = dbtables.get_xml(connection)
138 coinc_def_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
140 rankingstatpdf.collect_zero_lag_rates(connection, coinc_def_id)
150 # Apply density estimation to zero-lag rates
154 rankingstatpdf.density_estimate_zero_lag_rates()
158 # Now generate new ranking statistic PDFs by applying the clustering
159 # extinction model, and then initialize the FAP & FAR assignment machine
163 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
167 # Iterate over databases
172 print(
"assigning FAPs and FARs", file=sys.stderr)
174 for n, filename in enumerate(options.non_injection_db + options.injection_db, start = 1):
176 # get working copy of database
180 print(
"%d/%d: %s" % (n, len(options.non_injection_db + options.injection_db), filename), file=sys.stderr)
181 if not options.force and sqlite3.connect(filename).cursor().execute(
"""SELECT EXISTS(SELECT * FROM process WHERE program == ?);""", (u
"gstlal_compute_far_from_snr_chisq_histograms",)).fetchone()[0]:
183 print(
"already processed, skipping", file=sys.stderr)
185 with dbtables.workingcopy(filename, tmp_path = options.tmp_space, verbose = options.verbose) as working_filename:
186 connection = sqlite3.connect(str(working_filename))
192 xmldoc = dbtables.get_xml(connection)
193 process = ligolw_process.register_to_xmldoc(xmldoc, u
"gstlal_compute_far_from_snr_chisq_histograms", process_params)
196 # assign FAPs and FARs
199 fapfar.assign_fapfars(connection)
202 # done, file is restored to original location
205 ligolw_process.set_process_end_time(process)
206 connection.cursor().execute(
"UPDATE process SET end_time = ? WHERE process_id == ?", (process.end_time, process.process_id))
212 print(
"FAP and FAR assignment complete", file=sys.stderr)
216 # Write parameter and ranking statistic distribution file now with zero-lag
219 # FIXME: do not write this output file, rely on stand-alone tool to
220 # collect zero-lag counts before running this program, and make that
221 # information available to other tools that way
225 xmldoc = ligolw.Document()
226 xmldoc.appendChild(ligolw.LIGO_LW())
227 process = ligolw_process.register_to_xmldoc(xmldoc, u
"gstlal_compute_far_from_snr_chisq_histograms", process_params)
228 far.gen_likelihood_control_doc(xmldoc, None, rankingstatpdf)
229 ligolw_process.set_process_end_time(process)
231 outname =
"post_%s" % options.background_bins_file
232 ligolw_utils.write_filename(xmldoc, outname, verbose = options.verbose)
235 print(
"done", file=sys.stderr)