gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
inspiral_intrinsics.py
1 # Copyright (C) 2017,2018 Heather Fong
2 #
3 # This program is free software; you can redistribute it and/or modify it
4 # under the terms of the GNU General Public License as published by the
5 # Free Software Foundation; either version 2 of the License, or (at your
6 # option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11 # Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 
17 
18 #
19 # =============================================================================
20 #
21 # Preamble
22 #
23 # =============================================================================
24 #
25 
26 
27 import h5py
28 import math
29 import numpy
30 import os
31 try:
32  from scipy.interpolate import PPoly
33 except ImportError:
34  # argh, scipy too old
35  # FIXME: delete this when we can rely on LDG sites having a
36  # new-enough scipy
37  from lal.rate import IrregularBins
38  class PPoly(object):
39  def __init__(self, c, x):
40  self.intervals = IrregularBins(x)
41  self.coeffs = c
42  self.x0 = x
43 
44  def __call__(self, x):
45  i = self.intervals[x]
46  return numpy.poly1d(self.coeffs[:,i].squeeze())(x - self.x0[i]),
47 
48 
49 from gstlal import stats as gstlalstats
50 
51 
52 # FIXME: caution, this information might get organized differently later.
53 # for now we just need to figure out where the gstlal-inspiral directory in
54 # share/ is. don't write anything that assumes that this module will
55 # continue to define any of these symbols
56 from gstlal import paths as gstlal_config_paths
57 
58 
59 __all__ = [
60  "UniformInTemplatePopulationModel",
61  "SourcePopulationModel"
62 ]
63 
64 
65 #
66 # =============================================================================
67 #
68 # Population Model
69 #
70 # =============================================================================
71 #
72 
73 
75  # FIXME: this needs to learn the template chirp masses so it can
76  # take out the factor of mchirp**(5./3.) factor on which the
77  # horizon distance depends (which appears in a volume factor in the
78  # numerator of the likelihood ratio)
79  def __init__(self, template_ids):
80  """
81  Assumes uniform in template population model, no
82  astrophysical prior.
83  """
84  self.lnP = 0.
85 
86 
87  @gstlalstats.assert_ln_probability
88  def lnP_template_signal(self, template_id, snr):
89  assert snr >= 0.
90  return self.lnP
91 
92 
93 class SourcePopulationModel(object):
94  #
95  # NOTE: This is no longer the default file used in the population
96  # model. Various tools including the dag have been modified to allow
97  # the user to specify the mass model file at run time. If you want to
98  # use this file, you should point the dag script to wherever it is on
99  # your filesystem.
100  #
101  # NOTE: future code will have this comment and these next two lines deleted.
102  #
103  #POPULATION_MODELS_PATH = os.path.join(gstlal_config_paths["pkgdatadir"], "population_models")
104  #DEFAULT_FILENAME = os.path.join(POPULATION_MODELS_PATH, "O2/lnP_template_signal_BBH_logm_reweighted_mchirp.hdf5")
105 
106 
107  def __init__(self, template_ids, filename = None):
108  """
109  Sets the polynomial coefficients, given the template ID and
110  SNR for a source population model, from which lnP is then
111  computed using PPoly.
112  """
113  if filename is not None:
114  with h5py.File(filename, 'r') as model:
115  coefficients = model['coefficients'][()]
116  snr_bp = model['SNR'][()]
117  try:
118  model_ids = model['template_id'][()]
119  except KeyError:
120  # FIXME: assume sequential order if model['event_id'] doesn't exist
121  #model_ids = numpy.arange(numpy.shape(model['coefficients'][()])[-1])
122  model_ids = model['event_id'][()]
123  # PPoly can construct an array of polynomials by just
124  # feeding it the coefficients array all in one go, but then
125  # it insists on evaluating all of them at once. we don't
126  # want to suffer that cost, so we have to make an array of
127  # PPoly objects ourselves, and index into it to evaluate
128  # just one. since we have to do this anyway, we use a
129  # dictionary to also solve the problem of mapping
130  # template_id to a specific polynomial
131  template_indices = {}
132  for template_id in template_ids:
133  # maps template ID to the right coefficient array, since template IDs
134  # in the bank may not be in sequential order
135  try:
136  template_indices[template_id] = numpy.where(model_ids==template_id)[0][0]
137  except IndexError:
138  raise IndexError("template ID %d is not in this model".format(template_id))
139  self.polys = dict((template_id, PPoly(coefficients[:,:,[template_indices[template_id]]], snr_bp)) for template_id in template_ids)
140  self.max_snr = snr_bp.max()
141  else:
142  self.polys = None
143  self.max_snr = None
144 
145  @gstlalstats.assert_ln_probability
146  def lnP_template_signal(self, template_id, snr):
147  assert snr >= 0.
148  try:
149  lnP_vs_snr = self.polys[template_id]
150  except KeyError:
151  raise KeyError("template ID %d is not in this model".format(template_id))
152  # PPoly's .__call__() returns an array, so we need the
153  # final [0] to flatten it
154  return lnP_vs_snr(min(snr, self.max_snr))[0]