gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
inspiral_extrinsics.py
1 # Copyright (C) 2016,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 try:
30  from fpconst import NaN, NegInf, PosInf
31 except ImportError:
32  # fpconst is not part of the standard library and might not be
33  # available
34  NaN = float("nan")
35  NegInf = float("-inf")
36  PosInf = float("+inf")
37 import itertools
38 import math
39 import numpy
40 import os
41 import random
42 import scipy
43 from scipy import stats
44 from scipy import spatial
45 import sys
46 import h5py
47 
48 from ligo.lw import ligolw
49 from ligo.lw import lsctables
50 from ligo.lw import array as ligolw_array
51 from ligo.lw import param as ligolw_param
52 from ligo.lw import utils as ligolw_utils
53 from glue.text_progress_bar import ProgressBar
54 from gstlal import stats as gstlalstats
55 import lal
56 from lal import rate
57 from lalburst import snglcoinc
58 import lalsimulation
59 
60 
61 # FIXME: caution, this information might get organized differently later.
62 # for now we just need to figure out where the gstlal-inspiral directory in
63 # share/ is. don't write anything that assumes that this module will
64 # continue to define any of these symbols
65 from gstlal import paths as gstlal_config_paths
66 
67 
68 __all__ = [
69  "InspiralExtrinsics",
70  "TimePhaseSNR",
71  "p_of_instruments_given_horizons",
72  "margprob",
73  "chunker",
74 ]
75 
76 
77 __doc__ = r"""
78 
79 The goal of this module is to implement the probability of getting a given set
80 of extrinsic parameters for a set of detectors parameterized by n-tuples of
81 trigger parameters: (snr, horizon distance, end time and phase) assuming that
82 the event is a gravitational wave signal, *s*, coming from an isotropic
83 distribution in location, orientation and the volume of space. The
84 implementation of this in the calling code can be found in
85 :py:mod:`stats.inspiral_lr`.
86 
87 The probabilities are factored in the following way:
88 
89 .. math::
90 
91  P(\\vec{\\rho}, \\vec{t}, \\vec{\phi}, \\vec{O} | \\vec{D_H}, s)
92  =
93  \underbrace{P(\\vec{\\rho}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s)}_{\mathrm{1:\,TimePhaseSNR()}}
94  \\times
95  \underbrace{P(\\vec{O} | \\vec{D_H}, s)}_{\mathrm{2:\,p\_of\_instruments\_given\_horizons()}}
96 
97 where:
98 
99 * :math:`\\vec{\\rho}` denotes the vector of SNRs with one component from each detector
100 * :math:`\\vec{t}` denotes the vector of end time with one component from each detector
101 * :math:`\\vec{\phi}` denotes the vector of measured phases with one component from each detector
102 * :math:`\\vec{O}` denotes the vector of observing IFOs with one component from each detector. Strictly speaking this is just a label that desribes what detectors the components of the other vectors correspond to
103 * :math:`\\vec{D_H}` denotes the vector of horizon distances with one component from each detector
104 * :math:`s` denotes the signal hypothesis
105 
106 See the following for details:
107 
108 * :py:class:`InspiralExtrinsics` -- helper class to implement the full probability expression
109 * :py:class:`TimePhaseSNR` -- implementation of term 1 above
110 * :py:class:`p_of_instruments_given_horizons` -- implementation of term 2 above
111 
112 and :any:`gstlal_inspiral_plot_extrinsic_params` for some visualizations of
113 these PDFs.
114 
115 
116 Sanity Checks
117 -------------
118 
119 The code here is new for O3. We compared the result to the O2 code on 100,000
120 seconds of data searching for binary neutron stars in H and L. The injection
121 set was identical. Although an improvement for an HL search was not expected,
122 in fact it appears that the reimplementation is a bit more sensitive.
123 
124 .. |O2_O3_O2_LR_range| image:: ../images/O2_O3_O2_LR_range.png
125  :width: 400px
126 
127 .. |O2_O3_O3_LR_range| image:: ../images/O2_O3_O3_LR_range.png
128  :width: 400px
129 
130 .. |O2_O3_O2_cnt_vs_LR| image:: ../images/O2_O3_O2_cnt_vs_LR.png
131  :width: 400px
132 
133 .. |O2_O3_O3_cnt_vs_LR| image:: ../images/O2_O3_O3_cnt_vs_LR.png
134  :width: 400px
135 
136 .. |O2_O3_LR_double_vs_triple| image:: ../images/O2_O3_LR_double_vs_triple.png
137  :width: 400px
138 
139 .. |O2_O3_HVtest| image:: ../images/HVtest.png
140  :width: 400px
141 
142 .. |O2_O3_LR_ROC| image:: ../images/O2_O3_LR_ROC.png
143  :width: 400px
144 
145 +-------------------+-------------------------+-------------------------+
146 | | O2 Code | O3 Code |
147 +===================+=========================+=========================+
148 | **Found/Missed** | 939 / 2270 | 951 / 2258 |
149 +-------------------+-------------------------+-------------------------+
150 | **Range** | |O2_O3_O2_LR_range| | |O2_O3_O3_LR_range| |
151 +-------------------+-------------------------+-------------------------+
152 | **Count vs LR** | |O2_O3_O2_cnt_vs_LR| | |O2_O3_O3_cnt_vs_LR| |
153 +-------------------+-------------------------+-------------------------+
154 
155 Double vs triple found injections
156 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
157 
158 In this check we ran two analyses:
159 
160 - An HL only analysis
161 - An HLV analysis
162 
163 Both were over the same time period. A common set of found injections was
164 identified and the false alarm probability (FAP) was computed for the doubles
165 and triples. *Ideally* false alarm probabilities for all doubles would be
166 higher than all triples, but this is not a requirement since noise and
167 especially glitches can cause a triple to be ranked below a double. The plot
168 below shows that at least the trend is correct. NOTE we are not currently
169 computing doubles and triples and picking the best.
170 
171 |O2_O3_LR_double_vs_triple|
172 
173 Check of PDFs
174 ^^^^^^^^^^^^^
175 
176 We tested the procedure for evaluating the probabilility using the procedure described below (orange) against a monte carlo (blue). The details are in this script
177 
178 https://git.ligo.org/lscsoft/gstlal/blob/master/gstlal-inspiral/tests/dtdphitest.py
179 
180 You can modify this source code to implement different checks. The one
181 implemented is to plot the marginal distributions of time delay and phase delay
182 between Hanford and Virgo under the condition that the measured effective
183 distance is the same. NOTE this test assumes the same covariance matrix for
184 noise as the code below in order to test the procedure, but it doesn't prove
185 that the assumption is optimal.
186 
187 |O2_O3_HVtest|
188 
189 ROC Curves for HL Analysis with the O2 and O3 code
190 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
191 
192 Using the code here
193 
194 - https://git.ligo.org/lscsoft/gstlal/raw/master/gstlal-inspiral/tests/lv_stat_test
195 
196 we generated ROC curves for discriminiting a synthetic signal and noise model
197 in H and L. Three traces are shown. First, the the SNR only terms in the
198 likelihood ratio, which was the situation in O1 Code (red). Second, the O2
199 code with the previous implementation of additional dt and dphi terms (green)
200 and finally the current implementation (blue). The improvement of the present
201 implementation is consistent with the above injection results and this further
202 demonstrates that the reimplementation has "done no harm" to the O2
203 configuration.
204 
205 |O2_O3_LR_ROC|
206 
207 Review Status
208 -------------
209 
210 Do no harm check of O2 results (Complete)
211 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
212 
213 - Comparing runs before and after (done)
214 - Checking the probabilities returned by new code and old code to show consistent results (done)
215 
216 Check of error assumptions (For O3)
217 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
218 
219 - Calculate theoretical delta T, delta phi and snr ratio values of an O2 injection set. Then compute same parameters from injections. The difference between those (in e.g., a scatter plot) should give a sense of the errors on those parameters caused by noise. (sarah is working on it)
220 - Eventually use the fisher matrix for the error estimates (chad will do it, but not for O2)
221 
222 
223 Inclusion of virgo (Partially complete, rest for O3)
224 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
225 
226 - Virgo should not make the analysis worse in an average sense. (done, see https://dcc.ligo.org/LIGO-G1801491)
227 - Understand cases where / if virgo does downrank a trigger (addressed by below)
228 - Consider having the likelihood calculation maximize over all trigger subsets (Chad and Kipp will do this for O3)
229 
230 
231 +-------------------------------------------------+------------------------------------------+------------+
232 | Names | Hash | Date |
233 +=================================================+==========================================+============+
234 | -- | -- | -- |
235 +-------------------------------------------------+------------------------------------------+------------+
236 
237 
238 Documentation of classes and functions
239 --------------------------------------
240 
241 """
242 
243 
244 #
245 # =============================================================================
246 #
247 # Instrument Combos
248 #
249 # =============================================================================
250 #
251 
252 
253 # FIXME: This code is no longer used.
254 def P_instruments_given_signal(horizon_distances, n_samples = 500000, min_instruments = 2, min_distance = 0.):
255  r"""
256  Example:
257 
258  >>> P_instruments_given_signal({"H1": 120., "L1": 120.})
259  {frozenset(['H1', 'L1']): 1.0}
260  >>> P_instruments_given_signal({"H1": 120., "L1": 120.}, min_instruments = 1)
261  {frozenset(['L1']): 0.25423904879460091, frozenset(['H1', 'L1']): 0.49116512120682387, frozenset(['H1']): 0.25459582999857527}
262  """
263  if n_samples < 1:
264  raise ValueError("n_samples=%d must be >= 1" % n_samples)
265  if min_distance < 0.:
266  raise ValueError("min_distance=%g must be >= 0" % min_distance)
267  if min_instruments < 1:
268  raise ValueError("min_instruments=%d must be >= 1" % min_instruments)
269 
270  # get instrument names
271  names = tuple(horizon_distances.keys())
272  # get the horizon distances in that same order
273  DH = numpy.array(tuple(horizon_distances.values()))
274  # get detecor responses in that same order
275  resps = [lalsimulation.DetectorPrefixToLALDetector(str(inst)).response for inst in names]
276 
277  # initialize output. dictionary mapping instrument combination to
278  # probability (initially all 0).
279  result = dict.fromkeys((frozenset(instruments) for n in range(min_instruments, len(names) + 1) for instruments in itertools.combinations(names, n)), 0.0)
280  if not result:
281  raise ValueError("not enough instruments in horizon_distances to satisfy min_instruments")
282 
283  # check for no-op
284  if (DH != 0.).sum() < min_instruments:
285  # not enough instruments are on to form a coinc with the
286  # minimum required instruments. this is not considered an
287  # error condition, return all probabilities = 0. NOTE:
288  # result is not normalizable.
289  return result
290 
291  # we select random uniformly-distributed right ascensions so
292  # there's no point in also choosing random GMSTs and any value is
293  # as good as any other
294  gmst = 0.0
295 
296  # in the loop, we'll need a sequence of integers to enumerate
297  # instruments. construct it here to avoid doing it repeatedly in
298  # the loop
299  indexes = tuple(range(len(names)))
300 
301  # avoid attribute look-ups and arithmetic in the loop
302  acos = math.acos
303  numpy_array = numpy.array
304  numpy_dot = numpy.dot
305  numpy_sqrt = numpy.sqrt
306  random_uniform = random.uniform
307  twopi = 2. * math.pi
308  pi_2 = math.pi / 2.
309  xlal_am_resp = lal.ComputeDetAMResponse
310 
311  # loop as many times as requested
312  successes = fails = 0
313  while successes < n_samples:
314  # select random sky location and source orbital plane
315  # inclination and choice of polarization
316  ra = random_uniform(0., twopi)
317  dec = pi_2 - acos(random_uniform(-1., 1.))
318  psi = random_uniform(0., twopi)
319  cosi2 = random_uniform(-1., 1.)**2.
320 
321  # compute F+^2 and Fx^2 for each antenna from the sky
322  # location and antenna responses
323  fpfc2 = numpy_array(tuple(xlal_am_resp(resp, ra, dec, psi, gmst) for resp in resps))**2.
324 
325  # 1/8 ratio of inverse SNR to distance for each instrument
326  # (1/8 because horizon distance is defined for an SNR of 8,
327  # and we've omitted that factor for performance)
328  snr_times_D_over_8 = DH * numpy_sqrt(numpy_dot(fpfc2, ((1. + cosi2)**2. / 4., cosi2)))
329 
330  # the volume visible to each instrument given the
331  # requirement that a source be above the SNR threshold is
332  #
333  # V = [constant] * (8 * snr_times_D_over_8 / snr_threshold)**3.
334  #
335  # but in the end we'll only need ratios of these volumes so
336  # we can omit the proportionality constant and we can also
337  # omit the factor of (8 / snr_threshold)**3
338  #
339  # NOTE: noise-induced SNR fluctuations have the effect of
340  # allowing sources slightly farther away than would
341  # nominally allow them to be detectable to be seen above
342  # the detection threshold with some non-zero probability,
343  # and sources close enough to be detectable to be masked by
344  # noise and missed with some non-zero probability.
345  # accounting for this effect correctly shows it to provide
346  # an additional multiplicative factor to the volume that
347  # depends only on the SNR threshold. therefore, like all
348  # the other factors common to all instruments, it too can
349  # be ignored.
350  V_at_snr_threshold = snr_times_D_over_8**3.
351 
352  # order[0] is index of instrument that can see sources the
353  # farthest, order[1] is index of instrument that can see
354  # sources the next farthest, etc.
355  order = sorted(indexes, key = V_at_snr_threshold.__getitem__, reverse = True)
356  ordered_names = tuple(names[i] for i in order)
357 
358  # instrument combination and volume of space (up to
359  # irrelevant proportionality constant) visible to that
360  # combination given the requirement that a source be above
361  # the SNR threshold in that combination. sequence of
362  # instrument combinations is left as a generator expression
363  # for lazy evaluation
364  instruments = (frozenset(ordered_names[:n]) for n in range(min_instruments, len(order) + 1))
365  V = tuple(V_at_snr_threshold[i] for i in order[min_instruments - 1:])
366  if V[0] <= min_distance:
367  # fewer than the required minimum number of
368  # instruments can see sources in this configuration
369  # far enough way in this direction to form coincs.
370  # if this happens too often we report a convergence
371  # rate failure
372  # FIXME: min_distance is a misnomer, it's compared
373  # to a volume-like thing with a mystery
374  # proportionality constant factored out, so who
375  # knows what to call it. who cares.
376  fails += 1
377  if successes + fails >= n_samples and fails / float(successes + fails) > .90:
378  raise ValueError("convergence too slow: success/fail ratio = %d/%d" % (successes, fails))
379  continue
380 
381  # for each instrument combination, probability that a
382  # source visible to at least the minimum required number of
383  # instruments is visible to that combination (here is where
384  # the proportionality constant and factor of
385  # (8/snr_threshold)**3 drop out of the calculation)
386  P = tuple(x / V[0] for x in V)
387 
388  # accumulate result. p - pnext is the probability that a
389  # source (that is visible to at least the minimum required
390  # number of instruments) is visible to that combination of
391  # instruments and not any other combination of instruments.
392  for key, p, pnext in zip(instruments, P, P[1:] + (0.,)):
393  result[key] += p - pnext
394  successes += 1
395  for key in result:
396  result[key] /= n_samples
397 
398  #
399  # make sure it's normalized. allow an all-0 result in the event
400  # that too few instruments are available to ever form coincs
401  #
402 
403  total = sum(sorted(result.values()))
404  assert abs(total - 1.) < 1e-13 or total == 0., "result insufficiently well normalized: %s, sum = %g" % (result, total)
405  if total != 0.:
406  for key in result:
407  result[key] /= total
408 
409  #
410  # done
411  #
412 
413  return result
414 
415 
416 #
417 # =============================================================================
418 #
419 # SNR PDF
420 #
421 # =============================================================================
422 #
423 
424 
425 # FIXME: This code is no longer used.
426 class SNRPDF(object):
427  #
428  # cache of pre-computed P(instruments | horizon distances, signal)
429  # probabilities and P(SNRs | instruments, horizon distances,
430  # signal) PDFs.
431  #
432 
433  DEFAULT_FILENAME = os.path.join(gstlal_config_paths["pkgdatadir"], "inspiral_snr_pdf.xml.gz")
434  snr_joint_pdf_cache = {}
435 
436  @ligolw_array.use_in
437  @ligolw_param.use_in
438  class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
439  pass
440 
441 
442  class cacheentry(object):
443  """
444  One entry in the SNR PDF cache. For internal use only.
445  """
446  def __init__(self, lnP_instruments, pdf, binnedarray):
447  self.lnP_instruments = lnP_instruments
448  self.pdf = pdf
449  self.binnedarray = binnedarray
450 
451 
452  # FIXME: is the default choice of distance quantization appropriate?
453  def __init__(self, snr_cutoff, log_distance_tolerance = math.log(1.05), min_ratio = 0.1):
454  """
455  snr_cutoff sets the minimum SNR below which it is
456  impossible to obtain a candidate (the trigger SNR
457  threshold).
458 
459  min_ratio sets the minimum sensitivity an instrument must
460  achieve to be considered to be on at all. An instrument
461  whose horizon distance is less than min_ratio * the horizon
462  distance of the most sensitive instrument is considered to
463  be off (it's horizon distance is set to 0).
464  """
465  if log_distance_tolerance <= 0.:
466  raise ValueError("require log_distance_tolerance > 0")
467  if not 0. <= min_ratio < 1.:
468  raise ValueError("require 0 <= min_ratio < 1")
469  self.snr_cutoff = snr_cutoff
470  self.log_distance_tolerance = log_distance_tolerance
471  self.min_ratio = min_ratio
472 
473 
474  def quantize_horizon_distances(self, horizon_distances):
475  """
476  if two horizon distances, D1 and D2, differ by less than
477 
478  | ln(D1 / D2) | <= log_distance_tolerance
479 
480  then they are considered to be equal for the purpose of
481  recording horizon distance history, generating joint SNR
482  PDFs, and so on. if the smaller of the two is < min_ratio
483  * the larger then the smaller is treated as though it were
484  0.
485  """
486  if any(horizon_distance < 0. for horizon_distance in horizon_distances.values()):
487  raise ValueError("%s: negative horizon distance" % repr(horizon_distances))
488  horizon_distance_norm = max(horizon_distances.values())
489  # check for no-op: all distances are 0.
490  if horizon_distance_norm == 0.:
491  return dict.fromkeys(horizon_distances, NegInf)
492  # check for no-op: map all (non-zero) values to 1
493  if math.isinf(self.log_distance_tolerance):
494  return dict((instrument, 1 if horizon_distance > 0. else NegInf) for instrument, horizon_distance in horizon_distances.items())
495  min_distance = self.min_ratio * horizon_distance_norm
496  return dict((instrument, (NegInf if horizon_distance < min_distance else int(round(math.log(horizon_distance / horizon_distance_norm) / self.log_distance_tolerance)))) for instrument, horizon_distance in horizon_distances.items())
497 
498 
499  @property
500  def quants(self):
501  return [NegInf] + range(int(math.ceil(math.log(self.min_ratio) / self.log_distance_tolerance)), 1)
502 
503 
504  def quantized_horizon_distances(self, quants):
505  if math.isinf(self.log_distance_tolerance):
506  return dict((instrument, 0. if math.isinf(quant) else 1.) for instrument, quant in quants)
507  return dict((instrument, math.exp(quant * self.log_distance_tolerance)) for instrument, quant in quants)
508 
509 
510  def snr_joint_pdf_keyfunc(self, instruments, horizon_distances, min_instruments):
511  """
512  Internal function defining the key for cache: two element
513  tuple, first element is frozen set of instruments for which
514  this is the PDF, second element is frozen set of
515  (instrument, horizon distance) pairs for all instruments in
516  the network. horizon distances are normalized to fractions
517  of the largest among them and then the fractions aquantized
518  to integer powers of a common factor
519  """
520  return frozenset(instruments), frozenset(self.quantize_horizon_distances(horizon_distances).items()), min_instruments
521 
522 
523  def get_snr_joint_pdf_binnedarray(self, instruments, horizon_distances, min_instruments):
524  return self.snr_joint_pdf_cache[self.snr_joint_pdf_keyfunc(instruments, horizon_distances, min_instruments)].binnedarray
525 
526 
527  def get_snr_joint_pdf(self, instruments, horizon_distances, min_instruments):
528  return self.snr_joint_pdf_cache[self.snr_joint_pdf_keyfunc(instruments, horizon_distances, min_instruments)].pdf
529 
530 
531  def lnP_instruments(self, instruments, horizon_distances, min_instruments):
532  return self.snr_joint_pdf_cache[self.snr_joint_pdf_keyfunc(instruments, horizon_distances, min_instruments)].lnP_instruments
533 
534 
535  def lnP_snrs(self, snrs, horizon_distances, min_instruments):
536  """
537  snrs is an instrument-->SNR mapping containing one entry
538  for each instrument that sees a signal. snrs cannot
539  contain instruments that are not listed in
540  horizon_distances.
541 
542  horizon_distances is an instrument-->horizon distance mapping
543  containing one entry for each instrument in the network.
544  For instruments that are off set horizon distance to 0.
545  """
546  # retrieve the PDF using the keys of the snrs mapping for
547  # the participating instruments
548  lnpdf = self.get_snr_joint_pdf(snrs, horizon_distances, min_instruments)
549  # PDF axes are in alphabetical order
550  return lnpdf(*(snr for instrument, snr in sorted(snrs.items())))
551 
552 
553  def add_to_cache(self, horizon_distances, min_instruments, verbose = False):
554  #
555  # input check
556  #
557 
558  if len(horizon_distances) < min_instruments:
559  raise ValueError("require at least %d instruments, got %s" % (min_instruments, ", ".join(sorted(horizon_distances))))
560 
561  #
562  # compute P(instruments | horizon distances, signal)
563  #
564 
565  if verbose:
566  print("For horizon distances %s, requiring %d instrument(s):" % (", ".join("%s = %.4g Mpc" % item for item in sorted(horizon_distances.items())), min_instruments), file=sys.stderr)
567 
568  P_instruments = P_instruments_given_signal(
569  self.quantized_horizon_distances(self.quantize_horizon_distances(horizon_distances).items()),
570  min_instruments = min_instruments,
571  n_samples = 1000000
572  )
573 
574  if verbose:
575  for key_value in sorted((",".join(sorted(key)), value) for key, value in P_instruments.items()):
576  print("\tP(%s | signal) = %g" % key_value, file=sys.stderr)
577  print("generating P(snrs | signal) ...", file=sys.stderr)
578 
579  #
580  # compute P(snrs | instruments, horizon distances, signal)
581  #
582 
583  for n in range(min_instruments, len(horizon_distances) + 1):
584  for instruments in itertools.combinations(sorted(horizon_distances), n):
585  instruments = frozenset(instruments)
586  key = self.snr_joint_pdf_keyfunc(instruments, horizon_distances, min_instruments)
587  # already in cache?
588  if key in self.snr_joint_pdf_cache:
589  continue
590  # need to build
591  with ProgressBar(text = "%s candidates" % ", ".join(sorted(instruments))) if verbose else None as progressbar:
592  binnedarray = self.joint_pdf_of_snrs(instruments, self.quantized_horizon_distances(key[1]), self.snr_cutoff, progressbar = progressbar)
593  lnbinnedarray = binnedarray.copy()
594  with numpy.errstate(divide = "ignore"):
595  lnbinnedarray.array = numpy.log(lnbinnedarray.array)
596  pdf = rate.InterpBinnedArray(lnbinnedarray, fill_value = NegInf)
597  self.snr_joint_pdf_cache[key] = self.cacheentry(math.log(P_instruments[instruments]) if P_instruments[instruments] else NegInf, pdf, binnedarray)
598 
599 
600  @staticmethod
601  def joint_pdf_of_snrs(instruments, inst_horiz_mapping, snr_cutoff, n_samples = 160000, bins = rate.ATanLogarithmicBins(3.6, 1200., 170), progressbar = None):
602  """
603  Return a BinnedArray containing
604 
605  P(snr_{inst1}, snr_{inst2}, ... | signal seen in exactly
606  {inst1, inst2, ...} in a network of instruments
607  with a given set of horizon distances)
608 
609  i.e., the joint probability density of observing a set of
610  SNRs conditional on them being the result of signal that
611  has been recovered in a given subset of the instruments in
612  a network of instruments with a given set of horizon
613  distances.
614 
615  The snr_cutoff parameter sets the minimum SNR required for
616  a trigger (it is assumed SNRs below this value are
617  impossible to observe).
618 
619  The instruments parameter specifies the instruments upon
620  whose triggers the SNR distribution is conditional --- the
621  SNR distribution is conditional on the signal being
622  recovered by exactly these instruments and no others.
623 
624  The inst_horiz_mapping parameter is a dictionary mapping
625  instrument name (e.g., "H1") to horizon distance (arbitrary
626  units). For consistency, all instruments in the network
627  must be listed in inst_horiz_mapping regardless of which
628  instruments are operating and regardless of which
629  instruments the probability density is conditional on the
630  signal being recovered in; instruments that are included in
631  the network but not operating at the time should be listed
632  with a horizon distance of 0.
633 
634  The axes of the PDF correspond to the instruments in
635  alphabetical order. The binning used for all axes is set
636  with the bins parameter.
637 
638  The n_samples parameter sets the number of iterations for
639  the internal Monte Carlo sampling loop, and progressbar can
640  be a glue.text_progress_bar.ProgressBar instance for
641  verbosity.
642  """
643  if progressbar is not None:
644  progressbar.max = n_samples
645 
646  # get instrument names in alphabetical order
647  instruments = sorted(instruments)
648  if len(instruments) < 1:
649  raise ValueError(instruments)
650  # get horizon distances and responses in that same order
651  DH_times_8 = 8. * numpy.array([inst_horiz_mapping[inst] for inst in instruments])
652  resps = tuple(lalsimulation.DetectorPrefixToLALDetector(str(inst)).response for inst in instruments)
653 
654  # get horizon distances and responses of remaining
655  # instruments (order doesn't matter as long as they're in
656  # the same order)
657  DH_times_8_other = 8. * numpy.array([dist for inst, dist in inst_horiz_mapping.items() if inst not in instruments])
658  resps_other = tuple(lalsimulation.DetectorPrefixToLALDetector(str(inst)).response for inst in inst_horiz_mapping if inst not in instruments)
659 
660  # initialize the PDF array, and pre-construct the sequence
661  # of snr,d(snr) tuples. since the last SNR bin probably
662  # has infinite size, we remove it from the sequence
663  # (meaning the PDF will be left 0 in that bin).
664  pdf = rate.BinnedArray(rate.NDBins([bins] * len(instruments)))
665  snr_sequence = rate.ATanLogarithmicBins(3.6, 1200., 500)
666  snr_snrlo_snrhi_sequence = numpy.array(zip(snr_sequence.centres(), snr_sequence.lower(), snr_sequence.upper())[:-1])
667 
668  # compute the SNR at which to begin iterations over bins
669  assert type(snr_cutoff) is float
670  snr_min = snr_cutoff - 3.0
671  assert snr_min > 0.0
672 
673  # no-op if one of the instruments that must be able to
674  # participate in a coinc is not on. the PDF that gets
675  # returned is not properly normalized (it's all 0) but
676  # that's the correct value everywhere except at SNR-->+inf
677  # where the product of SNR * no sensitivity might be said
678  # to give a non-zero contribution, who knows. anyway, for
679  # finite SNR, 0 is the correct value.
680  if DH_times_8.min() == 0.:
681  if progressbar is not None:
682  progressbar.update(progressbar.max)
683  return pdf
684 
685  # we select random uniformly-distributed right ascensions
686  # so there's no point in also choosing random GMSTs and any
687  # value is as good as any other
688  gmst = 0.0
689 
690  # run the sampler the requested # of iterations. save some
691  # symbols to avoid doing module attribute look-ups in the
692  # loop
693  acos = math.acos
694  random_uniform = random.uniform
695  twopi = 2. * math.pi
696  pi_2 = math.pi / 2.
697  xlal_am_resp = lal.ComputeDetAMResponse
698  # FIXME: scipy.stats.rice.rvs broken on reference OS.
699  # switch to it when we can rely on a new-enough scipy
700  #rice_rvs = stats.rice.rvs # broken on reference OS
701  # the .reshape is needed in the event that x is a 1x1
702  # array: numpy returns a scalar from sqrt(), but we must
703  # have something that we can iterate over
704  rice_rvs = lambda x: numpy.sqrt(stats.ncx2.rvs(2., x**2.)).reshape(x.shape)
705  for i in range(n_samples):
706  if progressbar is not None:
707  progressbar.increment()
708  # select random sky location and source orbital
709  # plane inclination and choice of polarization
710  ra = random_uniform(0., twopi)
711  dec = pi_2 - acos(random_uniform(-1., 1.))
712  psi = random_uniform(0., twopi)
713  cosi2 = random_uniform(-1., 1.)**2.
714 
715  # F+^2 and Fx^2 for each instrument
716  fpfc2 = numpy.array(tuple(xlal_am_resp(resp, ra, dec, psi, gmst) for resp in resps))**2.
717  fpfc2_other = numpy.array(tuple(xlal_am_resp(resp, ra, dec, psi, gmst) for resp in resps_other))**2.
718 
719  # ratio of distance to inverse SNR for each instrument
720  fpfc_factors = ((1. + cosi2)**2. / 4., cosi2)
721  snr_times_D = DH_times_8 * numpy.dot(fpfc2, fpfc_factors)**0.5
722 
723  # snr * D in instrument whose SNR grows fastest
724  # with decreasing D
725  max_snr_times_D = snr_times_D.max()
726 
727  # snr_times_D.min() / snr_min = the furthest a
728  # source can be and still be above snr_min in all
729  # instruments involved. max_snr_times_D / that
730  # distance = the SNR that distance corresponds to
731  # in the instrument whose SNR grows fastest with
732  # decreasing distance --- the SNR the source has in
733  # the most sensitive instrument when visible to all
734  # instruments in the combo
735  try:
736  start_index = snr_sequence[max_snr_times_D / (snr_times_D.min() / snr_min)]
737  except ZeroDivisionError:
738  # one of the instruments that must be able
739  # to see the event is blind to it
740  continue
741 
742  # min_D_other is minimum distance at which source
743  # becomes visible in an instrument that isn't
744  # involved. max_snr_times_D / min_D_other gives
745  # the SNR in the most sensitive instrument at which
746  # the source becomes visible to one of the
747  # instruments not allowed to participate
748  if len(DH_times_8_other):
749  min_D_other = (DH_times_8_other * numpy.dot(fpfc2_other, fpfc_factors)**0.5).min() / snr_cutoff
750  try:
751  end_index = snr_sequence[max_snr_times_D / min_D_other] + 1
752  except ZeroDivisionError:
753  # all instruments that must not see
754  # it are blind to it
755  end_index = None
756  else:
757  # there are no other instruments
758  end_index = None
759 
760  # if start_index >= end_index then in order for the
761  # source to be close enough to be visible in all
762  # the instruments that must see it it is already
763  # visible to one or more instruments that must not.
764  # don't need to check for this, the for loop that
765  # comes next will simply not have any iterations.
766 
767  # iterate over the nominal SNRs (= noise-free SNR
768  # in the most sensitive instrument) at which we
769  # will add weight to the PDF. from the SNR in
770  # most sensitive instrument, the distance to the
771  # source is:
772  #
773  # D = max_snr_times_D / snr
774  #
775  # and the (noise-free) SNRs in all instruments are:
776  #
777  # snr_times_D / D
778  #
779  # scipy's Rice-distributed RV code is used to
780  # add the effect of background noise, converting
781  # the noise-free SNRs into simulated observed SNRs
782  #
783  # number of sources b/w Dlo and Dhi:
784  #
785  # d count \propto D^2 |dD|
786  # count \propto Dhi^3 - Dlo**3
787  D_Dhi_Dlo_sequence = max_snr_times_D / snr_snrlo_snrhi_sequence[start_index:end_index]
788  for snr, weight in zip(rice_rvs(snr_times_D / numpy.reshape(D_Dhi_Dlo_sequence[:,0], (len(D_Dhi_Dlo_sequence), 1))), D_Dhi_Dlo_sequence[:,1]**3. - D_Dhi_Dlo_sequence[:,2]**3.):
789  pdf[tuple(snr)] += weight
790 
791  # check for divide-by-zeros that weren't caught. also
792  # finds NaNs if they're there
793  assert numpy.isfinite(pdf.array).all()
794 
795  # convolve the samples with a Gaussian density estimation
796  # kernel
797  rate.filter_array(pdf.array, rate.gaussian_window(*(1.875,) * len(pdf.array.shape)))
798  # protect against round-off in FFT convolution leading to
799  # negative values in the PDF
800  numpy.clip(pdf.array, 0., PosInf, pdf.array)
801  # zero counts in bins that are below the trigger threshold.
802  # have to convert SNRs to indexes ourselves and adjust so
803  # that we don't zero the bin in which the SNR threshold
804  # falls
805  range_all = slice(None, None)
806  range_low = slice(None, pdf.bins[0][snr_cutoff])
807  for i in range(len(instruments)):
808  slices = [range_all] * len(instruments)
809  slices[i] = range_low
810  pdf.array[slices] = 0.
811  # convert bin counts to normalized PDF
812  pdf.to_pdf()
813  # one last sanity check
814  assert numpy.isfinite(pdf.array).all()
815  # done
816  return pdf
817 
818 
819  @classmethod
820  def from_xml(cls, xml, name = u"generic"):
821  name = u"%s:%s" % (name, u"inspiral_snr_pdf")
822  xml = [elem for elem in xml.getElementsByTagName(ligolw.LIGO_LW.tagName) if elem.hasAttribute(u"Name") and elem.Name == name]
823  if len(xml) != 1:
824  raise ValueError("XML tree must contain exactly one %s element named %s" % (ligolw.LIGO_LW.tagName, name))
825  xml, = xml
826  self = cls(
827  snr_cutoff = ligolw_param.get_pyvalue(xml, u"snr_cutoff"),
828  log_distance_tolerance = ligolw_param.get_pyvalue(xml, u"log_distance_tolerance"),
829  min_ratio = ligolw_param.get_pyvalue(xml, u"min_ratio")
830  )
831  for elem in xml.childNodes:
832  if elem.tagName != ligolw.LIGO_LW.tagName:
833  continue
834  binnedarray = rate.BinnedArray.from_xml(elem, elem.Name.rsplit(u":", 1)[0])
835 
836  key = (
837  frozenset(lsctables.instrumentsproperty.get(ligolw_param.get_pyvalue(elem, u"instruments:key"))),
838  frozenset((inst.strip(), float(quant) if math.isinf(float(quant)) else int(quant)) for inst, quant in (inst_quant.split(u"=") for inst_quant in ligolw_param.get_pyvalue(elem, u"quantizedhorizons:key").split(u","))),
839  ligolw_param.get_pyvalue(elem, u"min_instruments:key")
840  )
841 
842  lnbinnedarray = binnedarray.copy()
843  with numpy.errstate(divide = "ignore"):
844  lnbinnedarray.array = numpy.log(lnbinnedarray.array)
845  self.snr_joint_pdf_cache[key] = self.cacheentry(ligolw_param.get_pyvalue(elem, u"lnp_instruments"), rate.InterpBinnedArray(lnbinnedarray, fill_value = NegInf), binnedarray)
846  return self
847 
848 
849  def to_xml(self, name = u"generic"):
850  xml = ligolw.LIGO_LW()
851  xml.Name = u"%s:%s" % (name, u"inspiral_snr_pdf")
852  xml.appendChild(ligolw_param.Param.from_pyvalue(u"snr_cutoff", self.snr_cutoff))
853  xml.appendChild(ligolw_param.Param.from_pyvalue(u"log_distance_tolerance", self.log_distance_tolerance))
854  xml.appendChild(ligolw_param.Param.from_pyvalue(u"min_ratio", self.min_ratio))
855  for i, (key, entry) in enumerate(self.snr_joint_pdf_cache.items()):
856  elem = xml.appendChild(entry.binnedarray.to_xml(u"%d:pdf" % i))
857  elem.appendChild(ligolw_param.Param.from_pyvalue(u"lnp_instruments", entry.lnP_instruments))
858  elem.appendChild(ligolw_param.Param.from_pyvalue(u"instruments:key", lsctables.instrumentsproperty.set(key[0])))
859  elem.appendChild(ligolw_param.Param.from_pyvalue(u"quantizedhorizons:key", u",".join(u"%s=%.17g" % inst_quant for inst_quant in sorted(key[1]))))
860  elem.appendChild(ligolw_param.Param.from_pyvalue(u"min_instruments:key", key[2]))
861  return xml
862 
863 
864  @classmethod
865  def load(cls, fileobj = None, verbose = False):
866  if fileobj is None:
867  fileobj = open(cls.DEFAULT_FILENAME)
868  return cls.from_xml(ligolw_utils.load_fileobj(fileobj, contenthandler = cls.LIGOLWContentHandler))
869 
870 
871 #
872 # =============================================================================
873 #
874 # SNR, \chi^2 PDF
875 #
876 # =============================================================================
877 #
878 
879 
880 class NumeratorSNRCHIPDF(rate.BinnedLnPDF):
881  """
882  Reports ln P(chi^2/rho^2 | rho, signal)
883  """
884  # NOTE: by happy coincidence numpy's broadcasting rules allow the
885  # inherited .at_centres() method to be used as-is
886  def __init__(self, *args, **kwargs):
887  super(rate.BinnedLnPDF, self).__init__(*args, **kwargs)
888  self.volume = self.bins[1].upper() - self.bins[1].lower()
889  # FIXME: instead of .shape and repeat() use .broadcast_to()
890  # when we can rely on numpy >= 1.8
891  #self.volume = numpy.broadcast_to(self.volume, self.bins.shape)
892  self.volume.shape = (1, len(self.volume))
893  self.volume = numpy.repeat(self.volume, len(self.bins[0]), 0)
894  self.norm = numpy.zeros((len(self.bins[0]), 1))
895 
896  def __getitem__(self, coords):
897  return numpy.log(super(rate.BinnedLnPDF, self).__getitem__(coords)) - self.norm[self.bins(*coords)[0]]
898 
899  def marginalize(self, *args, **kwargs):
900  raise NotImplementedError
901 
902  def __iadd__(self, other):
903  # the total count is meaningless, it serves only to set the
904  # scale by which the density estimation kernel chooses its
905  # size, so we preserve the count across this operation. if
906  # the two arguments have different counts, use the
907  # geometric mean unless one of the two is 0 in which case
908  # don't screw with the total count
909  self_count, other_count = self.array.sum(), other.array.sum()
910  super(rate.BinnedLnPDF, self).__iadd__(other)
911  if self_count and other_count:
912  self.array *= numpy.exp((numpy.log(self_count) + numpy.log(other_count)) / 2.) / self.array.sum()
913  self.norm = numpy.log(numpy.exp(self.norm) + numpy.exp(other.norm))
914  return self
915 
916  def normalize(self):
917  # replace the vector with a new one so that we don't
918  # interfere with any copies that might have been made
919  with numpy.errstate(divide = "ignore"):
920  self.norm = numpy.log(self.array.sum(axis = 1))
921  self.norm.shape = (len(self.norm), 1)
922 
923  @staticmethod
924  def add_signal_model(lnpdf, n, prefactors_range, df, inv_snr_pow = 4., snr_min = 3.5, progressbar = None):
925  if df <= 0.:
926  raise ValueError("require df >= 0: %s" % repr(df))
927  pfs = numpy.linspace(prefactors_range[0], prefactors_range[1], 100)
928  if progressbar is not None:
929  progressbar.max = len(pfs)
930 
931  # FIXME: except for the low-SNR cut, the slicing is done
932  # to work around various overflow and loss-of-precision
933  # issues in the extreme parts of the domain of definition.
934  # it would be nice to identify the causes of these and
935  # either fix them or ignore them one-by-one with a comment
936  # explaining why it's OK to ignore the ones being ignored.
937  # for example, computing snrchi2 by exponentiating the sum
938  # of the logs of the terms might permit its evaluation
939  # everywhere on the domain. can ncx2pdf() be made to work
940  # everywhere?
941  snrindices, rcossindices = lnpdf.bins[snr_min:1e10, 1e-10:1e10]
942  snr, dsnr = lnpdf.bins[0].centres()[snrindices], lnpdf.bins[0].upper()[snrindices] - lnpdf.bins[0].lower()[snrindices]
943  rcoss, drcoss = lnpdf.bins[1].centres()[rcossindices], lnpdf.bins[1].upper()[rcossindices] - lnpdf.bins[1].lower()[rcossindices]
944 
945  snr2 = snr**2.
946  ncparam_per_pf = snr2
947  # takes into account the mean depending on noncentrality parameter
948  snrchi2 = numpy.outer(snr2 * df * (1.0 + max(pfs)), rcoss)
949 
950  arr = numpy.zeros_like(lnpdf.array)
951  for pf in pfs:
952  if progressbar is not None:
953  progressbar.increment()
954  arr[snrindices, rcossindices] += gstlalstats.ncx2pdf(snrchi2, df, numpy.array([pf * ncparam_per_pf]).T)
955 
956  # convert to counts by multiplying by bin volume, and also
957  # multiply by an SNR powr law
958  arr[snrindices, rcossindices] *= numpy.outer(dsnr / snr**inv_snr_pow, drcoss)
959 
960  # normalize to a total count of n
961  arr *= n / arr.sum()
962 
963  # add to lnpdf
964  lnpdf.array += arr
965 
966  @staticmethod
967  def add_glitch_model(lnpdf, n, prefactors_range, df, inv_snr_pow = 4., snr_min = 3.5, progressbar = None):
968  if df <= 0.:
969  raise ValueError("require df >= 0: %s" % repr(df))
970  pfs = numpy.linspace(prefactors_range[0], prefactors_range[1], 100)
971  if progressbar is not None:
972  progressbar.max = len(pfs)
973 
974  # FIXME: except for the low-SNR cut, the slicing is done
975  # to work around various overflow and loss-of-precision
976  # issues in the extreme parts of the domain of definition.
977  # it would be nice to identify the causes of these and
978  # either fix them or ignore them one-by-one with a comment
979  # explaining why it's OK to ignore the ones being ignored.
980  # for example, computing snrchi2 by exponentiating the sum
981  # of the logs of the terms might permit its evaluation
982  # everywhere on the domain. can ncx2pdf() be made to work
983  # everywhere?
984  snrindices, rcossindices = lnpdf.bins[snr_min:1e10, 1e-10:1e10]
985  snr, dsnr = lnpdf.bins[0].centres()[snrindices], lnpdf.bins[0].upper()[snrindices] - lnpdf.bins[0].lower()[snrindices]
986  rcoss, drcoss = lnpdf.bins[1].centres()[rcossindices], lnpdf.bins[1].upper()[rcossindices] - lnpdf.bins[1].lower()[rcossindices]
987 
988  snr2 = snr**2.
989  snrchi2 = numpy.outer(snr2, rcoss) * df
990 
991  arr = numpy.zeros_like(lnpdf.array)
992  for pf in pfs:
993  if progressbar is not None:
994  progressbar.increment()
995  arr[snrindices, rcossindices] += gstlalstats.ncx2pdf(snrchi2, df, numpy.array([pf * snr2]).T)
996 
997  # convert to counts by multiplying by bin volume, and also
998  # multiply by an SNR powr law
999  arr[snrindices, rcossindices] *= numpy.outer(dsnr / snr**inv_snr_pow, drcoss)
1000 
1001  # normalize to a total count of n
1002  arr *= n / arr.sum()
1003 
1004  # add to lnpdf
1005  lnpdf.array += arr
1006 
1007  def to_xml(self, *args, **kwargs):
1008  elem = super(rate.BinnedLnPDF, self).to_xml(*args, **kwargs)
1009  elem.appendChild(ligolw_array.Array.build("norm", self.norm))
1010  return elem
1011 
1012  @classmethod
1013  def from_xml(cls, xml, name):
1014  xml = cls.get_xml_root(xml, name)
1015  self = super(rate.BinnedLnPDF, cls).from_xml(xml, name)
1016  self.norm = ligolw_array.get_array(xml, "norm").array
1017  return self
1018 
1019 
1020 #
1021 # =============================================================================
1022 #
1023 # dt, dphi, deff ratio PDF
1024 #
1025 # =============================================================================
1026 #
1027 
1028 
1029 def chunker(seq, size, start = None, stop = None):
1030  """
1031  A generator to break up a sequence into chunks of length size, plus the
1032  remainder, e.g.,
1033 
1034  >>> for x in chunker([1, 2, 3, 4, 5, 6, 7], 3):
1035  ... print x
1036  ...
1037  [1, 2, 3]
1038  [4, 5, 6]
1039  [7]
1040  """
1041  if start is None:
1042  start = 0
1043  if stop is None:
1044  stop = len(seq)
1045  return (seq[pos:pos + size] for pos in range(start, stop, size))
1046 
1047 
1048 def normsq_along_one(x):
1049  """
1050  Compute the dot product squared along the first dimension in a fast
1051  way. Only works for real floats and numpy arrays. Not really for
1052  general use.
1053 
1054  >>> normsq_along_one(numpy.array([[1., 2., 3.], [2., 4., 6.]]))
1055  array([ 14., 56.])
1056 
1057  """
1058  return numpy.add.reduce(x * x, axis=(1,))
1059 
1060 
1061 def margprob(Dmat):
1062  """
1063  Compute the marginalized probability along the second dimension of a
1064  matrix Dmat. Assumes the probability is the form exp(-x_i^2/2.)
1065 
1066  >>> margprob(numpy.array([[1.,2.,3.,4.], [2.,3.,4.,5.]]))
1067  [0.41150885406464954, 0.068789418217400547]
1068  """
1069 
1070  out = []
1071  for D in Dmat:
1072  D = D[numpy.isfinite(D)]
1073  step = max(int(len(D) / 65536.), 1)
1074  D = D[::step]
1075  if len(D) == 65537:
1076  out.append(step * scipy.integrate.romb(numpy.exp(-D**2/2.)))
1077  else:
1078  out.append(step * scipy.integrate.simps(numpy.exp(-D**2/2.)))
1079  return out
1080 
1081 
1082 class TimePhaseSNR(object):
1083  """
1084  The goal of this is to compute:
1085 
1086  .. math::
1087 
1088  P(\\vec{\\rho}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s)
1089 
1090  Instead of evaluating the above probability we will parameterize it by
1091  pulling out an overall term that scales as the network SNR to the negative
1092  fourth power.
1093 
1094  .. math::
1095 
1096  P(\\vec{\\rho}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s)
1097  \\approx
1098  P(\\vec{\\rho_{\mathrm{1\,Mpc}}}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s) \\times |\\vec{\\rho}|^{-4}
1099 
1100 
1101  We reduce the dimensionality by computing things relative to the first
1102  instrument in alphabetical order and use effective distance instead of SNR,
1103  e.g.,
1104 
1105  .. math::
1106  P(\\vec{D_{\mathrm{eff}}} / D_{\mathrm{eff}\,0}, \\vec{t} - t_0, \\vec{\phi} - \phi_0 | \\vec{O}, s)
1107  \\times
1108  |\\vec{\\rho}|^{-4}
1109  \equiv
1110  P(\\vec\lambda|\\vec{O}, s)
1111  \\times
1112  |\\vec{\\rho}|^{-4}
1113 
1114  where now the absolute geocenter end time or coalescence phase does not
1115  matter since our new variables are relative to the first instrument in
1116  alphabetical order (denoted with 0 subscript). Since the first component of
1117  each of the new vectors is one by construction we don't track it and have
1118  reduced the dimensionality by three.
1119 
1120  We won't necessarily evalute exactly this distribution, but something
1121  that should be proportional to it. In order to evaluate this distribution. We
1122  assert that physical signals have a uniform distribution in earth based
1123  coordinates, :math:`\mathrm{RA}, \cos(\mathrm{DEC}), \cos(\iota), \psi`. We
1124  lay down a uniform densly sampled grid in these coordinates and assert that any
1125  signal should ``exactly" land on one of the grid points. We transform that
1126  regularly spaced grid into a grid of (irregularly spaced) points in
1127  :math:`\\vec{\lambda}`, which we denote as :math:`\\vec{\lambda_{\mathrm{m}i}}`
1128  for the *i*\ th model lambda vector. We consider that the **only** mechanism
1129  to push a signal away from one of these exact *i*\ th grid points is Gaussian
1130  noise. Furthermore we assume the probability distribution is of the form:
1131 
1132  .. math::
1133 
1134  P(\\vec{\lambda} | \\vec{O}, \\vec{\lambda_{mi}})
1135  =
1136  \\frac{1}{\sqrt{(2\pi)^k |\pmb{\Sigma}|}}
1137  \exp{ \left[ -\\frac{1}{2} \\vec{\Delta\lambda}^T \, \pmb{\Sigma}^{-1} \, \\vec{\Delta\lambda} \\right] }
1138 
1139  where :math:`\\vec{\Delta\lambda_i} = \\vec{\lambda} -
1140  \\vec{\lambda_{\mathrm{m}i}}` and :math:`\pmb{\Sigma}` is diagonal.
1141  For simplicity here forward we will set :math:`\pmb{\Sigma} = 1` and will drop the normalization, i.e.,
1142 
1143  .. math::
1144 
1145  P(\\vec{\lambda} | \\vec{O}, \\vec{\lambda_{mi}})
1146  \propto
1147  \exp{ \left[ -\\frac{1}{2} \\vec{\Delta\lambda_i}^2 \\right] }
1148 
1149  Then we assert that:
1150 
1151  .. math::
1152 
1153  P(\\vec\lambda|\\vec{O}, \\vec{D_H}, s) \propto \sum_i P(\\vec{\lambda} | \\vec{O}, \\vec{\lambda_{mi}}) \, p(\\vec{\lambda_{mi}})
1154 
1155  Where by construction :math:`p(\\vec{\lambda_{mi}})` doesn't depend on
1156  *i* since they were chosen uniform in prior signal probabality. Computing this
1157  probability on the fly is tough since the grid might have millions of points.
1158  Therefore we make another simplifying assumption that the noise only adds a
1159  contribution which is orthogonal to the hypersurface defined by the signal. In
1160  other words, we assume that noise cannot push a signal from one grid point
1161  towards another along the signal manifold. In this case we can simplify the
1162  marginalization step with a precomputation since
1163 
1164  .. math::
1165 
1166  \sum_i P(\\vec{\lambda} |\\vec{O}, \\vec{\lambda_{mi}}) \\approx P(\\vec{\lambda} |\\vec{O}, \\vec{\lambda_{m0}}) \\times \sum_{i > 0} \exp{ \left[ -\\frac{1}{2} \\vec{\Delta x_i}^2 \\right] }
1167 
1168 
1169  Where :math:`\\vec{\lambda_{m0}}` is the **nearest neighbor** to the
1170  measured :math:`\\vec{\lambda}`. The :math:`\\vec{\Delta x_i}^2` term is the
1171  distance squared for the *i*\ th grid point and the nearest neighbor point 0.
1172  This entire sum can be precomputed and stored.
1173 
1174  The geometric interpretation is shown in the following figure:
1175 
1176  .. image:: ../images/TimePhaseSNR01.png
1177  :width: 400px
1178 
1179  In order for this endeavor to be successful, we still need a fast way
1180  to find the nearest neighbor. We use scipy KDTree to accomplish this.
1181 
1182 
1183  """
1184  responses = {"H1": lal.CachedDetectors[lal.LHO_4K_DETECTOR].response, "L1":lal.CachedDetectors[lal.LLO_4K_DETECTOR].response, "V1":lal.CachedDetectors[lal.VIRGO_DETECTOR].response, "K1":lal.CachedDetectors[lal.KAGRA_DETECTOR].response}
1185  locations = {"H1":lal.CachedDetectors[lal.LHO_4K_DETECTOR].location, "L1":lal.CachedDetectors[lal.LLO_4K_DETECTOR].location, "V1":lal.CachedDetectors[lal.VIRGO_DETECTOR].location, "K1":lal.CachedDetectors[lal.KAGRA_DETECTOR].location}
1186  numchunks = 20
1187 
1188  def __init__(self, instruments = ("H1", "L1", "V1", "K1"), transtt = None, transtp = None, transpt = None, transpp = None, transdd = None, norm = None, tree_data = None, margsky = None, verbose = False, margstart = 0, margstop = None, SNR=None, psd_fname=None):
1189  """
1190  Initialize a new class from scratch via explicit computation
1191  of the tree data and marginalized probability distributions or by providing
1192  these. **NOTE** generally speaking a user will not initialize
1193  one of these from scratch, but instead will read the data from disk using the
1194  from_hdf() method below.
1195 
1196  transtt, transtp, transpt, transpp, transdd are required. They
1197  can be produced by running gstlal_inspiral_compute_dtdphideff_cov_matrix. An
1198  example is here
1199 
1200  gstlal_inspiral_compute_dtdphideff_cov_matrix --psd-xml share/O3/2019-05-09-H1L1V1psd_new.xml.gz --H-snr 5 --L-snr 7.0 --V-snr 2.25
1201 
1202  transtt = {frozenset(['V1', 'H1']): 1721.2939671945821, frozenset(['H1', 'L1']): 4264.931381497161, frozenset(['V1', 'L1']): 1768.5971596859304}
1203  transtp = {frozenset(['V1', 'H1']): -1.620591401760186, frozenset(['H1', 'L1']): -3.07346071253937, frozenset(['V1', 'L1']): -1.7020167980031902}
1204  transpt = {frozenset(['V1', 'H1']): 0.0, frozenset(['H1', 'L1']): 0.0, frozenset(['V1', 'L1']): 0.0}
1205  transpp = {frozenset(['V1', 'H1']): 1.2422379329336048, frozenset(['H1', 'L1']): 2.6540061786001834, frozenset(['V1', 'L1']): 1.2984050700516363}
1206  transdd = {frozenset(['V1', 'H1']): 2.0518233866439894, frozenset(['H1', 'L1']): 4.068667356033675, frozenset(['V1', 'L1']): 2.1420642628918447}
1207 
1208  norm is required. An example is:
1209 
1210  norm = {('H1', 'V1'):332.96168414700816, ('H1', 'L1', 'V1'):7.729877009864116, ('L1', 'V1'):313.34679951193306, ('L1',):0.0358423687136922, ('H1', 'L1'):409.06489455239137, ('H1',):0.0358423687136922, ('V1',):0.0358423687136922}
1211 
1212  typically a user would make a new inspiral_dt_dphi_pdf.h5 file
1213  which contains all of these by running:
1214 
1215  gstlal_inspiral_create_dt_dphi_snr_ratio_pdfs_dag
1216 
1217  """
1218 
1219  # This is such that the integral over the sky and over all
1220  # orientations is 1 for each combo. NOTE!!! the actual
1221  # probability of getting sources from these combos is not the
1222  # same. However, that is calculated as part of the
1223  # p_of_instruments_given_horizon() normalization.
1224  #
1225  # If you run this code you will see it is normalized
1226  #
1227  # import numpy
1228  # from gstlal.stats import inspiral_extrinsics
1229  #
1230  # TPDPDF = inspiral_extrinsics.InspiralExtrinsics()
1231  # time, phase, deff = inspiral_extrinsics.TimePhaseSNR.tile(NSIDE = 8, NANGLE = 17)
1232  # # This actually doesn't matter it is just needed to map from eff distance to
1233  # # snr, but the TimePhaseSNR code actually undoes this...
1234  # h = {"H1":1., "L1":1., "V1":1.}
1235  #
1236  # combos = TPDPDF.time_phase_snr.combos + (("H1",),("L1",),("V1",))
1237  #
1238  # result = dict((k, 0.) for k in combos)
1239  #
1240  # def extract_dict(DICT, keys):
1241  # return dict((k,v) for k,v in DICT.items() if k in keys)
1242  #
1243  # for i in range(len(time["H1"])):
1244  # t = dict((k, v[i]) for k, v in time.items())
1245  # p = dict((k, v[i]) for k, v in phase.items())
1246  # s = dict((k, h[k] / v[i]) for k, v in deff.items())
1247  #
1248  # for ifos in combos:
1249  # t2 = extract_dict(t, ifos)
1250  # p2 = extract_dict(p, ifos)
1251  # s2 = extract_dict(s, ifos)
1252  # h2 = extract_dict(h, ifos)
1253  # result[ifos] += TPDPDF.time_phase_snr(t2,p2,s2,h2) * (sum(x**2 for x in s2.values())**.5)**4 / len(time["H1"]) * 1. / (16. * numpy.pi**2)
1254  #
1255  # print result
1256  # >>> {('H1', 'V1'): array([ 1.00000003]), ('H1', 'L1', 'V1'): array([ 1.00000004]), ('L1', 'V1'): array([ 0.99999999]), ('L1',): 0.99999999999646638, ('H1', 'L1'): array([ 0.99999997]), ('H1',): 0.99999999999646638, ('V1',): 0.99999999999646638}
1257  self.instruments = instruments
1258 
1259  if any([x is None for x in (norm, transtt, transtp, transpt, transpp, transdd)]):
1260  raise ValueError("transtt, transtp, transpt, transpp, transdd and norm are required and cannot be None")
1261 
1262  self.norm = norm
1263  self.transtt = transtt
1264  self.transtp = transtp
1265  self.transpt = transpt
1266  self.transpp = transpp
1267  self.transdd = transdd
1268 
1269  self.tree_data = tree_data
1270  self.margsky = margsky
1271 
1272  self.snr = SNR
1273  self.psd_fname = psd_fname
1274 
1275  if self.tree_data is None:
1276  time, phase, deff = TimePhaseSNR.tile(verbose = verbose)
1277  self.tree_data = self.dtdphideffpoints(time, phase, deff, self.slices)
1278 
1279  # produce KD trees for all the combinations. NOTE we slice
1280  # into the same array for memory considerations. the KDTree
1281  # does *not* make copies of the data so be careful to not
1282  # modify it afterward
1283  self.KDTree = {}
1284  for combo in self.combos:
1285  if verbose:
1286  print("initializing tree for: ", combo, file=sys.stderr)
1287  slcs = sorted(sum(self.instrument_pair_slices(self.instrument_pairs(combo)).values(),[]))
1288  self.KDTree[combo] = spatial.cKDTree(self.tree_data[:,slcs], leafsize=64)
1289 
1290  # NOTE: This is super slow we have a premarginalized h5 file in
1291  # the tree, see the helper class InspiralExtrinsics
1292  if self.margsky is None:
1293  self.margsky = {}
1294  for combo in self.combos:
1295  if verbose:
1296  print("marginalizing tree for: ", combo, file=sys.stderr)
1297  slcs = sorted(sum(self.instrument_pair_slices(self.instrument_pairs(combo)).values(),[]))
1298  num_points = self.tree_data.shape[0]
1299 
1300  marg = numpy.zeros(num_points)
1301  for cnt, points in enumerate(chunker(self.tree_data[:,slcs], self.numchunks, margstart, margstop)):
1302  if verbose:
1303  print("%d/%d" % (cnt * self.numchunks, num_points), file=sys.stderr)
1304  Dmat = self.KDTree[combo].query(points, k=num_points, distance_upper_bound = 15.0)[0]
1305  marg[margstart + self.numchunks * cnt : margstart + self.numchunks * (cnt+1)] = margprob(Dmat)
1306  self.margsky[combo] = numpy.array(marg, dtype="float32")
1307 
1308  def to_hdf5(self, fname):
1309  """
1310  If you have initialized one of these from scratch and want to
1311  save it to disk, do so.
1312  """
1313  f = h5py.File(fname, "w")
1314  dgrp = f.create_group("gstlal_extparams")
1315  dgrp.create_dataset("treedata", data = self.tree_data, compression="gzip")
1316  mgrp = dgrp.create_group("marg")
1317  for combo in self.combos:
1318  mgrp.create_dataset(",".join(combo), data = self.margsky[combo], compression="gzip")
1319 
1320  h5_transtt = f.create_group("transtt")
1321  h5_transtp = f.create_group("transtp")
1322  h5_transpt = f.create_group("transpt")
1323  h5_transpp = f.create_group("transpp")
1324  h5_transdd = f.create_group("transdd")
1325  h5_norm = f.create_group("norm")
1326  for group, mat in zip((h5_transtt, h5_transtp, h5_transpt, h5_transpp, h5_transdd, h5_norm), (self.transtt, self.transtp, self.transpt, self.transpp, self.transdd, self.norm)):
1327  for k,v in mat.items():
1328  group.create_dataset(",".join(sorted(k)), data = float(v))
1329 
1330  f.create_dataset("psd", data=self.psd_fname)
1331  h5_snr = f.create_group("SNR")
1332  for ifo in self.snr:
1333  h5_snr.create_dataset(ifo, data=self.snr[ifo].value)
1334 
1335  f.close()
1336 
1337  @classmethod
1338  def from_hdf5(cls, fname, other_fnames = [], instruments = ("H1", "K1", "L1", "V1"), **kwargs):
1339  """
1340  Initialize one of these from a file instead of computing it from scratch
1341  """
1342  f = h5py.File(fname, "r")
1343  # These *have* to be here
1344  transtt = dict((frozenset(k.split(",")), numpy.array(f["transtt"][k])) for k in f["transtt"])
1345  transtp = dict((frozenset(k.split(",")), numpy.array(f["transtp"][k])) for k in f["transtp"])
1346  transpt = dict((frozenset(k.split(",")), numpy.array(f["transpt"][k])) for k in f["transpt"])
1347  transpp = dict((frozenset(k.split(",")), numpy.array(f["transpp"][k])) for k in f["transpp"])
1348  transdd = dict((frozenset(k.split(",")), numpy.array(f["transdd"][k])) for k in f["transdd"])
1349  norm = dict((frozenset(k.split(",")), numpy.array(f["norm"][k])) for k in f["norm"])
1350 
1351  try:
1352  dgrp = f["gstlal_extparams"]
1353  tree_data = numpy.array(dgrp["treedata"])
1354  margsky = {}
1355  for combo in cls.instrument_combos(instruments):
1356  key = ",".join(combo)
1357  margsky[combo] = numpy.array(dgrp["marg"][key])
1358  except:
1359  tree_data = None
1360  margsky = None
1361 
1362  f.close()
1363 
1364  # FIXME add sanity checking on this - also make it a += ? In
1365  # general this is kinda crappy.
1366  for fn in other_fnames:
1367  f = h5py.File(fn, "r")
1368  dgrp = f["gstlal_extparams"]
1369  for combo in cls.instrument_combos(instruments):
1370  key = ",".join(combo)
1371  margsky[combo] += numpy.array(dgrp["marg"][key])
1372  f.close()
1373 
1374  return cls(instruments = instruments, transtt = transtt, transtp = transtp, transpt = transpt, transpp = transpp, transdd = transdd, norm = norm, tree_data = tree_data, margsky = margsky, **kwargs)
1375 
1376  @property
1377  def combos(self):
1378  """
1379  return instrument combos for all the instruments internally stored in self.responses
1380 
1381  >>> TimePhaseSNR.combos
1382  (('H1', 'L1'), ('H1', 'L1', 'V1'), ('H1', 'V1'), ('L1', 'V1'))
1383  """
1384  return self.instrument_combos(self.instruments)
1385 
1386  @property
1387  def pairs(self):
1388  """
1389  Return all possible pairs of instruments for the
1390  instruments internally stored in self.responses
1391  >>> TimePhaseSNR.pairs
1392  (('H1', 'L1'), ('H1', 'V1'), ('L1', 'V1'))
1393  """
1394 
1395  out = []
1396  for combo in self.combos:
1397  out.extend(self.instrument_pairs(combo))
1398  return tuple(sorted(list(set(out))))
1399 
1400  @property
1401  def slices(self):
1402  """
1403  This provides a way to index into the internal tree data for
1404  the delta T, delta phi, and deff ratios for each instrument pair.
1405 
1406  >>> TimePhaseSNR.slices
1407  {('H1', 'L1'): [0, 1, 2], ('H1', 'V1'): [3, 4, 5], ('L1', 'V1'): [6, 7, 8]}
1408  """
1409  # we will define indexes for slicing into a subset of instrument data
1410  return dict((pair, [3*n,3*n+1,3*n+2]) for n,pair in enumerate(self.pairs))
1411 
1412  def instrument_pair_slices(self, pairs):
1413  """
1414  define slices into tree data for a given set of instrument
1415  pairs (which is possibly a subset of the full availalbe pairs)
1416  """
1417  s = self.slices
1418  return dict((pair, s[pair]) for pair in pairs)
1419 
1420  @classmethod
1421  def instrument_combos(cls, instruments, min_instruments = 2):
1422  """
1423  Given a list of instrument produce all the possible combinations of min_instruents or greater, e.g.,
1424 
1425  >>> TimePhaseSNR.instrument_combos(("H1","V1","L1"), min_instruments = 3)
1426  (('H1', 'L1', 'V1'),)
1427  >>> TimePhaseSNR.instrument_combos(("H1","V1","L1"), min_instruments = 2)
1428  (('H1', 'L1'), ('H1', 'L1', 'V1'), ('H1', 'V1'), ('L1', 'V1'))
1429  >>> TimePhaseSNR.instrument_combos(("H1","V1","L1"), min_instruments = 1)
1430  (('H1',), ('H1', 'L1'), ('H1', 'L1', 'V1'), ('H1', 'V1'), ('L1',), ('L1', 'V1'), ('V1',))
1431 
1432  **NOTE**: these combos are always returned in alphabetical order
1433 
1434  """
1435 
1436  combos = set()
1437  # FIXME this probably should be exposed, but 1 doesn't really make sense anyway
1438  for i in range(min_instruments, len(instruments,) + 1):
1439  for choice in itertools.combinations(instruments, i):
1440  # NOTE the reference IFO is always the first in
1441  # alphabetical order for any given combination,
1442  # hence the sort here
1443  combos.add(tuple(sorted(choice)))
1444  return tuple(sorted(list(combos)))
1445 
1446  def instrument_pairs(self, instruments):
1447  """
1448  Given a list of instruments, construct all possible pairs
1449 
1450  >>> TimePhaseSNR.instrument_pairs(("H1","K1","V1","L1"))
1451  (('H1', 'K1'), ('H1', 'L1'), ('H1', 'V1'))
1452 
1453  **NOTE**: These are always in alphabetical order
1454  """
1455  out = []
1456  instruments = tuple(sorted(instruments))
1457  for i in instruments[1:]:
1458  out.append((instruments[0], i))
1459  return tuple(out)
1460 
1461  def dtdphideffpoints(self, time, phase, deff, slices):
1462  """
1463  Given a dictionary of time, phase and deff, which could be
1464  lists of values, pack the delta t delta phi and eff distance
1465  ratios transformed by the covariance matrix according to
1466  the rules provided by slices.
1467 
1468  >>> TimePhaseSNR.dtdphideffpoints({"H1":0, "L1":-.001, "V1":.001}, {"H1":0, "L1":0, "V1":1}, {"H1":1, "L1":3, "V1":4}, TimePhaseSNR.slices)
1469  array([[ 1. , 0. , -5. , -1. , -2.54647899,
1470  -5. , -2. , -2.54647899, -5. ]], dtype=float32)
1471 
1472  **NOTE** You must have the same ifos in slices as in the time,
1473  phase, deff dictionaries. The result of self.slices gives slices for all the
1474  instruments stored in self.responses
1475  """
1476  # order is dt, dphi and effective distance ratio for each combination
1477  # NOTE the instruments argument here really needs to come from calling instrument_pairs()
1478  if hasattr(list(time.values())[0], "__iter__"):
1479  outlen = len(time.values()[0])
1480  else:
1481  outlen =1
1482  out = numpy.zeros((outlen, 1 + max(sum(slices.values(),[]))), dtype="float32")
1483 
1484  for ifos, slc in slices.items():
1485  ifo1, ifo2 = ifos
1486  dt = (time[ifo1] - time[ifo2])
1487  dphi = (phase[ifo1] - phase[ifo2])
1488  # FIXME precompute?
1489  dtdphivec = numpy.array([dt, dphi])
1490  coordtransmat = numpy.array([[self.transtt[frozenset((ifo1, ifo2))], self.transtp[frozenset((ifo1, ifo2))]],[self.transpt[frozenset((ifo1, ifo2))], self.transpp[frozenset((ifo1, ifo2))]]])
1491  out[:,slc[0]], out[:,slc[1]] = numpy.dot(coordtransmat, dtdphivec)
1492  # FIXME should this be the ratio - 1 or without the -1 ???
1493  out[:,slc[2]] = numpy.log(deff[ifo1] / deff[ifo2]) * self.transdd[frozenset((ifo1, ifo2))]
1494 
1495  return out
1496 
1497  @classmethod
1498  def tile(cls, NSIDE = 16, NANGLE = 33, verbose = False):
1499  """
1500  Tile the sky with equal area tiles defined by the healpix NSIDE
1501  and NANGLE parameters. Also tile polarization uniformly and inclination
1502  uniform in cosine. Convert these sky coordinates to time, phase and deff for
1503  each instrument in self.responses. Return the sky tiles in the detector
1504  coordinates as dictionaries. The default values have millions
1505  of points in the 4D grid
1506  """
1507  # FIXME should be put at top, but do we require healpy? It
1508  # isn't necessary for running at the moment since cached
1509  # versions of this will be used.
1510  import healpy
1511  healpix_idxs = numpy.arange(healpy.nside2npix(NSIDE))
1512  # We are concerned with a shell on the sky at some fiducial
1513  # time (which simply fixes Earth as a natural coordinate
1514  # system)
1515  T = lal.LIGOTimeGPS(0)
1516  GMST = lal.GreenwichMeanSiderealTime(T)
1517  D = 1.
1518  phase = dict((ifo, numpy.zeros(len(healpix_idxs) * NANGLE**2, dtype="float32")) for ifo in cls.responses)
1519  deff = dict((ifo, numpy.zeros(len(healpix_idxs) * NANGLE**2, dtype="float32")) for ifo in cls.responses)
1520  time = dict((ifo, numpy.zeros(len(healpix_idxs) * NANGLE**2, dtype="float32")) for ifo in cls.responses)
1521 
1522  if verbose:
1523  print("tiling sky: \n", file=sys.stderr)
1524  cnt = 0
1525  for i in healpix_idxs:
1526  if verbose:
1527  print("sky %04d of %04d\r" % (i, len(healpix_idxs)), file=sys.stderr)
1528  DEC, RA = healpy.pix2ang(NSIDE, i)
1529  DEC -= numpy.pi / 2
1530  for COSIOTA in numpy.linspace(-1, 1, NANGLE):
1531  hplus = 0.5 * (1.0 + COSIOTA**2)
1532  hcross = COSIOTA
1533  for PSI in numpy.linspace(0, numpy.pi * 2, NANGLE):
1534  for ifo in cls.responses:
1535  Fplus, Fcross = lal.ComputeDetAMResponse(cls.responses[ifo], RA, DEC, PSI, GMST)
1536  phase[ifo][cnt] = -numpy.arctan2(Fcross * hcross, Fplus * hplus)
1537  deff[ifo][cnt] = D / ((Fplus * hplus)**2 + (Fcross * hcross)**2)**0.5
1538  time[ifo][cnt] = lal.TimeDelayFromEarthCenter(cls.locations[ifo], RA, DEC, T)
1539  cnt += 1
1540 
1541  if verbose:
1542  print("\n...done", file=sys.stderr)
1543  return time, phase, deff
1544 
1545  def __call__(self, time, phase, snr, horizon):
1546  """
1547  Compute the probability of obtaining time, phase and SNR values
1548  for the instruments specified by the input dictionaries. We also need the
1549  horizon distance because we convert to effective distance internally.
1550 
1551  >>> TimePhaseSNR({"H1":0, "L1":0.001, "V1":0.001}, {"H1":0., "L1":1., "V1":1.}, {"H1":5., "L1":7., "V1":7.}, {"H1":1., "L1":1., "V1":1.})
1552  array([ 9.51668418e-14], dtype=float32)
1553 
1554  """
1555  combo = tuple(sorted(time))
1556  #
1557  # NOTE shortcut for single IFO
1558  #
1559  if len(snr) == 1:
1560  return 1. / self.norm[frozenset(combo)] * 5.66 / (sum(s**2 for s in snr.values())**.5)**4
1561 
1562  deff = dict((k, horizon[k] / snr[k] * 8.0) for k in snr)
1563  # FIXME can this be a function call??
1564  slices = dict((pair, [3*n,3*n+1,3*n+2]) for n,pair in enumerate(self.instrument_pairs(time)))
1565  point = self.dtdphideffpoints(time, phase, deff, slices)
1566  treedataslices = sorted(sum(self.instrument_pair_slices(self.instrument_pairs(combo)).values(),[]))
1567  nearestix = self.KDTree[combo].query(point)[1]
1568  nearestpoint = self.tree_data[nearestix, treedataslices]
1569  D = (point - nearestpoint)[0]
1570  D2 = numpy.dot(D,D)
1571  # FIXME 4. / (sum(s**2 for s in S.values())**.5)**4 is the term
1572  # that goes like rho^-4 with a somewhat arbitrary normilization
1573  # which comes form 5.66 ~ (4**2 + 4**2)**.5, so that the factor
1574  # is 1 for a double right at threshold.
1575  return numpy.exp(-D2 / 2.) * self.margsky[combo][nearestix] / self.norm[frozenset(combo)] * 5.66 / (sum(s**2 for s in snr.values())**.5)**4
1576 
1577 
1578 #
1579 # =============================================================================
1580 #
1581 # P(Ifos | Horizons)
1582 #
1583 # =============================================================================
1584 #
1585 
1586 
1588  """
1589  The goal of this class is to compute :math:`P(\\vec{O} | \\vec{D_H},
1590  s)`. In order to compute it, the SNR is calculated for an ideal signal as a
1591  function of given sky location and distance and then integrated over the
1592  extrinsic parameters to figure out the probability that a signal produces an
1593  above SNR event in each of the :math:`\\vec{O}` detectors. This
1594  probability is computed for many possible horizon distance combinations. In
1595  other words the probability of having H and L participate in a coinc when H, L,
1596  and V are operating is,
1597 
1598  .. math::
1599 
1600  P(H, L | D_H, D_L, D_V, s) = \int_\Sigma P(\\rho_{H}, \\rho_{L}, \\rho_{V} | D_H, D_L, D_V, s)
1601 
1602  where
1603 
1604  .. math::
1605 
1606  \Sigma \equiv
1607  \\begin{cases}
1608  \\rho_H \geq \\rho_m \\\\
1609  \\rho_H \geq \\rho_m \\\\
1610  \\rho_V \leq \\rho_m
1611  \end{cases}
1612 
1613  with :math:`\\rho_m` as the SNR threshold of the pipeline. We
1614  construct :math:`P(\\rho_{H},\ldots | \dots)` from random sampling of uniform
1615  location and orientation sources and according to distance squared. The
1616  location / orientation sampling is identical to the one used in
1617  :py:class:`TimePhaseSNR`. We add a random jitter to each SNR according to a
1618  chi-squared distribution with two degrees of freedom.
1619 
1620  The result of this is stored in a histogram, which means we choose quanta of horizon distances to do the calculation. Since we only care about
1621  the ratios of horizon distances in this calculation, the horizon distance for
1622  the first detector in alphabetical order are by convention 1. The ratios of horizon distances for the other detectors are logarithmically spaced between 0.05 and 20. Below are a couple of example histograms.
1623 
1624  **Example: 1D histogram for** :math:`p(H1,L1 | D_H, D_L)`:
1625 
1626  This is a 1x41 array representing the following probabilities:
1627 
1628  +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1629  | :math:`p(H1,L1| D_H = 1, D_L = 0.05)` | ... | ... | :math:`p(H1,L1| D_H = 1, D_L = 19)` |
1630  +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1631 
1632  Note, linear interpolation is used over the bins
1633 
1634  **Example 2D histogram for** :math:`p(H1,L1,V1 | D_H, D_L, D_V)`:
1635 
1636  This is a 41x41 array representing the following probabilities:
1637 
1638  +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1639  | :math:`p(H1,L1,V1| D_H = 1, D_L = 0.05, D_V= 0.05)` | ... | ... | :math:`p(H1,L1,V1| D_H = 1, D_L = 19, D_V= 0.05)` |
1640  +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1641  | :math:`p(H1,L1,V1| D_H = 1, D_L = 0.05, D_V= 0.06)` | ... | ... | :math:`p(H1,L1,V1| D_H = 1, D_L = 19, D_V= 0.06)` |
1642  +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1643  | ... | ... | ... | ... |
1644  +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1645  | :math:`p(H1,L1,V1| D_H = 1, D_L = 0.05, D_V= 19)` | ... | ... | :math:`p(H1,L1,V1| D_H = 1, D_L = 19, D_V= 19)` |
1646  +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1647 
1648  Note, linear interpolation is used over the bins
1649  """
1650  def __init__(self, instruments = ("H1", "L1", "V1"), snr_thresh = 4., nbins = 41, hmin = 0.05, hmax = 20.0, histograms = None, bin_start = 0, bin_stop = None):
1651  """
1652  for each sub-combintation of the "on" instruments, e.g.,
1653  "H1","L1" out of "H1","L1","V1", the probability of getting a trigger above the
1654  snr_thresh in each of e.g., "H1", "L1" is computed for different horizon
1655  distance ratios bracketed from hmin to hmax in nbins per dimension. Horizon
1656  distance ratios form an N-1 dimensional function where N is the number of
1657  instruments in the sub combination. Thus computing the probability of a triple
1658  coincidence detection requires a two dimensional histogram with nbins^2 number
1659  of points. The probability is interpolated over the bins with linear
1660  interpolation.
1661 
1662  NOTE! This is a very slow class to initialize from scratch in
1663  normal circumstances you would use the from_hdf5() method to load precomputed
1664  values. NOTE the :py:class`InspiralExtrinsics` provides a helper class to load
1665  precomputed data. See its documentation. In general *always
1666  use* :py:class`InspiralExtrinsics`
1667  """
1668  # The instruments that are being considered for this calculation
1669  self.instruments = tuple(sorted(list(instruments)))
1670 
1671  # The SNR threshold above which one declares a *found* trigger.
1672  self.snr_thresh = snr_thresh
1673 
1674  # The number of bins in the histogram of horizond distance ratios.
1675  self.nbins = nbins
1676 
1677  # Set the stop bin number and make sure that start/stop bin numbers are the multiple of nbins
1678  if bin_stop is not None and bin_stop % self.nbins:
1679  raise ValueError("stop bin indexd must be multiple of nbins=%d" % self.nbins)
1680  elif bin_start % self.nbins:
1681  raise ValueError("start bin index must be multiple of nbins=%d" % self.nbins)
1682 
1683  # The minimum and maximum horizon distance ratio to consider
1684  # for the binning. Anything outside this range will be
1685  # clipped.
1686  self.hmin = hmin
1687  self.hmax = hmax
1688 
1689  # If the user has provided the histograms already, we just use
1690  # them. This would be the case if the from_hdf5() method is
1691  # called
1692  if histograms is not None:
1693  self.histograms = histograms
1694  # NOTE we end up pushing any value outside of our
1695  # histogram to just be the value in the last(first)
1696  # bin, so we track those center values here in order to
1697  # decide if something should be clipped.
1698  self.first_center = list(self.histograms.values())[0].centres()[0][0]
1699  self.last_center = list(self.histograms.values())[0].centres()[0][-1]
1700  # Otherwise we need to initialize these ourselves, which can be pretty slow.
1701  else:
1702  # We reuse the function in TimePhaseSNR to get
1703  # combinations of instruments. We compute
1704  # probabilities for all instruments including singles.
1705  # Even if you are running a min_instruments = 2
1706  # analysis, the helper class InspiralExtrinsics will
1707  # renormalize this pdf for you. So you should never
1708  # call this directly
1709  combos = TimePhaseSNR.instrument_combos(self.instruments, min_instruments = 1)
1710 
1711  # Setup the bins needed to store the probabilities of
1712  # getting a combination of instruments: Since we only
1713  # care about ratios, this will always be a
1714  # len(instruments) - 1 dimensional histogram, e.g., 2D
1715  # for H,L,V. Obviously this approach won't scale to 5
1716  # detectors very well and we will need something new,
1717  # but it should hopefully be okay for 4 detectors to
1718  # get us through O3,O4,... We use only 41 bins per
1719  # dimension, so a 3D histogram still has fewer than
1720  # 100,000 points. While a pain to precompute, it is
1721  # not difficult to store or use.
1722  self.histograms = {}
1723  bins = []
1724  for i in range(len(self.instruments) - 1):
1725  # There are N-1 possible horizon distance ratio combinations
1726  bins.append(rate.LogarithmicBins(self.hmin, self.hmax, self.nbins))
1727  for combo in combos:
1728  # Each possible sub combination of ifos gets its own histogram.
1729  self.histograms[combo] = rate.BinnedArray(rate.NDBins(bins))
1730 
1731  # NOTE we end up clipping any value outside of our
1732  # histogram to just be the value in the last(first)
1733  # bin, so we track those center values here.
1734  self.first_center = self.histograms.values()[0].centres()[0][0]
1735  self.last_center = self.histograms.values()[0].centres()[0][-1]
1736 
1737  # Now we start the monte carlo simulation of a bunch of
1738  # signals distributed uniformly in the volume of space
1739 
1740  # The sky tile resolution here is lower than the
1741  # TimePhaseSNR calculation, but it seems good enough.
1742  # The only variable we care about here is deff, which a
1743  # dictionary of effective distances keyed by IFO for
1744  # the sky grid produced here assuming a physical
1745  # distance of 1 (thus deff is strictly >= 1).
1746  _, _, deff = TimePhaseSNR.tile(NSIDE = 8, NANGLE = 17)
1747 
1748  # Figure out the min and max effective distances to help with the integration over physical distance
1749  alldeff = []
1750  for v in deff.values():
1751  alldeff.extend(v)
1752  mindeff = min(alldeff)
1753  maxdeff = max(alldeff)
1754 
1755  # Iterate over the (# of instruments - 1) horizon
1756  # distance ratios for all of the instruments that could
1757  # have produced coincs
1758  for horizontuple in list(itertools.product(*[b.centres() for b in bins]))[bin_start:bin_stop]:
1759  horizondict = {}
1760  # Calculate horizon distances for each of the
1761  # instruments based on these ratios NOTE by
1762  # convention the first instrument in
1763  # alphabetical order will always have a horizon
1764  # of 1 since we are only concerned about the ratio!
1765  horizondict[self.instruments[0]] = 1.0
1766  for i, ifo in enumerate(self.instruments[1:]):
1767  horizondict[ifo] = horizontuple[i]
1768 
1769  #
1770  # Begin the count of sources, intended to
1771  # simulate real GWS, which pass a SNR threshold
1772  # to be found in a given set of detectors for a
1773  # given set of horizon distance ratios provided
1774  # by horizondict keyed by ifo
1775  #
1776  # 1) We generate a source at each point of a
1777  # coarse grid on the sky (healpix NSIDE = 8) as
1778  # well as a coarse gridding in psi and iota (17
1779  # points each)) for a total of 221952 source
1780  # locations and orientations
1781  #
1782  # 2) We interate over 200 points in distance
1783  # between a LOW value and a HIGH value taken
1784  # from the range of effective distances between
1785  # detectors in the sky grid that should ensure
1786  # that we properly sample the probability space
1787  #
1788  # 3) We calculate the SNR for each distance for
1789  # each ifo for each sky point by choosing a
1790  # random number with the calculated SNR as the
1791  # mean but drawn from a chi2 distribution, in
1792  # order to model noise. We track the above and
1793  # below threshold counts
1794  #
1795  # Note: The above samples should all be uniform
1796  # in the volume of space (and thereby a good
1797  # prior for GWs). We actually do a linear in
1798  # distance sampling but weight it by D^2 to
1799  # ensure this.
1800  snrs = {}
1801  snrs_above_thresh = {}
1802  snrs_below_thresh = {}
1803  prob = []
1804  for cnt, ifo in enumerate(horizondict):
1805  # We want to integrate over physical
1806  # distance with limits set by the min
1807  # and max effective distance
1808  # FIXME these variables, LOW and HIGH
1809  # should be moved out of the loop for
1810  # clarity. The point is that they are
1811  # the same for every instrument
1812  LOW = self.hmin * 8. / self.snr_thresh / maxdeff
1813  HIGH = max(horizontuple + (1,)) * 8. / self.snr_thresh / mindeff
1814  for D in numpy.linspace(LOW, HIGH, 200):
1815  # go from horizon distance to an expected SNR
1816  # NOTE deff[ifo] is an array of effective distances
1817  snrs.setdefault(ifo,[]).extend(8 * horizondict[ifo] / (D * deff[ifo]))
1818  # We store the probability
1819  # associated with this
1820  # distance, but we only need to
1821  # do it the first time through
1822  if cnt == 0:
1823  prob.extend([D**2] * len(deff[ifo]))
1824  # Actually choose the SNR from a chi
1825  # distribution with two degrees of
1826  # freedom. Only use the calculated SNR
1827  # as the mean.
1828  snrs[ifo] = stats.ncx2.rvs(2, numpy.array(snrs[ifo])**2)**.5
1829  snrs_above_thresh[ifo] = snrs[ifo] >= self.snr_thresh
1830  snrs_below_thresh[ifo] = snrs[ifo] < self.snr_thresh
1831  prob = numpy.array(prob)
1832 
1833  #
1834  # Now that we have figured out how many
1835  # triggers survive above the threshold and how
1836  # many are below threshold, we can go through
1837  # and work out the prbabilities that we are
1838  # after for each combination of IFOs.
1839  # Normalizing the fractional counts gives us
1840  # the P(ifos | horizons).
1841  #
1842  total = 0.
1843  # iterate over all subsets
1844  for combo in combos:
1845  # All the ifos in this combo must be above threshold.
1846  for cnt, ifo in enumerate(combo):
1847  if cnt == 0:
1848  must_be_above = snrs_above_thresh[ifo].copy()
1849  else:
1850  must_be_above &= snrs_above_thresh[ifo]
1851  # The ones above thresh must be accompanied with the compliment to this combo being below thresh
1852  for ifo in set(self.instruments) - set(combo):
1853  must_be_above &= snrs_below_thresh[ifo]
1854  # sum up the prob
1855  count = sum(prob[must_be_above])
1856  # record this probability in the histograms
1857  self.histograms[combo][horizontuple] += count
1858  total += count
1859  if bin_stop is None:
1860  # normalize the result so that the sum at this horizon ratio is one over all the combinations
1861  for I in self.histograms:
1862  self.histograms[I][horizontuple] /= total
1863  self.mkinterp()
1864 
1865  def mkinterp(self):
1866  """
1867  Create an interpolated represenation over the grid of horizon ratios
1868  """
1869  self.interps = {}
1870  for I in self.histograms:
1871  self.interps[I] = rate.InterpBinnedArray(self.histograms[I])
1872 
1873  def __call__(self, instruments, horizon_distances):
1874  """
1875  Calculate the probability of getting a trigger in instruments
1876  given the horizon distances. NOTE! this should never be called directly.
1877  Always use the helper class InspiralExtrinsics in order to deal with different
1878  possibilities for min_instruments (i.e., running an analysis with singles
1879  enabled or not)
1880  """
1881  H = [horizon_distances[k] for k in sorted(horizon_distances)]
1882  return self.interps[tuple(sorted(instruments))](*[min(max(h / H[0], self.first_center), self.last_center) for h in H[1:]])
1883 
1884  def to_hdf5(self, fname):
1885  """
1886  Record the class data to a file so that you don't have to remake it from scratch
1887  """
1888  f = h5py.File(fname, "w")
1889  grp = f.create_group("gstlal_p_of_instruments")
1890  grp.attrs["snr_thresh"] = self.snr_thresh
1891  grp.attrs["hmin"] = self.hmin
1892  grp.attrs["hmax"] = self.hmax
1893  grp.attrs["nbins"] = self.nbins
1894  grp.attrs["instruments"] = ",".join(self.instruments)
1895  for combo in self.histograms:
1896  grp.create_dataset(",".join(combo), data = self.histograms[combo].array, compression="gzip")
1897  f.close()
1898 
1899  @staticmethod
1900  def from_hdf5(fname, other_fnames=[], **kwargs):
1901  """
1902  Read data from a file so that you don't have to remake it from scratch
1903  """
1904  f = h5py.File(fname, "r")
1905  grp = f["gstlal_p_of_instruments"]
1906  snr_thresh = grp.attrs["snr_thresh"]
1907  hmin = grp.attrs["hmin"]
1908  hmax = grp.attrs["hmax"]
1909  nbins = int(grp.attrs["nbins"])
1910  instruments_attr = grp.attrs["instruments"]
1911  if isinstance(instruments_attr, bytes):
1912  instruments_attr = instruments_attr.decode("utf-8")
1913  instruments = tuple(sorted(instruments_attr.split(",")))
1914  histograms = {}
1915  bins = []
1916  combos = TimePhaseSNR.instrument_combos(instruments, min_instruments = 1)
1917  for i in range(len(instruments) - 1):
1918  bins.append(rate.LogarithmicBins(hmin, hmax, nbins))
1919  for combo in combos:
1920  histograms[combo] = rate.BinnedArray(rate.NDBins(bins))
1921  histograms[combo].array[:] = numpy.array(grp[",".join(combo)])[:]
1922  f.close()
1923 
1924  if len(other_fnames) > 0:
1925  for fn in other_fnames:
1926  f = h5py.File(fn, "r")
1927  grp = f['gstlal_p_of_instruments']
1928  for combo in combos:
1929  histograms[combo].array[:] += numpy.array(grp[",".join(combo)])[:]
1930  f.close()
1931  norm = numpy.sum([BinnedArray.array[:] for BinnedArray in histograms.values()], axis=0)
1932  for combo in combos:
1933  histograms[combo].array[:][norm!=0] /= norm[norm!=0]
1934 
1935  return p_of_instruments_given_horizons(instruments = instruments, snr_thresh = snr_thresh, nbins = nbins, hmin = hmin, hmax = hmax, histograms = histograms, **kwargs)
1936 
1937 
1938 #
1939 # =============================================================================
1940 #
1941 # Helper class to wrap dt, dphi, deff ratio PDF and P(Ifos | Horizons)
1942 #
1943 # =============================================================================
1944 #
1945 
1946 
1947 class InspiralExtrinsics(object):
1948  """
1949  Helper class to use preinitialized data for the extrinsic parameter
1950  calculation. Presently only H,L,V is supported. K could be added by making new
1951  data files with :py:class:`TimePhaseSNR` and :py:class:`p_of_instruments_given_horizons`.
1952 
1953  This class is used to compute p_of_instruments_given_horizons
1954  and the probability of getting time phase and snrs from
1955  a given instrument combination. The argument min_instruments will be
1956  used to normalize the p_of_instruments_given_horizons to set the probability of
1957  a combination with fewer than min_instruments to be 0.
1958 
1959  >>> IE = InspiralExtrinsics()
1960  >>> IE.p_of_instruments_given_horizons(("H1","L1"), {"H1":200, "L1":200})
1961  0.36681567679586446
1962  >>> IE.p_of_instruments_given_horizons(("H1","L1"), {"H1":20, "L1":200})
1963  0.0021601523270060085
1964  >>> IE.p_of_instruments_given_horizons(("H1","L1"), {"H1":200, "L1":200, "V1":200})
1965  0.14534898937680402
1966 
1967  >>> IE.p_of_instruments_given_horizons(("H1","L1"), {"H1":200, "L1":200, "V1":200}) + IE.p_of_instruments_given_horizons(("H1","V1"), {"H1":200, "L1":200, "V1":200}) + IE.p_of_instruments_given_horizons(("L1","V1"), {"H1":200, "L1":200, "V1":200}) + IE.p_of_instruments_given_horizons(("H1","L1","V1"), {"H1":200, "L1":200, "V1":200})
1968  1.0
1969 
1970  >>> IE.time_phase_snr({"H1":0.001, "L1":0.0, "V1":0.004}, {"H1":1.3, "L1":4.6, "V1":5.3}, {"H1":20, "L1":20, "V1":4}, {"H1":200, "L1":200, "V1":50})
1971  array([ 1.01240596e-06], dtype=float32)
1972  >>> IE.time_phase_snr({"H1":0.001, "L1":0.0, "V1":0.004}, {"H1":1.3, "L1":1.6, "V1":5.3}, {"H1":20, "L1":20, "V1":4}, {"H1":200, "L1":200, "V1":50})
1973  array([ 1.47201028e-15], dtype=float32)
1974 
1975  The total probability would be the product, e.g.,
1976 
1977  >>> IE.time_phase_snr({"H1":0.001, "L1":0.0, "V1":0.004}, {"H1":1.3, "L1":4.6, "V1":5.3}, {"H1":20, "L1":20, "V1":8}, {"H1":200, "L1":200, "V1":200}) * IE.p_of_instruments_given_horizons(("H1","L1","V1"), {"H1":200, "L1":200, "V1":200})
1978  array([ 2.00510986e-08], dtype=float32)
1979 
1980  See the following for more details:
1981 
1982  * :py:class:`TimePhaseSNR`
1983  * :py:class:`p_of_instruments_given_horizons`
1984  """
1985  p_of_ifos = {}
1986  p_of_ifos[("H1", "K1", "L1", "V1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "H1K1L1V1_p_of_instruments_given_H_d.h5"))
1987  p_of_ifos[("H1", "L1", "V1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "H1L1V1_p_of_instruments_given_H_d.h5"))
1988  p_of_ifos[("H1", "K1", "V1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "H1K1V1_p_of_instruments_given_H_d.h5"))
1989  p_of_ifos[("H1", "K1", "L1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "H1K1L1_p_of_instruments_given_H_d.h5"))
1990  p_of_ifos[("K1", "L1", "V1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "K1L1V1_p_of_instruments_given_H_d.h5"))
1991  p_of_ifos[("H1", "L1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "H1L1_p_of_instruments_given_H_d.h5"))
1992  p_of_ifos[("H1", "V1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "H1V1_p_of_instruments_given_H_d.h5"))
1993  p_of_ifos[("L1", "V1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "L1V1_p_of_instruments_given_H_d.h5"))
1994  p_of_ifos[("H1", "K1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "H1K1_p_of_instruments_given_H_d.h5"))
1995  p_of_ifos[("K1", "L1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "K1L1_p_of_instruments_given_H_d.h5"))
1996  p_of_ifos[("K1", "V1",)] = p_of_instruments_given_horizons.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "K1V1_p_of_instruments_given_H_d.h5"))
1997 
1998  time_phase_snr = None
1999 
2000  def __init__(self, instruments = ("H1", "K1", "L1", "V1"), min_instruments = 1, filename = None):
2001  #
2002  # NOTE every instance will repeat this min_instruments
2003  # normalization. Therefore different min_instruments are not
2004  # supported in the same process. You will get incorrect
2005  # results.
2006  #
2007  self.min_instruments = min_instruments
2008  # remove combinations less than min instruments and renormalize
2009  for pofI in self.p_of_ifos.values():
2010  total = numpy.zeros(list(pofI.histograms.values())[0].array.shape)
2011  for combo in list(pofI.histograms.keys()):
2012  if len(combo) < self.min_instruments:
2013  del pofI.histograms[combo]
2014  else:
2015  total += pofI.histograms[combo].array
2016  for combo in pofI.histograms:
2017  pofI.histograms[combo].array /= total
2018  pofI.mkinterp()
2019 
2020  # load time phase snr if not already available
2021  self.load_time_phase_snr(filename, instruments = instruments)
2022 
2023 
2024  def p_of_instruments_given_horizons(self, instruments, horizons):
2025  horizons = dict((k,v) for k,v in horizons.items() if v != 0)
2026  # if only one instrument is on the probability is 1.0
2027  if set(horizons) & set(instruments) != set(instruments):
2028  raise ValueError("A trigger exists for a detector with zero horizon distance")
2029  if len(horizons) == 1:
2030  return 1.0
2031  on_ifos = tuple(sorted(horizons.keys()))
2032  return self.p_of_ifos[on_ifos](instruments, horizons)
2033 
2034 
2035  @classmethod
2036  def load_time_phase_snr(cls, filename = None, instruments = ("H1", "K1", "L1", "V1")):
2037  if not cls.time_phase_snr:
2038  if filename is not None:
2039  cls.time_phase_snr = TimePhaseSNR.from_hdf5(filename, instruments=instruments)
2040  else:
2041  cls.time_phase_snr = TimePhaseSNR.from_hdf5(os.path.join(gstlal_config_paths["pkgdatadir"], "inspiral_dtdphi_pdf.h5"), instruments=instruments)
2042 
2043 
2044 #
2045 # =============================================================================
2046 #
2047 # NOTE OLD CODE! dt dphi PDF
2048 #
2049 # =============================================================================
2050 #
2051 
2052 
2053 dt_chebyshev_coeffs_polynomials = []
2054 dt_chebyshev_coeffs_polynomials.append(numpy.poly1d([-597.94227757949329, 2132.773853473127, -2944.126306979932, 1945.3033368083029, -603.91576991927593, 70.322754873993347]))
2055 dt_chebyshev_coeffs_polynomials.append(numpy.poly1d([-187.50681052710425, 695.84172327044325, -1021.0688423797938, 744.3266490236075, -272.12853221391498, 35.542404632554508]))
2056 dt_chebyshev_coeffs_polynomials.append(numpy.poly1d([52.128579054466599, -198.32054234352267, 301.34865541080791, -230.8522943433488, 90.780611645135437, -16.310130528927655]))
2057 dt_chebyshev_coeffs_polynomials.append(numpy.poly1d([48.216566165393878, -171.70632176976451, 238.48370471322843, -159.65005032451785, 50.122296925755677, -5.5466740894321367]))
2058 dt_chebyshev_coeffs_polynomials.append(numpy.poly1d([-34.030336093450863, 121.44714070928059, -169.91439486329773, 115.86873916702386, -38.08411813067778, 4.7396784315927816]))
2059 dt_chebyshev_coeffs_polynomials.append(numpy.poly1d([3.4576823675810178, -12.362609260376738, 17.3300203922424, -11.830868787176165, 3.900284020272442, -0.47157315012399248]))
2060 dt_chebyshev_coeffs_polynomials.append(numpy.poly1d([4.0423239651315113, -14.492611904657275, 20.847419746265583, -15.033846689362553, 5.3953159232942216, -0.78132676885883601]))
2061 norm_polynomial = numpy.poly1d([-348550.84040194791, 2288151.9147818103, -6623881.5646601757, 11116243.157047395, -11958335.1384027, 8606013.1361163966, -4193136.6690072878, 1365634.0450674745, -284615.52077054407, 34296.855844416605, -1815.7135263788341])
2062 
2063 dt_chebyshev_coeffs = [0]*13
2064 
2065 
2066 def __dphi_calc_A(combined_snr, delta_t):
2067  B = -10.840765 * numpy.abs(delta_t) + 1.072866
2068  M = 46.403738 * numpy.abs(delta_t) - 0.160205
2069  nu = 0.009032 * numpy.abs(delta_t) + 0.001150
2070  return (1.0 / (1.0 + math.exp(-B*(combined_snr - M)))**(1.0/nu))
2071 
2072 
2073 def __dphi_calc_mu(combined_snr, delta_t):
2074  if delta_t >= 0.0:
2075  A = 76.234617*delta_t + 0.001639
2076  B = 0.290863
2077  C = 4.775688
2078  return (3.145953 - A* math.exp(-B*(combined_snr-C)))
2079  elif delta_t < 0.0:
2080  A = -130.877663*delta_t - 0.002814
2081  B = 0.31023
2082  C = 3.184671
2083  return (3.145953 + A* math.exp(-B*(combined_snr-C)))
2084 
2085 
2086 def __dphi_calc_kappa(combined_snr, delta_t):
2087  K = -176.540199*numpy.abs(delta_t) + 7.4387
2088  B = -7.599585*numpy.abs(delta_t) + 0.215074
2089  M = -1331.386835*numpy.abs(delta_t) - 35.309173
2090  nu = 0.012225*numpy.abs(delta_t) + 0.000066
2091  return (K / (1.0 + math.exp(-B*(combined_snr - M)))**(1.0/nu))
2092 
2093 
2094 def lnP_dphi_signal(delta_phi, delta_t, combined_snr):
2095  # Compute von mises parameters
2096  A_param = __dphi_calc_A(combined_snr, delta_t)
2097  mu_param = __dphi_calc_mu(combined_snr, delta_t)
2098  kappa_param = __dphi_calc_kappa(combined_snr, delta_t)
2099  C_param = 1.0 - A_param
2100 
2101  return math.log(A_param*stats.vonmises.pdf(delta_phi, kappa_param, loc=mu_param) + C_param/(2*math.pi))
2102 
2103 
2104 def lnP_dt_signal(dt, snr_ratio):
2105  # FIXME Work out correct model
2106 
2107  # Fits below an snr ratio of 0.33 are not reliable
2108  if snr_ratio < 0.33:
2109  snr_ratio = 0.33
2110 
2111  dt_chebyshev_coeffs[0] = dt_chebyshev_coeffs_polynomials[0](snr_ratio)
2112  dt_chebyshev_coeffs[2] = dt_chebyshev_coeffs_polynomials[1](snr_ratio)
2113  dt_chebyshev_coeffs[4] = dt_chebyshev_coeffs_polynomials[2](snr_ratio)
2114  dt_chebyshev_coeffs[6] = dt_chebyshev_coeffs_polynomials[3](snr_ratio)
2115  dt_chebyshev_coeffs[8] = dt_chebyshev_coeffs_polynomials[4](snr_ratio)
2116  dt_chebyshev_coeffs[10] = dt_chebyshev_coeffs_polynomials[5](snr_ratio)
2117  dt_chebyshev_coeffs[12] = dt_chebyshev_coeffs_polynomials[6](snr_ratio)
2118 
2119  return numpy.polynomial.chebyshev.chebval(dt/0.015013, dt_chebyshev_coeffs) - numpy.log(norm_polynomial(snr_ratio))
2120 
2121 def lnP_dt_dphi_uniform_H1L1(coincidence_window_extension):
2122  # FIXME Dont hardcode
2123  # NOTE This assumes the standard delta t
2124  return -math.log((snglcoinc.light_travel_time("H1", "L1") + coincidence_window_extension) * (2. * math.pi))
2125 
2126 
2127 def lnP_dt_dphi_uniform(coincidence_window_extension):
2128  # NOTE Currently hardcoded for H1L1
2129  # NOTE this is future proofed so that in > 2 ifo scenarios, the
2130  # appropriate length can be chosen for the uniform dt distribution
2131  return lnP_dt_dphi_uniform_H1L1(coincidence_window_extension)
2132 
2133 
2134 def lnP_dt_dphi_signal(snrs, phase, dt, horizons, coincidence_window_extension):
2135  # Return P(dt, dphi|{rho_{IFO}}, signal)
2136  # FIXME Insert actual signal models
2137  if sorted(dt.keys()) == ("H1", "L1"):
2138  delta_t = float(dt["H1"] - dt["L1"])
2139  delta_phi = (phase["H1"] - phase["L1"]) % (2*math.pi)
2140  combined_snr = math.sqrt(snrs["H1"]**2. + snrs["L1"]**2.)
2141  if horizons["H1"] != 0 and horizons["L1"] != 0:
2142  # neither are zero, proceed as normal
2143  H1_snr_over_horizon = snrs["H1"] / horizons["H1"]
2144  L1_snr_over_horizon = snrs["L1"] / horizons["L1"]
2145 
2146  elif horizons["H1"] == horizons["L1"]:
2147  # both are zero, treat as equal
2148  H1_snr_over_horizon = snrs["H1"]
2149  L1_snr_over_horizon = snrs["L1"]
2150 
2151  else:
2152  # one of them is zero, treat snr_ratio as 0, which will get changed to 0.33 in lnP_dt_signal
2153  # FIXME is this the right thing to do?
2154  return lnP_dt_signal(abs(delta_t), 0.33) + lnP_dphi_signal(delta_phi, delta_t, combined_snr)
2155 
2156  if H1_snr_over_horizon > L1_snr_over_horizon:
2157  snr_ratio = L1_snr_over_horizon / H1_snr_over_horizon
2158 
2159  else:
2160  snr_ratio = H1_snr_over_horizon / L1_snr_over_horizon
2161 
2162  return lnP_dt_signal(abs(delta_t), snr_ratio) + lnP_dphi_signal(delta_phi, delta_t, combined_snr)
2163 
2164  else:
2165  # IFOs != {H1,L1} case, thus just return uniform
2166  # distribution so that dt/dphi terms dont affect
2167  # likelihood ratio
2168  # FIXME Work out general N detector case
2169  return lnP_dt_dphi_uniform(coincidence_window_extension)
2170 
2171