gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
far.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 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License as published by the
6 # Free Software Foundation; either version 2 of the License, or (at your
7 # option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
12 # Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 
18 ## @file
19 # The python module to implement false alarm probability and false alarm rate
20 #
21 # ### Review Status
22 #
23 # STATUS: reviewed with actions
24 #
25 # | Names | Hash | Date | Diff to Head of Master |
26 # | ------------------------------------------- | ------------------------------------------- | ---------- | --------------------------- |
27 # | Hanna, Cannon, Meacher, Creighton J, Robinet, Sathyaprakash, Messick, Dent, Blackburn | 7fb5f008afa337a33a72e182d455fdd74aa7aa7a | 2014-11-05 |<a href="@gstlal_inspiral_cgit_diff/python/far.py?id=HEAD&id2=7fb5f008afa337a33a72e182d455fdd74aa7aa7a">far.py</a> |
28 # | Hanna, Cannon, Meacher, Creighton J, Sathyaprakash, | 72875f5cb241e8d297cd9b3f9fe309a6cfe3f716 | 2015-11-06 |<a href="@gstlal_inspiral_cgit_diff/python/far.py?id=HEAD&id2=72875f5cb241e8d297cd9b3f9fe309a6cfe3f716">far.py</a> |
29 #
30 # #### Action items
31 #
32 
33 # - Address the fixed SNR PDF using median PSD which could be pre-computed and stored on disk. (Store database of SNR pdfs for a variety of horizon)
34 # - The binning parameters are hard-coded too; Could it be a problem?
35 # - Chisquare binning hasn't been tuned to be a good representation of the PDFs; could be improved in future
36 
37 ## @package far
38 
39 
40 #
41 # =============================================================================
42 #
43 # Preamble
44 #
45 # =============================================================================
46 #
47 
48 
49 try:
50  from fpconst import NaN, NegInf, PosInf
51 except ImportError:
52  # fpconst is not part of the standard library and might not be
53  # available
54  NaN = float("nan")
55  NegInf = float("-inf")
56  PosInf = float("+inf")
57 import itertools
58 import math
59 import multiprocessing
60 import numpy
61 import random
62 from scipy import interpolate
63 from scipy import optimize
64 import os
65 import sys
66 import time
67 
68 
69 from ligo.lw import ligolw
70 from ligo.lw import array as ligolw_array
71 from ligo.lw import param as ligolw_param
72 from ligo.lw import lsctables
73 from ligo.lw import utils as ligolw_utils
74 from glue.text_progress_bar import ProgressBar
75 from lal import rate
76 from lalburst import snglcoinc
77 from ligo import segments
78 from ligo.segments import utils as segmentsUtils
79 
80 
81 from gstlal import stats as gstlalstats
82 from gstlal.stats import inspiral_lr
83 
84 
85 #
86 # =============================================================================
87 #
88 # Ranking Statistic
89 #
90 # =============================================================================
91 #
92 
93 
94 def kwarggeniter(d, min_instruments):
95  d = tuple(sorted(d.items()))
96  return map(dict, itertools.chain(*(itertools.combinations(d, i) for i in range(min_instruments, len(d) + 1))))
97 
98 
99 def kwarggen(segments, snrs, chi2s_over_snr2s, phase, dt, template_id, min_instruments):
100  # segments and template_id held fixed
101  for snrs, chi2s_over_snr2s, phase, dt in zip(
102  kwarggeniter(snrs, min_instruments),
103  kwarggeniter(chi2s_over_snr2s, min_instruments),
104  kwarggeniter(phase, min_instruments),
105  kwarggeniter(dt, min_instruments)
106  ):
107  yield {
108  "segments": segments,
109  "snrs": snrs,
110  "chi2s_over_snr2s": chi2s_over_snr2s,
111  "phase": phase,
112  "dt": dt,
113  "template_id": template_id
114  }
115 
116 
117 class RankingStat(snglcoinc.LnLikelihoodRatioMixin):
118  ligo_lw_name_suffix = u"gstlal_inspiral_rankingstat"
119 
120  #
121  # Default content handler for loading RankingStat objects from XML
122  # documents
123  #
124 
125  @ligolw_array.use_in
126  @ligolw_param.use_in
127  @lsctables.use_in
128  class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
129  pass
130 
131  # network SNR threshold
132  network_snrsq_threshold = 49.0
133 
134  def __init__(self, template_ids = None, instruments = frozenset(("H1", "L1", "V1")), population_model_file = None, dtdphi_file = None, min_instruments = 1, delta_t = 0.005, horizon_factors = None, idq_file = None):
135  self.numerator = inspiral_lr.LnSignalDensity(template_ids = template_ids, instruments = instruments, delta_t = delta_t, population_model_file = population_model_file, dtdphi_file = dtdphi_file, min_instruments = min_instruments, horizon_factors = horizon_factors, idq_file = idq_file)
136  self.denominator = inspiral_lr.LnNoiseDensity(template_ids = template_ids, instruments = instruments, delta_t = delta_t, min_instruments = min_instruments)
137  self.zerolag = inspiral_lr.LnLRDensity(template_ids = template_ids, instruments = instruments, delta_t = delta_t, min_instruments = min_instruments)
138 
139  def fast_path_cut(self, snrs, **kwargs):
140  """
141  Return True if the candidate described by kwargs should be
142  cut, False otherwise. Used to fast-path out of the full
143  likelihood evaluation, and to drop coincs from the
144  coincidence engine to reduce data rate.
145 
146  NOTE: surviving this cut is not an endorsement of the
147  candidate, many candidates that survive this cut will
148  subsequently be discarded for other reasons. This code is
149  only intended to achieve a computationally efficient data
150  rate reduction that does not negatively impact the search
151  sensitivity.
152  """
153  # network SNR cut
154  if sum(snr**2. for snr in snrs.values()) < self.network_snrsq_threshold:
155  return True
156  return False
157 
158  def __call__(self, **kwargs):
159  """
160  Evaluate the ranking statistic.
161  """
162  # ranking statistic is only defined for SNRs at or above
163  # the threshold. modern gstlal_inspiral generates
164  # sub-threshold triggers for Bayestar and we need to be
165  # ceratin they don't leak into here.
166  assert all(snr >= self.snr_min for snr in kwargs["snrs"].values())
167 
168  # fast-path cut
169  if self.fast_path_cut(**kwargs):
170  return NegInf
171 
172  # FIXME NOTE
173  # Here we put in a penalty for single detector triggers.
174  # This is a tuned parameter.
175  lnP = 0. if len(kwargs["snrs"]) > 1 else -10.
176 
177  # full ln L ranking stat. we define the ranking statistic
178  # to be the largest ln L from all allowed subsets of
179  # triggers. Maximizes over higher than double IFO combos.
180  return lnP + super(RankingStat, self).__call__(**kwargs) if len(kwargs["snrs"])==1 else max(super(RankingStat, self).__call__(**kwargs) for kwargs in kwarggen(min_instruments = max(2, self.min_instruments), **kwargs))
181 
182  @property
183  def template_ids(self):
184  return self.denominator.template_ids
185 
186  @template_ids.setter
187  def template_ids(self, value):
188  self.numerator.template_ids = value
189  self.denominator.template_ids = value
190  self.zerolag.template_ids = value
191 
192  @property
193  def snr_min(self):
194  return self.numerator.snr_min
195 
196  @property
197  def instruments(self):
198  return self.denominator.instruments
199 
200  @property
201  def min_instruments(self):
202  return self.denominator.min_instruments
203 
204  @property
205  def delta_t(self):
206  return self.denominator.delta_t
207 
208  @property
209  def population_model_file(self):
210  return self.numerator.population_model_file
211 
212  @property
213  def dtdphi_file(self):
214  return self.numerator.dtdphi_file
215 
216  @property
217  def idq_file(self):
218  return self.numerator.idq_file
219 
220  @property
221  def horizon_factors(self):
222  return self.numerator.horizon_factors
223 
224  @property
225  def segmentlists(self):
226  return self.denominator.segmentlists
227 
228  def __iadd__(self, other):
229  if type(other) != type(self):
230  raise TypeError(other)
231  self.numerator += other.numerator
232  self.denominator += other.denominator
233  self.zerolag += other.zerolag
234  return self
235 
236  def copy(self):
237  new = type(self)(template_ids = self.template_ids, instruments = self.instruments, population_model_file = self.population_model_file, dtdphi_file = self.dtdphi_file, min_instruments = self.min_instruments, delta_t = self.delta_t)
238  new.numerator = self.numerator.copy()
239  new.denominator = self.denominator.copy()
240  new.zerolag = self.zerolag.copy()
241  # NOTE: only if denominator.lnzerolagdensity is pointing
242  # to *our* zero-lag density will the copy's be set,
243  # otherwise the copy's will be reset to None
244  if self.denominator.lnzerolagdensity is self.zerolag:
245  new.denominator.lnzerolagdensity = new.zerolag
246  return new
247 
248  def kwargs_from_triggers(self, events, offsetvector):
249  """
250  Constructs the key-word arguments to be passed to
251  .__call__() from a sequence of single-detector triggers
252  constituting a coincident candidate collected with the
253  given offset vector. For internal use by the
254  *_from_triggers() methods.
255  """
256  #
257  # exclude triggers that are below the SNR threshold. this
258  # is easier to do here, when what we have is triggers, than
259  # in the .__call__() method where their parameters have
260  # already been mixed into the kwargs.
261  #
262 
263  events = tuple(event for event in events if event.snr >= self.snr_min)
264  assert len(events) >= self.min_instruments, "coincidence engine failed to respect minimum instrument count requirement for candidates: found candidate with %d < %d instruments" % (len(events), self.min_instruments)
265 
266  #
267  # pick a random, but reproducible, trigger to provide a
268  # reference timestamp for, e.g, the \Delta t's between
269  # instruments and the time spanned by the candidate.
270  #
271  # the trigger times are conveyed as offsets-from-epoch.
272  # the trigger times are taken to be their time-shifted
273  # values, the time-shifted reference trigger is used to
274  # define the epoch. the objective here is to allow the
275  # trigger times to be converted to floats without loss of
276  # precision, without loosing knowledge of the \Delta t's
277  # between triggers, and in such a way that singles always
278  # have a time-shifted offset-from-epoch of 0.
279  #
280  # for the time spanned by the event, we need a segment for
281  # every instrument whether or not it provided a trigger,
282  # and reflecting the offset vector that was considered when
283  # this candidate was formed (the ranking statistic needs to
284  # know when it was we were looking for triggers in the
285  # instruments that failed to provide them). for
286  # instruments that do not provide a trigger, we time-shift
287  # the reference trigger's interval under the assumption
288  # that because we use exact-match coincidence the interval
289  # is the same for all instruments.
290  #
291 
292  reference = min(events, key = lambda event: event.ifo)
293  ref_end, ref_offset = reference.end, offsetvector[reference.ifo]
294  template_id = reference.template_id
295  if template_id not in self.template_ids:
296  raise ValueError("event IDs %s are from the wrong template" % ", ".join(sorted(str(event.event_id) for event in events)))
297  # segment spanned by reference event
298  seg = segments.segment(ref_end - reference.template_duration, ref_end)
299  # initially populate segs dictionary shifting reference
300  # instrument's segment according to offset vectors
301  segs = dict((instrument, seg.shift(ref_offset - offsetvector[instrument])) for instrument in self.instruments)
302  # for any any real triggers we have, use their true
303  # intervals
304  segs.update((event.ifo, segments.segment(event.end - event.template_duration, event.end)) for event in events)
305 
306  # done
307  return dict(
308  segments = segs,
309  snrs = dict((event.ifo, event.snr) for event in events),
310  chi2s_over_snr2s = dict((event.ifo, event.chisq / event.snr**2.) for event in events),
311  phase = dict((event.ifo, event.coa_phase) for event in events),
312  dt = dict((event.ifo, float(event.end - ref_end) + offsetvector[event.ifo] - ref_offset) for event in events),
313  template_id = template_id
314  )
315 
316  def fast_path_cut_from_triggers(self, events, offsetvector):
317  """
318  Evaluate the ranking statistic's fast-path cut for a
319  sequence of single-detector triggers constituting a
320  coincident candidate collected with the given offset
321  vector.
322  """
323  return self.fast_path_cut(**self.kwargs_from_triggers(events, offsetvector))
324 
325  def ln_lr_from_triggers(self, events, offsetvector):
326  """
327  Evaluate the ranking statistic for a sequence of
328  single-detector triggers constituting a coincident
329  candidate collected with the given offset vector.
330  """
331  try:
332  return self(**self.kwargs_from_triggers(events, offsetvector))
333  except (ValueError, AssertionError) as e:
334  raise type(e)("%s: event IDs %s, offsets %s" % (str(e), ", ".join(sorted(str(event.event_id) for event in events)), str(offsetvector)))
335 
336  def finish(self):
337  self.numerator.finish()
338  self.denominator.finish()
339  self.zerolag.finish()
340  return self
341 
342  def is_healthy(self, verbose = False):
343  # do we believe the PDFs are sufficiently well-defined to
344  # compute ln L? not healthy until at least one instrument
345  # in the analysis has produced triggers, and until all that
346  # have produced triggers have each produced at least 10
347  # million.
348  # NOTE: this will go badly if a detector that has never
349  # produced triggers, say because it joins an observing run
350  # late, suddenly starts producing triggers between snapshot
351  # cycles of an online analysis. we're assuming, here, that
352  # detectors join science runs not at random times, but at
353  # scheduled times, say, during maintenance breaks, and that
354  # the analysis will not be collecting any candidates for
355  # approximately one snapshot interval around the addition
356  # of the new detector.
357  nonzero_counts = [count for count in self.denominator.triggerrates.counts.values() if count]
358  health = 0. if not nonzero_counts else min(nonzero_counts) / 10000000.
359  if verbose:
360  ProgressBar(text = "ranking stat. health", value = health).show()
361  return health >= 1.
362 
363  @classmethod
364  def get_xml_root(cls, xml, name):
365  """
366  Sub-classes can use this in their overrides of the
367  .from_xml() method to find the root element of the XML
368  serialization.
369  """
370  name = u"%s:%s" % (name, cls.ligo_lw_name_suffix)
371  xml = [elem for elem in xml.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name") and elem.Name == name]
372  if len(xml) != 1:
373  raise ValueError("XML tree must contain exactly one %s element named %s" % (ligolw.LIGO_LW.tagName, name))
374  return xml[0]
375 
376  @classmethod
377  def from_xml(cls, xml, name):
378  """
379  In the XML document tree rooted at xml, search for the
380  serialized RankingStat object named name, and deserialize
381  it. The return value is a two-element tuple. The first
382  element is the deserialized RankingStat object, the second
383  is the process ID recorded when it was written to XML.
384  """
385  xml = cls.get_xml_root(xml, name)
386  self = cls.__new__(cls)
387  self.numerator = inspiral_lr.LnSignalDensity.from_xml(xml, "numerator")
388  self.denominator = inspiral_lr.LnNoiseDensity.from_xml(xml, "denominator")
389  self.zerolag = inspiral_lr.LnLRDensity.from_xml(xml, "zerolag")
390  return self
391 
392  def to_xml(self, name):
393  """
394  Serialize this RankingStat object to an XML fragment and
395  return the root element of the resulting XML tree.
396  """
397  xml = ligolw.LIGO_LW({u"Name": u"%s:%s" % (name, self.ligo_lw_name_suffix)})
398  xml.appendChild(self.numerator.to_xml("numerator"))
399  xml.appendChild(self.denominator.to_xml("denominator"))
400  xml.appendChild(self.zerolag.to_xml("zerolag"))
401  return xml
402 
403 
405  # NOTE: .__iadd__(), .copy() and I/O are forbidden, but these
406  # operations will be blocked by the .numerator and .denominator
407  # instances, no need to add extra code here to prevent these
408  # operations
409  def __init__(self, *args, **kwargs):
410  self.numerator = inspiral_lr.DatalessLnSignalDensity(*args, **kwargs)
411  kwargs.pop("population_model_file", None)
412  kwargs.pop("dtdphi_file", None)
413  kwargs.pop("idq_file", None)
414  self.denominator = inspiral_lr.DatalessLnNoiseDensity(*args, **kwargs)
415 
416  def finish(self):
417  # no zero-lag
418  self.numerator.finish()
419  self.denominator.finish()
420  return self
421 
422  def is_healthy(self, verbose = False):
423  if verbose:
424  ProgressBar(text = "ranking stat. health", value = 1.).show()
425  return True
426 
427 
429  """
430  Version of RankingStat with horizon distance history and trigger
431  rate history spliced in from another instance. Used to solve a
432  chicken-or-egg problem and assign ranking statistic values in an
433  aonline anlysis. NOTE: the donor data is not copied, instances of
434  this class hold references to the donor's data, so as it is
435  modified those modifications are immediately reflected here.
436 
437  For safety's sake, instances cannot be written to or read from
438  files, cannot be marginalized together with other instances, nor
439  accept updates from new data.
440  """
441  # NOTE: .__iadd__(), .copy() and I/O are forbidden, but these
442  # operations will be blocked by the .numerator and .denominator
443  # instances, no need to add extra code here to prevent these
444  # operations
445  def __init__(self, src, donor):
446  self.numerator = inspiral_lr.OnlineFrankensteinLnSignalDensity.splice(src.numerator, donor.numerator)
447  self.denominator = inspiral_lr.OnlineFrankensteinLnNoiseDensity.splice(src.denominator, donor.denominator)
448 
449  def finish(self):
450  # no zero-lag
451  self.numerator.finish()
452  self.denominator.finish()
453  return self
454 
455 
456 #
457 # =============================================================================
458 #
459 # False Alarm Book-Keeping Object
460 #
461 # =============================================================================
462 #
463 
464 
465 def binned_log_likelihood_ratio_rates_from_samples(signal_lr_lnpdf, noise_lr_lnpdf, samples, nsamples):
466  """
467  Populate signal and noise BinnedLnPDF densities from a sequence of
468  samples (which can be a generator). The first nsamples elements
469  from the sequence are used. The samples must be a sequence of
470  three-element tuples (or sequences) in which the first element is a
471  value of the ranking statistic (likelihood ratio) and the second
472  and third elements the logs of the probabilities of obtaining that
473  value of the ranking statistic in the signal and noise populations
474  respectively.
475  """
476  exp = math.exp
477  isnan = math.isnan
478  signal_lr_lnpdf_count = signal_lr_lnpdf.count
479  noise_lr_lnpdf_count = noise_lr_lnpdf.count
480  for ln_lamb, lnP_signal, lnP_noise in itertools.islice(samples, nsamples):
481  if isnan(ln_lamb):
482  raise ValueError("encountered NaN likelihood ratio")
483  if isnan(lnP_signal) or isnan(lnP_noise):
484  raise ValueError("encountered NaN signal or noise model probability densities")
485  signal_lr_lnpdf_count[ln_lamb,] += exp(lnP_signal)
486  noise_lr_lnpdf_count[ln_lamb,] += exp(lnP_noise)
487 
488 
489 #
490 # Class to compute ranking statistic PDFs for background-like and
491 # signal-like populations
492 #
493 
494 
495 class RankingStatPDF(object):
496  ligo_lw_name_suffix = u"gstlal_inspiral_rankingstatpdf"
497 
498  @staticmethod
499  def density_estimate(lnpdf, name, kernel = rate.gaussian_window(4.)):
500  """
501  For internal use only.
502  """
503  assert not numpy.isnan(lnpdf.array).any(), "%s log likelihood ratio PDF contain NaNs" % name
504  rate.filter_array(lnpdf.array, kernel)
505 
506  @staticmethod
507  def binned_log_likelihood_ratio_rates_from_samples_wrapper(queue, signal_lr_lnpdf, noise_lr_lnpdf, samples, nsamples):
508  """
509  For internal use only.
510  """
511  try:
512  # want the forked processes to use different random
513  # number sequences, so we re-seed Python and
514  # numpy's random number generators here in the
515  # wrapper in the hope that that takes care of it
516  random.seed()
517  numpy.random.seed()
518  binned_log_likelihood_ratio_rates_from_samples(signal_lr_lnpdf, noise_lr_lnpdf, samples, nsamples)
519  queue.put((signal_lr_lnpdf.array, noise_lr_lnpdf.array))
520  except:
521  queue.put((None, None))
522  raise
523 
524  def __init__(self, rankingstat, signal_noise_pdfs = None, nsamples = 2**24, nthreads = 8, verbose = False):
525  #
526  # bailout out used by .from_xml() class method to get an
527  # uninitialized instance
528  #
529 
530  if rankingstat is None:
531  return
532 
533  #
534  # initialize binnings
535  #
536 
537  self.noise_lr_lnpdf = rate.BinnedLnPDF(rate.NDBins((rate.ATanBins(0., 110., 6000),)))
538  self.signal_lr_lnpdf = rate.BinnedLnPDF(rate.NDBins((rate.ATanBins(0., 110., 6000),)))
539  self.zero_lag_lr_lnpdf = rate.BinnedLnPDF(rate.NDBins((rate.ATanBins(0., 110., 6000),)))
540  self.segments = segmentsUtils.vote(rankingstat.segmentlists.values(), rankingstat.min_instruments)
541  if rankingstat.template_ids is None:
542  raise ValueError("cannot be initialized from a RankingStat that is not for a specific set of templates")
543  self.template_ids = rankingstat.template_ids
544 
545  #
546  # bailout used by codes that want all-zeros histograms
547  #
548 
549  if not nsamples:
550  return
551 
552  #
553  # run importance-weighted random sampling to populate
554  # binnings.
555  #
556 
557  if signal_noise_pdfs is None:
558  signal_noise_pdfs = rankingstat
559 
560  nthreads = int(nthreads)
561  assert nthreads >= 1
562  threads = []
563  for i in range(nthreads):
564  assert nsamples // nthreads >= 1
565  q = multiprocessing.SimpleQueue()
566  p = multiprocessing.Process(target = lambda: self.binned_log_likelihood_ratio_rates_from_samples_wrapper(
567  q,
568  self.signal_lr_lnpdf,
569  self.noise_lr_lnpdf,
570  rankingstat.ln_lr_samples(rankingstat.denominator.random_params(), signal_noise_pdfs),
571  nsamples = nsamples // nthreads
572  ))
573  p.start()
574  threads.append((p, q))
575  nsamples -= nsamples // nthreads
576  nthreads -= 1
577  # sleep a bit to help random number seeds change
578  time.sleep(1.5)
579  while threads:
580  p, q = threads.pop(0)
581  signal_counts, noise_counts = q.get()
582  self.signal_lr_lnpdf.array += signal_counts
583  self.noise_lr_lnpdf.array += noise_counts
584  p.join()
585  if p.exitcode:
586  raise Exception("sampling thread failed")
587  if verbose:
588  print("done computing ranking statistic PDFs", file=sys.stderr)
589 
590  #
591  # apply density estimation kernels to counts
592  #
593 
594  self.density_estimate(self.noise_lr_lnpdf, "noise model")
595  self.density_estimate(self.signal_lr_lnpdf, "signal model")
596 
597  #
598  # set the total sample count in the noise and signal
599  # ranking statistic histogram equal to the total expected
600  # count of the respective events from the experiment. this
601  # information is required so that when adding ranking
602  # statistic PDFs in our .__iadd__() method they are
603  # combined with the correct relative weights, so that
604  # .__iadd__() has the effect of marginalizing the
605  # distribution over the experiments being combined.
606  #
607 
608  self.noise_lr_lnpdf.array *= sum(rankingstat.denominator.candidate_count_model().values()) / self.noise_lr_lnpdf.array.sum()
609  self.noise_lr_lnpdf.normalize()
610  self.signal_lr_lnpdf.array *= rankingstat.numerator.candidate_count_model() / self.signal_lr_lnpdf.array.sum()
611  self.signal_lr_lnpdf.normalize()
612 
613 
614  def copy(self):
615  new = self.__class__(None)
616  new.noise_lr_lnpdf = self.noise_lr_lnpdf.copy()
617  new.signal_lr_lnpdf = self.signal_lr_lnpdf.copy()
618  new.zero_lag_lr_lnpdf = self.zero_lag_lr_lnpdf.copy()
619  new.segments = type(self.segments)(self.segments)
620  new.template_ids = self.template_ids
621  return new
622 
623 
624  def collect_zero_lag_rates(self, connection, coinc_def_id):
625  # FIXME: Gamma0 contains the template_id, switch to proper
626  # column when one is available
627  for ln_likelihood_ratio, template_id in connection.cursor().execute("""
628 SELECT
629  likelihood,
630  (SELECT
631  Gamma0
632  FROM
633  sngl_inspiral
634  JOIN coinc_event_map ON (
635  coinc_event_map.table_name == "sngl_inspiral"
636  AND coinc_event_map.event_id == sngl_inspiral.event_id
637  )
638  WHERE
639  coinc_event_map.coinc_event_id == coinc_event.coinc_event_id
640  LIMIT 1
641  )
642 FROM
643  coinc_event
644 WHERE
645  coinc_def_id == ?
646  AND NOT EXISTS (
647  SELECT
648  *
649  FROM
650  time_slide
651  WHERE
652  time_slide.time_slide_id == coinc_event.time_slide_id
653  AND time_slide.offset != 0
654  )
655 """, (coinc_def_id,)):
656  assert ln_likelihood_ratio is not None, "null likelihood ratio encountered. probably coincs have not been ranked"
657  if template_id not in self.template_ids:
658  raise ValueError("zero-lag candidate encountered with template ID not for this RankingStatPDF")
659  self.zero_lag_lr_lnpdf.count[ln_likelihood_ratio,] += 1.
660  self.zero_lag_lr_lnpdf.normalize()
661 
662 
663  def density_estimate_zero_lag_rates(self):
664  # apply density estimation preserving total count, then
665  # normalize PDF
666  count_before = self.zero_lag_lr_lnpdf.array.sum()
667  # FIXME: should .normalize() be able to handle NaN?
668  if count_before:
669  self.density_estimate(self.zero_lag_lr_lnpdf, "zero lag")
670  self.zero_lag_lr_lnpdf.array *= count_before / self.zero_lag_lr_lnpdf.array.sum()
671  self.zero_lag_lr_lnpdf.normalize()
672 
673 
674  def __iadd__(self, other):
675  self.noise_lr_lnpdf += other.noise_lr_lnpdf
676  self.noise_lr_lnpdf.normalize()
677  self.signal_lr_lnpdf += other.signal_lr_lnpdf
678  self.signal_lr_lnpdf.normalize()
679  self.zero_lag_lr_lnpdf += other.zero_lag_lr_lnpdf
680  self.zero_lag_lr_lnpdf.normalize()
681  # FIXME: now that we know what templates this is for, we
682  # could conceivably impose a policy that if the segments
683  # overlap then the templates must be different, and if the
684  # templates are the same then the segments must be disjoint
685  self.segments += other.segments
686  self.template_ids |= other.template_ids
687  return self
688 
689 
690  def new_with_extinction(self):
691  self = self.copy()
692 
693  # the probability that an event survives clustering is the
694  # probability that no event with a higher value of the
695  # ranking statistic is within +/- dt of the event in
696  # question. .noise_lr_lnpdf.count contains an accurate
697  # model of the counts of pre-clustered events in each
698  # ranking statistic bin, but we know the events are not
699  # independent and so the total number of them cannot be
700  # used to form a Poisson rate for the purpose of computing
701  # the probability we desire. it has been found,
702  # empirically, that if the CCDF of pre-clustered background
703  # event counts is raised to some power and the clustering
704  # survival probability computed from that as though it were
705  # the CCDF of a Poisson process with some effective mean
706  # event rate, the result is a very good model for the
707  # post-clustering distribution of ranking statistics. we
708  # have two unknown parameters: the power to which to raise
709  # the pre-clustered ranking statistic's CCDF, and the mean
710  # event rate to assume. we solve for these parameters by
711  # fitting to the observed zero-lag ranking statistic
712  # histogram
713 
714  x = self.noise_lr_lnpdf.bins[0].centres()
715  assert (x == self.zero_lag_lr_lnpdf.bins[0].centres()).all()
716 
717  # some candidates are rejected by the ranking statistic,
718  # causing there to be a spike in the zero-lag density at ln
719  # L = -inf. if enough candidates get rejected this spike
720  # becomes the mode of the PDF which messes up the mask
721  # constructed below for the fit. we zero the first 40 bins
722  # here to prevent that from happening (assume density
723  # estimation kernel = 4 bins wide, with 10 sigma impulse
724  # length)
725  zl_counts = self.zero_lag_lr_lnpdf.array.copy()
726  zl_counts[:40] = 0.
727  if not zl_counts.any():
728  raise ValueError("zero-lag counts are all zero")
729 
730  # get the noise counts
731  noise_counts = self.noise_lr_lnpdf.array.copy()
732 
733  # get the zerolag counts.
734  # we model the tail of the distribution - top 0.1 - 1% - where
735  # clustering only effects the result at a < 1% level.
736  if zl_counts.sum() < 100 * 1000:
737  tail_zl_counts = zl_counts.sum() * 0.99
738  else:
739  tail_zl_counts = zl_counts.sum() - 1000
740  onepercent = zl_counts.cumsum().searchsorted(tail_zl_counts)
741 
742  # normalize the counts
743  noise_counts /= noise_counts.sum()
744  zl_counts /= zl_counts.sum()
745 
746  # compute survival probability
747  norm = zl_counts[onepercent] / noise_counts[onepercent]
748  zl_counts[onepercent:] = 0
749  noise_counts[onepercent:] = 0
750  survival_probability = zl_counts / noise_counts
751  survival_probability[onepercent:] = norm
752  survival_probability[numpy.isnan(survival_probability)] = 0.0
753 
754  # apply to background counts and signal counts
755  self.noise_lr_lnpdf.array *= survival_probability
756  self.noise_lr_lnpdf.normalize()
757  self.signal_lr_lnpdf.array *= survival_probability
758  self.signal_lr_lnpdf.normalize()
759 
760  #
761  # never allow PDFs that have had the extinction model
762  # applied to be written to disk: on-disk files must only
763  # ever provide the original data. forbid PDFs that have
764  # been extincted from being re-extincted.
765  #
766 
767  def new_with_extinction(*args, **kwargs):
768  raise NotImplementedError("re-extincting an extincted RankingStatPDF object is forbidden")
769  self.new_with_extinction = new_with_extinction
770  def to_xml(*args, **kwargs):
771  raise NotImplementedError("writing extincted RankingStatPDF object to disk is forbidden")
772  self.to_xml = to_xml
773 
774  return self
775 
776 
777  def is_healthy(self, verbose = False):
778  # do we believe the PDFs are sufficiently well-defined to
779  # compute FAPs and FARs?
780  health = min(self.noise_lr_lnpdf.array.sum() / 1000000., self.zero_lag_lr_lnpdf.array.sum() / 10000.)
781  if verbose:
782  ProgressBar(text = "ranking stat. health", value = health).show()
783  return health >= 1.
784 
785 
786  @classmethod
787  def get_xml_root(cls, xml, name):
788  """
789  Sub-classes can use this in their overrides of the
790  .from_xml() method to find the root element of the XML
791  serialization.
792  """
793  name = u"%s:%s" % (name, cls.ligo_lw_name_suffix)
794  xml = [elem for elem in xml.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name") and elem.Name == name]
795  if len(xml) != 1:
796  raise ValueError("XML tree must contain exactly one %s element named %s" % (ligolw.LIGO_LW.tagName, name))
797  return xml[0]
798 
799 
800  @classmethod
801  def from_xml(cls, xml, name):
802  # find the root of the XML tree containing the
803  # serialization of this object
804  xml = cls.get_xml_root(xml, name)
805  # create a mostly uninitialized instance
806  self = cls(None)
807  # populate from XML
808  self.noise_lr_lnpdf = rate.BinnedLnPDF.from_xml(xml, u"noise_lr_lnpdf")
809  self.signal_lr_lnpdf = rate.BinnedLnPDF.from_xml(xml, u"signal_lr_lnpdf")
810  self.zero_lag_lr_lnpdf = rate.BinnedLnPDF.from_xml(xml, u"zero_lag_lr_lnpdf")
811  self.segments = ligolw_param.get_pyvalue(xml, u"segments").strip()
812  self.segments = segmentsUtils.from_range_strings(self.segments.split(",") if self.segments else [], float)
813  self.template_ids = frozenset(map(int, ligolw_param.get_pyvalue(xml, u"template_ids").split(",")))
814  return self
815 
816  def to_xml(self, name):
817  # do not allow ourselves to be written to disk without our
818  # PDFs' internal normalization metadata being up to date
819  self.noise_lr_lnpdf.normalize()
820  self.signal_lr_lnpdf.normalize()
821  self.zero_lag_lr_lnpdf.normalize()
822 
823  xml = ligolw.LIGO_LW({u"Name": u"%s:%s" % (name, self.ligo_lw_name_suffix)})
824  xml.appendChild(self.noise_lr_lnpdf.to_xml(u"noise_lr_lnpdf"))
825  xml.appendChild(self.signal_lr_lnpdf.to_xml(u"signal_lr_lnpdf"))
826  xml.appendChild(self.zero_lag_lr_lnpdf.to_xml(u"zero_lag_lr_lnpdf"))
827  xml.appendChild(ligolw_param.Param.from_pyvalue(u"segments", ",".join(segmentsUtils.to_range_strings(self.segments))))
828  xml.appendChild(ligolw_param.Param.from_pyvalue(u"template_ids", ",".join("%d" % template_id for template_id in sorted(self.template_ids))))
829  return xml
830 
831 
832 #
833 # Class to compute false-alarm probabilities and false-alarm rates from
834 # ranking statistic PDFs
835 #
836 
837 
838 class FAPFAR(object):
839  def __init__(self, rankingstatpdf):
840  # input checks
841  if not rankingstatpdf.zero_lag_lr_lnpdf.array.any():
842  raise ValueError("RankingStatPDF's zero-lag counts are all zero")
843 
844  # save the livetime
845  self.livetime = float(abs(rankingstatpdf.segments))
846 
847  # set the rate normalization LR threshold to be the mode of
848  # the zero-lag LR distribution. NOTE: this is a hack to
849  # work around the extinction model's inability to model the
850  # rate of extremly low significance events. if the
851  # extinction model can ever be made to model the observed
852  # candidate rate at all ranking statistic values then this
853  # threshold nonsense can be removed. NOTE: some candidates
854  # are rejected by the ranking statistic, causing there to
855  # be a spike in the zero-lag density at ln L = -inf. if
856  # enough candidates get rejected this spike becomes the
857  # mode of the PDF. .new_with_extinction() above has a hack
858  # to work around this in its noise mode fitting code, which
859  # we need to reproduce here when picking the threshold
860  # above which we believe the noise model to be correct
861  zl = rankingstatpdf.zero_lag_lr_lnpdf.copy()
862  zl.array[:40] = 0.
863  rate_normalization_lr_threshold, = zl.argmax()
864 
865  # record trials factor, with safety checks
866  counts = rankingstatpdf.zero_lag_lr_lnpdf.count
867  assert not numpy.isnan(counts.array).any(), "zero lag log likelihood ratio counts contain NaNs"
868  assert (counts.array >= 0.).all(), "zero lag log likelihood ratio rates contain negative values"
869  self.count_above_threshold = counts[rate_normalization_lr_threshold:,].sum()
870 
871  # get noise model ranking stat values and event counts from
872  # bins
873  threshold_index = rankingstatpdf.noise_lr_lnpdf.bins[0][rate_normalization_lr_threshold]
874  ranks = rankingstatpdf.noise_lr_lnpdf.bins[0].lower()[threshold_index:]
875  counts = rankingstatpdf.noise_lr_lnpdf.array[threshold_index:]
876  assert not numpy.isnan(counts).any(), "background log likelihood ratio rates contain NaNs"
877  assert (counts >= 0.).all(), "background log likelihood ratio rates contain negative values"
878 
879  # complementary cumulative distribution function
880  ccdf = counts[::-1].cumsum()[::-1]
881  ccdf /= ccdf[0]
882 
883  # ccdf is P(ranking stat > threshold | a candidate). we
884  # need P(ranking stat > threshold), i.e. need to correct
885  # for the possibility that no candidate is present.
886  # specifically, the ccdf needs to =1-1/e at the candidate
887  # identification threshold, and cdf=1/e at the candidate
888  # threshold, in order for FAR(threshold) * livetime to
889  # equal the actual observed number of candidates.
890  ccdf = gstlalstats.poisson_p_not_0(ccdf)
891 
892  # safety checks
893  assert not numpy.isnan(ranks).any(), "log likelihood ratio co-ordinates contain NaNs"
894  assert not numpy.isinf(ranks).any(), "log likelihood ratio co-ordinates are not all finite"
895  assert not numpy.isnan(ccdf).any(), "log likelihood ratio CCDF contains NaNs"
896  assert ((0. <= ccdf) & (ccdf <= 1.)).all(), "log likelihood ratio CCDF failed to be normalized"
897 
898  # build interpolator.
899  self.ccdf_interpolator = interpolate.interp1d(ranks, ccdf)
900 
901  # record min and max ranks so we know which end of the ccdf
902  # to use when we're out of bounds
903  self.minrank = ranks[0]
904  self.maxrank = ranks[-1]
905 
906  @gstlalstats.assert_probability
907  def ccdf_from_rank(self, rank):
908  return self.ccdf_interpolator(numpy.clip(rank, self.minrank, self.maxrank))
909 
910  def fap_from_rank(self, rank):
911  # implements equation (8) from Phys. Rev. D 88, 024025.
912  # arXiv:1209.0718.
913  return gstlalstats.fap_after_trials(self.ccdf_from_rank(rank), self.count_above_threshold)
914 
915  def rank_from_fap(self, p, tolerance = 1e-6):
916  """
917  Inverts .fap_from_rank(). This function is sensitive to
918  numerical noise for probabilities that are close to 1. The
919  tolerance sets the absolute error of the result.
920  """
921  assert 0. <= p <= 1., "p (%g) is not a valid probability" % p
922  lo, hi = self.minrank, self.maxrank
923  while hi - lo > tolerance:
924  mid = (hi + lo) / 2.
925  mid_fap = self.fap_from_rank(mid)
926  if p > mid_fap:
927  # desired rank is below the middle
928  hi = mid
929  elif p < mid_fap:
930  # desired rank is above the middle
931  lo = mid
932  else:
933  # jackpot
934  return mid
935  return (hi + lo) / 2.
936  rank_from_fap.__get__ = numpy.vectorize(rank_from_fap, otypes = (numpy.float64,), excluded = (0, 2, 'self', 'tolerance'))
937 
938  def far_from_rank(self, rank):
939  # implements equation (B4) of Phys. Rev. D 88, 024025.
940  # arXiv:1209.0718. the return value is divided by T to
941  # convert events/experiment to events/second. "tdp" =
942  # true-dismissal probability = 1 - single-event false-alarm
943  # probability, the integral in equation (B4)
944  log_tdp = numpy.log1p(-self.ccdf_from_rank(rank))
945  return self.count_above_threshold * -log_tdp / self.livetime
946 
947  def rank_from_far(self, rate, tolerance = 1e-6):
948  """
949  Inverts .far_from_rank() using a bisection search. The
950  tolerance sets the absolute error of the result.
951  """
952  lo, hi = self.minrank, self.maxrank
953  while hi - lo > tolerance:
954  mid = (hi + lo) / 2.
955  mid_far = self.far_from_rank(mid)
956  if rate > mid_far:
957  # desired rank is below the middle
958  hi = mid
959  elif rate < mid_far:
960  # desired rank is above the middle
961  lo = mid
962  else:
963  # jackpot
964  return mid
965  return (hi + lo) / 2.
966  rank_from_far.__get__ = numpy.vectorize(rank_from_far, otypes = (numpy.float64,), excluded = (0, 2, 'self', 'tolerance'))
967 
968  def assign_fapfars(self, connection):
969  # assign false-alarm probabilities and false-alarm rates
970  # FIXME: abusing false_alarm_rate column to store FAP,
971  # move to a false_alarm_probability column??
972  def as_float(f):
973  def g(x):
974  return float(f(x))
975  return g
976  connection.create_function("fap_from_rankingstat", 1, as_float(self.fap_from_rank))
977  connection.create_function("far_from_rankingstat", 1, as_float(self.far_from_rank))
978  connection.cursor().execute("""
979 UPDATE
980  coinc_inspiral
981 SET
982  false_alarm_rate = (
983  SELECT
984  fap_from_rankingstat(coinc_event.likelihood)
985  FROM
986  coinc_event
987  WHERE
988  coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
989  ),
990  combined_far = (
991  SELECT
992  far_from_rankingstat(coinc_event.likelihood)
993  FROM
994  coinc_event
995  WHERE
996  coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
997  )
998 """)
999 
1000 
1001 #
1002 # =============================================================================
1003 #
1004 # I/O
1005 #
1006 # =============================================================================
1007 #
1008 
1009 
1010 def gen_likelihood_control_doc(xmldoc, rankingstat, rankingstatpdf):
1011  name = u"gstlal_inspiral_likelihood"
1012  node = xmldoc.childNodes[-1]
1013  assert node.tagName == ligolw.LIGO_LW.tagName
1014 
1015  if rankingstat is not None:
1016  node.appendChild(rankingstat.to_xml(name))
1017 
1018  if rankingstatpdf is not None:
1019  node.appendChild(rankingstatpdf.to_xml(name))
1020 
1021  return xmldoc
1022 
1023 
1024 def parse_likelihood_control_doc(xmldoc):
1025  name = u"gstlal_inspiral_likelihood"
1026  try:
1027  rankingstat = RankingStat.from_xml(xmldoc, name)
1028  except ValueError:
1029  rankingstat = None
1030  try:
1031  rankingstatpdf = RankingStatPDF.from_xml(xmldoc, name)
1032  except ValueError:
1033  rankingstatpdf = None
1034  if rankingstat is None and rankingstatpdf is None:
1035  raise ValueError("document does not contain likelihood ratio data")
1036  return rankingstat, rankingstatpdf
1037 
1038 
1039 def marginalize_pdf_urls(urls, which, ignore_missing_files = False, verbose = False):
1040  """
1041  Implements marginalization of PDFs in ranking statistic data files.
1042  The marginalization is over the degree of freedom represented by
1043  the file collection. One or both of the candidate parameter PDFs
1044  and ranking statistic PDFs can be processed, with errors thrown if
1045  one or more files is missing the required component.
1046  """
1047  name = u"gstlal_inspiral_likelihood"
1048  data = None
1049  for n, url in enumerate(urls, start = 1):
1050  #
1051  # load input document
1052  #
1053 
1054  if verbose:
1055  print("%d/%d:" % (n, len(urls)), file=sys.stderr)
1056  try:
1057  xmldoc = ligolw_utils.load_url(url, verbose = verbose, contenthandler = RankingStat.LIGOLWContentHandler)
1058  except IOError:
1059  # IOError is raised when an on-disk file is
1060  # missing. urllib2.URLError is raised when a URL
1061  # cannot be loaded, but this is subclassed from
1062  # IOError so IOError will catch those, too.
1063  if not ignore_missing_files:
1064  raise
1065  if verbose:
1066  print("Could not load \"%s\" ... skipping as requested" % url, file=sys.stderr)
1067  continue
1068 
1069  #
1070  # extract PDF objects compute weighted sum of ranking data
1071  # PDFs
1072  #
1073 
1074  if which == "RankingStat":
1075  if data is None:
1076  data = RankingStat.from_xml(xmldoc, name)
1077  else:
1078  data += RankingStat.from_xml(xmldoc, name)
1079  elif which == "RankingStatPDF":
1080  if data is None:
1081  data = RankingStatPDF.from_xml(xmldoc, name)
1082  else:
1083  data += RankingStatPDF.from_xml(xmldoc, name)
1084  else:
1085  raise ValueError("invalid which (%s)" % which)
1086  xmldoc.unlink()
1087 
1088  return data
def rank_from_far
Definition: far.py:947
def far_from_rank
Definition: far.py:938
def rank_from_fap
Definition: far.py:915
def fap_from_rank
Definition: far.py:910
def instruments
Definition: far.py:197
def density_estimate
Definition: far.py:499
minrank
Definition: far.py:903
def binned_log_likelihood_ratio_rates_from_samples_wrapper
Definition: far.py:507
ccdf_interpolator
Definition: far.py:899
def get_xml_root
Definition: far.py:787
def from_xml
Definition: far.py:377
def to_xml
Definition: far.py:392
def delta_t
Definition: far.py:205
string ligo_lw_name_suffix
Definition: far.py:496
def template_ids
Definition: far.py:183
def kwargs_from_triggers
Definition: far.py:248
def ln_lr_from_triggers
Definition: far.py:325
def dtdphi_file
Definition: far.py:213
def population_model_file
Definition: far.py:209
def snr_min
Definition: far.py:193
maxrank
Definition: far.py:904
string ligo_lw_name_suffix
Definition: far.py:118
def fast_path_cut_from_triggers
Definition: far.py:316
def min_instruments
Definition: far.py:201
def fast_path_cut
Definition: far.py:139
def ccdf_from_rank
Definition: far.py:907
livetime
Definition: far.py:845
def __call__
Definition: far.py:158
count_above_threshold
Definition: far.py:869
float network_snrsq_threshold
Definition: far.py:132
def get_xml_root
Definition: far.py:364