30 from fpconst
import NaN, NegInf, PosInf
35 NegInf = float(
"-inf")
36 PosInf = float(
"+inf")
43 from scipy
import stats
44 from scipy
import spatial
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
57 from lalburst
import snglcoinc
65 from gstlal
import paths
as gstlal_config_paths
71 "p_of_instruments_given_horizons",
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`.
87 The probabilities are factored in the following way:
91 P(\\vec{\\rho}, \\vec{t}, \\vec{\phi}, \\vec{O} | \\vec{D_H}, s)
93 \underbrace{P(\\vec{\\rho}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s)}_{\mathrm{1:\,TimePhaseSNR()}}
95 \underbrace{P(\\vec{O} | \\vec{D_H}, s)}_{\mathrm{2:\,p\_of\_instruments\_given\_horizons()}}
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
106 See the following for details:
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
112 and :any:`gstlal_inspiral_plot_extrinsic_params` for some visualizations of
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.
124 .. |O2_O3_O2_LR_range| image:: ../images/O2_O3_O2_LR_range.png
127 .. |O2_O3_O3_LR_range| image:: ../images/O2_O3_O3_LR_range.png
130 .. |O2_O3_O2_cnt_vs_LR| image:: ../images/O2_O3_O2_cnt_vs_LR.png
133 .. |O2_O3_O3_cnt_vs_LR| image:: ../images/O2_O3_O3_cnt_vs_LR.png
136 .. |O2_O3_LR_double_vs_triple| image:: ../images/O2_O3_LR_double_vs_triple.png
139 .. |O2_O3_HVtest| image:: ../images/HVtest.png
142 .. |O2_O3_LR_ROC| image:: ../images/O2_O3_LR_ROC.png
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 +-------------------+-------------------------+-------------------------+
155 Double vs triple found injections
156 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
158 In this check we ran two analyses:
160 - An HL only analysis
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.
171 |O2_O3_LR_double_vs_triple|
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
178 https://git.ligo.org/lscsoft/gstlal/blob/master/gstlal-inspiral/tests/dtdphitest.py
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.
189 ROC Curves for HL Analysis with the O2 and O3 code
190 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
194 - https://git.ligo.org/lscsoft/gstlal/raw/master/gstlal-inspiral/tests/lv_stat_test
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
210 Do no harm check of O2 results (Complete)
211 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
213 - Comparing runs before and after (done)
214 - Checking the probabilities returned by new code and old code to show consistent results (done)
216 Check of error assumptions (For O3)
217 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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)
223 Inclusion of virgo (Partially complete, rest for O3)
224 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
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)
231 +-------------------------------------------------+------------------------------------------+------------+
232 | Names | Hash | Date |
233 +=================================================+==========================================+============+
235 +-------------------------------------------------+------------------------------------------+------------+
238 Documentation of classes and functions
239 --------------------------------------
254 def P_instruments_given_signal(horizon_distances, n_samples = 500000, min_instruments = 2, min_distance = 0.):
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}
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)
271 names = tuple(horizon_distances.keys())
273 DH = numpy.array(tuple(horizon_distances.values()))
275 resps = [lalsimulation.DetectorPrefixToLALDetector(str(inst)).response
for inst
in names]
279 result = dict.fromkeys((frozenset(instruments)
for n
in range(min_instruments, len(names) + 1)
for instruments
in itertools.combinations(names, n)), 0.0)
281 raise ValueError(
"not enough instruments in horizon_distances to satisfy min_instruments")
284 if (DH != 0.).sum() < min_instruments:
299 indexes = tuple(range(len(names)))
303 numpy_array = numpy.array
304 numpy_dot = numpy.dot
305 numpy_sqrt = numpy.sqrt
306 random_uniform = random.uniform
309 xlal_am_resp = lal.ComputeDetAMResponse
312 successes = fails = 0
313 while successes < n_samples:
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.
323 fpfc2 = numpy_array(tuple(xlal_am_resp(resp, ra, dec, psi, gmst)
for resp
in resps))**2.
328 snr_times_D_over_8 = DH * numpy_sqrt(numpy_dot(fpfc2, ((1. + cosi2)**2. / 4., cosi2)))
350 V_at_snr_threshold = snr_times_D_over_8**3.
355 order = sorted(indexes, key = V_at_snr_threshold.__getitem__, reverse =
True)
356 ordered_names = tuple(names[i]
for i
in order)
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:
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))
386 P = tuple(x / V[0]
for x
in V)
392 for key, p, pnext
in zip(instruments, P, P[1:] + (0.,)):
393 result[key] += p - pnext
396 result[key] /= n_samples
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)
433 DEFAULT_FILENAME = os.path.join(gstlal_config_paths[
"pkgdatadir"],
"inspiral_snr_pdf.xml.gz")
434 snr_joint_pdf_cache = {}
444 One entry in the SNR PDF cache. For internal use only.
446 def __init__(self, lnP_instruments, pdf, binnedarray):
449 self.binnedarray = binnedarray
453 def __init__(self, snr_cutoff, log_distance_tolerance = math.log(1.05), min_ratio = 0.1):
455 snr_cutoff sets the minimum SNR below which it is
456 impossible to obtain a candidate (the trigger SNR
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).
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")
476 if two horizon distances, D1 and D2, differ by less than
478 | ln(D1 / D2) | <= log_distance_tolerance
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
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())
490 if horizon_distance_norm == 0.:
491 return dict.fromkeys(horizon_distances, NegInf)
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())
504 def quantized_horizon_distances(self, quants):
506 return dict((instrument, 0.
if math.isinf(quant)
else 1.)
for instrument, quant
in quants)
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
523 def get_snr_joint_pdf_binnedarray(self, instruments, horizon_distances, min_instruments):
527 def get_snr_joint_pdf(self, instruments, horizon_distances, min_instruments):
531 def lnP_instruments(self, instruments, horizon_distances, min_instruments):
535 def lnP_snrs(self, snrs, horizon_distances, min_instruments):
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
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.
550 return lnpdf(*(snr
for instrument, snr
in sorted(snrs.items())))
553 def add_to_cache(self, horizon_distances, min_instruments, verbose = False):
558 if len(horizon_distances) < min_instruments:
559 raise ValueError(
"require at least %d instruments, got %s" % (min_instruments,
", ".join(sorted(horizon_distances))))
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)
568 P_instruments = P_instruments_given_signal(
570 min_instruments = min_instruments,
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)
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)
591 with ProgressBar(text =
"%s candidates" %
", ".join(sorted(instruments)))
if verbose
else None as 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)
601 def joint_pdf_of_snrs(instruments, inst_horiz_mapping, snr_cutoff, n_samples = 160000, bins = rate.ATanLogarithmicBins(3.6, 1200., 170), progressbar =
None):
603 Return a BinnedArray containing
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)
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
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).
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.
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.
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.
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
643 if progressbar
is not None:
644 progressbar.max = n_samples
647 instruments = sorted(instruments)
648 if len(instruments) < 1:
649 raise ValueError(instruments)
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)
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)
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])
669 assert type(snr_cutoff)
is float
670 snr_min = snr_cutoff - 3.0
680 if DH_times_8.min() == 0.:
681 if progressbar
is not None:
682 progressbar.update(progressbar.max)
694 random_uniform = random.uniform
697 xlal_am_resp = lal.ComputeDetAMResponse
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()
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.
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.
720 fpfc_factors = ((1. + cosi2)**2. / 4., cosi2)
721 snr_times_D = DH_times_8 * numpy.dot(fpfc2, fpfc_factors)**0.5
725 max_snr_times_D = snr_times_D.max()
736 start_index = snr_sequence[max_snr_times_D / (snr_times_D.min() / snr_min)]
737 except ZeroDivisionError:
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
751 end_index = snr_sequence[max_snr_times_D / min_D_other] + 1
752 except ZeroDivisionError:
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
793 assert numpy.isfinite(pdf.array).all()
797 rate.filter_array(pdf.array, rate.gaussian_window(*(1.875,) * len(pdf.array.shape)))
800 numpy.clip(pdf.array, 0., PosInf, pdf.array)
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.
814 assert numpy.isfinite(pdf.array).all()
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]
824 raise ValueError(
"XML tree must contain exactly one %s element named %s" % (ligolw.LIGO_LW.tagName, name))
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")
831 for elem
in xml.childNodes:
832 if elem.tagName != ligolw.LIGO_LW.tagName:
834 binnedarray = rate.BinnedArray.from_xml(elem, elem.Name.rsplit(
u":", 1)[0])
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")
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)
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))
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]))
865 def load(cls, fileobj = None, verbose = False):
867 fileobj = open(cls.DEFAULT_FILENAME)
868 return cls.from_xml(ligolw_utils.load_fileobj(fileobj, contenthandler = cls.LIGOLWContentHandler))
882 Reports ln P(chi^2/rho^2 | rho, signal)
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()
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))
896 def __getitem__(self, coords):
897 return numpy.log(super(rate.BinnedLnPDF, self).__getitem__(coords)) - self.
norm[self.bins(*coords)[0]]
899 def marginalize(self, *args, **kwargs):
900 raise NotImplementedError
902 def __iadd__(self, other):
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))
919 with numpy.errstate(divide =
"ignore"):
920 self.
norm = numpy.log(self.array.sum(axis = 1))
921 self.norm.shape = (len(self.
norm), 1)
924 def add_signal_model(lnpdf, n, prefactors_range, df, inv_snr_pow = 4., snr_min = 3.5, progressbar = None):
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)
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]
946 ncparam_per_pf = snr2
948 snrchi2 = numpy.outer(snr2 * df * (1.0 + max(pfs)), rcoss)
950 arr = numpy.zeros_like(lnpdf.array)
952 if progressbar
is not None:
953 progressbar.increment()
954 arr[snrindices, rcossindices] += gstlalstats.ncx2pdf(snrchi2, df, numpy.array([pf * ncparam_per_pf]).T)
958 arr[snrindices, rcossindices] *= numpy.outer(dsnr / snr**inv_snr_pow, drcoss)
967 def add_glitch_model(lnpdf, n, prefactors_range, df, inv_snr_pow = 4., snr_min = 3.5, progressbar = None):
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)
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]
989 snrchi2 = numpy.outer(snr2, rcoss) * df
991 arr = numpy.zeros_like(lnpdf.array)
993 if progressbar
is not None:
994 progressbar.increment()
995 arr[snrindices, rcossindices] += gstlalstats.ncx2pdf(snrchi2, df, numpy.array([pf * snr2]).T)
999 arr[snrindices, rcossindices] *= numpy.outer(dsnr / snr**inv_snr_pow, drcoss)
1002 arr *= n / arr.sum()
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))
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
1029 def chunker(seq, size, start = None, stop = None):
1031 A generator to break up a sequence into chunks of length size, plus the
1034 >>> for x in chunker([1, 2, 3, 4, 5, 6, 7], 3):
1045 return (seq[pos:pos + size]
for pos
in range(start, stop, size))
1048 def normsq_along_one(x):
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
1054 >>> normsq_along_one(numpy.array([[1., 2., 3.], [2., 4., 6.]]))
1058 return numpy.add.reduce(x * x, axis=(1,))
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.)
1066 >>> margprob(numpy.array([[1.,2.,3.,4.], [2.,3.,4.,5.]]))
1067 [0.41150885406464954, 0.068789418217400547]
1072 D = D[numpy.isfinite(D)]
1073 step = max(int(len(D) / 65536.), 1)
1076 out.append(step * scipy.integrate.romb(numpy.exp(-D**2/2.)))
1078 out.append(step * scipy.integrate.simps(numpy.exp(-D**2/2.)))
1084 The goal of this is to compute:
1088 P(\\vec{\\rho}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s)
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
1096 P(\\vec{\\rho}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s)
1098 P(\\vec{\\rho_{\mathrm{1\,Mpc}}}, \\vec{t}, \\vec{\phi} | \\vec{O}, \\vec{D_H}, s) \\times |\\vec{\\rho}|^{-4}
1101 We reduce the dimensionality by computing things relative to the first
1102 instrument in alphabetical order and use effective distance instead of SNR,
1106 P(\\vec{D_{\mathrm{eff}}} / D_{\mathrm{eff}\,0}, \\vec{t} - t_0, \\vec{\phi} - \phi_0 | \\vec{O}, s)
1110 P(\\vec\lambda|\\vec{O}, s)
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.
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:
1134 P(\\vec{\lambda} | \\vec{O}, \\vec{\lambda_{mi}})
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] }
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.,
1145 P(\\vec{\lambda} | \\vec{O}, \\vec{\lambda_{mi}})
1147 \exp{ \left[ -\\frac{1}{2} \\vec{\Delta\lambda_i}^2 \\right] }
1149 Then we assert that:
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}})
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
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] }
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.
1174 The geometric interpretation is shown in the following figure:
1176 .. image:: ../images/TimePhaseSNR01.png
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.
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}
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):
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.
1196 transtt, transtp, transpt, transpp, transdd are required. They
1197 can be produced by running gstlal_inspiral_compute_dtdphideff_cov_matrix. An
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
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}
1208 norm is required. An example is:
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}
1212 typically a user would make a new inspiral_dt_dphi_pdf.h5 file
1213 which contains all of these by running:
1215 gstlal_inspiral_create_dt_dphi_snr_ratio_pdfs_dag
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")
1276 time, phase, deff = TimePhaseSNR.tile(verbose = verbose)
1284 for combo
in self.
combos:
1286 print(
"initializing tree for: ", combo, file=sys.stderr)
1288 self.
KDTree[combo] = spatial.cKDTree(self.
tree_data[:,slcs], leafsize=64)
1294 for combo
in self.
combos:
1296 print(
"marginalizing tree for: ", combo, file=sys.stderr)
1298 num_points = self.tree_data.shape[0]
1300 marg = numpy.zeros(num_points)
1301 for cnt, points
in enumerate(chunker(self.
tree_data[:,slcs], self.
numchunks, margstart, margstop)):
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")
1310 If you have initialized one of these from scratch and want to
1311 save it to disk, do so.
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")
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))
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)
1338 def from_hdf5(cls, fname, other_fnames = [], instruments = (
"H1",
"K1",
"L1",
"V1"), **kwargs):
1340 Initialize one of these from a file instead of computing it from scratch
1342 f = h5py.File(fname,
"r")
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"])
1352 dgrp = f[
"gstlal_extparams"]
1353 tree_data = numpy.array(dgrp[
"treedata"])
1355 for combo
in cls.instrument_combos(instruments):
1356 key =
",".join(combo)
1357 margsky[combo] = numpy.array(dgrp[
"marg"][key])
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])
1374 return cls(instruments = instruments, transtt = transtt, transtp = transtp, transpt = transpt, transpp = transpp, transdd = transdd, norm = norm, tree_data = tree_data, margsky = margsky, **kwargs)
1379 return instrument combos for all the instruments internally stored in self.responses
1381 >>> TimePhaseSNR.combos
1382 (('H1', 'L1'), ('H1', 'L1', 'V1'), ('H1', 'V1'), ('L1', 'V1'))
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'))
1396 for combo
in self.
combos:
1398 return tuple(sorted(list(set(out))))
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.
1406 >>> TimePhaseSNR.slices
1407 {('H1', 'L1'): [0, 1, 2], ('H1', 'V1'): [3, 4, 5], ('L1', 'V1'): [6, 7, 8]}
1410 return dict((pair, [3*n,3*n+1,3*n+2])
for n,pair
in enumerate(self.
pairs))
1414 define slices into tree data for a given set of instrument
1415 pairs (which is possibly a subset of the full availalbe pairs)
1418 return dict((pair, s[pair])
for pair
in pairs)
1423 Given a list of instrument produce all the possible combinations of min_instruents or greater, e.g.,
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',))
1432 **NOTE**: these combos are always returned in alphabetical order
1438 for i
in range(min_instruments, len(instruments,) + 1):
1439 for choice
in itertools.combinations(instruments, i):
1443 combos.add(tuple(sorted(choice)))
1444 return tuple(sorted(list(combos)))
1448 Given a list of instruments, construct all possible pairs
1450 >>> TimePhaseSNR.instrument_pairs(("H1","K1","V1","L1"))
1451 (('H1', 'K1'), ('H1', 'L1'), ('H1', 'V1'))
1453 **NOTE**: These are always in alphabetical order
1456 instruments = tuple(sorted(instruments))
1457 for i
in instruments[1:]:
1458 out.append((instruments[0], i))
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.
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)
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
1478 if hasattr(list(time.values())[0],
"__iter__"):
1479 outlen = len(time.values()[0])
1482 out = numpy.zeros((outlen, 1 + max(sum(slices.values(),[]))), dtype=
"float32")
1484 for ifos, slc
in slices.items():
1486 dt = (time[ifo1] - time[ifo2])
1487 dphi = (phase[ifo1] - phase[ifo2])
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)
1493 out[:,slc[2]] = numpy.log(deff[ifo1] / deff[ifo2]) * self.
transdd[frozenset((ifo1, ifo2))]
1498 def tile(cls, NSIDE = 16, NANGLE = 33, verbose = False):
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
1511 healpix_idxs = numpy.arange(healpy.nside2npix(NSIDE))
1515 T = lal.LIGOTimeGPS(0)
1516 GMST = lal.GreenwichMeanSiderealTime(T)
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)
1523 print(
"tiling sky: \n", file=sys.stderr)
1525 for i
in healpix_idxs:
1527 print(
"sky %04d of %04d\r" % (i, len(healpix_idxs)), file=sys.stderr)
1528 DEC, RA = healpy.pix2ang(NSIDE, i)
1530 for COSIOTA
in numpy.linspace(-1, 1, NANGLE):
1531 hplus = 0.5 * (1.0 + COSIOTA**2)
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)
1542 print(
"\n...done", file=sys.stderr)
1543 return time, phase, deff
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.
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)
1555 combo = tuple(sorted(time))
1560 return 1. / self.
norm[frozenset(combo)] * 5.66 / (sum(s**2
for s
in snr.values())**.5)**4
1562 deff = dict((k, horizon[k] / snr[k] * 8.0)
for k
in snr)
1564 slices = dict((pair, [3*n,3*n+1,3*n+2])
for n,pair
in enumerate(self.
instrument_pairs(time)))
1567 nearestix = self.
KDTree[combo].query(point)[1]
1568 nearestpoint = self.
tree_data[nearestix, treedataslices]
1569 D = (point - nearestpoint)[0]
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
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,
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)
1608 \\rho_H \geq \\rho_m \\\\
1609 \\rho_H \geq \\rho_m \\\\
1610 \\rho_V \leq \\rho_m
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.
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.
1624 **Example: 1D histogram for** :math:`p(H1,L1 | D_H, D_L)`:
1626 This is a 1x41 array representing the following probabilities:
1628 +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1629 | :math:`p(H1,L1| D_H = 1, D_L = 0.05)` | ... | ... | :math:`p(H1,L1| D_H = 1, D_L = 19)` |
1630 +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1632 Note, linear interpolation is used over the bins
1634 **Example 2D histogram for** :math:`p(H1,L1,V1 | D_H, D_L, D_V)`:
1636 This is a 41x41 array representing the following probabilities:
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 +-----------------------------------------------------+------------+----------+-----------------------------------------------------+
1648 Note, linear interpolation is used over the bins
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):
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
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`
1669 self.
instruments = tuple(sorted(list(instruments)))
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)
1692 if histograms
is not None:
1698 self.
first_center = list(self.histograms.values())[0].centres()[0][0]
1699 self.
last_center = list(self.histograms.values())[0].centres()[0][-1]
1709 combos = TimePhaseSNR.instrument_combos(self.
instruments, min_instruments = 1)
1726 bins.append(rate.LogarithmicBins(self.
hmin, self.
hmax, self.
nbins))
1727 for combo
in combos:
1729 self.
histograms[combo] = rate.BinnedArray(rate.NDBins(bins))
1734 self.
first_center = self.histograms.values()[0].centres()[0][0]
1735 self.
last_center = self.histograms.values()[0].centres()[0][-1]
1746 _, _, deff = TimePhaseSNR.tile(NSIDE = 8, NANGLE = 17)
1750 for v
in deff.values():
1752 mindeff = min(alldeff)
1753 maxdeff = max(alldeff)
1758 for horizontuple
in list(itertools.product(*[b.centres()
for b
in bins]))[bin_start:bin_stop]:
1767 horizondict[ifo] = horizontuple[i]
1801 snrs_above_thresh = {}
1802 snrs_below_thresh = {}
1804 for cnt, ifo
in enumerate(horizondict):
1813 HIGH = max(horizontuple + (1,)) * 8. / self.
snr_thresh / mindeff
1814 for D
in numpy.linspace(LOW, HIGH, 200):
1817 snrs.setdefault(ifo,[]).extend(8 * horizondict[ifo] / (D * deff[ifo]))
1823 prob.extend([D**2] * len(deff[ifo]))
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)
1844 for combo
in combos:
1846 for cnt, ifo
in enumerate(combo):
1848 must_be_above = snrs_above_thresh[ifo].copy()
1850 must_be_above &= snrs_above_thresh[ifo]
1853 must_be_above &= snrs_below_thresh[ifo]
1855 count = sum(prob[must_be_above])
1857 self.
histograms[combo][horizontuple] += count
1859 if bin_stop
is None:
1867 Create an interpolated represenation over the grid of horizon ratios
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
1881 H = [horizon_distances[k]
for k
in sorted(horizon_distances)]
1886 Record the class data to a file so that you don't have to remake it from scratch
1888 f = h5py.File(fname,
"w")
1889 grp = f.create_group(
"gstlal_p_of_instruments")
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)
1896 grp.create_dataset(
",".join(combo), data = self.
histograms[combo].array, compression=
"gzip")
1902 Read data from a file so that you don't have to remake it from scratch
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(
",")))
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)])[:]
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)])[:]
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]
1935 return p_of_instruments_given_horizons(instruments = instruments, snr_thresh = snr_thresh, nbins = nbins, hmin = hmin, hmax = hmax, histograms = histograms, **kwargs)
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`.
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.
1959 >>> IE = InspiralExtrinsics()
1960 >>> IE.p_of_instruments_given_horizons(("H1","L1"), {"H1":200, "L1":200})
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})
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})
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)
1975 The total probability would be the product, e.g.,
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)
1980 See the following for more details:
1982 * :py:class:`TimePhaseSNR`
1983 * :py:class:`p_of_instruments_given_horizons`
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"))
1998 time_phase_snr =
None
2000 def __init__(self, instruments = (
"H1",
"K1",
"L1",
"V1"), min_instruments = 1, filename =
None):
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()):
2013 del pofI.histograms[combo]
2015 total += pofI.histograms[combo].array
2016 for combo
in pofI.histograms:
2017 pofI.histograms[combo].array /= total
2025 horizons = dict((k,v)
for k,v
in horizons.items()
if v != 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:
2031 on_ifos = tuple(sorted(horizons.keys()))
2032 return self.
p_of_ifos[on_ifos](instruments, horizons)
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)
2041 cls.time_phase_snr = TimePhaseSNR.from_hdf5(os.path.join(gstlal_config_paths[
"pkgdatadir"],
"inspiral_dtdphi_pdf.h5"), instruments=instruments)
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])
2063 dt_chebyshev_coeffs = [0]*13
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))
2073 def __dphi_calc_mu(combined_snr, delta_t):
2075 A = 76.234617*delta_t + 0.001639
2078 return (3.145953 - A* math.exp(-B*(combined_snr-C)))
2080 A = -130.877663*delta_t - 0.002814
2083 return (3.145953 + A* math.exp(-B*(combined_snr-C)))
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))
2094 def lnP_dphi_signal(delta_phi, delta_t, combined_snr):
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
2101 return math.log(A_param*stats.vonmises.pdf(delta_phi, kappa_param, loc=mu_param) + C_param/(2*math.pi))
2104 def lnP_dt_signal(dt, snr_ratio):
2108 if snr_ratio < 0.33:
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)
2119 return numpy.polynomial.chebyshev.chebval(dt/0.015013, dt_chebyshev_coeffs) - numpy.log(norm_polynomial(snr_ratio))
2121 def lnP_dt_dphi_uniform_H1L1(coincidence_window_extension):
2124 return -math.log((snglcoinc.light_travel_time(
"H1",
"L1") + coincidence_window_extension) * (2. * math.pi))
2127 def lnP_dt_dphi_uniform(coincidence_window_extension):
2131 return lnP_dt_dphi_uniform_H1L1(coincidence_window_extension)
2134 def lnP_dt_dphi_signal(snrs, phase, dt, horizons, coincidence_window_extension):
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:
2143 H1_snr_over_horizon = snrs[
"H1"] / horizons[
"H1"]
2144 L1_snr_over_horizon = snrs[
"L1"] / horizons[
"L1"]
2146 elif horizons[
"H1"] == horizons[
"L1"]:
2148 H1_snr_over_horizon = snrs[
"H1"]
2149 L1_snr_over_horizon = snrs[
"L1"]
2154 return lnP_dt_signal(abs(delta_t), 0.33) + lnP_dphi_signal(delta_phi, delta_t, combined_snr)
2156 if H1_snr_over_horizon > L1_snr_over_horizon:
2157 snr_ratio = L1_snr_over_horizon / H1_snr_over_horizon
2160 snr_ratio = H1_snr_over_horizon / L1_snr_over_horizon
2162 return lnP_dt_signal(abs(delta_t), snr_ratio) + lnP_dphi_signal(delta_phi, delta_t, combined_snr)
2169 return lnP_dt_dphi_uniform(coincidence_window_extension)
def instrument_pair_slices
def quantize_horizon_distances
dictionary snr_joint_pdf_cache
def quantized_horizon_distances
def snr_joint_pdf_keyfunc