3 # Copyright (C) 2010--2014 Kipp Cannon, Chad Hanna
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 ### A program to compute the likelhood ratios of inspiral triggers
23 # =============================================================================
27 # =============================================================================
31 from optparse
import OptionParser
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
46 process_name = u
"gstlal_inspiral_calc_likelihood"
49 __author__ =
"Kipp Cannon <kipp.cannon@ligo.org>"
50 __version__ =
"git id %s" %
"" # FIXME
55 # =============================================================================
59 # =============================================================================
63 def parse_command_line():
64 parser = OptionParser(
65 version =
"Name: %%prog\n%s" %
"" # FIXME
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()
77 paramdict = options.__dict__.copy()
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")
87 if options.input_cache:
88 urls += [CacheEntry(line).path for line in open(options.input_cache)]
90 return options, paramdict, urls
94 # =============================================================================
96 # Support Funcs for Likelihood Ratio Code
98 # =============================================================================
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]
108 # =============================================================================
112 # =============================================================================
121 options, paramdict, urls = parse_command_line()
125 # load parameter distribution data
129 rankingstat = far.marginalize_pdf_urls(options.likelihood_urls,
"RankingStat", verbose = options.verbose)
133 # include zero-lag candidates in ranking statistic denominator if requested
137 if options.add_zerolag_to_background:
138 rankingstat.denominator.lnzerolagdensity = rankingstat.zerolag
142 # apply density estimation kernels, etc.
150 # iterate over candidate files
155 for n, url in enumerate(urls, 1):
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
166 print(
"%d/%d:" % (n, len(urls)), file=sys.stderr)
168 xmldoc = ligolw_utils.load_url(url, contenthandler = far.RankingStat.LIGOLWContentHandler, verbose = options.verbose)
169 except Exception as e:
171 print(
"failed to load '%s': %s. trying to continue with remaining files" % (url, str(e)), file=sys.stderr)
175 if not options.force and ligolw_process.doc_includes_process(xmldoc, process_name):
177 print(
"already processed, skipping", file=sys.stderr)
182 # summarize the database, and record our passage.
186 coinc_def_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
189 print(
"document does not contain inspiral coincidences. skipping.", file=sys.stderr)
193 process = ligolw_process.register_to_xmldoc(xmldoc, process_name, paramdict, instruments = rankingstat.instruments)
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:
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))
206 offset_vectors = lsctables.TimeSlideTable.get_table(xmldoc).as_dict()
208 if options.vetoes_name is not None:
209 vetoseglists = ligolw_segments.segmenttable_get_by_name(xmldoc, options.vetoes_name).coalesce()
211 vetoseglists = segments.segmentlistdict()
213 print(
"done", file=sys.stderr)
216 # run likelihood ratio calculation.
219 calc_likelihood.assign_likelihood_ratios_xml(
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
231 # close out process metadata.
234 ligolw_process.set_process_end_time(process)
240 ligolw_utils.write_url(xmldoc, url, verbose = options.verbose)
245 # crash if any input files were broken
250 raise ValueError(
"%s could not be processed" %
", ".join(
"'%s'" % url for url in failed))