gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
p_astro_gstlal.py
1 import numpy as np
2 from ligo.lw import ligolw
3 from ligo.lw.ligolw import LIGOLWContentHandler
4 from ligo.lw import array as ligolw_array
5 from ligo.lw import param as ligolw_param
6 from ligo.lw import utils as ligolw_utils
7 from ligo.lw import lsctables
8 from ligo.segments import utils as segments_utils
9 from lal import rate
10 from gstlal.far import FAPFAR
11 import json
12 
13 def p_astro_update(category, event_bayesfac_dict, mean_values_dict):
14  """
15  Compute `p_astro` for a new event using mean values of Poisson expected
16  counts constructed from all the previous events. Invoked with every new
17  GraceDB entry.
18 
19  Parameters
20  ----------
21  category : string
22  source category
23  event_bayesfac_dict : dictionary
24  event Bayes factors
25  mean_values_dict : dictionary
26  mean values of Poisson counts
27 
28  Returns
29  -------
30  p_astro : float
31  p_astro by source category
32  """
33  if category == "counts_Terrestrial":
34  numerator = mean_values_dict["counts_Terrestrial"]
35  else:
36  numerator = \
37  event_bayesfac_dict[category] * mean_values_dict[category]
38 
39  denominator = mean_values_dict["counts_Terrestrial"] + \
40  np.sum([mean_values_dict[key] * event_bayesfac_dict[key]
41  for key in event_bayesfac_dict.keys()])
42 
43  return numerator / denominator
44 
45 
46 def evaluate_p_astro_from_bayesfac(astro_bayesfac,
47  mean_values_dict,
48  mass1,
49  mass2,
50  activation_counts=None):
51  """
52  Evaluates `p_astro` for a new event using Bayes factor, masses, and number
53  of astrophysical categories. Invoked with every new GraceDB entry.
54 
55  Parameters
56  ----------
57  astro_bayesfac : float
58  astrophysical Bayes factor
59  mean_values_dict: dictionary
60  mean values of Poisson counts
61  mass1 : float
62  event mass1
63  mass2 : float
64  event mass2
65  activation_counts: dictionary
66  array of activation counts keyed on source type and bin number
67 
68  Returns
69  -------
70  p_astro : dictionary
71  p_astro for all source categories
72  """
73 
74  a_hat_bns, a_hat_bbh, a_hat_nsbh, a_hat_mg, num_bins = \
75  make_weights_from_histograms(mass1,
76  mass2,
77  activation_counts)
78 
79  # Compute category-wise Bayes factors
80  # from astrophysical Bayes factor
81  rescaled_fb = num_bins * astro_bayesfac
82  bns_bayesfac = a_hat_bns * rescaled_fb
83  nsbh_bayesfac = a_hat_nsbh * rescaled_fb
84  bbh_bayesfac = a_hat_bbh * rescaled_fb
85  mg_bayesfac = a_hat_mg * rescaled_fb
86 
87  # Construct category-wise Bayes factor dictionary
88  event_bayesfac_dict = {"counts_BNS": bns_bayesfac,
89  "counts_NSBH": nsbh_bayesfac,
90  "counts_BBH": bbh_bayesfac,
91  "counts_MassGap": mg_bayesfac}
92 
93  # Compute the p-astro values for each source category
94  # using the mean values
95  p_astro_values = {}
96  for category in mean_values_dict:
97  p_astro_values[category.split("_")[1]] = \
98  p_astro_update(category=category,
99  event_bayesfac_dict=event_bayesfac_dict,
100  mean_values_dict=mean_values_dict)
101 
102  return p_astro_values
103 
104 
105 def make_weights_from_hardcuts(mass1, mass2):
106  """
107  Construct binary weights from component masses based on cuts in component
108  mass space that define astrophysical source categories. To be used for
109  MBTA, PyCBC and SPIIR.
110 
111  Parameters
112  ----------
113  mass1 : float
114  heavier component mass of the event
115  mass2 : float
116  lighter component mass of the event
117 
118  Returns
119  -------
120  a_bns, a_bbh, a_nshb, a_mg : floats
121  binary weights (i.e, 1 or 0)
122  """
123 
124  a_hat_bns = int(mass1 <= 3 and mass2 <= 3)
125  a_hat_bbh = int(mass1 > 5 and mass2 > 5)
126  a_hat_nsbh = int(min(mass1, mass2) <= 3 and
127  max(mass1, mass2) > 5)
128  a_hat_mg = int(3 < mass1 <= 5 or 3 < mass2 <= 5)
129  num_bins = 4
130 
131  return a_hat_bns, a_hat_bbh, a_hat_nsbh, a_hat_mg, num_bins
132 
133 
134 def make_weights_from_histograms(mass1,
135  mass2,
136  activation_counts=None):
137  """
138  Construct binary weights from bin number provided by GstLAL, and a weights
139  matrix pre-constructed and stored in a file, to be read from ???. The
140  weights are keyed on template parameters of Gstlal's template bank. If that
141  doesn't work, construct binary weights.
142 
143  Parameters
144  ----------
145  mass1 : float
146  heavier component mass of the event
147  mass2 : float
148  lighter component mass of the event
149  spin1z : float
150  z component spin of heavier mass
151  spin2z : float
152  z component spin of lighter mass
153  activation_counts : hdf5 object/ dictionary
154  dictionary of activation counts keyed on bin number and source category
155 
156  Returns
157  -------
158  a_hat_bns, a_hat_bbh, a_hat_nsbh, a_hat_mg : floats
159  mass-based template weights
160  """
161 
162  if activation_counts is None:
163  a_hat_bns, a_hat_bbh, a_hat_nsbh, a_hat_mg, num_bins = \
164  make_weights_from_hardcuts(mass1, mass2)
165  else:
166  a_hat_bns = activation_counts['BNS']
167  a_hat_mg = activation_counts['MassGap']
168  a_hat_nsbh = activation_counts['NSBH']
169  a_hat_bbh = activation_counts['BBH']
170  num_bins = activation_counts['num_bins']
171 
172  return a_hat_bns, a_hat_bbh, a_hat_nsbh, a_hat_mg, num_bins
173 
174 
175 def _get_event_ln_likelihood_ratio_svd_endtime_mass(xmldoc):
176  """
177  Task to acquire event parameters
178 
179  Parameters
180  ----------
181  xmldoc : lsctables object
182  Object from which event parameters can be extracted
183 
184  Returns
185  -------
186  event parameters : tuple
187  Tuple of event parameters: lnl, component masses, snr, far
188  """
189 
190  coinc_event, = lsctables.CoincTable.get_table(xmldoc)
191  sngl_inspiral = lsctables.SnglInspiralTable.get_table(xmldoc)
192  coinc_inspiral = lsctables.CoincInspiralTable.get_table(xmldoc)
193 
194  return (coinc_event.likelihood,
195  sngl_inspiral[0].mass1,
196  sngl_inspiral[0].mass2,
197  coinc_inspiral.snr,
198  coinc_inspiral.combined_far)
199 
200 
201 def _get_ln_f_over_b(rankingstatpdf,
202  ln_likelihood_ratios,
203  livetime):
204 
205  # affect the zeroing of the PDFs below threshold by hacking the
206  # histograms. Do the indexing ourselves to not 0 the bin @ threshold
207  noise_lr_lnpdf = rankingstatpdf.noise_lr_lnpdf
208  signal_lr_lnpdf = rankingstatpdf.signal_lr_lnpdf
209  zero_lag_lr_lnpdf = rankingstatpdf.zero_lag_lr_lnpdf
210  ssorted = zero_lag_lr_lnpdf.array.cumsum()[-1] - 10000
211  idx = zero_lag_lr_lnpdf.array.cumsum().searchsorted(ssorted)
212 
213  ln_likelihood_ratio_threshold = \
214  zero_lag_lr_lnpdf.bins[0].lower()[idx]
215 
216  # Compute FAR for threshold, and estimate
217  # terrestrial count consistent with threshold
218  fapfar = \
219  FAPFAR(rankingstatpdf.new_with_extinction())
220  far_threshold = fapfar.far_from_rank(ln_likelihood_ratio_threshold)
221  lam_0 = far_threshold*livetime
222  rankingstatpdf.noise_lr_lnpdf.array[
223  :noise_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] \
224  = 0.
225  rankingstatpdf.noise_lr_lnpdf.normalize()
226 
227  rankingstatpdf.signal_lr_lnpdf.array[
228  :signal_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] \
229  = 0.
230  rankingstatpdf.signal_lr_lnpdf.normalize()
231 
232  rankingstatpdf.zero_lag_lr_lnpdf.array[
233  :zero_lag_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] \
234  = 0.
235  rankingstatpdf.zero_lag_lr_lnpdf.normalize()
236 
237  f = rankingstatpdf.signal_lr_lnpdf
238  b = rankingstatpdf.noise_lr_lnpdf
239  ln_f_over_b = \
240  np.array([f[ln_lr, ] - b[ln_lr, ] for ln_lr in ln_likelihood_ratios])
241  if np.isnan(ln_f_over_b).any():
242  lnlr = ln_likelihood_ratios[0]
243  raise ValueError("NaN encountered in ranking statistic PDF ratios")
244  if np.isinf(np.exp(ln_f_over_b)).any():
245  raise ValueError(
246  "infinity encountered in ranking statistic PDF ratios")
247  return ln_f_over_b, lam_0
248 
249 
250 def compute_p_astro(event_ln_likelihood_ratio,
251  event_mass1,
252  event_mass2,
253  snr,
254  far,
255  rankingstatpdf,
256  livetime = 166.6 * 86400,
257  mean_values_dict = {"counts_BNS": 2.11050326523,
258  "counts_NSBH": 1.56679410666,
259  "counts_BBH": 9.26042350393,
260  "counts_MassGap": 2.40800240248,
261  "counts_Terrestrial": 3923},
262  activation_counts = None
263  ):
264  """
265  Task to compute `p_astro` by source category.
266 
267  Parameters
268  ----------
269  event_ln_likelihood_ratio : float
270  Event's log likelihood ratio value
271  event_mass1 : float
272  Event's heavier component mass value
273  event_mass2 : float
274  Event's lighter component mass value
275  snr: float
276  Event's snr value
277  far: float
278  Event's far value
279  livetime: float
280  Livetime consistent with estimate of Poisson counts.
281  Eg. If counts are from O1 and O2, livetime is O1-O2
282  livetime in seconds.
283  mean_values_dict : dictionary
284  dictionary of source specific FGMC Poisson counts
285  activation_counts : dictionary
286  (optional) dictionary of activation counts keyed on
287  bin number and source category
288 
289  Returns
290  -------
291  p_astros : str
292  JSON dump of the p_astro by source category
293 
294  Example
295  -------
296  >>> import json
297  >>> p_astros = json.loads(compute_p_astro(files))
298  >>> p_astros
299  {'BNS': 0.999, 'BBH': 0.0, 'NSBH': 0.0, 'Terrestrial': 0.001}
300  """
301 
302  # Using the zerolag log likelihood ratio value event,
303  # and the foreground/background model information provided
304  # in ranking_data.xml.gz, compute the ln(f/b) value for this event
305  zerolag_ln_likelihood_ratios = np.array([event_ln_likelihood_ratio])
306  try:
307  ln_f_over_b, lam_0 = \
308  _get_ln_f_over_b(rankingstatpdf,
309  zerolag_ln_likelihood_ratios,
310  livetime)
311  except ValueError as e:
312  return compute_p_astro_approx(snr,
313  far,
314  event_mass1,
315  event_mass2,
316  livetime,
317  mean_values_dict)
318 
319  # Read mean values from url file
320  mean_values_dict["counts_Terrestrial"] = lam_0
321 
322  # Compute categorical p_astro values
323  p_astro_values = \
324  evaluate_p_astro_from_bayesfac(np.exp(ln_f_over_b[0]),
325  mean_values_dict,
326  event_mass1,
327  event_mass2,
328  activation_counts=activation_counts)
329 
330  # Dump values in json file
331  return json.dumps(p_astro_values)
332 
333 
334 def compute_p_astro_approx(snr, far, mass1, mass2, livetime, mean_values_dict):
335  """
336  Task to compute `p_astro` by source category.
337 
338  Parameters
339  ----------
340  snr : float
341  event's SNR
342  far : float
343  event's cfar
344  mass1 : float
345  event's mass1
346  mass2 : float
347  event's mass2
348  livetime: float
349  Livetime consistent with estimate of Poisson counts.
350  Eg. If counts are from O1 and O2, livetime is O1-O2
351  livetime in seconds.
352  mean_values_dict : dictionary
353  dictionary of source specific FGMC Poisson counts
354 
355  Returns
356  -------
357  p_astros : str
358  JSON dump of the p_astro by source category
359 
360  Example
361  -------
362  >>> import json
363  >>> p_astros = json.loads(compute_p_astro(files))
364  >>> p_astros
365  {'BNS': 0.999, 'BBH': 0.0, 'NSBH': 0.0, 'Terrestrial': 0.001}
366  """
367 
368  # Define constants to compute bayesfactors
369  snr_star = 8.5
370  far_star = 1. / (30 * 86400)
371 
372  # Compute astrophysical bayesfactor for
373  # GraceDB event
374  fground = 3 * snr_star**3 / (snr**4)
375  bground = far / far_star
376  astro_bayesfac = fground / bground
377 
378  # Update terrestrial count based on far threshold
379  lam_0 = far_star * livetime
380  mean_values_dict["counts_Terrestrial"] = lam_0
381 
382  # Compute categorical p_astro values
383  p_astro_values = \
384  evaluate_p_astro_from_bayesfac(astro_bayesfac,
385  mean_values_dict,
386  mass1,
387  mass2)
388  # Dump mean values in json file
389  return json.dumps(p_astro_values)