50 from fpconst
import NaN, NegInf, PosInf
55 NegInf = float(
"-inf")
56 PosInf = float(
"+inf")
59 import multiprocessing
62 from scipy
import interpolate
63 from scipy
import optimize
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
76 from lalburst
import snglcoinc
77 from ligo
import segments
78 from ligo.segments
import utils
as segmentsUtils
81 from gstlal
import stats
as gstlalstats
82 from gstlal.stats
import inspiral_lr
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))))
99 def kwarggen(segments, snrs, chi2s_over_snr2s, phase, dt, template_id, min_instruments):
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)
108 "segments": segments,
110 "chi2s_over_snr2s": chi2s_over_snr2s,
113 "template_id": template_id
118 ligo_lw_name_suffix =
u"gstlal_inspiral_rankingstat"
132 network_snrsq_threshold = 49.0
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)
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.
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
160 Evaluate the ranking statistic.
166 assert all(snr >= self.
snr_min for snr
in kwargs[
"snrs"].values())
175 lnP = 0.
if len(kwargs[
"snrs"]) > 1
else -10.
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))
183 def template_ids(self):
184 return self.denominator.template_ids
187 def template_ids(self, value):
188 self.numerator.template_ids = value
189 self.denominator.template_ids = value
190 self.zerolag.template_ids = value
194 return self.numerator.snr_min
197 def instruments(self):
198 return self.denominator.instruments
201 def min_instruments(self):
202 return self.denominator.min_instruments
206 return self.denominator.delta_t
209 def population_model_file(self):
210 return self.numerator.population_model_file
213 def dtdphi_file(self):
214 return self.numerator.dtdphi_file
218 return self.numerator.idq_file
221 def horizon_factors(self):
222 return self.numerator.horizon_factors
225 def segmentlists(self):
226 return self.denominator.segmentlists
228 def __iadd__(self, other):
229 if type(other) != type(self):
230 raise TypeError(other)
238 new.numerator = self.numerator.copy()
239 new.denominator = self.denominator.copy()
240 new.zerolag = self.zerolag.copy()
244 if self.denominator.lnzerolagdensity
is self.
zerolag:
245 new.denominator.lnzerolagdensity = new.zerolag
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.
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)
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
296 raise ValueError(
"event IDs %s are from the wrong template" %
", ".join(sorted(str(event.event_id)
for event
in events)))
298 seg = segments.segment(ref_end - reference.template_duration, ref_end)
301 segs = dict((instrument, seg.shift(ref_offset - offsetvector[instrument]))
for instrument
in self.
instruments)
304 segs.update((event.ifo, segments.segment(event.end - event.template_duration, event.end))
for event
in events)
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
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
327 Evaluate the ranking statistic for a sequence of
328 single-detector triggers constituting a coincident
329 candidate collected with the given offset vector.
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)))
337 self.numerator.finish()
338 self.denominator.finish()
339 self.zerolag.finish()
342 def is_healthy(self, verbose = False):
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.
360 ProgressBar(text =
"ranking stat. health", value = health).show()
366 Sub-classes can use this in their overrides of the
367 .from_xml() method to find the root element of the XML
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]
373 raise ValueError(
"XML tree must contain exactly one %s element named %s" % (ligolw.LIGO_LW.tagName, name))
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.
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")
394 Serialize this RankingStat object to an XML fragment and
395 return the root element of the resulting XML tree.
398 xml.appendChild(self.numerator.to_xml(
"numerator"))
399 xml.appendChild(self.denominator.to_xml(
"denominator"))
400 xml.appendChild(self.zerolag.to_xml(
"zerolag"))
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)
418 self.numerator.finish()
419 self.denominator.finish()
422 def is_healthy(self, verbose = False):
424 ProgressBar(text =
"ranking stat. health", value = 1.).show()
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.
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.
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)
451 self.numerator.finish()
452 self.denominator.finish()
465 def binned_log_likelihood_ratio_rates_from_samples(signal_lr_lnpdf, noise_lr_lnpdf, samples, nsamples):
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
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):
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)
496 ligo_lw_name_suffix =
u"gstlal_inspiral_rankingstatpdf"
501 For internal use only.
503 assert not numpy.isnan(lnpdf.array).any(),
"%s log likelihood ratio PDF contain NaNs" % name
504 rate.filter_array(lnpdf.array, kernel)
509 For internal use only.
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))
521 queue.put((
None,
None))
524 def __init__(self, rankingstat, signal_noise_pdfs = None, nsamples = 2**24, nthreads = 8, verbose = False):
530 if rankingstat
is None:
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")
557 if signal_noise_pdfs
is None:
558 signal_noise_pdfs = rankingstat
560 nthreads = int(nthreads)
563 for i
in range(nthreads):
564 assert nsamples // nthreads >= 1
565 q = multiprocessing.SimpleQueue()
570 rankingstat.ln_lr_samples(rankingstat.denominator.random_params(), signal_noise_pdfs),
571 nsamples = nsamples // nthreads
574 threads.append((p, q))
575 nsamples -= nsamples // nthreads
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
586 raise Exception(
"sampling thread failed")
588 print(
"done computing ranking statistic PDFs", file=sys.stderr)
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()
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()
624 def collect_zero_lag_rates(self, connection, coinc_def_id):
627 for ln_likelihood_ratio, template_id
in connection.cursor().execute(
"""
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
639 coinc_event_map.coinc_event_id == coinc_event.coinc_event_id
652 time_slide.time_slide_id == coinc_event.time_slide_id
653 AND time_slide.offset != 0
655 """, (coinc_def_id,)):
656 assert ln_likelihood_ratio
is not None,
"null likelihood ratio encountered. probably coincs have not been ranked"
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()
663 def density_estimate_zero_lag_rates(self):
666 count_before = self.zero_lag_lr_lnpdf.array.sum()
670 self.zero_lag_lr_lnpdf.array *= count_before / self.zero_lag_lr_lnpdf.array.sum()
671 self.zero_lag_lr_lnpdf.normalize()
674 def __iadd__(self, other):
676 self.noise_lr_lnpdf.normalize()
678 self.signal_lr_lnpdf.normalize()
680 self.zero_lag_lr_lnpdf.normalize()
690 def new_with_extinction(self):
714 x = self.noise_lr_lnpdf.bins[0].centres()
715 assert (x == self.zero_lag_lr_lnpdf.bins[0].centres()).all()
725 zl_counts = self.zero_lag_lr_lnpdf.array.copy()
727 if not zl_counts.any():
728 raise ValueError(
"zero-lag counts are all zero")
731 noise_counts = self.noise_lr_lnpdf.array.copy()
736 if zl_counts.sum() < 100 * 1000:
737 tail_zl_counts = zl_counts.sum() * 0.99
739 tail_zl_counts = zl_counts.sum() - 1000
740 onepercent = zl_counts.cumsum().searchsorted(tail_zl_counts)
743 noise_counts /= noise_counts.sum()
744 zl_counts /= zl_counts.sum()
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
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()
767 def new_with_extinction(*args, **kwargs):
768 raise NotImplementedError(
"re-extincting an extincted RankingStatPDF object is forbidden")
770 def to_xml(*args, **kwargs):
771 raise NotImplementedError(
"writing extincted RankingStatPDF object to disk is forbidden")
777 def is_healthy(self, verbose = False):
780 health = min(self.noise_lr_lnpdf.array.sum() / 1000000., self.zero_lag_lr_lnpdf.array.sum() / 10000.)
782 ProgressBar(text =
"ranking stat. health", value = health).show()
789 Sub-classes can use this in their overrides of the
790 .from_xml() method to find the root element of the XML
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]
796 raise ValueError(
"XML tree must contain exactly one %s element named %s" % (ligolw.LIGO_LW.tagName, name))
801 def from_xml(cls, xml, name):
804 xml = cls.get_xml_root(xml, name)
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")
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(
",")))
816 def to_xml(self, name):
819 self.noise_lr_lnpdf.normalize()
820 self.signal_lr_lnpdf.normalize()
821 self.zero_lag_lr_lnpdf.normalize()
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))))
839 def __init__(self, rankingstatpdf):
841 if not rankingstatpdf.zero_lag_lr_lnpdf.array.any():
842 raise ValueError(
"RankingStatPDF's zero-lag counts are all zero")
845 self.
livetime = float(abs(rankingstatpdf.segments))
861 zl = rankingstatpdf.zero_lag_lr_lnpdf.copy()
863 rate_normalization_lr_threshold, = zl.argmax()
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"
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"
880 ccdf = counts[::-1].cumsum()[::-1]
890 ccdf = gstlalstats.poisson_p_not_0(ccdf)
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"
906 @gstlalstats.assert_probability
907 def ccdf_from_rank(self, rank):
910 def fap_from_rank(self, rank):
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.
921 assert 0. <= p <= 1.,
"p (%g) is not a valid probability" % p
923 while hi - lo > tolerance:
935 return (hi + lo) / 2.
936 rank_from_fap.__get__ = numpy.vectorize(rank_from_fap, otypes = (numpy.float64,), excluded = (0, 2,
'self',
'tolerance'))
938 def far_from_rank(self, rank):
949 Inverts .far_from_rank() using a bisection search. The
950 tolerance sets the absolute error of the result.
953 while hi - lo > tolerance:
965 return (hi + lo) / 2.
966 rank_from_far.__get__ = numpy.vectorize(rank_from_far, otypes = (numpy.float64,), excluded = (0, 2,
'self',
'tolerance'))
968 def assign_fapfars(self, connection):
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(
"""
984 fap_from_rankingstat(coinc_event.likelihood)
988 coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
992 far_from_rankingstat(coinc_event.likelihood)
996 coinc_event.coinc_event_id == coinc_inspiral.coinc_event_id
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
1015 if rankingstat
is not None:
1016 node.appendChild(rankingstat.to_xml(name))
1018 if rankingstatpdf
is not None:
1019 node.appendChild(rankingstatpdf.to_xml(name))
1024 def parse_likelihood_control_doc(xmldoc):
1025 name =
u"gstlal_inspiral_likelihood"
1027 rankingstat = RankingStat.from_xml(xmldoc, name)
1031 rankingstatpdf = RankingStatPDF.from_xml(xmldoc, name)
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
1039 def marginalize_pdf_urls(urls, which, ignore_missing_files = False, verbose = False):
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.
1047 name =
u"gstlal_inspiral_likelihood"
1049 for n, url
in enumerate(urls, start = 1):
1055 print(
"%d/%d:" % (n, len(urls)), file=sys.stderr)
1063 if not ignore_missing_files:
1066 print(
"Could not load \"%s\" ... skipping as requested" % url, file=sys.stderr)
1074 if which ==
"RankingStat":
1076 data = RankingStat.from_xml(xmldoc, name)
1078 data += RankingStat.from_xml(xmldoc, name)
1079 elif which ==
"RankingStatPDF":
1081 data = RankingStatPDF.from_xml(xmldoc, name)
1083 data += RankingStatPDF.from_xml(xmldoc, name)
1085 raise ValueError(
"invalid which (%s)" % which)
def binned_log_likelihood_ratio_rates_from_samples_wrapper
string ligo_lw_name_suffix
def population_model_file
string ligo_lw_name_suffix
def fast_path_cut_from_triggers
float network_snrsq_threshold