3 # Copyright (C) 2013,2014 Kipp Cannon, Chad Hanna, Jacob Peoples
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 comput the signal and noise rate posteriors of a gstlal inspiral analysis
23 # =============================================================================
27 # =============================================================================
33 from fpconst
import NegInf
35 NegInf = float(
"-inf")
38 matplotlib.rcParams.update({
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,
49 from matplotlib
import figure
50 from matplotlib
import ticker
51 from matplotlib.backends.backend_agg
import FigureCanvasAgg as FigureCanvas
53 from optparse
import OptionParser
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
69 from gstlal
import far
70 from gstlal
import rate_estimation
71 from gstlal.plotutil
import golden_ratio
74 process_name = u
"gstlal_inspiral_rate_posterior"
77 __author__ =
"Kipp Cannon <kipp.cannon@ligo.org>"
78 __version__ =
"" # FIXME
83 # =============================================================================
87 # =============================================================================
91 def parse_command_line():
92 parser = OptionParser(
93 version =
"Name: %%prog\n%s" % __version__,
94 usage =
"%prog [options] candidates_database [...]"
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()
108 paramdict = options.__dict__.copy()
110 options.credible_intervals = map(
float, options.credible_intervals.split(","))
112 if options.samples is not None and options.samples < 0:
113 raise ValueError("--samples cannot be negative")
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")
122 if options.input_cache:
123 filenames += [CacheEntry(line).path for line in open(options.input_cache)]
125 return options, paramdict, filenames
129 # =============================================================================
133 # =============================================================================
137 def load_ranking_data(filenames, ln_likelihood_ratio_threshold, verbose = False):
139 raise ValueError(
"no likelihood files!")
140 rankingstatpdf = far.marginalize_pdf_urls(filenames,
"RankingStatPDF", verbose = verbose)
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()
149 if not zl.array.any():
150 raise ValueError("zero-lag counts are all zero")
151 ln_likelihood_ratio_threshold, = zl.argmax()
153 # apply the extinction model
154 rankingstatpdf = rankingstatpdf.new_with_extinction()
156 # affect the zeroing of the PDFs below threshold by hacking the
157 # histograms. do the indexing ourselves to not 0 the bin @
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()
166 return rankingstatpdf, ln_likelihood_ratio_threshold
169 def load_search_results(filenames, ln_likelihood_ratio_threshold, tmp_path = None, verbose = False):
170 zerolag_ln_likelihood_ratios = []
172 for n, filename in enumerate(filenames, 1):
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))
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)
181 for ln_likelihood_ratio in connection.cursor().execute("""
183 coinc_event.likelihood,
186 JOIN coinc_inspiral ON (
187 coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
190 coinc_event.coinc_def_id == ?
197 time_slide.time_slide_id == coinc_event.time_slide_id
198 AND time_slide.offset != 0
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)
206 return zerolag_ln_likelihood_ratios
209 def plot_rates(signal_rate_ln_pdf, credible_intervals = None):
210 fig = figure.Figure()
212 fig.set_size_inches((4., 4. / golden_ratio))
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})$")
223 #axes.set_ylim((1e-8, 1.))
224 axes.set_xlim((0., axes.get_xlim()[1]))
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)))
228 axes.grid(which = "both", linestyle = "-", linewidth = 0.2)
230 if credible_intervals is not None:
231 alphas = dict(zip(sorted(credible_intervals), [.6, .4, .2]))
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())
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)]
239 for cred, segs in credible_intervals:
241 axes.fill_between(x[lo:hi+1], y[lo:hi+1], 1e-8, color = "k", alpha = alphas[cred])
248 # =============================================================================
252 # =============================================================================
261 options, paramdict, filenames = parse_command_line()
265 # load ranking statistic PDFs
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)
272 rankingstatpdf, ln_likelihood_ratio_threshold = None, None
276 # load search results
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)
284 # calculate rate posteriors
289 print >>sys.stderr, "calculating rate posteriors using %d likelihood ratios ..." % len(zerolag_ln_likelihood_ratios)
290 progressbar = ProgressBar()
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
307 # find credible intervals
311 if options.credible_intervals:
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)
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)
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)
340 fig = plot_rates(signal_rate_ln_pdf, credible_intervals = credible_intervals)
341 for filename in ("rate_posteriors.png", "rate_posteriors.pdf"):
343 print >>sys.stderr, "writing %s ..." % filename
344 fig.savefig(filename)
347 print >>sys.stderr, "done"