47 from fpconst
import NaN, NegInf, PosInf
52 NegInf = float(
"-inf")
53 PosInf = float(
"+inf")
56 from scipy
import optimize
57 from scipy
import special
61 from glue.text_progress_bar
import ProgressBar
65 from gstlal
import emcee
66 from gstlal._rate_estimation
import LogPosterior
78 def run_mcmc(n_walkers, n_dim, n_samples_per_walker, lnprobfunc, pos0 = None, args = (), n_burn = 100, progressbar =
None):
80 A generator function that yields samples distributed according to a
81 user-supplied probability density function that need not be
82 normalized. lnprobfunc computes and returns the natural logarithm
83 of the probability density, up to a constant offset. n_dim sets
84 the number of dimensions of the parameter space over which the PDF
85 is defined and args gives any additional arguments to be passed to
86 lnprobfunc, whose signature must be::
88 ln(P) = lnprobfunc(X, *args)
90 where X is a numpy array of length n_dim.
92 The generator yields a total of n_samples_per_walker arrays each of
93 which is n_walkers by n_dim in size. Each row is a sample drawn
94 from the n_dim-dimensional parameter space.
96 pos0 is an n_walkers by n_dim array giving the initial positions of
97 the walkers (this parameter is currently not optional). n_burn
98 iterations of the MCMC sampler will be executed and discarded to
99 allow the system to stabilize before samples are yielded to the
100 calling code. A chain can be continued by passing the last return
101 value as pos0 and setting n_burn = 0.
103 NOTE: the samples yielded by this generator are not drawn from the
104 PDF independently of one another. The correlation length is not
111 sampler = emcee.EnsembleSampler(n_walkers, n_dim, lnprobfunc, args = args)
118 assert pos0
is not None,
"auto-selection of initial positions not implemented"
127 pos0, ignored, ignored = sampler.run_mcmc(pos0, n_burn, storechain =
False)
128 if progressbar
is not None:
129 progressbar.increment(delta = n_burn)
130 if n_burn
and sampler.acceptance_fraction.min() < 0.4:
131 print(
"\nwarning: low burn-in acceptance fraction (min = %g)" % sampler.acceptance_fraction.min(), file=sys.stderr)
139 for coordslist, ignored, ignored
in sampler.sample(pos0, iterations = n_samples_per_walker, storechain =
False):
141 if progressbar
is not None:
142 progressbar.increment()
143 if n_samples_per_walker
and sampler.acceptance_fraction.min() < 0.5:
144 print(
"\nwarning: low sampler acceptance fraction (min %g)" % sampler.acceptance_fraction.min(), file=sys.stderr)
147 def moment_from_lnpdf(ln_pdf, moment, c = 0.):
148 if len(ln_pdf.bins) != 1:
149 raise ValueError(
"BinnedLnPDF must have 1 dimension")
150 x, = ln_pdf.centres()
151 return ((x - c)**moment * (ln_pdf.array / ln_pdf.array.sum())).sum()
154 def mean_from_lnpdf(ln_pdf):
155 return moment_from_lnpdf(ln_pdf, 1.)
158 def variance_from_lnpdf(ln_pdf):
159 return moment_from_pdf(ln_pdf, 2., mean_from_lnpdf(ln_pdf))
162 def median_from_lnpdf(ln_pdf):
167 assert (ln_pdf.array >= 0.).all(),
"PDF contains negative counts"
168 cdf = ln_pdf.array.cumsum()
181 func = rate.InterpBinnedArray(rate.BinnedArray(ln_pdf.bins, cdf - 0.5))
182 median = optimize.bisect(
184 ln_pdf.bins[0].lower()[2], ln_pdf.bins[0].upper()[-3],
185 xtol = 1e-14, disp =
False
193 assert abs(func(median)) < 1e-13,
"failed to find median (got %g)" % median
202 def confidence_interval_from_lnpdf(ln_pdf, confidence = 0.95):
204 Constructs a confidence interval based on a BinnedArray object
205 containing a normalized 1-D PDF. Returns the tuple (mode, lower bound,
209 if numpy.isnan(ln_pdf.array).any():
210 raise ValueError(
"NaNs encountered in PDF")
211 if numpy.isinf(ln_pdf.array).any():
212 raise ValueError(
"infinities encountered in PDF")
213 if (ln_pdf.array < 0.).any():
214 raise ValueError(
"negative values encountered in PDF")
215 if not 0.0 <= confidence <= 1.0:
216 raise ValueError(
"confidence must be in [0, 1]")
218 centres, = ln_pdf.centres()
219 upper = ln_pdf.bins[0].upper()
220 lower = ln_pdf.bins[0].lower()
222 mode_index = ln_pdf.bins[ln_pdf.argmax()]
225 P = ln_pdf.array / ln_pdf.array.sum()
226 assert (0. <= P).all()
227 assert (P <= 1.).all()
228 if abs(P.sum() - 1.0) > 1e-13:
229 raise ValueError(
"PDF is not normalized (integral = %g)" % P.sum())
232 ln_pdf = ln_pdf.at_centres()
235 P_sum = P[mode_index]
236 while P_sum < confidence:
237 if li <= 0
and ri >= len(P) - 1:
238 raise ValueError(
"failed to achieve requested confidence")
241 ln_pdf_li = ln_pdf[li - 1]
247 ln_pdf_ri = ln_pdf[ri + 1]
253 if ln_pdf_li > ln_pdf_ri:
256 elif ln_pdf_ri > ln_pdf_li:
262 ri = min(ri + 1, len(P) - 1)
264 return centres[mode_index], lower[li], upper[ri]
267 def f_over_b(rankingstatpdf, ln_likelihood_ratios):
269 For each sample of the ranking statistic, evaluate the ratio of the
270 signal ranking statistic PDF to background ranking statistic PDF.
276 if any(math.isnan(ln_lr)
for ln_lr
in ln_likelihood_ratios):
277 raise ValueError(
"NaN log likelihood ratio encountered")
285 f = rankingstatpdf.signal_lr_lnpdf.mkinterp()
286 b = rankingstatpdf.noise_lr_lnpdf.mkinterp()
287 f_over_b = numpy.array([math.exp(f(ln_lr) - b(ln_lr))
for ln_lr
in ln_likelihood_ratios])
289 if numpy.isnan(f_over_b).any():
290 raise ValueError(
"NaN encountered in ranking statistic PDF ratios")
291 if numpy.isinf(f_over_b).any():
292 raise ValueError(
"infinity encountered in ranking statistic PDF ratios")
310 def maximum_likelihood_rates(rankingstatpdf, ln_likelihood_ratios):
312 log_posterior = LogPosterior(numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios)))
316 f =
lambda x: -log_posterior(x)
319 return tuple(optimize.fmin(f, (1.0, len(ln_likelihood_ratios)), disp =
False))
322 def rate_posterior_from_samples(samples):
324 Construct and return a BinnedArray containing a histogram of a
325 sequence of samples. If limits is None (default) then the limits
326 of the binning will be determined automatically from the sequence,
327 otherwise limits is expected to be a tuple or other two-element
328 sequence providing the (low, high) limits, and in that case the
329 sequence can be a generator.
331 nbins = int(math.sqrt(len(samples)) / 40.)
332 assert nbins >= 1,
"too few samples to construct histogram"
333 lo = samples.min() * (1. - nbins / len(samples))
334 hi = samples.max() * (1. + nbins / len(samples))
335 ln_pdf = rate.BinnedLnPDF(rate.NDBins((rate.LogarithmicBins(lo, hi, nbins),)))
337 for sample
in samples:
339 rate.filter_array(ln_pdf.array, rate.gaussian_window(5), use_fft =
False)
344 def calculate_rate_posteriors(rankingstatpdf, ln_likelihood_ratios, progressbar = None, chain_file = None, nsample = 400000):
353 raise ValueError(
"nsample < 0: %d" % nsample)
361 if rankingstatpdf
is not None:
362 ln_f_over_b = numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios))
364 raise ValueError(
"must supply ranking data to run MCMC sampler")
367 ln_f_over_b = numpy.array([])
375 nwalkers = 10 * 2 * ndim
378 pos0 = numpy.zeros((nwalkers, ndim), dtype =
"double")
380 if progressbar
is not None:
381 progressbar.max = nsample + nburn
385 if chain_file
is not None and "chain" in chain_file:
386 chain = chain_file[
"chain"].values()
387 length = sum(sample.shape[0]
for sample
in chain)
388 samples = numpy.empty((max(nsample, length), nwalkers, ndim), dtype =
"double")
389 if progressbar
is not None:
390 progressbar.max = samples.shape[0]
393 samples[i:i+sample.shape[0],:,:] = sample
395 if progressbar
is not None:
396 progressbar.update(i)
400 pos0 = samples[i - 1,:,:]
402 raise ValueError(
"no chain file to load or invalid chain file, and no new samples requested")
408 samples = numpy.empty((nsample, nwalkers, ndim), dtype =
"double")
409 pos0[:,0] = numpy.random.exponential(scale = 1., size = (nwalkers,))
410 pos0[:,1] = numpy.random.poisson(lam = len(ln_likelihood_ratios), size = (nwalkers,))
420 log_posterior = LogPosterior(ln_f_over_b)
424 for j, coordslist
in enumerate(run_mcmc(nwalkers, ndim, max(0, nsample - i), (
lambda x: log_posterior(x) / exponent), n_burn = nburn, pos0 = pos0, progressbar = progressbar), i):
426 samples[j,:,:] = coordslist
428 if j + 1 >= i + 2048
and chain_file
is not None:
429 chain_file[
"chain/%08d" % i] = samples[i:j+1,:,:]
433 if chain_file
is not None and i < samples.shape[0]:
434 chain_file[
"chain/%08d" % i] = samples[i:,:,:]
441 if samples.min() < 0:
442 raise ValueError(
"MCMC sampler yielded negative rate(s)")
460 Rf_ln_pdf = rate_posterior_from_samples(samples[:,:,0].flatten())
461 Rf_ln_pdf.array = Rf_ln_pdf.array**exponent / Rf_ln_pdf.bins.volumes()**(exponent - 1.)
462 Rf_ln_pdf.normalize()
464 Rb_ln_pdf = rate_posterior_from_samples(samples[:,:,1].flatten())
465 Rb_ln_pdf.array = Rb_ln_pdf.array**exponent / Rb_ln_pdf.bins.volumes()**(exponent - 1.)
466 Rb_ln_pdf.normalize()
472 return Rf_ln_pdf, Rb_ln_pdf
475 def calculate_alphabetsoup_rate_posteriors(rankingstatpdf, ln_likelihood_ratios, progressbar = None, nsample = 400000):
484 raise ValueError(
"nsample < 0: %d" % nsample)
492 ln_f_over_b = numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios))
500 nwalkers = 10 * 2 * ndim
503 pos0 = numpy.zeros((nwalkers, ndim), dtype =
"double")
505 if progressbar
is not None:
506 progressbar.max = nsample + nburn
514 samples = numpy.empty((nsample, nwalkers, ndim), dtype =
"double")
515 pos0[:,0] = numpy.random.exponential(scale = 1., size = (nwalkers,))
516 pos0[:,1] = numpy.random.exponential(scale = 1., size = (nwalkers,))
517 pos0[:,2] = numpy.random.poisson(lam = len(ln_likelihood_ratios), size = (nwalkers,))
525 def log_posterior(Rf1f2b, x1 = math.exp(ln_f_over_b[-1]), x2 = math.exp(ln_f_over_b[-2]), std_log_posterior = LogPosterior(ln_f_over_b[:-2])):
526 Rf1, Rf2, Rb = Rf1f2b
527 if Rf1 < 0.
or Rf2 < 0.
or Rb < 0.:
529 return math.log(Rf1 / Rb * x1 + 1.) + math.log(Rf2 / Rb * x2 + 1.) + 2. * math.log(Rb) + std_log_posterior((Rf1 + Rf2, Rb))
531 for j, coordslist
in enumerate(run_mcmc(nwalkers, ndim, nsample, log_posterior, n_burn = nburn, pos0 = pos0, progressbar = progressbar)):
533 samples[j,:,:] = coordslist
539 if samples.min() < 0:
540 raise ValueError(
"MCMC sampler yielded negative rate(s)")
548 Rf1_pdf = rate_posterior_from_samples(samples[:,:,0].flatten())
550 Rf2_pdf = rate_posterior_from_samples(samples[:,:,1].flatten())
552 Rf12_pdf = rate_posterior_from_samples((samples[:,:,0] + samples[:,:,1]).flatten())
554 Rb_pdf = rate_posterior_from_samples(samples[:,:,2].flatten())
560 return Rf1_pdf, Rf2_pdf, Rf12_pdf, Rb_pdf
591 def ln_double_fac_table(N):
593 Compute a look-up table giving
595 ln (2m - 1)!! (2n - 1)!!
597 for 0 <= m <= N, n + m = N.
621 lnfac =
lambda x: special.gammaln(x + 1.)
623 m = numpy.arange(N + 1)
626 return lnfac(2. * m) + lnfac(2. * n) - lnfac(m) - lnfac(n) - N * math.log(2.)
629 def calculate_psignal_posteriors(rankingstatpdf, ln_likelihood_ratios, progressbar = None, chain_file = None, nsample = 400000):
638 raise ValueError(
"nsample < 0: %d" % nsample)
646 if rankingstatpdf
is not None:
647 ln_f_over_b = numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios))
649 raise ValueError(
"must supply ranking data to run MCMC sampler")
652 ln_f_over_b = numpy.array([])
658 ndim = len(ln_likelihood_ratios)
659 nwalkers = 50 * 2 * ndim
662 pos0 = numpy.random.random((nwalkers, ndim)).round()
668 if progressbar
is not None:
669 progressbar.max = nsample + nburn
672 def log_posterior(f, ln_f_over_b = ln_f_over_b, ln_double_fac_table = ln_double_fac_table(len(ln_f_over_b))):
674 Compute the natural logarithm of
676 [ \prod_{\{i | f_i = 1\}} \hat{f}(x_i) / \hat{b}(x_i) ] (2 m - 1)!! (2 n - 1)!!
678 assert len(f) == len(ln_f_over_b)
681 if (f < 0.).any()
or (f > 1.).any():
684 terms = numpy.compress(f.round(), ln_f_over_b)
686 return terms.sum() + ln_double_fac_table[len(terms)]
688 counts = numpy.zeros((nwalkers, ndim), dtype =
"double")
689 for coordslist
in run_mcmc(nwalkers, ndim, nsample, log_posterior, n_burn = nburn, pos0 = pos0, progressbar = progressbar):
690 counts += coordslist.round()
697 p_signal = (counts / nsample).mean(0)
706 def calculate_psignal_posteriors_from_rate_samples(rankingstatpdf, ln_likelihood_ratios, nsample = 100000, progressbar = None):
716 f_on_b = f_over_b(rankingstatpdf, ln_likelihood_ratios)
727 nwalkers = 10 * 2 * ndim
730 pos0 = numpy.zeros((nwalkers, ndim), dtype =
"double")
731 pos0[:,0] = numpy.random.exponential(scale = 1., size = (nwalkers,))
732 pos0[:,1] = numpy.random.poisson(lam = len(ln_likelihood_ratios), size = (nwalkers,))
734 if progressbar
is not None:
735 progressbar.max = nsample + nburn
738 p_signal = numpy.zeros_like(f_on_b)
739 for coordslist
in run_mcmc(nwalkers, ndim, nsample, LogPosterior(numpy.log(f_on_b)), n_burn = nburn, pos0 = pos0, progressbar = progressbar):
742 for Rf, Rb
in coordslist:
744 p_signal += x / (x + Rb)
745 p_signal /= nwalkers * nsample