gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
rate_estimation.py
Go to the documentation of this file.
1 # Copyright (C) 2011--2014 Kipp Cannon, Chad Hanna, Drew Keppel
2 # Copyright (C) 2013 Jacob Peoples
3 # Copyright (C) 2015 Heather Fong
4 # Copyright (C) 2015--2016 Kipp Cannon
5 #
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the
8 # Free Software Foundation; either version 2 of the License, or (at your
9 # option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 # Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 
20 ##
21 # @file
22 #
23 # A file that contains the rate estimation code.
24 #
25 # Review Status: Reviewed with actions
26 #
27 # | Names | Hash | Date |
28 # | ------------------------------------------- | ------------------------------------------- | ---------- |
29 # | Sathya, Duncan Me, Jolien, Kipp, Chad | 2fb185eda0edb9d49d79b8185f7b35457cafa06b | 2015-05-14 |
30 #
31 # #### Actions
32 # - Increase nbins to at least 10,000
33 # - Check max acceptance
34 
35 ## @package rate_estimation
36 
37 #
38 # =============================================================================
39 #
40 # Preamble
41 #
42 # =============================================================================
43 #
44 
45 
46 try:
47  from fpconst import NaN, NegInf, PosInf
48 except ImportError:
49  # fpconst is not part of the standard library and might not be
50  # available
51  NaN = float("nan")
52  NegInf = float("-inf")
53  PosInf = float("+inf")
54 import math
55 import numpy
56 from scipy import optimize
57 from scipy import special
58 import sys
59 
60 
61 from glue.text_progress_bar import ProgressBar
62 from lal import rate
63 
64 
65 from gstlal import emcee
66 from gstlal._rate_estimation import LogPosterior
67 
68 
69 #
70 # =============================================================================
71 #
72 # Helper Code
73 #
74 # =============================================================================
75 #
76 
77 
78 def run_mcmc(n_walkers, n_dim, n_samples_per_walker, lnprobfunc, pos0 = None, args = (), n_burn = 100, progressbar = None):
79  """
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::
87 
88  ln(P) = lnprobfunc(X, *args)
89 
90  where X is a numpy array of length n_dim.
91 
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.
95 
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.
102 
103  NOTE: the samples yielded by this generator are not drawn from the
104  PDF independently of one another. The correlation length is not
105  known at this time.
106  """
107  #
108  # construct a sampler
109  #
110 
111  sampler = emcee.EnsembleSampler(n_walkers, n_dim, lnprobfunc, args = args)
112 
113  #
114  # set walkers at initial positions
115  #
116 
117  # FIXME: implement
118  assert pos0 is not None, "auto-selection of initial positions not implemented"
119 
120  #
121  # burn-in: run for a while to get better initial positions.
122  # run_mcmc() doesn't like being asked for 0 iterations, so need to
123  # check for that
124  #
125 
126  if n_burn:
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)
132 
133  #
134  # reset and yield positions distributed according to the supplied
135  # PDF
136  #
137 
138  sampler.reset()
139  for coordslist, ignored, ignored in sampler.sample(pos0, iterations = n_samples_per_walker, storechain = False):
140  yield coordslist
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)
145 
146 
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()
152 
153 
154 def mean_from_lnpdf(ln_pdf):
155  return moment_from_lnpdf(ln_pdf, 1.)
156 
157 
158 def variance_from_lnpdf(ln_pdf):
159  return moment_from_pdf(ln_pdf, 2., mean_from_lnpdf(ln_pdf))
160 
161 
162 def median_from_lnpdf(ln_pdf):
163  #
164  # get bin probabilities from bin counts
165  #
166 
167  assert (ln_pdf.array >= 0.).all(), "PDF contains negative counts"
168  cdf = ln_pdf.array.cumsum()
169  cdf /= cdf[-1]
170 
171  #
172  # wrap (CDF - 0.5) in an InterpBinnedArray and use bisect to solve
173  # for 0 crossing. the interpolator gets confused where the x
174  # co-ordinates are infinite and it breaks the bisect function for
175  # some reason, so to work around the issue we start the upper and
176  # lower boundaries in a little bit from the edges of the domain.
177  # FIXME: this is stupid, find a root finder that gives the correct
178  # answer regardless.
179  #
180 
181  func = rate.InterpBinnedArray(rate.BinnedArray(ln_pdf.bins, cdf - 0.5))
182  median = optimize.bisect(
183  func,
184  ln_pdf.bins[0].lower()[2], ln_pdf.bins[0].upper()[-3],
185  xtol = 1e-14, disp = False
186  )
187 
188  #
189  # check result (detects when the root finder has failed for some
190  # reason)
191  #
192 
193  assert abs(func(median)) < 1e-13, "failed to find median (got %g)" % median
194 
195  #
196  # done
197  #
198 
199  return median
200 
201 
202 def confidence_interval_from_lnpdf(ln_pdf, confidence = 0.95):
203  """
204  Constructs a confidence interval based on a BinnedArray object
205  containing a normalized 1-D PDF. Returns the tuple (mode, lower bound,
206  upper bound).
207  """
208  # check for funny input
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]")
217 
218  centres, = ln_pdf.centres()
219  upper = ln_pdf.bins[0].upper()
220  lower = ln_pdf.bins[0].lower()
221 
222  mode_index = ln_pdf.bins[ln_pdf.argmax()]
223 
224  # get bin probabilities from bin counts
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())
230 
231  # don't need ln_pdf anymore. only need values at bin centres
232  ln_pdf = ln_pdf.at_centres()
233 
234  li = ri = mode_index
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")
239 
240  if li > 0:
241  ln_pdf_li = ln_pdf[li - 1]
242  P_li = P[li - 1]
243  else:
244  ln_pdf_li = NegInf
245  P_li = 0.
246  if ri < len(P) - 1:
247  ln_pdf_ri = ln_pdf[ri + 1]
248  P_ri = P[ri + 1]
249  else:
250  ln_pdf_ri = NegInf
251  P_ri = 0.
252 
253  if ln_pdf_li > ln_pdf_ri:
254  li -= 1
255  P_sum += P_li
256  elif ln_pdf_ri > ln_pdf_li:
257  ri += 1
258  P_sum += P_ri
259  else:
260  P_sum += P_li + P_ri
261  li = max(li - 1, 0)
262  ri = min(ri + 1, len(P) - 1)
263 
264  return centres[mode_index], lower[li], upper[ri]
265 
266 
267 def f_over_b(rankingstatpdf, ln_likelihood_ratios):
268  """
269  For each sample of the ranking statistic, evaluate the ratio of the
270  signal ranking statistic PDF to background ranking statistic PDF.
271  """
272  #
273  # check for bad input
274  #
275 
276  if any(math.isnan(ln_lr) for ln_lr in ln_likelihood_ratios):
277  raise ValueError("NaN log likelihood ratio encountered")
278 
279  #
280  # for each sample of the ranking statistic, evaluate the ratio of
281  # the signal ranking statistic PDF to background ranking statistic
282  # PDF.
283  #
284 
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])
288  # safety checks
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")
293 
294  #
295  # done
296  #
297 
298  return f_over_b
299 
300 
301 #
302 # =============================================================================
303 #
304 # Event Rate Posteriors
305 #
306 # =============================================================================
307 #
308 
309 
310 def maximum_likelihood_rates(rankingstatpdf, ln_likelihood_ratios):
311  # initialize posterior PDF for rates
312  log_posterior = LogPosterior(numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios)))
313 
314  # going to use a minimizer to find the max, so need to flip
315  # function upside down
316  f = lambda x: -log_posterior(x)
317 
318  # initial guesses are Rf=1, Rb=(# candidates)
319  return tuple(optimize.fmin(f, (1.0, len(ln_likelihood_ratios)), disp = False))
320 
321 
322 def rate_posterior_from_samples(samples):
323  """
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.
330  """
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),)))
336  count = ln_pdf.count # avoid attribute look-up in loop
337  for sample in samples:
338  count[sample,] += 1.
339  rate.filter_array(ln_pdf.array, rate.gaussian_window(5), use_fft = False)
340  ln_pdf.normalize()
341  return ln_pdf
342 
343 
344 def calculate_rate_posteriors(rankingstatpdf, ln_likelihood_ratios, progressbar = None, chain_file = None, nsample = 400000):
345  """
346  FIXME: document this
347  """
348  #
349  # check for bad input
350  #
351 
352  if nsample < 0:
353  raise ValueError("nsample < 0: %d" % nsample)
354 
355  #
356  # for each sample of the ranking statistic, evaluate the ratio of
357  # the signal ranking statistic PDF to background ranking statistic
358  # PDF.
359  #
360 
361  if rankingstatpdf is not None:
362  ln_f_over_b = numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios))
363  elif nsample > 0:
364  raise ValueError("must supply ranking data to run MCMC sampler")
365  else:
366  # no-op path
367  ln_f_over_b = numpy.array([])
368 
369  #
370  # initialize MCMC chain. try loading a chain from a chain file if
371  # provided, otherwise seed the walkers for a burn-in period
372  #
373 
374  ndim = 2
375  nwalkers = 10 * 2 * ndim # must be even and >= 2 * ndim
376  nburn = 1000
377 
378  pos0 = numpy.zeros((nwalkers, ndim), dtype = "double")
379 
380  if progressbar is not None:
381  progressbar.max = nsample + nburn
382  progressbar.show()
383 
384  i = 0
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]
391  # load chain from HDF file
392  for sample in chain:
393  samples[i:i+sample.shape[0],:,:] = sample
394  i += sample.shape[0]
395  if progressbar is not None:
396  progressbar.update(i)
397  if i:
398  # skip burn-in, restart chain from last position
399  nburn = 0
400  pos0 = samples[i - 1,:,:]
401  elif nsample <= 0:
402  raise ValueError("no chain file to load or invalid chain file, and no new samples requested")
403  if not i:
404  # no chain file provided, or file does not contain sample
405  # chain or sample chain is empty. still need burn-in.
406  # seed signal rate walkers from exponential distribution,
407  # background rate walkers from poisson distribution
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,))
411  i = 0
412 
413  #
414  # run MCMC sampler to generate (foreground rate, background rate)
415  # samples. to improve the measurement of the tails of the PDF
416  # using the MCMC sampler, we draw from a power of the PDF
417  # and then correct the histogram of the samples (see below).
418  #
419 
420  log_posterior = LogPosterior(ln_f_over_b)
421 
422  exponent = 2.25
423 
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):
425  # coordslist is nwalkers x ndim
426  samples[j,:,:] = coordslist
427  # dump samples to the chain file every 2048 steps
428  if j + 1 >= i + 2048 and chain_file is not None:
429  chain_file["chain/%08d" % i] = samples[i:j+1,:,:]
430  chain_file.flush()
431  i = j + 1
432  # dump any remaining samples to chain file
433  if chain_file is not None and i < samples.shape[0]:
434  chain_file["chain/%08d" % i] = samples[i:,:,:]
435  chain_file.flush()
436 
437  #
438  # safety check
439  #
440 
441  if samples.min() < 0:
442  raise ValueError("MCMC sampler yielded negative rate(s)")
443 
444  #
445  # compute marginalized PDFs for the foreground and background
446  # rates. for each PDF, the samples from the MCMC are histogrammed
447  # and convolved with a density estimation kernel. the samples have
448  # been drawn from some power of the correct PDF, so the counts in
449  # the bins must be corrected (BinnedLnPDF's internal array always
450  # stores raw counts). how to correct count:
451  #
452  # correct count = (correct PDF) * (bin size)
453  # = (measured PDF)^exponent * (bin size)
454  # = (measured count / (bin size))^exponent * (bin size)
455  # = (measured count)^exponent / (bin size)^(exponent - 1)
456  #
457  # this assumes small bin sizes.
458  #
459 
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()
463 
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()
467 
468  #
469  # done
470  #
471 
472  return Rf_ln_pdf, Rb_ln_pdf
473 
474 
475 def calculate_alphabetsoup_rate_posteriors(rankingstatpdf, ln_likelihood_ratios, progressbar = None, nsample = 400000):
476  """
477  FIXME: document this
478  """
479  #
480  # check for bad input
481  #
482 
483  if nsample < 0:
484  raise ValueError("nsample < 0: %d" % nsample)
485 
486  #
487  # for each sample of the ranking statistic, evaluate the ratio of
488  # the signal ranking statistic PDF to background ranking statistic
489  # PDF.
490  #
491 
492  ln_f_over_b = numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios))
493 
494  #
495  # initialize MCMC chain. try loading a chain from a chain file if
496  # provided, otherwise seed the walkers for a burn-in period
497  #
498 
499  ndim = 3
500  nwalkers = 10 * 2 * ndim # must be even and >= 2 * ndim
501  nburn = 1000
502 
503  pos0 = numpy.zeros((nwalkers, ndim), dtype = "double")
504 
505  if progressbar is not None:
506  progressbar.max = nsample + nburn
507  progressbar.show()
508 
509  #
510  # seed signal rate walkers from exponential distribution,
511  # background rate walkers from poisson distribution
512  #
513 
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,))
518 
519  #
520  # run MCMC sampler to generate (foreground rate 1, foreground rate
521  # 2, background rate) samples.
522  #
523 
524  ln_f_over_b.sort()
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.:
528  return NegInf
529  return math.log(Rf1 / Rb * x1 + 1.) + math.log(Rf2 / Rb * x2 + 1.) + 2. * math.log(Rb) + std_log_posterior((Rf1 + Rf2, Rb))
530 
531  for j, coordslist in enumerate(run_mcmc(nwalkers, ndim, nsample, log_posterior, n_burn = nburn, pos0 = pos0, progressbar = progressbar)):
532  # coordslist is nwalkers x ndim
533  samples[j,:,:] = coordslist
534 
535  #
536  # safety check
537  #
538 
539  if samples.min() < 0:
540  raise ValueError("MCMC sampler yielded negative rate(s)")
541 
542  #
543  # compute marginalized PDFs for the foreground and background
544  # rates. for each PDF, the samples from the MCMC are histogrammed
545  # and convolved with a density estimation kernel.
546  #
547 
548  Rf1_pdf = rate_posterior_from_samples(samples[:,:,0].flatten())
549 
550  Rf2_pdf = rate_posterior_from_samples(samples[:,:,1].flatten())
551 
552  Rf12_pdf = rate_posterior_from_samples((samples[:,:,0] + samples[:,:,1]).flatten())
553 
554  Rb_pdf = rate_posterior_from_samples(samples[:,:,2].flatten())
555 
556  #
557  # done
558  #
559 
560  return Rf1_pdf, Rf2_pdf, Rf12_pdf, Rb_pdf
561 
562 
563 #
564 # =============================================================================
565 #
566 # Foreground Posteriors
567 #
568 # =============================================================================
569 #
570 
571 
572 #
573 # code to compute P(signal) for each candidate.
574 #
575 # starting with equation (18) in Farr et al., and using (22) to marginalize
576 # over Rf and Rb we obtain
577 #
578 # P(\{f_i\}) \propto
579 # [ \prod_{\{i | f_i = 1\}} \hat{f}(x_i) ] [ \prod_{\{i | f_i = 0\}}
580 # \hat{b}(x_i) ] (2 m - 1)!! (2 n - 1)!!
581 #
582 # where m is the number of terms for which f_i = 1 and n = N - m is the
583 # number of terms for which f_i = 0. rearranging factors of \hat{b} this
584 # can be written as
585 #
586 # \propto [ \prod_{\{i | f_i = 1\}} \hat{f}(x_i) / \hat{b}(x_i) ] (2
587 # m - 1)!! (2 n - 1)!!
588 #
589 
590 
591 def ln_double_fac_table(N):
592  """
593  Compute a look-up table giving
594 
595  ln (2m - 1)!! (2n - 1)!!
596 
597  for 0 <= m <= N, n + m = N.
598  """
599  #
600  # (2m - 1)!! = (2m)! / (2^m m!)
601  #
602  # so
603  #
604  # ln (2m - 1)!! (2n - 1)!! =
605  # ln (2m)! + ln (2n)! - ln m! - ln n! - N ln 2
606  #
607  # and ln x! = ln \Gamma(x + 1)
608  #
609  # for which we can use the gammaln() function from scipy. the
610  # final N ln 2 term can be dropped because we only need the answer
611  # up to an arbitrary constant but it's cheap to calculate so we
612  # don't bother with that simplification.
613  #
614  # the array is invariant under reversal so a factor of 2 savings
615  # can be realized by computing only the first half, and using it to
616  # populate the second half without additional arithmetic cost, but
617  # at the time of writing the array takes less than a second to
618  # compute up to N = 10^6 so we don't bother getting fancy.
619  #
620 
621  lnfac = lambda x: special.gammaln(x + 1.)
622 
623  m = numpy.arange(N + 1)
624  n = N - m
625 
626  return lnfac(2. * m) + lnfac(2. * n) - lnfac(m) - lnfac(n) - N * math.log(2.)
627 
628 
629 def calculate_psignal_posteriors(rankingstatpdf, ln_likelihood_ratios, progressbar = None, chain_file = None, nsample = 400000):
630  """
631  FIXME: document this
632  """
633  #
634  # check for bad input
635  #
636 
637  if nsample < 0:
638  raise ValueError("nsample < 0: %d" % nsample)
639 
640  #
641  # for each sample of the ranking statistic, evaluate the ratio of
642  # the signal ranking statistic PDF to background ranking statistic
643  # PDF.
644  #
645 
646  if rankingstatpdf is not None:
647  ln_f_over_b = numpy.log(f_over_b(rankingstatpdf, ln_likelihood_ratios))
648  elif nsample > 0:
649  raise ValueError("must supply ranking data to run MCMC sampler")
650  else:
651  # no-op path
652  ln_f_over_b = numpy.array([])
653 
654  #
655  # initialize MCMC sampler. seed the walkers randomly
656  #
657 
658  ndim = len(ln_likelihood_ratios)
659  nwalkers = 50 * 2 * ndim # must be even and >= 2 * ndim
660  nburn = 1000
661 
662  pos0 = numpy.random.random((nwalkers, ndim)).round()
663 
664  #
665  # run MCMC sampler to generate {f_i} vector samples
666  #
667 
668  if progressbar is not None:
669  progressbar.max = nsample + nburn
670  progressbar.show()
671 
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))):
673  """
674  Compute the natural logarithm of
675 
676  [ \prod_{\{i | f_i = 1\}} \hat{f}(x_i) / \hat{b}(x_i) ] (2 m - 1)!! (2 n - 1)!!
677  """
678  assert len(f) == len(ln_f_over_b)
679 
680  # require 0 <= f_i <= 1
681  if (f < 0.).any() or (f > 1.).any():
682  return NegInf
683 
684  terms = numpy.compress(f.round(), ln_f_over_b)
685 
686  return terms.sum() + ln_double_fac_table[len(terms)]
687 
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()
691 
692  #
693  # compute P(signal) for each candidate from the mean of the boolean
694  # samples
695  #
696 
697  p_signal = (counts / nsample).mean(0)
698 
699  #
700  # done
701  #
702 
703  return p_signal
704 
705 
706 def calculate_psignal_posteriors_from_rate_samples(rankingstatpdf, ln_likelihood_ratios, nsample = 100000, progressbar = None):
707  """
708  FIXME: document this
709  """
710  #
711  # for each sample of the ranking statistic, evaluate the ratio of
712  # the signal ranking statistic PDF to background ranking statistic
713  # PDF.
714  #
715 
716  f_on_b = f_over_b(rankingstatpdf, ln_likelihood_ratios)
717 
718  #
719  # run MCMC sampler to generate (foreground rate, background rate)
720  # samples and compute
721  #
722  # p(g_j = 1 | d) = 1/N \sum_{k = 1}^{N} Rf_k * f(x_j) / [Rf_k*f(x_j) + Rb_k*b(x_j)]
723  #
724  #
725 
726  ndim = 2
727  nwalkers = 10 * 2 * ndim # must be even and >= 2 * ndim
728  nburn = 1000
729 
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,))
733 
734  if progressbar is not None:
735  progressbar.max = nsample + nburn
736  progressbar.show()
737 
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):
740  # coordslist is nwalkers x 2 array providing an array of
741  # (Rf, Rb) sample pairs
742  for Rf, Rb in coordslist:
743  x = Rf * f_on_b
744  p_signal += x / (x + Rb)
745  p_signal /= nwalkers * nsample
746 
747  #
748  # done
749  #
750 
751  return p_signal