gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_mass_model
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2017,2018 Heather Fong and Chad Hanna
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 import h5py
20 import argparse
21 import numpy
22 from ligo.lw import ligolw
23 from ligo.lw import lsctables, param as ligolw_param, array as ligolw_array
24 from ligo.lw import utils as ligolw_utils
25 from ligo.lw.utils import process as ligolw_process
26 import lal.series
27 from lal import rate
28 from gstlal import reference_psd
29 
30 @ligolw_array.use_in
31 @ligolw_param.use_in
32 @lsctables.use_in
33 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
34  pass
35 
36 def chirpmass(m1, m2):
37  return (m1 * m2)**.6 / (m1 + m2)**.2
38 
39 def schechter_norm(lower, upper, maxM, alpha):
40  norm_masses = numpy.linspace(lower, upper, 10000)
41  return numpy.sum(schechter(norm_masses, maxM, alpha)) * (norm_masses[1] - norm_masses[0])
42 
43 def schechter(mass, maxM, alpha):
44  return (mass / maxM)**alpha * numpy.exp(-mass / maxM) / maxM
45 
46 parser = argparse.ArgumentParser(description = "Create analytic mass models for prior weighting of templates")
47 parser.add_argument("--template-bank", metavar='name', type=str, help='The input template bank file name.', required = True)
48 parser.add_argument("--reference-psd", metavar='filename', help = "Load the spectrum from this LIGO light-weight XML file")
49 parser.add_argument("--output", metavar='name', type=str, help='The output file name', default = "inspiral_mass_model.h5")
50 parser.add_argument("--min-instrument", metavar='name', type=int, default=2, help='Minimum instruments operating. Specified for calculating horizon distance in uniform in template model.')
51 parser.add_argument("--model", metavar='name', type=str, help='Mass model. Options are: ligo, narrow-bns, ligo-bns, bbh, uniform-template. If you want another one, submit a patch.')
52 parser.add_argument("--verbose", help='Be verbose', action="store_true")
53 options = parser.parse_args()
54 
55 # Read the template bank file
56 xmldoc = ligolw_utils.load_filename(options.template_bank, verbose = options.verbose, contenthandler = LIGOLWContentHandler)
57 sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
58 if options.model in ("uniform-template"):
59  psd = lal.series.read_psd_xmldoc(ligolw_utils.load_filename(options.reference_psd, verbose = True, contenthandler = lal.series.PSDContentHandler))
60 
61 mchirps_of_tmps = chirpmass(sngl_inspiral_table.getColumnByName("mass1").asarray(), sngl_inspiral_table.getColumnByName("mass2").asarray())
62 
63 num_templates = len(mchirps_of_tmps)
64 num_bins = max(10, num_templates // 10000)
65 massBA = rate.BinnedDensity(rate.NDBins((rate.LogarithmicBins(min(mchirps_of_tmps)-5e-6, max(mchirps_of_tmps)+5e-6, num_bins),)))
66 for m in mchirps_of_tmps:
67  massBA.count[(m,)] += 1
68 # Does weird stuff at edges :(
69 #TEMPDENS = rate.InterpBinnedArray(massBA)
70 TEMPDENS = lambda x: massBA[x,]
71 
72 # Assign the proper mass probabilities
73 prob = {}
74 mchirps = {}
75 
76 ligo_min = 3
77 ligo_max = 30
78 ligo_peak = 30
79 ligo_alpha = -2.0
80 ligonorm = schechter_norm(ligo_min, ligo_max, ligo_peak, ligo_alpha)
81 
82 bbh_min = 3
83 bbh_max = 100
84 bbh_peak = 100
85 bbh_alpha = -1.5
86 bbhnorm = schechter_norm(bbh_min, bbh_max, bbh_peak, bbh_alpha)
87 
88 for row in sngl_inspiral_table:
89  assert row.template_id not in prob
90 
91  mchirp = chirpmass(row.mass1, row.mass2)
92  mchirps[row.template_id] = mchirp
93 
94  if options.model == "narrow-bns":
95  # comes from component mass mean 1.33, std 0.09, and redshift 0.02
96  sigma = 0.055
97  mean = 1.18
98  prob[row.template_id] = 1. / (2 * numpy.pi * sigma**2)**.5 * numpy.exp(-(mchirp - mean)**2 / 2. / sigma**2)
99  # Divide out the template density
100  prob[row.template_id] /= TEMPDENS(mchirp)
101 
102  elif options.model == "ligo-bns":
103  sigma = 0.25
104  mean = 1.33
105  prob[row.template_id] = 1. / (2 * numpy.pi * sigma**2)**.5 * numpy.exp(-(mchirp - mean)**2 / 2. / sigma**2)
106  # Divide out the template density
107  prob[row.template_id] /= TEMPDENS(mchirp)
108 
109  elif options.model == "uniform-template":
110  hdist = sorted([reference_psd.HorizonDistance(15, 1024, 1./4., row.mass1, row.mass2, (0., 0., row.spin1z), (0., 0., row.spin2z))(psd[ifo])[0] for ifo in psd.keys()])
111  prob[row.template_id] = 1.0 / (hdist[-options.min_instrument]**3)
112 
113  elif options.model == "bbh":
114  #
115  # BBH portion
116  #
117 
118  # From: https://www.lsc-group.phys.uwm.edu/ligovirgo/cbcnote/RatesAndSignificance/O1O2CatalogRates
119  prob[row.template_id] = schechter(mchirp, bbh_peak, bbh_alpha) / bbhnorm
120  # Divide out the template density
121  prob[row.template_id] /= TEMPDENS(mchirp)
122 
123  elif options.model == "ligo":
124 
125  #
126  # BNS portion
127  #
128 
129  # assume a 0.25 solar mass std deviation, this should capture both population distribution and snr effects
130  # motivated by LIGO detections
131  sigma = 0.25
132  mean = 1.33
133  bnsprob = 1. / (2 * numpy.pi * sigma**2)**.5 * numpy.exp(-(mchirp - mean)**2 / 2. / sigma**2)
134 
135  #
136  # BBH portion
137  #
138 
139  bbhprob = schechter(mchirp, ligo_peak, ligo_alpha) / ligonorm
140 
141  #
142  # Combined
143  #
144 
145  # make intrinsic BNS rate 7 times higher (it is actually probably 20 times higher)
146  bns_rate = 7.
147  bbh_rate = 1.
148  prob[row.template_id] = (bns_rate * bnsprob + bbh_rate * bbhprob) / (bns_rate + bbh_rate)
149  # Divide out the template density
150  prob[row.template_id] /= TEMPDENS(mchirp)
151  else:
152  raise ValueError("Invalid mass model")
153 
154 
155 ids = sorted(list(prob.keys()))
156 norm = numpy.sum(list(prob.values()))
157 chirpmasses = numpy.array([mchirps[tid] for tid in ids])
158 coefficients = numpy.zeros((1, 1, len(ids)+1), dtype=float)
159 for idx, tid in enumerate(ids):
160  if options.model == "uniform-template":
161  coefficients[0,0,idx] = numpy.log(prob[tid])
162  else:
163  coefficients[0,0,idx] = numpy.log(prob[tid]) - numpy.log(norm)
164 
165 #import matplotlib
166 #matplotlib.use('agg')
167 #from matplotlib import pyplot
168 #print len(chirpmasses), coefficients.shape
169 #pyplot.semilogx(chirpmasses, coefficients[0,0,:-1], "*")
170 #pyplot.grid()
171 #pyplot.ylim([-20, 0])
172 #pyplot.savefig("blah.png")
173 
174 # Write it out
175 f = h5py.File(options.output, "w")
176 # put in a dummy interval for the piecewise polynomials in SNR
177 f.create_dataset("SNR", data = numpy.array([0., 100.]))
178 f.create_dataset("coefficients", data = coefficients, compression="gzip")
179 f.create_dataset("template_id", data = numpy.array(ids).astype(int))
180 f.close()