3 # Copyright (C) 2016 Kipp Cannon, Jolien Creighton, Heather Fong
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 ### A program to calculate P(astro) from a running gstlal_inspiral job
21 ### based on gracedb submissions notified by lvalert, plots rate posteriors
22 ### and writes P(astro), the credible interval values to file
25 ### Compute P(terrestrial) (1-P(astro)) for an event - given graceid
26 ### Calculate the rate posteriors and uploads a plot of the posteriors for the event
27 ### Default threshold of log likelihood = 6
28 ### Default confidence intervals = [0.68, 0.9, 0.99]
31 # =============================================================================
35 # =============================================================================
39 from optparse
import OptionParser
42 import urllib.parse as urlparse
46 from
operator import methodcaller
50 from gstlal
import far
51 from gstlal
import rate_estimation
53 from ligo
import segments
54 from glue.lal
import CacheEntry
55 from glue.ligolw
import ligolw
56 from glue.ligolw
import dbtables
57 from glue.ligolw
import utils as ligolw_utils
58 from glue.ligolw
import lsctables
59 from glue.ligolw.utils
import process as ligolw_process
60 from glue.text_progress_bar
import ProgressBar
62 from lalinspiral
import thinca
63 from gstlal
import lvalert_helper
64 from gstlal.plotutil
import golden_ratio
65 from ligo.gracedb
import rest as gracedb
69 from fpconst
import NegInf
71 NegInf = float(
"-inf")
77 from matplotlib import figure
78 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
79 matplotlib.rcParams.update({
81 "axes.titlesize": 10.0,
82 "axes.labelsize": 10.0,
83 "xtick.labelsize": 8.0,
84 "ytick.labelsize": 8.0,
85 "legend.fontsize": 8.0,
93 # =============================================================================
97 # =============================================================================
100 def lvalert_load_ranking_data(gracedb_client, graceid, ln_likelihood_ratio_threshold, filename =
"ranking_data.xml.gz", ignore_404 = False, verbose = False):
101 response = lvalert_helper.get_filename(gracedb_client, graceid, filename = filename, ignore_404 = ignore_404)
102 ranking_data_xmldoc = ligolw_utils.load_fileobj(response, contenthandler = far.RankingStat.LIGOLWContentHandler)[0]
103 _, rankingstatpdf = far.parse_likelihood_control_doc(ranking_data_xmldoc)
105 # affect the zeroing of the PDFs below threshold by hacking the
106 # histograms. do the indexing ourselves to not 0 the bin @
108 if ln_likelihood_ratio_threshold is not None:
109 rankingstatpdf.noise_lr_lnpdf.array[:rankingstatpdf.noise_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
110 rankingstatpdf.noise_lr_lnpdf.normalize()
111 rankingstatpdf.signal_lr_lnpdf.array[:rankingstatpdf.signal_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
112 rankingstatpdf.signal_lr_lnpdf.normalize()
113 rankingstatpdf.zero_lag_lr_lnpdf.array[:rankingstatpdf.zero_lag_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
114 rankingstatpdf.zero_lag_lr_lnpdf.normalize()
116 return rankingstatpdf
118 def lvalert_event_ln_likelihood_ratio_endtime_mass(gracedb_client, graceid, ignore_404 = False):
119 coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, graceid)
120 coinc_event, = lsctables.CoincTable.get_table(coinc_xmldoc)
121 coinc_inspiral, = lsctables.CoincInspiralTable.get_table(coinc_xmldoc)
122 return coinc_event.likelihood, coinc_inspiral.end_time, coinc_inspiral.mass
125 # =============================================================================
129 # =============================================================================
132 def parse_command_line():
133 parser = OptionParser()
134 parser.add_option(
"--no-upload", action =
"store_true", help =
"Write plots to disk.")
135 parser.add_option(
"--skip-404", action =
"store_true", help =
"Skip events that give 404 (file not found) errors (default is to abort).")
136 parser.add_option(
"--gracedb-service-url", default=
"%s" % gracedb.DEFAULT_SERVICE_URL, help =
"GraceDb service url to upload to (default: %s)" % gracedb.DEFAULT_SERVICE_URL)
137 parser.add_option(
"-c",
"--credible-intervals", metavar =
"credibility[,...]", default =
"0.68,0.90,0.99", help =
"Compute and report credible intervals in the signal count for these credibilities (default = \".68,.90,.99\", clear to disable).")
138 parser.add_option(
"--trigger-database-glob", metavar =
"filename", default =
"H1L1-ALL_LLOID-0-2000000000.sqlite", help =
"trigger database files (sqlite)")
139 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.")
140 parser.add_option(
"--threshold", metavar =
"log likelihood ratio", type =
"float", default = 6, help =
"Derive the rate posterior by considering only events ranked at or above this value of the log likelihood ratio ranking statistic (default = use all events).")
141 parser.add_option(
"-v",
"--verbose", action =
"store_true", help =
"Be verbose.")
143 options, graceids = parser.parse_args()
145 options.credible_intervals = map(float, options.credible_intervals.split(
","))
146 options.trigger_database_glob = map(methodcaller(
"split",
","), [options.trigger_database_glob])[0]
149 # FIXME: lvalert_listen doesn
't allow command-line
150 # options, enable logging for online analysis
151 options.verbose = True
153 # can only call basicConfig once (otherwise need to switch to more
154 # complex logging configuration)
156 logging.basicConfig(format = "%(asctime)s:%(message)s", level = logging.INFO)
158 logging.basicConfig(format = "%(asctime)s:%(message)s")
160 return options, graceids
163 # =============================================================================
167 # =============================================================================
170 class count_ratio_posterior(scipy.stats.rv_continuous):
172 def __init__(self, ln_f_over_b, ln_prior=None):
173 super(count_ratio_posterior, self).__init__(a=1e-10, b=100.0/len(ln_f_over_b))
174 self.ln_f_over_b = numpy.sort(ln_f_over_b)
175 #FIXME: Jeffrey's prior already hardcoded in LogPosterior
176 #if ln_prior is None:
177 # self.ln_prior = lambda Rf: -0.5*numpy.log(Rf) # Jeffrey
's prior
179 # self.ln_prior = ln_prior
180 self.Rb = len(ln_f_over_b)
182 self.norm = 1.0 / scipy.integrate.quad(self.pdf, self.a, self.b)[0]
187 logposterior = rate_estimation.LogPosterior(self.ln_f_over_b) # initialize
188 logp = lambda Rf: logposterior((Rf, self.Rb)) - logposterior((1., self.Rb)) # turn into lambda function to integrate over
189 return numpy.exp(logp(Rf))*self.norm
191 def _munp(self, n, *args):
192 return scipy.integrate.quad(lambda x: x**n * self.pdf(x), self.a, self.b)[0]
195 if self._mode is None:
196 self._mode = scipy.optimize.fminbound(lambda x: -self.pdf(x), self.a, self.b)
199 def hpd_credible_interval(alpha, rv):
200 # computes the highest posterior density bayesian credible interval
204 return pp if pp > p else 0.
205 prob1, _ = scipy.integrate.quad(pdf_above_p, rv.a, rv.mode())
206 prob2, _ = scipy.integrate.quad(pdf_above_p, rv.mode(), rv.b)
207 return prob1 + prob2 - alpha
208 pmax = rv.pdf(rv.mode())
209 p = scipy.optimize.brentq(err, 0.0, pmax)
210 if rv.pdf(rv.a) > p: # upper limit
213 a = scipy.optimize.brentq(lambda x: rv.pdf(x) - p, rv.a, rv.mode())
214 b = scipy.optimize.brentq(lambda x: rv.pdf(x) - p, rv.mode(), rv.b)
215 print("credible interval computed for %f [%f, %f]" %(alpha, a, b))
218 def false_alarm_probability(event_f_over_b, rv):
219 p, _ = scipy.integrate.quad(lambda x: rv.pdf(x)/(1.0 + x * event_f_over_b), rv.a, rv.b)
222 def load_search_results(filenames, end_time, mass, ln_likelihood_ratio_threshold = None, tmp_path = None, verbose = False):
223 background_ln_likelihood_ratios = []
224 zerolag_ln_likelihood_ratios = []
226 for n, filename in enumerate(filenames, 1):
228 print("%d/%d: %s" % (n, len(filenames), filename), file=sys.stderr)
229 with dbtables.workingcopy(filename, tmp_path = tmp_path, discard = True, verbose = verbose) as working_filename:
230 connection = sqlite3.connect(str(working_filename))
232 xmldoc = dbtables.get_xml(connection)
233 definer_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
235 for ln_likelihood_ratio, is_background in connection.cursor().execute("""
237 coinc_event.likelihood,
244 time_slide.time_slide_id == coinc_event.time_slide_id
245 AND time_slide.offset != 0
249 JOIN coinc_inspiral ON (
250 coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
253 coinc_event.coinc_def_id == ?
254 AND coinc_event.likelihood >= ?
255 AND coinc_inspiral.end_time != ?
256 AND coinc_inspiral.mass != ?"""
257 , (definer_id, (ln_likelihood_ratio_threshold if ln_likelihood_ratio_threshold is not None else NegInf), end_time, mass)):
259 background_ln_likelihood_ratios.append(ln_likelihood_ratio)
261 zerolag_ln_likelihood_ratios.append(ln_likelihood_ratio)
264 return background_ln_likelihood_ratios, zerolag_ln_likelihood_ratios
267 def plot_rates(rv, credible_intervals = None):
268 props = dict(boxstyle='round
',facecolor='white
',alpha=0.5)
269 fig = figure.Figure()
271 fig.set_size_inches((4., 4. / golden_ratio))
272 signal_axes = fig.gca()
274 x = numpy.logspace(numpy.log10(min(credible_intervals.values())[0]*rv.Rb), numpy.log10(max(credible_intervals.values())[1]*rv.Rb)+1.0)
275 y = numpy.array([rv.pdf(xx / rv.Rb) / rv.Rb for xx in x])
276 line1, = signal_axes.plot(x, y, color = "k", linestyle = "-", label = "Signal")
277 signal_axes.set_title("Event Rate Posterior")
278 signal_axes.set_xlabel("Event Rate ($\mathrm{signals} / \mathrm{experiment}$)")
279 signal_axes.set_ylabel(r"$P(\mathrm{signals} / \mathrm{experiment})$")
282 signal_axes.set_ylim((1e-3, 1.))
284 textstr = "mean: %.3g\nmedian: %.3g\nmode: %.3g" % (rv.mean()*rv.Rb, rv.median()*rv.Rb, rv.mode()*rv.Rb)
285 signal_axes.text(0.03,0.95,textstr,transform=signal_axes.transAxes,fontsize=8,verticalalignment='top
',bbox=props)
287 if credible_intervals is not None:
288 alpha = 1.0 / (1.0 + len(credible_intervals))
289 for lo, hi in credible_intervals.values():
291 x = numpy.logspace(numpy.log10(lo), numpy.log10(hi)) * rv.Rb
292 y = numpy.array([rv.pdf(xx / rv.Rb) / rv.Rb for xx in x])
293 signal_axes.fill_between(x, y, 1e-8, color = "k", alpha = alpha)
298 def get_ln_f_over_b(rankingstatpdf, ln_likelihood_ratios):
299 if any(math.isnan(ln_lr) for ln_lr in ln_likelihood_ratios):
300 raise ValueError("NaN log likelihood ratio encountered")
302 f = rankingstatpdf.signal_lr_lnpdf
303 b = rankingstatpdf.noise_lr_lnpdf
304 ln_f_over_b = numpy.array([f[ln_lr,]-b[ln_lr,] for ln_lr in ln_likelihood_ratios])
305 if numpy.isnan(numpy.exp(ln_f_over_b)).any():
306 raise ValueError("NaN encountered in ranking statistic PDF ratios")
307 if numpy.isinf(numpy.exp(ln_f_over_b)).any():
308 raise ValueError("infinity encountered in ranking statistic PDF ratios")
311 def build_trigger_database(trigger_databases):
312 if len(trigger_databases)>1:
314 for i in range(len(trigger_databases)):
315 filelist.append(glob.glob(trigger_databases[i]))
316 assert (len(filelist)==len(trigger_databases)), "Files not found in directory!"
318 filelist = glob.glob(trigger_databases[0])
319 assert (len(filelist)>0), "File not found in directory!"
322 # =============================================================================
326 # =============================================================================
329 options, graceids = parse_command_line()
332 lvalert_data = json.loads(sys.stdin.read())
333 logging.info("%(alert_type)s-type alert for event %(uid)s" % lvalert_data)
334 logging.info("lvalert data: %s" % repr(lvalert_data))
335 if "filename" in lvalert_data["data"]:
336 filename = os.path.split(urlparse.urlparse(lvalert_data["data"]["file"]).path)[-1]
337 if filename not in (u"ranking_data.xml.gz",):
338 logging.info("filename is not 'ranking_data.xml.gz
'. skipping")
340 graceids = [str(lvalert_data["uid"])]
342 logging.info("json key filename not in lvalert data, skipping")
344 gracedb_client = gracedb.GraceDb(service_url = options.gracedb_service_url)
345 trigger_databases = build_trigger_database(options.trigger_database_glob)
347 for graceid in graceids:
348 #load ranking statistic PDFs and compute event log likelihood ratio
349 rankingstatpdf = lvalert_load_ranking_data(gracedb_client, graceid, options.threshold, ignore_404 = options.skip_404, verbose = options.verbose)
350 event_ln_likelihood_ratio, event_endtime, event_mass = lvalert_event_ln_likelihood_ratio_endtime_mass(gracedb_client, graceid, ignore_404 = options.skip_404)
352 # load search results
353 background_ln_likelihood_ratios, zerolag_ln_likelihood_ratios = load_search_results(trigger_databases, event_endtime, event_mass, ln_likelihood_ratio_threshold = options.threshold, verbose = options.verbose)
356 filename1 = "%s_rate_posteriors.png" % graceid
357 filename2 = "%s_rate_posteriors.txt" % graceid
358 txt_file = open(filename2, "w")
360 # calculate rate posteriors
362 print("calculating rate posteriors using %d likelihood ratios ..." % len(zerolag_ln_likelihood_ratios), file=sys.stderr)
363 txt_file.write("calculating rate posteriors using %d likelihood ratios ...\n" % len(zerolag_ln_likelihood_ratios))
364 ln_f_over_b = get_ln_f_over_b(rankingstatpdf, zerolag_ln_likelihood_ratios)
365 event_ln_f_over_b = get_ln_f_over_b(rankingstatpdf, [event_ln_likelihood_ratio])
367 print("adding event to zerolag events", file=sys.stderr)
368 txt_file.write("adding event to zerolag events\n")
369 ln_f_over_b = numpy.append(ln_f_over_b, event_ln_f_over_b)
373 Rr_posterior = count_ratio_posterior(ln_f_over_b)
375 # terrestrial probabilities
376 p_terrestrial = [false_alarm_probability(x, Rr_posterior) for x in numpy.exp(event_ln_f_over_b)]
377 txt_file.write("terrestrial probability of event = %g\n" % p_terrestrial[0])
379 print("terrestrial probability of event = %g" % p_terrestrial[0], file=sys.stderr)
381 # find credible intervals
382 if options.credible_intervals:
384 print("determining credible intervals ...", file=sys.stderr)
386 credible_intervals = dict((cred, hpd_credible_interval(cred, Rr_posterior)) for cred in options.credible_intervals)
388 print("unable to get credible intervals, setting value to None", file=sys.stderr)
389 credible_intervals = None
391 credible_intervals = None
392 if credible_intervals is not None:
393 txt_file.write("rate posterior mean = %g signals/experiment\n" % (Rr_posterior.mean() * Rr_posterior.Rb))
394 txt_file.write("rate posterior median = %g signals/experiment\n" % (Rr_posterior.median() * Rr_posterior.Rb))
395 txt_file.write("maximum-likelihood rate = %g signals/experiment\n" % (Rr_posterior.mode() * Rr_posterior.Rb))
397 print("rate posterior mean = %g signals/experiment" % (Rr_posterior.mean() * Rr_posterior.Rb), file=sys.stderr)
398 print("rate posterior median = %g signals/experiment" % (Rr_posterior.median() * Rr_posterior.Rb), file=sys.stderr)
399 # all modes are the same, pick one and report it
400 print("maximum-likelihood rate = %g signals/experiment" % (Rr_posterior.mode() * Rr_posterior.Rb), file=sys.stderr)
401 for cred, (lo, hi) in sorted(credible_intervals.items()):
402 print("%g%% credible interval = [%g, %g] signals/experiment" % (cred * 100., lo * Rr_posterior.Rb, hi * Rr_posterior.Rb), file=sys.stderr)
403 txt_file.write("%g%% credible interval = [%g, %g] signals/experiment\n" % (cred * 100., lo * Rr_posterior.Rb, hi * Rr_posterior.Rb))
407 fig = plot_rates(Rr_posterior, credible_intervals = credible_intervals)
408 if options.no_upload:
409 logging.info("writing %s ..." % filename1)
410 fig.savefig(filename1)
412 lvalert_helper.upload_fig(fig, gracedb_client, graceid, filename = filename1, log_message = "Rate posteriors plot", tagname = 'pe
')
413 lvalert_helper.upload_file(gracedb_client, graceid, filename = filename2, log_message = "P(terrestrial) = %g" % p_terrestrial[0], tagname = 'pe
')
414 logging.info("finished processing %s" % graceid)
416 print("done", file=sys.stderr)