gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
inspiral_lr.py
1 # Copyright (C) 2017 Kipp Cannon
2 # Copyright (C) 2011--2014 Kipp Cannon, Chad Hanna, Drew Keppel
3 # Copyright (C) 2013 Jacob Peoples
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 2 of the License, or (at your
8 # option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 # Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 
19 
20 #
21 # =============================================================================
22 #
23 # Preamble
24 #
25 # =============================================================================
26 #
27 
28 
29 import cmath
30 try:
31  from fpconst import NegInf
32 except ImportError:
33  # not all machines have fpconst installed
34  NegInf = float("-inf")
35 import math
36 import numpy
37 import os
38 import random
39 from scipy import interpolate
40 from scipy import stats
41 import sys
42 import warnings
43 import json
44 
45 
46 from ligo.lw import ligolw
47 from ligo.lw import lsctables
48 from ligo.lw import array as ligolw_array
49 from ligo.lw import param as ligolw_param
50 from ligo.lw import utils as ligolw_utils
51 from ligo import segments
52 from gstlal import chirptime
53 from gstlal.stats import horizonhistory
54 from gstlal.stats import inspiral_extrinsics
55 from gstlal.stats import inspiral_intrinsics
56 from gstlal.stats import trigger_rate
57 import lal
58 from lal import rate
59 from lalburst import snglcoinc
60 import lalsimulation
61 
62 
63 # FIXME: caution, this information might get organized differently later.
64 # for now we just need to figure out where the gstlal-inspiral directory in
65 # share/ is. don't write anything that assumes that this module will
66 # continue to define any of these symbols
67 from gstlal import paths as gstlal_config_paths
68 
69 
70 __all__ = [
71  "LnSignalDensity",
72  "LnNoiseDensity",
73  "DatalessLnSignalDensity",
74  "DatalessLnNoiseDensity",
75  "OnlineFrankensteinLnSignalDensity",
76  "OnlineFrankensteinLnNoiseDensity"
77 ]
78 
79 
80 # The typical horizon distance used to normalize such values in the likelihood
81 # ratio. Units are Mpc
82 TYPICAL_HORIZON_DISTANCE = 150.
83 
84 
85 # utility function to make an idq interpolator from an h5 file
86 def idq_interp(idq_file):
87  # set a default function to simply return 0
88  out = {}
89  for ifo in ("H1", "L1", "V1", "K1"):
90  out[ifo] = lambda x: numpy.zeros(len(x))
91  if idq_file is not None:
92  import h5py
93  from scipy.interpolate import interp1d
94  f = h5py.File(idq_file, "r")
95  for ifo in f:
96  # Pad the boundaries - FIXME remove
97  t = [0.] + list(numpy.array(f[ifo]["time"])) + [2000000000.]
98  d = [0.] + list(numpy.array(f[ ifo]["data"])) + [0.]
99  out[ifo] = interp1d(t, d)
100  return out
101 
102 
103 #
104 # =============================================================================
105 #
106 # Base Class
107 #
108 # =============================================================================
109 #
110 
111 
112 class LnLRDensity(snglcoinc.LnLRDensity):
113  # range of SNRs covered by this object
114  snr_min = 4.0
115  chi2_over_snr2_min = 1e-5
116  chi2_over_snr2_max = 1e20
117 
118  # SNR, \chi^2 binning definition
119  snr_chi_binning = rate.NDBins((rate.ATanLogarithmicBins(2.6, 26., 300), rate.ATanLogarithmicBins(.001, 0.2, 280)))
120 
121  def __init__(self, template_ids, instruments, delta_t, min_instruments = 2):
122  #
123  # check input
124  #
125 
126  if template_ids is not None and not template_ids:
127  raise ValueError("template_ids cannot be empty")
128  if min_instruments < 1:
129  raise ValueError("min_instruments=%d must be >= 1" % min_instruments)
130  if min_instruments > len(instruments):
131  raise ValueError("not enough instruments (%s) to satisfy min_instruments=%d" % (", ".join(sorted(instruments)), min_instruments))
132  if delta_t < 0.:
133  raise ValueError("delta_t=%g must be >= 0" % delta_t)
134 
135  #
136  # initialize
137  #
138 
139  self.template_ids = frozenset(template_ids) if template_ids is not None else template_ids
140  self.instruments = frozenset(instruments)
141  self.min_instruments = min_instruments
142  self.delta_t = delta_t
143  # install SNR, chi^2 PDFs. numerator will override this
144  self.densities = {}
145  for instrument in instruments:
146  self.densities["%s_snr_chi" % instrument] = rate.BinnedLnPDF(self.snr_chi_binning)
147 
148  def __iadd__(self, other):
149  if type(other) != type(self):
150  raise TypeError(other)
151  # template_id set mismatch is allowed in the special case
152  # that one or the other is None to make it possible to
153  # construct generic seed objects providing initialization
154  # data for the ranking statistics.
155  if self.template_ids is not None and other.template_ids is not None and self.template_ids != other.template_ids:
156  raise ValueError("incompatible template IDs")
157  if self.instruments != other.instruments:
158  raise ValueError("incompatible instrument sets")
159  if self.min_instruments != other.min_instruments:
160  raise ValueError("incompatible minimum number of instruments")
161  if self.delta_t != other.delta_t:
162  raise ValueError("incompatible delta_t coincidence thresholds")
163 
164  if self.template_ids is None and other.template_ids is not None:
165  self.template_ids = frozenset(other.template_ids)
166 
167  for key, lnpdf in self.densities.items():
168  lnpdf += other.densities[key]
169 
170  try:
171  del self.interps
172  except AttributeError:
173  pass
174  return self
175 
176  def increment(self, event):
177  # this test is intended to fail if .template_ids is None:
178  # must not collect trigger statistics unless we can verify
179  # that they are for the correct templates.
180  if event.template_id not in self.template_ids:
181  raise ValueError("event from wrong template")
182  # ignore events below threshold. the trigger generation
183  # mechanism now produces sub-threshold triggers to
184  # facilitiate the construction of sky maps in the online
185  # search. it's therefore now our responsibility to exclude
186  # them from the PDFs in the ranking statistic here.
187  #
188  # FIXME: this creates an inconsistency. we exclude events
189  # from the PDFs, but we don't exclude them from the
190  # evaluation of those PDFs in the .__call__() method,
191  # instead we'll report that the candidate is impossible
192  # because it contains a trigger in a "forbidden" region of
193  # the parameter space (forbidden because we've ensured
194  # nothing populates those bins). the .__call__() methods
195  # should probably be modified to exclude triggers with
196  # sub-threshold SNRs just as we've excluded them here, but
197  # I'm not yet sure. instead, for the time being, we
198  # resolve the problem by excluding sub-threshold triggers
199  # from the "-from-triggers" method in far.py. there is a
200  # FIXME related to this same issue in that code.
201  if event.snr < self.snr_min:
202  return
203  self.densities["%s_snr_chi" % event.ifo].count[event.snr, event.chisq / event.snr**2.] += 1.0
204 
205  def copy(self):
206  new = type(self)(self.template_ids, self.instruments, self.delta_t, self.min_instruments)
207  for key, lnpdf in self.densities.items():
208  new.densities[key] = lnpdf.copy()
209  return new
210 
211  def mkinterps(self):
212  self.interps = dict((key, lnpdf.mkinterp()) for key, lnpdf in self.densities.items())
213 
214  def finish(self):
215  snr_kernel_width_at_8 = 8.,
216  chisq_kernel_width = 0.08,
217  sigma = 10.
218  for key, lnpdf in self.densities.items():
219  # construct the density estimation kernel. be
220  # extremely conservative and assume only 1 in 10
221  # samples are independent, but assume there are
222  # always at least 1e7 samples.
223  numsamples = max(lnpdf.array.sum() / 10. + 1., 1e6)
224  snr_bins, chisq_bins = lnpdf.bins
225  snr_per_bin_at_8 = (snr_bins.upper() - snr_bins.lower())[snr_bins[8.]]
226  chisq_per_bin_at_0_02 = (chisq_bins.upper() - chisq_bins.lower())[chisq_bins[0.02]]
227 
228  # apply Silverman's rule so that the width scales
229  # with numsamples**(-1./6.) for a 2D PDF
230  snr_kernel_bins = snr_kernel_width_at_8 / snr_per_bin_at_8 / numsamples**(1./6.)
231  chisq_kernel_bins = chisq_kernel_width / chisq_per_bin_at_0_02 / numsamples**(1./6.)
232 
233  # check the size of the kernel. We don't ever let
234  # it get smaller than the 2.5 times the bin size
235  if snr_kernel_bins < 2.5:
236  snr_kernel_bins = 2.5
237  warnings.warn("Replacing snr kernel bins with 2.5")
238  if chisq_kernel_bins < 2.5:
239  chisq_kernel_bins = 2.5
240  warnings.warn("Replacing chisq kernel bins with 2.5")
241 
242  # convolve bin count with density estimation kernel
243  rate.filter_array(lnpdf.array, rate.gaussian_window(snr_kernel_bins, chisq_kernel_bins, sigma = sigma))
244 
245  # zero everything below the SNR cut-off. need to
246  # do the slicing ourselves to avoid zeroing the
247  # at-threshold bin
248  lnpdf.array[:lnpdf.bins[0][self.snr_min],:] = 0.
249 
250  # normalize what remains
251  lnpdf.normalize()
252  self.mkinterps()
253 
254  #
255  # never allow PDFs that have had the density estimation
256  # transform applied to be written to disk: on-disk files
257  # must only ever provide raw counts. also don't allow
258  # density estimation to be applied twice
259  #
260 
261  def to_xml(*args, **kwargs):
262  raise NotImplementedError("writing .finish()'ed LnLRDensity object to disk is forbidden")
263  self.to_xml = to_xml
264  def finish(*args, **kwargs):
265  raise NotImplementedError(".finish()ing a .finish()ed LnLRDensity object is forbidden")
266  self.finish = finish
267 
268  def to_xml(self, name):
269  xml = super(LnLRDensity, self).to_xml(name)
270  xml.appendChild(ligolw_param.Param.from_pyvalue(u"template_ids", ",".join("%d" % template_id for template_id in sorted(self.template_ids)) if self.template_ids is not None else None))
271  # FIXME this is not an ideal way to get only one into the file
272  xml.appendChild(ligolw_param.Param.from_pyvalue(u"instruments", lsctables.instrumentsproperty.set(self.instruments)))
273  xml.appendChild(ligolw_param.Param.from_pyvalue(u"min_instruments", self.min_instruments))
274  xml.appendChild(ligolw_param.Param.from_pyvalue(u"delta_t", self.delta_t))
275  for key, lnpdf in self.densities.items():
276  # never write PDFs to disk without ensuring the
277  # normalization metadata is up to date
278  lnpdf.normalize()
279  xml.appendChild(lnpdf.to_xml(key))
280  return xml
281 
282  @classmethod
283  def from_xml(cls, xml, name):
284  xml = cls.get_xml_root(xml, name)
285  template_ids = ligolw_param.get_pyvalue(xml, u"template_ids")
286  # FIXME find a better way to do this: Allow a file to not have
287  # a mass model filename. This is can happen when e.g., gstlal
288  # inspiral produces a ranking stat file which just records but
289  # doesn't evaluate LRs. Then you marginalize it in with a
290  # create prior diststats file which does have the mass model.
291  # The iadd method makes sure that the mass model is unique or
292  # that it doesn't exist.
293  if template_ids is not None:
294  template_ids = frozenset(int(i) for i in template_ids.split(","))
295  self = cls(
296  template_ids = template_ids,
297  instruments = lsctables.instrumentsproperty.get(ligolw_param.get_pyvalue(xml, u"instruments")),
298  delta_t = ligolw_param.get_pyvalue(xml, u"delta_t"),
299  min_instruments = ligolw_param.get_pyvalue(xml, u"min_instruments")
300  )
301  for key in self.densities:
302  self.densities[key] = self.densities[key].from_xml(xml, key)
303  return self
304 
305 
306 #
307 # =============================================================================
308 #
309 # Numerator Density
310 #
311 # =============================================================================
312 #
313 
314 
316  def __init__(self, *args, **kwargs):
317  self.population_model_file = kwargs.pop("population_model_file", None)
318  self.dtdphi_file = kwargs.pop("dtdphi_file", None)
319  self.horizon_factors = kwargs.pop("horizon_factors", None)
320  self.idq_file = kwargs.pop("idq_file", None)
321  super(LnSignalDensity, self).__init__(*args, **kwargs)
322  # install SNR, chi^2 PDF (one for all instruments)
323  self.densities = {
325  }
326 
327  # record of horizon distances for all instruments in the
328  # network
330  # source population model
331  # FIXME: introduce a mechanism for selecting the file
334 
335  # initialize an IDQ likelihood of glitch interpolator
336  self.idq_glitch_lnl = idq_interp(self.idq_file)
337 
338  def set_horizon_factors(self, horizon_factors):
339  self.horizon_factors = horizon_factors
340 
341  def __call__(self, segments, snrs, chi2s_over_snr2s, phase, dt, template_id):
342  assert frozenset(segments) == self.instruments
343  if len(snrs) < self.min_instruments:
344  return NegInf
345 
346  # use volume-weighted average horizon distance over
347  # duration of event to estimate sensitivity
348  assert all(segments.values()), "encountered trigger with duration = 0"
349  horizons = dict((instrument, (self.horizon_history[instrument].functional_integral(map(float, seg), lambda d: d**3.) / float(abs(seg)))**(1./3.)) for instrument, seg in segments.items())
350 
351  # compute P(t). P(t) \propto volume within which a signal will
352  # produce a candidate * number of trials \propto cube of
353  # distance to which the mininum required number of instruments
354  # can see (I think) * number of templates. we measure the
355  # distance in multiples of TYPICAL_HORIZON_DISTANCE Mpc just to
356  # get a number that will be, typically, a little closer to 1,
357  # in lieu of properly normalizating this factor. we can't
358  # normalize the factor because the normalization depends on the
359  # duration of the experiment, and that keeps changing when
360  # running online, combining offline chunks from different
361  # times, etc., and that would prevent us from being able to
362  # compare a ln L ranking statistic value defined during one
363  # period to ranking statistic values defined in other periods.
364  # by removing the normalization, and leaving this be simply a
365  # factor that is proportional to the rate of signals, we can
366  # compare ranking statistics across analysis boundaries but we
367  # loose meaning in the overall scale: ln L = 0 is not a
368  # special value, as it would be if the numerator and
369  # denominator were both normalized properly.
370  horizon = sorted(horizons.values())[-self.min_instruments] / TYPICAL_HORIZON_DISTANCE
371  if not horizon:
372  return NegInf
373  # horizon factors adjusts the computed horizon factor according
374  # to the sigma values computed at the time of the SVD. This
375  # gives a good approximation to the horizon distance for each
376  # template without computing them each explicitly. Only one
377  # template has its horizon calculated explicitly.
378  lnP = 3. * math.log(horizon * self.horizon_factors[template_id]) + math.log(len(self.template_ids))
379 
380  # Add P(instruments | horizon distances)
381  try:
382  lnP += math.log(self.InspiralExtrinsics.p_of_instruments_given_horizons(snrs.keys(), horizons))
383  except ValueError:
384  # The code raises a value error when a needed horizon distance is zero
385  return NegInf
386 
387  # Evaluate dt, dphi, snr probability
388  try:
389  lnP += math.log(self.InspiralExtrinsics.time_phase_snr(dt, phase, snrs, horizons))
390  # FIXME need to make sure this is really a math domain error
391  except ValueError:
392  return NegInf
393 
394  # evaluate population model
395  lnP += self.population_model.lnP_template_signal(template_id, max(snrs.values()))
396 
397  # evalute the (snr, \chi^2 | snr) PDFs (same for all
398  # instruments)
399  interp = self.interps["snr_chi"]
400 
401  # Evaluate the IDQ glitch probability # FIXME put in denominator
402  for ifo, seg in segments.items():
403  # only proceed if we have a trigger from this ifo
404  if ifo in snrs:
405  # FIXME don't just use the last segment, somehow include whole template duration?
406  t = float(seg[1])
407  # NOTE choose max over +-1 seconds because the sampling is only at 1 Hz.
408  lnP -= max(self.idq_glitch_lnl[ifo]([t-1., t, t+1.]))
409 
410  return lnP + sum(interp(snrs[instrument], chi2_over_snr2) for instrument, chi2_over_snr2 in chi2s_over_snr2s.items())
411 
412  def __iadd__(self, other):
413  super(LnSignalDensity, self).__iadd__(other)
414  self.horizon_history += other.horizon_history
415  if self.population_model_file is not None and other.population_model_file is not None and other.population_model_file != self.population_model_file:
416  raise ValueError("incompatible mass model file names")
417  if self.population_model_file is None and other.population_model_file is not None:
418  self.population_model_file = other.population_model_file
419  if self.dtdphi_file is not None and other.dtdphi_file is not None and other.dtdphi_file != self.dtdphi_file:
420  raise ValueError("incompatible dtdphi files")
421  if self.dtdphi_file is None and other.dtdphi_file is not None:
422  self.dtdphi_file = other.dtdphi_file
423  if self.idq_file is not None and other.idq_file is not None and other.idq_file != self.idq_file:
424  raise ValueError("incompatible idq files")
425  if self.idq_file is None and other.idq_file is not None:
426  self.idq_file = other.idq_file
427  if self.horizon_factors is not None and other.horizon_factors is not None and other.horizon_factors != self.horizon_factors:
428  # require that the horizon factors be the same within 1%
429  for k in self.horizon_factors:
430  if 0.99 > self.horizon_factors[k] / other.horizon_factors[k] > 1.01:
431  raise ValueError("incompatible horizon_factors")
432  if self.horizon_factors is None and other.horizon_factors is not None:
433  self.horizon_factors = other.horizon_factors
434 
435  return self
436 
437  def increment(self, *args, **kwargs):
438  raise NotImplementedError
439 
440  def copy(self):
441  new = super(LnSignalDensity, self).copy()
442  new.horizon_history = self.horizon_history.copy()
443  new.population_model_file = self.population_model_file
444  new.dtdphi_file = self.dtdphi_file
445  new.idq_file = self.idq_file
446  # okay to use references because read-only data
447  new.population_model = self.population_model
448  new.InspiralExtrinsics = self.InspiralExtrinsics
449  new.horizon_factors = self.horizon_factors
450  new.idq_glitch_lnl = self.idq_glitch_lnl
451  return new
452 
453  def local_mean_horizon_distance(self, gps, window = segments.segment(-32., +2.)):
454  # horizon distance window is in seconds. this is sort of a
455  # hack, we should really tie this to each waveform's filter
456  # length somehow, but we don't have a way to do that and
457  # it's not clear how much would be gained by going to the
458  # trouble of implementing that. I don't even know what to
459  # set it to, so for now it's set to something like the
460  # typical width of the whitening filter's impulse response.
461  t = abs(window)
462  vtdict = self.horizon_history.functional_integral_dict(window.shift(float(gps)), lambda D: D**3.)
463  return dict((instrument, (vt / t)**(1./3.)) for instrument, vt in vtdict.items())
464 
465  def add_signal_model(self, prefactors_range = (0.001, 0.30), df = 100, inv_snr_pow = 4.):
466  # normalize to 10 *mi*llion signals. this count makes the
467  # density estimation code choose a suitable kernel size
468  inspiral_extrinsics.NumeratorSNRCHIPDF.add_signal_model(self.densities["snr_chi"], 1e12, prefactors_range, df, inv_snr_pow = inv_snr_pow, snr_min = self.snr_min)
469  self.densities["snr_chi"].normalize()
470 
471  def candidate_count_model(self, rate = 1000.):
472  """
473  Compute and return a prediction for the total number of
474  above-threshold signal candidates expected. The rate
475  parameter sets the nominal signal rate in units of Gpc^-3
476  a^-1.
477  """
478  # FIXME: this needs to understand a mass distribution
479  # model and what part of the mass space this numerator PDF
480  # is for
481  seg = (self.horizon_history.minkey(), self.horizon_history.maxkey())
482  V_times_t = self.horizon_history.functional_integral(seg, lambda horizons: sorted(horizons.values())[-self.min_instruments]**3.)
483  # Mpc**3 --> Gpc**3, seconds --> years
484  V_times_t *= 1e-9 / (86400. * 365.25)
485  return V_times_t * rate * len(self.template_ids)
486 
487  def random_sim_params(self, sim, template_id = None, snr_efficiency = 1.0, f_low = 15.):
488  """
489  Generator that yields an endless sequence of randomly
490  generated parameter dictionaries drawn from the
491  distribution of parameters expected for the given
492  injection, which is an instance of a SimInspiral table row
493  object (see ligo.lw.lsctables.SimInspiral for more
494  information). Each value in the sequence is a tuple, the
495  first element of which is the random parameter dictionary
496  and the second is 0.
497 
498  See also:
499 
500  LnNoiseDensity.random_params()
501 
502  The parameters do not necessarily represent valid
503  candidates, for example the number of detectors reporting a
504  trigger might be less than the .min_instruments parameter
505  configured for the ranking statistic. It is the job of the
506  calling code to check the parameters for validity before
507  using them to compute ranking statistic values. This is
508  done to allow the calling code to measure the frequency
509  with which the injection is expected to be undetectable.
510  Otherwise, the sequence is suitable for input to the
511  .ln_lr_samples() log likelihood ratio generator.
512 
513  Bugs:
514 
515  The second element in each tuple in the sequence is merely
516  a placeholder, not the natural logarithm of the PDF from
517  which the sample has been drawn, as in the case of
518  random_params(). Therefore, when used in combination with
519  .ln_lr_samples(), the two probability densities computed
520  and returned by that generator along with each log
521  likelihood ratio value will simply be the probability
522  densities of the signal and noise populations at that point
523  in parameter space. They cannot be used to form an
524  importance weighted sampler of the log likelihood ratios.
525  """
526  #
527  # retrieve horizon distances from history. NOTE: some
528  # might be zero. FIXME: apply template-specific
529  # correction factor
530  #
531 
532  horizon_distance = self.local_mean_horizon_distance(sim.time_geocent)
533  assert set(horizon_distance) == self.instruments
534 
535  #
536  # compute nominal SNRs. NOTE: some might be below
537  # threshold, or even 0.
538  #
539 
540  cosi = math.cos(sim.inclination)
541  gmst = lal.GreenwichMeanSiderealTime(sim.time_geocent)
542  snr_0 = {}
543  phase_0 = {}
544  # FIXME: use horizon distance from above instead of this
545  params = {u"H1":"alpha4", u"L1":"alpha5", u"V1":"alpha6"}
546  for instrument in self.instruments:
547  fp, fc = lal.ComputeDetAMResponse(lalsimulation.DetectorPrefixToLALDetector(str(instrument)).response, sim.longitude, sim.latitude, sim.polarization, gmst)
548  snr_0[instrument] = getattr(sim, params[instrument]) if horizon_distance[instrument] != 0. else 0.
549  phase_0[instrument] = math.atan2(fc * cosi, fp * (1. + cosi**2.)/2.) - 2*sim.coa_phase + numpy.pi/2.
550  phase_0[instrument] = phase_0[instrument] - math.floor((phase_0[instrument] + numpy.pi)/numpy.pi/2.)*numpy.pi*2
551 
552  #
553  # compute template duration and retrieve valid template IDs
554  #
555 
556  template_duration = chirptime.imr_time(f_low, sim.mass1*lal.MSUN_SI, sim.mass2*lal.MSUN_SI, numpy.sqrt(numpy.dot(sim.spin1, sim.spin1)), numpy.sqrt(numpy.dot(sim.spin2, sim.spin2)))
557 
558  template_ids = tuple(self.template_ids)
559 
560  #
561  # construct SNR generators, and approximating the SNRs to
562  # be fixed at the nominal SNRs construct \chi^2 generators
563  #
564 
565  def snr_phase_gen(snr0, phase):
566  if snr0 == 0.:
567  # if the expected SNR is identically 0,
568  # that indicates the instrument was off at
569  # the time so the observed SNR must always
570  # be 0
571  while 1:
572  yield 0., phase
573  else:
574  snr0 = cmath.rect(snr0, phase)
575  randn = numpy.random.randn
576  while 1:
577  yield cmath.polar(snr0 + complex(*randn(2)))
578  def chi2_over_snr2_gen(snr):
579  # rates_lnx = ln(chi^2/snr^2)
580  rates_lnx = numpy.log(self.densities["snr_chi"].bins[1].centres())
581  # FIXME: kinda broken for SNRs below self.snr_min
582  # (right_hand) = lnP(chi^2/snr^2|snr)*const
583  rates_cdf = self.densities["snr_chi"][max(snr, self.snr_min),:]
584  assert not numpy.isnan(rates_cdf).any()
585  # (right_hand) = P(<=chi^2/snr^2|snr)*const
586  drcoss = self.densities["snr_chi"].bins[1].upper() - self.densities["snr_chi"].bins[1].lower()
587  rates_cdf =(numpy.exp(rates_cdf)[:-1]*drcoss[:-1]).cumsum()
588  assert not numpy.isnan(rates_cdf).any()
589  # add a small tilt to break degeneracies so the
590  # inverse function is defined everywhere then
591  # normalize
592  rates_cdf += numpy.linspace(0., 0.00001 * rates_cdf[-1], len(rates_cdf))
593  rates_cdf /= rates_cdf[-1]
594  # guarantee the inverse function is defined in the domain [0, 1], and check for nan failures
595  rates_cdf[0] = 0.0
596  assert rates_cdf[-1] == 1.0
597  assert not numpy.isnan(rates_cdf).any()
598  # construct an interpolator for the inverse CDF
599  interp = interpolate.interp1d(rates_cdf, rates_lnx[:-1])
600  # draw endless random values of chi^2/snr^2 from
601  # P(chi^2/snr^2|snr)
602  math_exp = math.exp
603  random_random = random.random
604  while 1:
605  yield math_exp(interp(random_random()))
606 
607  def time_gen(time):
608  rvs = stats.norm(loc=time, scale = 0.002).rvs
609  #rvs = stats.norm(loc=time-1.7e-3, scale = 4e-4).rvs #more accurate for BNS
610  while 1:
611  yield rvs()
612 
613  snr_phase = dict((instrument, iter(snr_phase_gen(snr, phase_0[instrument])).__next__) for instrument, snr in snr_0.items())
614  #chi2s_over_snr2s = dict((instrument, iter(chi2_over_snr2_gen(instrument, snr)).__next__) for instrument, snr in snr_0.items())
615  gens_t = dict((instrument, iter(time_gen(sim.time_at_instrument(instrument, {instrument: 0.0}))).__next__) for instrument in self.instruments)
616 
617  #
618  # yield a sequence of randomly generated parameters for
619  # this sim.
620  #
621 
622  while 1:
623  kwargs = {
624  "segments":{},
625  "snrs": {},
626  "chi2s_over_snr2s": {},
627  "phase": {},
628  "dt": dict((instrument, time()) for instrument, time in gens_t.items()),
629  "template_id": template_id if template_id else random.choice(template_ids)
630  }
631  ref_end = kwargs["dt"][min(kwargs["dt"])]
632  for instrument, time in list(kwargs["dt"].items()):
633  kwargs["segments"][instrument] = segments.segment(time - template_duration, time)
634  kwargs["snrs"][instrument], kwargs["phase"][instrument] = snr_phase[instrument]()
635  kwargs["chi2s_over_snr2s"][instrument] = chi2_over_snr2_gen(kwargs["snrs"][instrument]).__next__()
636  kwargs["dt"][instrument] = time - ref_end
637  yield kwargs
638 
639  def to_xml(self, name):
640  xml = super(LnSignalDensity, self).to_xml(name)
641  xml.appendChild(self.horizon_history.to_xml(u"horizon_history"))
642  xml.appendChild(ligolw_param.Param.from_pyvalue(u"population_model_file", self.population_model_file))
643  xml.appendChild(ligolw_param.Param.from_pyvalue(u"horizon_factors", json.dumps(self.horizon_factors) if self.horizon_factors is not None else None))
644  xml.appendChild(ligolw_param.Param.from_pyvalue(u"dtdphi_file", self.dtdphi_file))
645  xml.appendChild(ligolw_param.Param.from_pyvalue(u"idq_file", self.idq_file))
646  return xml
647 
648  @classmethod
649  def from_xml(cls, xml, name):
650  xml = cls.get_xml_root(xml, name)
651  self = super(LnSignalDensity, cls).from_xml(xml, name)
652  self.horizon_history = horizonhistory.HorizonHistories.from_xml(xml, u"horizon_history")
653  self.population_model_file = ligolw_param.get_pyvalue(xml, u"population_model_file")
654  self.dtdphi_file = ligolw_param.get_pyvalue(xml, u"dtdphi_file")
655  # FIXME this should be removed once there are not legacy files
656  try:
657  self.idq_file = ligolw_param.get_pyvalue(xml, u"idq_file")
658  except ValueError as e:
659  print("idq file not found", e, file=sys.stderr)
660  self.idq_file = None
661  self.horizon_factors = ligolw_param.get_pyvalue(xml, u"horizon_factors")
662  if self.horizon_factors is not None:
663  # FIXME, how do we properly decode the json, I assume something in ligolw can do this?
664  self.horizon_factors = self.horizon_factors.replace("\\","").replace('\\"','"')
665  self.horizon_factors = json.loads(self.horizon_factors)
666  self.horizon_factors = dict((int(k), v) for k, v in self.horizon_factors.items())
667  assert set(self.template_ids) == set(self.horizon_factors)
670  self.idq_glitch_lnl = idq_interp(self.idq_file)
671  return self
672 
673 
675  """
676  Stripped-down version of LnSignalDensity for use in estimating
677  ranking statistics when no data has been collected from an
678  instrument with which to define the ranking statistic.
679 
680  Used, for example, to implement low-significance candidate culls,
681  etc.
682 
683  Assumes all available instruments are on and have the same horizon
684  distance, and assess candidates based only on SNR and \chi^2
685  distributions.
686  """
687  def __init__(self, *args, **kwargs):
688  super(DatalessLnSignalDensity, self).__init__(*args, **kwargs)
689  # so we're ready to go!
690  self.add_signal_model()
691 
692  def __call__(self, segments, snrs, chi2s_over_snr2s, phase, dt, template_id):
693  # evaluate P(t) \propto number of templates
694  lnP = math.log(len(self.template_ids))
695 
696  # Add P(instruments | horizon distances). assume all
697  # instruments have TYPICAL_HORIZON_DISTANCE horizon
698  # distance
699  horizons = dict.fromkeys(segments, TYPICAL_HORIZON_DISTANCE)
700  try:
701  lnP += math.log(self.InspiralExtrinsics.p_of_instruments_given_horizons(snrs.keys(), horizons))
702  except ValueError:
703  # raises ValueError when a needed horizon distance
704  # is zero
705  return NegInf
706 
707  # Evaluate dt, dphi, snr probability
708  try:
709  lnP += math.log(self.InspiralExtrinsics.time_phase_snr(dt, phase, snrs, horizons))
710  # FIXME need to make sure this is really a math domain error
711  except ValueError:
712  return NegInf
713 
714  # evaluate population model
715  lnP += self.population_model.lnP_template_signal(template_id, max(snrs.values()))
716 
717  # evalute the (snr, \chi^2 | snr) PDFs (same for all
718  # instruments)
719  interp = self.interps["snr_chi"]
720  return lnP + sum(interp(snrs[instrument], chi2_over_snr2) for instrument, chi2_over_snr2 in chi2s_over_snr2s.items())
721 
722  def __iadd__(self, other):
723  raise NotImplementedError
724 
725  def increment(self, *args, **kwargs):
726  raise NotImplementedError
727 
728  def copy(self):
729  raise NotImplementedError
730 
731  def to_xml(self, name):
732  # I/O not permitted: the on-disk version would be
733  # indistinguishable from a real ranking statistic and could
734  # lead to accidents
735  raise NotImplementedError
736 
737  @classmethod
738  def from_xml(cls, xml, name):
739  # I/O not permitted: the on-disk version would be
740  # indistinguishable from a real ranking statistic and could
741  # lead to accidents
742  raise NotImplementedError
743 
744 
746  """
747  Version of LnSignalDensity with horizon distance history spliced in
748  from another instance. Used to solve a chicken-or-egg problem and
749  assign ranking statistic values in an aonline anlysis. NOTE: the
750  horizon history is not copied from the donor, instances of this
751  class hold a reference to the donor's data, so as it is modified
752  those modifications are immediately reflected here.
753 
754  For safety's sake, instances cannot be written to or read from
755  files, cannot be marginalized together with other instances, nor
756  accept updates from new data.
757  """
758  @classmethod
759  def splice(cls, src, Dh_donor):
760  self = cls(src.template_ids, src.instruments, src.delta_t, population_model_file = src.population_model_file, dtdphi_file = src.dtdphi_file, min_instruments = src.min_instruments, horizon_factors = src.horizon_factors)
761  for key, lnpdf in src.densities.items():
762  self.densities[key] = lnpdf.copy()
763  # NOTE: not a copy. we hold a reference to the donor's
764  # data so that as it is updated, we get the updates.
765  self.horizon_history = Dh_donor.horizon_history
766  return self
767 
768  def __iadd__(self, other):
769  raise NotImplementedError
770 
771  def increment(self, *args, **kwargs):
772  raise NotImplementedError
773 
774  def copy(self):
775  raise NotImplementedError
776 
777  def to_xml(self, name):
778  # I/O not permitted: the on-disk version would be
779  # indistinguishable from a real ranking statistic and could
780  # lead to accidents
781  raise NotImplementedError
782 
783  @classmethod
784  def from_xml(cls, xml, name):
785  # I/O not permitted: the on-disk version would be
786  # indistinguishable from a real ranking statistic and could
787  # lead to accidents
788  raise NotImplementedError
789 
790 
791 #
792 # =============================================================================
793 #
794 # Denominator Density
795 #
796 # =============================================================================
797 #
798 
799 
801  def __init__(self, *args, **kwargs):
802  super(LnNoiseDensity, self).__init__(*args, **kwargs)
803 
804  # record of trigger counts vs time for all instruments in
805  # the network
806  self.triggerrates = trigger_rate.triggerrates((instrument, trigger_rate.ratebinlist()) for instrument in self.instruments)
807  # point this to a LnLRDensity object containing the
808  # zero-lag densities to mix zero-lag into the model.
809  self.lnzerolagdensity = None
810 
811  # initialize a CoincRates object. NOTE: this is
812  # potentially time-consuming. the current implementation
813  # includes hard-coded fast-paths for the standard
814  # gstlal-based inspiral pipeline's coincidence and network
815  # configurations, but if those change then doing this will
816  # suck. when scipy >= 0.19 becomes available on LDG
817  # clusters this issue will go away (can use qhull's
818  # algebraic geometry code for the probability
819  # calculations).
820  self.coinc_rates = snglcoinc.CoincRates(
821  instruments = self.instruments,
822  delta_t = self.delta_t,
823  min_instruments = self.min_instruments
824  )
825 
826  @property
827  def segmentlists(self):
828  return self.triggerrates.segmentlistdict()
829 
830  def __call__(self, segments, snrs, chi2s_over_snr2s, phase, dt, template_id):
831  assert frozenset(segments) == self.instruments
832  if len(snrs) < self.min_instruments:
833  return NegInf
834 
835  # FIXME: the +/-3600 s window thing is a temporary hack to
836  # work around the problem of vetoes creating short segments
837  # that have no triggers in them but that can have
838  # injections recovered in them. the +/- 3600 s window is
839  # just a guess as to what might be sufficient to work
840  # around it. you might might to make this bigger.
841  triggers_per_second_per_template = {}
842  for instrument, seg in segments.items():
843  triggers_per_second_per_template[instrument] = (self.triggerrates[instrument] & trigger_rate.ratebinlist([trigger_rate.ratebin(seg[1] - 3600., seg[1] + 3600., count = 0)])).density / len(self.template_ids)
844  # sanity check rates
845  assert all(triggers_per_second_per_template[instrument] for instrument in snrs), "impossible candidate in %s at %s when rates were %s triggers/s/template" % (", ".join(sorted(snrs)), ", ".join("%s s in %s" % (str(seg[1]), instrument) for instrument, seg in sorted(segments.items())), str(triggers_per_second_per_template))
846 
847  # P(t | noise) = (candidates per unit time @ t) / total
848  # candidates. by not normalizing by the total candidates
849  # the return value can only ever be proportional to the
850  # probability density, but we avoid the problem of the
851  # ranking statistic definition changing on-the-fly while
852  # running online, allowing candidates collected later to
853  # have their ranking statistics compared meaningfully to
854  # the values assigned to candidates collected earlier, when
855  # the total number of candidates was smaller.
856  lnP = math.log(sum(self.coinc_rates.strict_coinc_rates(**triggers_per_second_per_template).values()) * len(self.template_ids))
857 
858  # P(instruments | t, noise)
859  lnP += self.coinc_rates.lnP_instruments(**triggers_per_second_per_template)[frozenset(snrs)]
860 
861  # evaluate dt and dphi parameters
862  # NOTE: uniform and normalized so that the log should be zero, but there is no point in doing that
863  # lnP += 0
864 
865  # evaluate the rest
866  interps = self.interps
867  return lnP + sum(interps["%s_snr_chi" % instrument](snrs[instrument], chi2_over_snr2) for instrument, chi2_over_snr2 in chi2s_over_snr2s.items())
868 
869  def __iadd__(self, other):
870  super(LnNoiseDensity, self).__iadd__(other)
871  self.triggerrates += other.triggerrates
872  return self
873 
874  def copy(self):
875  new = super(LnNoiseDensity, self).copy()
876  new.triggerrates = self.triggerrates.copy()
877  # NOTE: lnzerolagdensity in the copy is reset to None by
878  # this operation. it is left as an exercise to the calling
879  # code to re-connect it to the appropriate object if
880  # desired.
881  return new
882 
883  def mkinterps(self):
884  #
885  # override to mix zero-lag densities in if requested
886  #
887 
888  if self.lnzerolagdensity is None:
889  super(LnNoiseDensity, self).mkinterps()
890  else:
891  # same as parent class, but with .lnzerolagdensity
892  # added
893  self.interps = dict((key, (pdf + self.lnzerolagdensity.densities[key]).mkinterp()) for key, pdf in self.densities.items())
894 
895  def add_noise_model(self, number_of_events = 1):
896  #
897  # populate snr,chi2 binnings with a slope to force
898  # higher-SNR events to be assesed to be more significant
899  # when in the regime beyond the edge of measured or even
900  # extrapolated background.
901  #
902 
903  # pick a canonical PDF to definine the binning (we assume
904  # they're all the same and only compute this array once to
905  # save time
906  lnpdf = list(self.densities.values())[0]
907  arr = numpy.zeros_like(lnpdf.array)
908 
909  snrindices, rcossindices = lnpdf.bins[self.snr_min:1e10, 1e-6:1e2]
910  snr, dsnr = lnpdf.bins[0].centres()[snrindices], lnpdf.bins[0].upper()[snrindices] - lnpdf.bins[0].lower()[snrindices]
911  rcoss, drcoss = lnpdf.bins[1].centres()[rcossindices], lnpdf.bins[1].upper()[rcossindices] - lnpdf.bins[1].lower()[rcossindices]
912 
913  prcoss = numpy.ones(len(rcoss))
914  # This adds a faint power law that falls off faster than GWs
915  # but not exponential (to avoid numerical errors). It has
916  # approximately the same value at SNR 8 as does exp(-8**2 / 2.)
917  psnr = snr**-15
918  psnr = numpy.outer(psnr, numpy.ones(len(rcoss)))
919  vol = numpy.outer(dsnr, drcoss)
920  # arr[snrindices, rcossindices] = psnr
921  arr[snrindices, rcossindices] = psnr * vol
922 
923  # normalize to the requested count. give 99% of the
924  # requested events to this portion of the model
925  arr *= number_of_events / arr.sum()
926 
927  for lnpdf in self.densities.values():
928  # add in the noise model
929  lnpdf.array += arr
930  # re-normalize
931  lnpdf.normalize()
932 
934  """
935  Compute and return a prediction for the total number of
936  noise candidates expected for each instrument
937  combination.
938  """
939  # assumes the trigger rate is uniformly distributed among
940  # the templates and uniform in live time, calculates
941  # coincidence rate assuming template exact-match
942  # coincidence is required, then multiplies by the template
943  # count to get total coincidence rate.
944  return dict((instruments, count * len(self.template_ids)) for instruments, count in self.coinc_rates.marginalized_strict_coinc_counts(
945  self.triggerrates.segmentlistdict(),
946  **dict((instrument, rate / len(self.template_ids)) for instrument, rate in self.triggerrates.densities.items())
947  ).items())
948 
949  def random_params(self):
950  """
951  Generator that yields an endless sequence of randomly
952  generated candidate parameters. NOTE: the parameters will
953  be within the domain of the repsective binnings but are not
954  drawn from the PDF stored in those binnings --- this is not
955  an MCMC style sampler. Each value in the sequence is a
956  three-element tuple. The first two elements of each tuple
957  provide the *args and **kwargs values for calls to this PDF
958  or the numerator PDF or the ranking statistic object. The
959  final is the natural logarithm (up to an arbitrary
960  constant) of the PDF from which the parameters have been
961  drawn evaluated at the point described by the *args and
962  **kwargs.
963 
964  See also:
965 
966  random_sim_params()
967 
968  The sequence is suitable for input to the .ln_lr_samples()
969  log likelihood ratio generator.
970  """
971  snr_slope = 0.8 / len(self.instruments)**3
972 
973  snrchi2gens = dict((instrument, iter(self.densities["%s_snr_chi" % instrument].bins.randcoord(ns = (snr_slope, 1.), domain = (slice(self.snr_min, None), slice(self.chi2_over_snr2_min, self.chi2_over_snr2_max)))).__next__) for instrument in self.instruments)
974  t_and_rate_gen = iter(self.triggerrates.random_uniform()).__next__
975  t_offsets_gen = dict((instruments, self.coinc_rates.plausible_toas(instruments).__next__) for instruments in self.coinc_rates.all_instrument_combos)
976  random_randint = random.randint
977  random_sample = random.sample
978  random_uniform = random.uniform
979  segment = segments.segment
980  twopi = 2. * math.pi
981  ln_1_2 = math.log(0.5)
982  lnP_template_id = -math.log(len(self.template_ids))
983  template_ids = tuple(self.template_ids)
984  def nCk(n, k):
985  return math.factorial(n) // math.factorial(k) // math.factorial(n - k)
986  while 1:
987  t, rates, lnP_t = t_and_rate_gen()
988 
989  instruments = tuple(instrument for instrument, rate in rates.items() if rate > 0)
990  if len(instruments) < self.min_instruments:
991  # FIXME: doing this invalidates lnP_t. I
992  # think the error is merely an overall
993  # normalization error, though, and nothing
994  # cares about the normalization
995  continue
996  # to pick instruments, we first pick an integer k
997  # between m = min_instruments and n =
998  # len(instruments) inclusively, then choose that
999  # many unique names from among the available
1000  # instruments. the probability of the outcome is
1001  #
1002  # = P(k) * P(selection | k)
1003  # = 1 / (n - m + 1) * 1 / nCk
1004  #
1005  # where nCk = number of k choices without
1006  # replacement from a collection of n things.
1007  k = random_randint(self.min_instruments, len(instruments))
1008  lnP_instruments = -math.log((len(instruments) - self.min_instruments + 1) * nCk(len(instruments), k))
1009  instruments = frozenset(random_sample(instruments, k))
1010 
1011  seq = sum((snrchi2gens[instrument]() for instrument in instruments), ())
1012  kwargs = {
1013  # FIXME: waveform duration hard-coded to
1014  # 10 s, generalize
1015  "segments": dict.fromkeys(self.instruments, segment(t - 10.0, t)),
1016  "snrs": dict((instrument, value[0]) for instrument, value in zip(instruments, seq[0::2])),
1017  "chi2s_over_snr2s": dict((instrument, value[1]) for instrument, value in zip(instruments, seq[0::2])),
1018  "phase": dict((instrument, random_uniform(0., twopi)) for instrument in instruments),
1019  # FIXME: add dt to segments? not
1020  # self-consistent if we don't, but doing so
1021  # screws up the test that was done to check
1022  # which instruments are on and off at "t"
1023  "dt": t_offsets_gen[instruments](),
1024  # FIXME random_params needs to be given a
1025  # meaningful template_id, but for now it is
1026  # not used in the likelihood-ratio
1027  # assignment so we don't care
1028  "template_id": random.choice(template_ids)
1029  }
1030  # NOTE: I think the result of this sum is, in
1031  # fact, correctly normalized, but nothing requires
1032  # it to be (only that it be correct up to an
1033  # unknown constant) and I've not checked that it is
1034  # so the documentation doesn't promise that it is.
1035  # FIXME: no, it's not normalized until the dt_dphi
1036  # bit is corrected for other than H1L1
1037  yield (), kwargs, sum(seq[1::2], lnP_t + lnP_instruments + lnP_template_id)
1038 
1039  def to_xml(self, name):
1040  xml = super(LnNoiseDensity, self).to_xml(name)
1041  xml.appendChild(self.triggerrates.to_xml(u"triggerrates"))
1042  return xml
1043 
1044  @classmethod
1045  def from_xml(cls, xml, name):
1046  xml = cls.get_xml_root(xml, name)
1047  self = super(LnNoiseDensity, cls).from_xml(xml, name)
1048  self.triggerrates = trigger_rate.triggerrates.from_xml(xml, u"triggerrates")
1049  self.triggerrates.coalesce() # just in case
1050  return self
1051 
1052 
1054  """
1055  Stripped-down version of LnNoiseDensity for use in estimating
1056  ranking statistics when no data has been collected from an
1057  instrument with which to define the ranking statistic.
1058 
1059  Used, for example, to implement low-significance candidate culls,
1060  etc.
1061 
1062  Assumes all available instruments are on and have the same horizon
1063  distance, and assess candidates based only on SNR and \chi^2
1064  distributions.
1065  """
1066 
1067  DEFAULT_FILENAME = os.path.join(gstlal_config_paths["pkgdatadir"], "inspiral_datalesslndensity.xml.gz")
1068 
1069  @ligolw_array.use_in
1070  @ligolw_param.use_in
1071  class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
1072  pass
1073 
1074  def __init__(self, *args, **kwargs):
1075  super(DatalessLnNoiseDensity, self).__init__(*args, **kwargs)
1076 
1077  # install SNR, chi^2 PDF (one for all instruments)
1078  # FIXME: make mass dependent
1079  self.densities = {
1080  "snr_chi": rate.BinnedLnPDF.from_xml(ligolw_utils.load_filename(self.DEFAULT_FILENAME, contenthandler = self.LIGOLWContentHandler), u"datalesslnnoisedensity")
1081  }
1082 
1083 
1084  def __call__(self, segments, snrs, chi2s_over_snr2s, phase, dt, template_id):
1085  # assume all instruments are on, 1 trigger per second per
1086  # template
1087  triggers_per_second_per_template = dict.fromkeys(segments, 1.)
1088 
1089  # P(t | noise) = (candidates per unit time @ t) / total
1090  # candidates. by not normalizing by the total candidates
1091  # the return value can only ever be proportional to the
1092  # probability density, but we avoid the problem of the
1093  # ranking statistic definition changing on-the-fly while
1094  # running online, allowing candidates collected later to
1095  # have their ranking statistics compared meaningfully to
1096  # the values assigned to candidates collected earlier, when
1097  # the total number of candidates was smaller.
1098  lnP = math.log(sum(self.coinc_rates.strict_coinc_rates(**triggers_per_second_per_template).values()) * len(self.template_ids))
1099 
1100  # P(instruments | t, noise)
1101  lnP += self.coinc_rates.lnP_instruments(**triggers_per_second_per_template)[frozenset(snrs)]
1102 
1103  # evalute the (snr, \chi^2 | snr) PDFs (same for all
1104  # instruments)
1105  interp = self.interps["snr_chi"]
1106  return lnP + sum(interp(snrs[instrument], chi2_over_snr2) for instrument, chi2_over_snr2 in chi2s_over_snr2s.items())
1107 
1108  def random_params(self):
1109  # won't work
1110  raise NotImplementedError
1111 
1112  def __iadd__(self, other):
1113  raise NotImplementedError
1114 
1115  def increment(self, *args, **kwargs):
1116  raise NotImplementedError
1117 
1118  def copy(self):
1119  raise NotImplementedError
1120 
1121  def to_xml(self, name):
1122  # I/O not permitted: the on-disk version would be
1123  # indistinguishable from a real ranking statistic and could
1124  # lead to accidents
1125  raise NotImplementedError
1126 
1127  @classmethod
1128  def from_xml(cls, xml, name):
1129  # I/O not permitted: the on-disk version would be
1130  # indistinguishable from a real ranking statistic and could
1131  # lead to accidents
1132  raise NotImplementedError
1133 
1134 
1136  """
1137  Version of LnNoiseDensity with trigger rate data spliced in from
1138  another instance. Used to solve a chicken-or-egg problem and
1139  assign ranking statistic values in an aonline anlysis. NOTE: the
1140  trigger rate data is not copied from the donor, instances of this
1141  class hold a reference to the donor's data, so as it is modified
1142  those modifications are immediately reflected here.
1143 
1144  For safety's sake, instances cannot be written to or read from
1145  files, cannot be marginalized together with other instances, nor
1146  accept updates from new data.
1147  """
1148  @classmethod
1149  def splice(cls, src, rates_donor):
1150  self = cls(src.template_ids, src.instruments, src.delta_t, min_instruments = src.min_instruments)
1151  for key, lnpdf in src.densities.items():
1152  self.densities[key] = lnpdf.copy()
1153  # NOTE: not a copy. we hold a reference to the donor's
1154  # data so that as it is updated, we get the updates.
1155  self.triggerrates = rates_donor.triggerrates
1156  return self
1157 
1158  def __iadd__(self, other):
1159  raise NotImplementedError
1160 
1161  def increment(self, *args, **kwargs):
1162  raise NotImplementedError
1163 
1164  def copy(self):
1165  raise NotImplementedError
1166 
1167  def to_xml(self, name):
1168  # I/O not permitted: the on-disk version would be
1169  # indistinguishable from a real ranking statistic and could
1170  # lead to accidents
1171  raise NotImplementedError
1172 
1173  @classmethod
1174  def from_xml(cls, xml, name):
1175  # I/O not permitted: the on-disk version would be
1176  # indistinguishable from a real ranking statistic and could
1177  # lead to accidents
1178  raise NotImplementedError
def imr_time
Definition: chirptime.py:126