3 # Copyright (C) 2019-2020 Hiroaki Ohta
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.
20 from fpconst
import NegInf
22 # not all machines have fpconst installed
23 NegInf = float(
"-inf")
26 from optparse import OptionParser
29 np.random.seed(
int(time.time()))
32 from lalburst.snglcoinc import light_travel_time
33 from lalinspiral import inspinjfind
34 from ligo.lw import ligolw
35 from ligo.lw import lsctables
36 from ligo.lw import utils as ligolw_utils
37 from gstlal import far
40 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
43 def build_tmplt_to_sim_index(xmldoc):
44 coinc_def_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(inspinjfind.InspiralSTCoincDef.search, inspinjfind.InspiralSTCoincDef.search_coinc_type, create_new = False)
45 coinc_event_ids = set(row.coinc_event_id for row in lsctables.CoincTable.get_table(xmldoc) if row.coinc_def_id == coinc_def_id)
47 sim_index = dict((row.simulation_id, row) for row in lsctables.SimInspiralTable.get_table(xmldoc))
49 # index maps template_id to list of simulation_ids for which that is the best template
51 for coinc_event_id, coinc_event_maps in itertools.groupby(sorted(lsctables.CoincMapTable.get_table(xmldoc), key = lambda row: (row.coinc_event_id, row.table_name)), lambda row: row.coinc_event_id):
52 # implicitly checks that there are only two rows in the coinc
53 coinc_event_map_sim, coinc_event_map_sngl = coinc_event_maps
55 index.setdefault(coinc_event_map_sngl.event_id, []).append(sim_index[coinc_event_map_sim.event_id])
61 def lnL_wrapper(rankingstat, params):
62 # not all the triggers are above the SNR threshold. they have been
63 # left in the param stream so that calling codes can account for
64 # the rate at which threshold crossing fails to occur in their
65 # statistics. which instruments are below threshold?
66 blind = frozenset(instrument for instrument, snr in params[
"snrs"].items() if snr < rankingstat.snr_min)
67 # remove them from params. injection is missed if not enough
69 for instrument in blind:
70 del params[
"snrs"][instrument]
71 del params[
"chi2s_over_snr2s"][instrument]
72 del params[
"phase"][instrument]
73 del params[
"dt"][instrument]
74 if len(params[
"snrs"]) < rankingstat.min_instruments:
77 # the triggers are not neccessarily mutually coincident because the
78 # time error distribution is unbounded. as with the SNRs, these
79 # noise-induced coincidence failures are left in the simulated
80 # param stream so the rate at which they occur can be accounted for
83 # dealing with this is tricky. if we have a full n-way coincidence
84 # then we compute the ranking statistic and we are done. however,
85 # if some pairs of triggers are not coincident, for example if we
86 # have an {H1, L1, V1} network and the {H1, L1} and {H1, V1} pairs
87 # are coincident but {L1, V1} is not, what the detection pipeline
88 # would do is report this as two doubles. the injection is found
89 # if one of these yields a ranking statistic above the detection
90 # threshold. what we do is work our way down from the
91 # largest number of available triggers to the smallest allowed by
92 # min_instruments, until we find at least one coincidence with that
93 # many triggers in it, then we report the largest ranking statistic
94 # value for all the coincidences with that many
95 # triggers (if more than one can be formed). considering the {H1,
96 # L1, V1} example above the sequence would be:
98 # is {H1, L1, V1} coincident? --> no
99 # are any of the pairs coincident? --> yes
100 # compute ln L for all coincident pairs
101 # report largest value
104 # if no doubles are coincident and min_instruments is 1 then we
105 # would continue to singles, otherwise if min_instruments is 2 we
106 # would stop at the doubles and report a missed injection
108 for n in range(len(params[
"snrs"]), rankingstat.min_instruments - 1, -1):
110 for selected_instruments in itertools.combinations(params[
"snrs"], n):
111 if len(selected_instruments) > 1:
112 if max(abs(params[
"dt"][insta] - params[
"dt"][instb]) - light_travel_time(insta, instb) for insta, instb in itertools.combinations(selected_instruments, 2)) > rankingstat.delta_t:
113 # this combo is not mutually coincident
117 # make a new params object for just these
119 selected_params = params.copy()
120 for param in (
"snrs",
"chi2s_over_snr2s",
"phase",
"dt"):
121 selected_params[param] = dict((instrument, val) for instrument, val in selected_params[param].items() if instrument in selected_instruments)
123 lnL.append(rankingstat(**selected_params))
125 # if at least one combo was coincident, report largest ln
126 # L, otherwise move on to next smaller n
131 # if we get here, no set of instruments was actually coincident,
132 # report a missed injection
136 def parse_command_line():
137 parser = OptionParser(description = __doc__)
140 parser.add_option(
"--f-low", metavar =
"Hertz", default = 15., type =
"float", help =
"Low frequency cutoff. Default is 15 Hz")
141 parser.add_option(
"--trials-per-injection", metavar =
"count", default = 1000, type =
"int", help =
"Set the number of trials to run per injection. Default is 1000.")
142 parser.add_option(
"--xaxis-points", metavar =
"count", default = 100, type =
"int", help =
"Specify the number of false-alarm rates for which to compute the search volume. Default is 100.")
145 parser.add_option(
"--injection-template-match-file", metavar =
"filename", help =
"XML file containing injection template match (required).")
146 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. (required).")
148 # Output data options
149 parser.add_option(
"--output-file", metavar =
"URL", help =
"Text file of factored lnlrcdf_signal")
150 parser.add_option(
"-v",
"--verbose", action =
"store_true", help =
"Be verbose (optional).")
152 options, filenames = parser.parse_args()
154 required_options = (
"injection_template_match_file",
"likelihood_url",
"output_file")
155 missing_options = [option for option in required_options if not getattr(options, option)]
157 raise ValueError(
"%s must be set" %
", ".join(
"--%s" % option.replace(
"_",
"-") for option in missing_options))
165 options = parse_command_line()
168 # create output factor
171 # Should choose a sufficiently large interval and small density for false alarm rate
172 lnL_th = np.linspace(-75, 75, options.xaxis_points)
174 lnlrcdfsignals = {
"lnlrcdf": [],
"lnL_th": lnL_th}
178 # read and index injection<-->template mapping
182 tmplt_to_sim = build_tmplt_to_sim_index(ligolw_utils.load_filename(options.injection_template_match_file, contenthandler = LIGOLWContentHandler, verbose = options.verbose))
186 # iterate over ranking stat files
189 for filename in tqdm(options.likelihood_url, desc =
"opening likelihood", disable = not options.verbose):
190 rankingstat = far.marginalize_pdf_urls([filename],
"RankingStat", verbose = options.verbose)
194 # iterate over templates covered by this ranking stat object
197 for template_id in tqdm(rankingstat.template_ids, desc =
"expanding rankingstat.template_ids", disable = not options.verbose):
199 # iterate over injections for which that is the best match (if any)
202 if template_id not in tmplt_to_sim:
205 for inj in tqdm(tmplt_to_sim[template_id], leave = False, desc =
"calculating lnL cdf", disable = not options.verbose):
207 # draw ln L
's for this injection
210 lnL = [lnL_wrapper(rankingstat, params) for params in itertools.islice(rankingstat.numerator.random_sim_params(inj, f_low = options.f_low), options.trials_per_injection)]
213 # calc P(lnL >= threshold | candidate) and estimate its uncertainty
216 lnlrcdf = np.array([sum(x >= threshold for x in lnL) for threshold in lnL_th]) / float(options.trials_per_injection)
217 lnlrcdfsignals["lnlrcdf"].append(((inj.distance, inj.mchirp), lnlrcdf))
225 print("saving lnL CDF")
227 with open(options.output_file, "wb") as f:
228 pickle.dump(lnlrcdfsignals, f)