gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_rate_posterior
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2013,2014 Kipp Cannon, Chad Hanna, Jacob Peoples
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 comput the signal and noise rate posteriors of a gstlal inspiral analysis
20 
21 
22 #
23 # =============================================================================
24 #
25 # Preamble
26 #
27 # =============================================================================
28 #
29 
30 
31 import bisect
32 try:
33  from fpconst import NegInf
34 except ImportError:
35  NegInf = float("-inf")
36 import h5py
37 import matplotlib
38 matplotlib.rcParams.update({
39  "font.size": 8.0,
40  "axes.titlesize": 10.0,
41  "axes.labelsize": 10.0,
42  "xtick.labelsize": 8.0,
43  "ytick.labelsize": 8.0,
44  "legend.fontsize": 8.0,
45  "figure.dpi": 600,
46  "savefig.dpi": 600,
47  "text.usetex": True
48 })
49 from matplotlib import figure
50 from matplotlib import ticker
51 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
52 import numpy
53 from optparse import OptionParser
54 import sqlite3
55 import sys
56 
57 
58 from ligo import segments
59 from ligo.lw import ligolw
60 from ligo.lw import dbtables
61 from ligo.lw import lsctables
62 from ligo.lw import utils as ligolw_utils
63 from ligo.lw.utils import process as ligolw_process
64 from glue.text_progress_bar import ProgressBar
65 from lal.utils import CacheEntry
66 from lalinspiral import thinca
67 
68 
69 from gstlal import far
70 from gstlal import rate_estimation
71 from gstlal.plotutil import golden_ratio
72 
73 
74 process_name = u"gstlal_inspiral_rate_posterior"
75 
76 
77 __author__ = "Kipp Cannon <kipp.cannon@ligo.org>"
78 __version__ = "" # FIXME
79 __date__ = "" # FIXME
80 
81 
82 #
83 # =============================================================================
84 #
85 # Command Line
86 #
87 # =============================================================================
88 #
89 
90 
91 def parse_command_line():
92  parser = OptionParser(
93  version = "Name: %%prog\n%s" % __version__,
94  usage = "%prog [options] candidates_database [...]"
95  )
96  parser.add_option("-c", "--credible-intervals", metavar = "credibility[,...]", default = "0.68,0.95,0.999999", help = "Compute and report credible intervals in the signal count for these credibilities (default = \".68,.95,.999999\", clear to disable).")
97  parser.add_option("-i", "--input-cache", metavar = "filename", help = "Also process the candidate databases named in this LAL cache. See lalapps_path2cache for information on how to produce a LAL cache file.")
98  parser.add_option("--chain-file", metavar = "filename", help = "Read chain from this file, save chain to this file.")
99  parser.add_option("--ranking-stat-pdf", metavar = "filename", action = "append", help = "Load ranking statistic PDFs for the signal and noise models from this file. Can be given multiple times.")
100  parser.add_option("--ranking-stat-pdf-cache", metavar = "filename", help = "Load ranking statistic PDFs for the signal and noise models from the files in this LAL cache.")
101  parser.add_option("--ranking-stat-threshold", metavar = "value", type = "float", help = "Only consider candidates at or above this value of the ranking statistic. The default is to set the threshold automatically from the extinction model's domain of validity.")
102  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.")
103  parser.add_option("--with-background", action = "store_true", help = "Show background posterior on plot.")
104  parser.add_option("--samples", metavar = "count", type = "int", help = "Run this many samples. Set to 0 to load and plot the contents of a previously-recorded chain file without doing any additional samples.")
105  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
106  options, filenames = parser.parse_args()
107 
108  paramdict = options.__dict__.copy()
109 
110  options.credible_intervals = map(float, options.credible_intervals.split(","))
111 
112  if options.samples is not None and options.samples < 0:
113  raise ValueError("--samples cannot be negative")
114 
115  if options.ranking_stat_pdf_cache is not None:
116  if options.ranking_stat_pdf is None:
117  options.ranking_stat_pdf = []
118  options.ranking_stat_pdf += [CacheEntry(line).path for line in open(options.ranking_stat_pdf_cache)]
119  if not options.ranking_stat_pdf and options.samples > 0:
120  raise ValueError("must provide ranking statistic PDF data if --samples is non-zero")
121 
122  if options.input_cache:
123  filenames += [CacheEntry(line).path for line in open(options.input_cache)]
124 
125  return options, paramdict, filenames
126 
127 
128 #
129 # =============================================================================
130 #
131 # Support Functions
132 #
133 # =============================================================================
134 #
135 
136 
137 def load_ranking_data(filenames, ln_likelihood_ratio_threshold, verbose = False):
138  if not filenames:
139  raise ValueError("no likelihood files!")
140  rankingstatpdf = far.marginalize_pdf_urls(filenames, "RankingStatPDF", verbose = verbose)
141 
142  if ln_likelihood_ratio_threshold is None:
143  # determine the treshold below which the extinction model
144  # will be invalid. FIXME: this shouldn't have to be
145  # repeated in code like this, the extinction model itself
146  # should provide this information somehow.
147  zl = rankingstatpdf.zero_lag_lr_lnpdf.copy()
148  zl.array[:40] = 0.
149  if not zl.array.any():
150  raise ValueError("zero-lag counts are all zero")
151  ln_likelihood_ratio_threshold, = zl.argmax()
152 
153  # apply the extinction model
154  rankingstatpdf = rankingstatpdf.new_with_extinction()
155 
156  # affect the zeroing of the PDFs below threshold by hacking the
157  # histograms. do the indexing ourselves to not 0 the bin @
158  # threshold
159  rankingstatpdf.noise_lr_lnpdf.array[:rankingstatpdf.noise_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
160  rankingstatpdf.noise_lr_lnpdf.normalize()
161  rankingstatpdf.signal_lr_lnpdf.array[:rankingstatpdf.signal_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
162  rankingstatpdf.signal_lr_lnpdf.normalize()
163  rankingstatpdf.zero_lag_lr_lnpdf.array[:rankingstatpdf.zero_lag_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
164  rankingstatpdf.zero_lag_lr_lnpdf.normalize()
165 
166  return rankingstatpdf, ln_likelihood_ratio_threshold
167 
168 
169 def load_search_results(filenames, ln_likelihood_ratio_threshold, tmp_path = None, verbose = False):
170  zerolag_ln_likelihood_ratios = []
171 
172  for n, filename in enumerate(filenames, 1):
173  if verbose:
174  print >>sys.stderr, "%d/%d: %s" % (n, len(filenames), filename)
175  with dbtables.workingcopy(filename, tmp_path = tmp_path, discard = True, verbose = verbose) as working_filename:
176  connection = sqlite3.connect(str(working_filename))
177 
178  xmldoc = dbtables.get_xml(connection)
179  definer_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
180 
181  for ln_likelihood_ratio in connection.cursor().execute("""
182 SELECT
183  coinc_event.likelihood,
184 FROM
185  coinc_event
186  JOIN coinc_inspiral ON (
187  coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
188  )
189 WHERE
190  coinc_event.coinc_def_id == ?
191  AND NOT EXISTS (
192  SELECT
193  *
194  FROM
195  time_slide
196  WHERE
197  time_slide.time_slide_id == coinc_event.time_slide_id
198  AND time_slide.offset != 0
199  )
200  AND coinc_event.likelihood >= ?"""
201  , (definer_id, (ln_likelihood_ratio_threshold if ln_likelihood_ratio_threshold is not None else NegInf))):
202  zerolag_ln_likelihood_ratios.append(ln_likelihood_ratio)
203 
204  connection.close()
205 
206  return zerolag_ln_likelihood_ratios
207 
208 
209 def plot_rates(signal_rate_ln_pdf, credible_intervals = None):
210  fig = figure.Figure()
211  FigureCanvas(fig)
212  fig.set_size_inches((4., 4. / golden_ratio))
213  axes = fig.gca()
214 
215  x, = signal_rate_ln_pdf.centres()
216  y = numpy.exp(signal_rate_ln_pdf.at_centres())
217  line1, = axes.plot(x, y, color = "k", linestyle = "-", label = "Signal")
218  axes.set_title("Event Rate Posterior Probability Density")
219  axes.set_xlabel("Event Rate ($\mathrm{signals} / \mathrm{experiment}$)")
220  axes.set_ylabel(r"$P(\mathrm{signals} / \mathrm{experiment})$")
221 
222  axes.semilogy()
223  #axes.set_ylim((1e-8, 1.))
224  axes.set_xlim((0., axes.get_xlim()[1]))
225 
226  axes.yaxis.set_minor_locator(ticker.LogLocator(10., subs = (0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9)))
227  axes.minorticks_on()
228  axes.grid(which = "both", linestyle = "-", linewidth = 0.2)
229 
230  if credible_intervals is not None:
231  alphas = dict(zip(sorted(credible_intervals), [.6, .4, .2]))
232 
233  # convert lo and hi bounds to co-ordinate index segments
234  credible_intervals = sorted((cred, segments.segmentlist([segments.segment(bisect.bisect_left(x, lo), bisect.bisect_right(x, hi))])) for cred, (mode, lo, hi) in credible_intervals.items())
235 
236  # remove from each the indexes spanned by lower credible regions
237  credible_intervals = [(cred, indexes - sum((segs for cred, segs in credible_intervals[:i]), segments.segmentlist())) for i, (cred, indexes) in enumerate(credible_intervals)]
238 
239  for cred, segs in credible_intervals:
240  for lo, hi in segs:
241  axes.fill_between(x[lo:hi+1], y[lo:hi+1], 1e-8, color = "k", alpha = alphas[cred])
242 
243  fig.tight_layout()
244  return fig
245 
246 
247 #
248 # =============================================================================
249 #
250 # Main
251 #
252 # =============================================================================
253 #
254 
255 
256 #
257 # command line
258 #
259 
260 
261 options, paramdict, filenames = parse_command_line()
262 
263 
264 #
265 # load ranking statistic PDFs
266 #
267 
268 
269 if options.ranking_stat_pdf:
270  rankingstatpdf, ln_likelihood_ratio_threshold = load_ranking_data(options.ranking_stat_pdf, options.ln_likelihood_ratio_threshold, verbose = options.verbose)
271 else:
272  rankingstatpdf, ln_likelihood_ratio_threshold = None, None
273 
274 
275 #
276 # load search results
277 #
278 
279 
280 zerolag_ln_likelihood_ratios = load_search_results(filenames, ln_likelihood_ratio_threshold = ln_likelihood_ratio_threshold, tmp_path = options.tmp_space, verbose = options.verbose)
281 
282 
283 #
284 # calculate rate posteriors
285 #
286 
287 
288 if options.verbose:
289  print >>sys.stderr, "calculating rate posteriors using %d likelihood ratios ..." % len(zerolag_ln_likelihood_ratios)
290  progressbar = ProgressBar()
291 else:
292  progressbar = None
293 kwargs = {}
294 if options.chain_file is not None:
295  kwargs["chain_file"] = h5py.File(options.chain_file)
296 if options.samples is not None:
297  kwargs["nsample"] = options.samples
298 signal_rate_ln_pdf, noise_rate_ln_pdf = rate_estimation.calculate_rate_posteriors(rankingstatpdf, zerolag_ln_likelihood_ratios, progressbar = progressbar, **kwargs)
299 #p_signal = rate_estimation.calculate_psignal_posteriors_from_rate_samples(rankingstatpdf, zerolag_ln_likelihood_ratios, progressbar = progressbar)
300 #while open("p_signal.txt", "w") as f:
301 # for vals in zip(zerolag_ln_likelihood_ratios, p_signal):
302 # print >>f, "%.17g %.17g" % vals
303 del progressbar
304 
305 
306 #
307 # find credible intervals
308 #
309 
310 
311 if options.credible_intervals:
312  if options.verbose:
313  print >>sys.stderr, "determining credible intervals ..."
314  credible_intervals = dict((cred, rate_estimation.confidence_interval_from_lnpdf(signal_rate_ln_pdf, cred)) for cred in options.credible_intervals)
315 else:
316  credible_intervals = None
317 if options.verbose and credible_intervals is not None:
318  print >>sys.stderr, "rate posterior mean = %g signals/experiment" % rate_estimation.mean_from_lnpdf(signal_rate_ln_pdf)
319  print >>sys.stderr, "rate posterior median = %g signals/experiment" % rate_estimation.median_from_lnpdf(signal_rate_ln_pdf)
320  # all modes are the same, pick one and report it
321  print >>sys.stderr, "maximum-likelihood rate = %g signals/experiment" % credible_intervals.values()[0][0]
322  for cred, (mode, lo, hi) in sorted(credible_intervals.items()):
323  print >>sys.stderr, "%g%% credible interval = [%g, %g] signals/experiment" % (cred * 100., lo, hi)
324 
325 
326 #
327 # save results
328 #
329 
330 
331 filename = "rate_posteriors.xml.gz"
332 xmldoc = ligolw.Document()
333 xmldoc.appendChild(ligolw.LIGO_LW())
334 process = ligolw_process.register_to_xmldoc(xmldoc, process_name, paramdict)
335 xmldoc.childNodes[-1].appendChild(signal_rate_ln_pdf.to_xml(u"%s:signal_ln_pdf" % process_name))
336 xmldoc.childNodes[-1].appendChild(noise_rate_ln_pdf.to_xml(u"%s:noise_ln_pdf" % process_name))
337 ligolw_utils.write_filename(xmldoc, filename, verbose = options.verbose)
338 
339 
340 fig = plot_rates(signal_rate_ln_pdf, credible_intervals = credible_intervals)
341 for filename in ("rate_posteriors.png", "rate_posteriors.pdf"):
342  if options.verbose:
343  print >>sys.stderr, "writing %s ..." % filename
344  fig.savefig(filename)
345 
346 if options.verbose:
347  print >>sys.stderr, "done"