gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_calc_likelihood
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2010--2014 Kipp Cannon, Chad Hanna
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 ### A program to compute the likelhood ratios of inspiral triggers
20 
21 
22 #
23 # =============================================================================
24 #
25 # Preamble
26 #
27 # =============================================================================
28 #
29 
30 
31 from optparse import OptionParser
32 import sys
33 
34 
35 from ligo.lw import lsctables
36 from ligo.lw import utils as ligolw_utils
37 from ligo.lw.utils import process as ligolw_process
38 from ligo.lw.utils import segments as ligolw_segments
39 from ligo import segments
40 from lalburst import calc_likelihood
41 from lalinspiral import thinca
42 from gstlal import far
43 from lal.utils import CacheEntry
44 
45 
46 process_name = u"gstlal_inspiral_calc_likelihood"
47 
48 
49 __author__ = "Kipp Cannon <kipp.cannon@ligo.org>"
50 __version__ = "git id %s" % "" # FIXME
51 __date__ = "" # FIXME
52 
53 
54 #
55 # =============================================================================
56 #
57 # Command Line
58 #
59 # =============================================================================
60 #
61 
62 
63 def parse_command_line():
64  parser = OptionParser(
65  version = "Name: %%prog\n%s" % "" # FIXME
66  )
67  parser.add_option("-c", "--input-cache", metavar = "filename", help = "Also process the files named in this LAL cache. See lalapps_path2cache for information on how to produce a LAL cache file.")
68  parser.add_option("-l", "--likelihood-url", metavar = "URL", action = "append", help = "Set the name of the likelihood ratio data file to use. Can be given more than once. Filenames and URLs are accepted.")
69  parser.add_option("--likelihood-cache", metavar = "filename", help = "Also load the likelihood ratio data files listsed in this LAL cache. See lalapps_path2cache for information on how to produce a LAL cache file.")
70  parser.add_option("-t", "--tmp-space", metavar = "path", help = "Path to a directory suitable for use as a work area while manipulating the database file. The database file will be worked on in this directory, and then moved to the final location when complete. This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
71  parser.add_option("--vetoes-name", metavar = "name", help = "Set the name of the segment lists to use as vetoes (default = do not apply vetoes).")
72  parser.add_option("--add-zerolag-to-background", action = "store_true", help = "Add zerolag events to background before populating coincident parameter PDF histograms")
73  parser.add_option("-f", "--force", action = "store_true", help = "Force recomputation of likelihood values.")
74  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
75  options, urls = parser.parse_args()
76 
77  paramdict = options.__dict__.copy()
78 
79  options.likelihood_urls = []
80  if options.likelihood_url is not None:
81  options.likelihood_urls += options.likelihood_url
82  if options.likelihood_cache is not None:
83  options.likelihood_urls += [CacheEntry(line).url for line in open(options.likelihood_cache)]
84  if not options.likelihood_urls:
85  raise ValueError("no likelihood URLs specified")
86 
87  if options.input_cache:
88  urls += [CacheEntry(line).path for line in open(options.input_cache)]
89 
90  return options, paramdict, urls
91 
92 
93 #
94 # =============================================================================
95 #
96 # Support Funcs for Likelihood Ratio Code
97 #
98 # =============================================================================
99 #
100 
101 
102 def sngl_inspiral_veto_func(event, vetoseglists):
103  # return True if event should be *retained*
104  return event.ifo not in vetoseglists or event.end not in vetoseglists[event.ifo]
105 
106 
107 #
108 # =============================================================================
109 #
110 # Main
111 #
112 # =============================================================================
113 #
114 
115 
116 #
117 # command line
118 #
119 
120 
121 options, paramdict, urls = parse_command_line()
122 
123 
124 #
125 # load parameter distribution data
126 #
127 
128 
129 rankingstat = far.marginalize_pdf_urls(options.likelihood_urls, "RankingStat", verbose = options.verbose)
130 
131 
132 #
133 # include zero-lag candidates in ranking statistic denominator if requested
134 #
135 
136 
137 if options.add_zerolag_to_background:
138  rankingstat.denominator.lnzerolagdensity = rankingstat.zerolag
139 
140 
141 #
142 # apply density estimation kernels, etc.
143 #
144 
145 
146 rankingstat.finish()
147 
148 
149 #
150 # iterate over candidate files
151 #
152 
153 
154 failed = []
155 for n, url in enumerate(urls, 1):
156  #
157  # open the file. be lazy and use the content handler for the
158  # distribution data files because it's fine for this, too. if a
159  # file can't be loaded because of a filesystem failure or CRC
160  # failure, or whatever, try to do the rest of the files before
161  # exiting instead of crashing right away to reduce the time spent
162  # in rescue dags.
163  #
164 
165  if options.verbose:
166  print("%d/%d:" % (n, len(urls)), file=sys.stderr)
167  try:
168  xmldoc = ligolw_utils.load_url(url, contenthandler = far.RankingStat.LIGOLWContentHandler, verbose = options.verbose)
169  except Exception as e:
170  if options.verbose:
171  print("failed to load '%s': %s. trying to continue with remaining files" % (url, str(e)), file=sys.stderr)
172  failed.append(url)
173  continue
174 
175  if not options.force and ligolw_process.doc_includes_process(xmldoc, process_name):
176  if options.verbose:
177  print("already processed, skipping", file=sys.stderr)
178  xmldoc.unlink()
179  continue
180 
181  #
182  # summarize the database, and record our passage.
183  #
184 
185  try:
186  coinc_def_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
187  except KeyError:
188  if options.verbose:
189  print("document does not contain inspiral coincidences. skipping.", file=sys.stderr)
190  xmldoc.unlink()
191  continue
192 
193  process = ligolw_process.register_to_xmldoc(xmldoc, process_name, paramdict, instruments = rankingstat.instruments)
194 
195  if options.verbose:
196  print("indexing document ...", file=sys.stderr)
197  sngl_inspiral_table_index = dict((row.event_id, row) for row in lsctables.SnglInspiralTable.get_table(xmldoc))
198  coinc_event_map_index = dict((row.coinc_event_id, []) for row in lsctables.CoincTable.get_table(xmldoc) if row.coinc_def_id == coinc_def_id)
199  for row in lsctables.CoincMapTable.get_table(xmldoc):
200  if row.coinc_event_id not in coinc_event_map_index:
201  continue
202  coinc_event_map_index[row.coinc_event_id].append(sngl_inspiral_table_index[row.event_id])
203  del sngl_inspiral_table_index
204  coinc_inspiral_index = dict((row.coinc_event_id, row) for row in lsctables.CoincInspiralTable.get_table(xmldoc))
205 
206  offset_vectors = lsctables.TimeSlideTable.get_table(xmldoc).as_dict()
207 
208  if options.vetoes_name is not None:
209  vetoseglists = ligolw_segments.segmenttable_get_by_name(xmldoc, options.vetoes_name).coalesce()
210  else:
211  vetoseglists = segments.segmentlistdict()
212  if options.verbose:
213  print("done", file=sys.stderr)
214 
215  #
216  # run likelihood ratio calculation.
217  #
218 
219  calc_likelihood.assign_likelihood_ratios_xml(
220  xmldoc = xmldoc,
221  coinc_def_id = coinc_def_id,
222  offset_vectors = offset_vectors,
223  vetoseglists = vetoseglists,
224  events_func = lambda _, coinc_event_id: coinc_event_map_index[coinc_event_id],
225  veto_func = sngl_inspiral_veto_func,
226  ln_likelihood_ratio_func = rankingstat.ln_lr_from_triggers,
227  verbose = options.verbose
228  )
229 
230  #
231  # close out process metadata.
232  #
233 
234  ligolw_process.set_process_end_time(process)
235 
236  #
237  # clean up.
238  #
239 
240  ligolw_utils.write_url(xmldoc, url, verbose = options.verbose)
241  xmldoc.unlink()
242 
243 
244 #
245 # crash if any input files were broken
246 #
247 
248 
249 if failed:
250  raise ValueError("%s could not be processed" % ", ".join("'%s'" % url for url in failed))