gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_compute_far_from_snr_chisq_histograms
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2011--2013 Kipp Cannon, Chad Hanna, Drew Keppel
4 #
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.
9 #
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.
14 #
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.
18 
19 ### Compute FAR and FAP distributions from the likelihood CCDFs.
20 
21 #
22 # =============================================================================
23 #
24 # Preamble
25 #
26 # =============================================================================
27 #
28 
29 
30 from optparse import OptionParser
31 try:
32  import sqlite3
33 except ImportError:
34  # pre 2.5.x
35  from pysqlite2 import dbapi2 as sqlite3
36 sqlite3.enable_callback_tracebacks(True)
37 import sys
38 
39 
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
47 
48 
49 #
50 # =============================================================================
51 #
52 # Command Line
53 #
54 # =============================================================================
55 #
56 
57 
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()
67 
68  process_params = options.__dict__.copy()
69 
70  if options.background_bins_file is None:
71  raise ValueError("must set --background-bins-file")
72 
73  if not options.non_injection_db + options.injection_db:
74  raise ValueError("must provide at least one database file to process")
75 
76  if filenames:
77  raise ValueError("unrecognized trailing arguments")
78 
79  return options, process_params, filenames
80 
81 
82 #
83 # =============================================================================
84 #
85 # Main
86 #
87 # =============================================================================
88 #
89 
90 
91 #
92 # Parse command line
93 #
94 
95 
96 options, process_params, filenames = parse_command_line()
97 
98 
99 #
100 # Retrieve distribution data
101 #
102 
103 
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)
107 
108 
109 #
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.
114 #
115 
116 
117 if options.verbose:
118  print("beginning count of above-threshold events", file=sys.stderr)
119 
120 rankingstatpdf.zero_lag_lr_lnpdf.array[:] = 0.
121 
122 for n, filename in enumerate(options.non_injection_db, start = 1):
123  #
124  # get working copy of database. do not use scratch space for this,
125  # query is very fast
126  #
127 
128  if options.verbose:
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))
132 
133  #
134  # update counts
135  #
136 
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)
139  xmldoc.unlink()
140  rankingstatpdf.collect_zero_lag_rates(connection, coinc_def_id)
141 
142  #
143  # done
144  #
145 
146  connection.close()
147 
148 
149 #
150 # Apply density estimation to zero-lag rates
151 #
152 
153 
154 rankingstatpdf.density_estimate_zero_lag_rates()
155 
156 
157 #
158 # Now generate new ranking statistic PDFs by applying the clustering
159 # extinction model, and then initialize the FAP & FAR assignment machine
160 #
161 
162 
163 fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
164 
165 
166 #
167 # Iterate over databases
168 #
169 
170 
171 if options.verbose:
172  print("assigning FAPs and FARs", file=sys.stderr)
173 
174 for n, filename in enumerate(options.non_injection_db + options.injection_db, start = 1):
175  #
176  # get working copy of database
177  #
178 
179  if options.verbose:
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]:
182  if options.verbose:
183  print("already processed, skipping", file=sys.stderr)
184  continue
185  with dbtables.workingcopy(filename, tmp_path = options.tmp_space, verbose = options.verbose) as working_filename:
186  connection = sqlite3.connect(str(working_filename))
187 
188  #
189  # record our passage
190  #
191 
192  xmldoc = dbtables.get_xml(connection)
193  process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_compute_far_from_snr_chisq_histograms", process_params)
194 
195  #
196  # assign FAPs and FARs
197  #
198 
199  fapfar.assign_fapfars(connection)
200 
201  #
202  # done, file is restored to original location
203  #
204 
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))
207 
208  connection.commit()
209  connection.close()
210 
211 if options.verbose:
212  print("FAP and FAR assignment complete", file=sys.stderr)
213 
214 
215 #
216 # Write parameter and ranking statistic distribution file now with zero-lag
217 # counts populated.
218 #
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
222 #
223 
224 
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)
230 
231 outname = "post_%s" % options.background_bins_file
232 ligolw_utils.write_filename(xmldoc, outname, verbose = options.verbose)
233 
234 if options.verbose:
235  print("done", file=sys.stderr)