3 # Copyright (C) 2017,2018 Heather Fong and Chad Hanna
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.
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.
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.
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
28 from gstlal
import reference_psd
33 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
36 def chirpmass(m1, m2):
37 return (m1 * m2)**.6 / (m1 + m2)**.2
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])
43 def schechter(mass, maxM, alpha):
44 return (mass / maxM)**alpha * numpy.exp(-mass / maxM) / maxM
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()
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))
61 mchirps_of_tmps = chirpmass(sngl_inspiral_table.getColumnByName("mass1").asarray(), sngl_inspiral_table.getColumnByName("mass2").asarray())
63 num_templates = len(mchirps_of_tmps)
64 num_bins = max(10, num_templates
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,]
72 # Assign the proper mass probabilities
80 ligonorm = schechter_norm(ligo_min, ligo_max, ligo_peak, ligo_alpha)
86 bbhnorm = schechter_norm(bbh_min, bbh_max, bbh_peak, bbh_alpha)
88 for row in sngl_inspiral_table:
89 assert row.template_id not in prob
91 mchirp = chirpmass(row.mass1, row.mass2)
92 mchirps[row.template_id] = mchirp
94 if options.model == "narrow-bns":
95 # comes from component mass mean 1.33, std 0.09, and redshift 0.02
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)
102 elif options.model == "ligo-bns":
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)
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)
113 elif options.model == "bbh":
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)
123 elif options.model == "ligo":
129 # assume a 0.25 solar mass std deviation, this should capture both population distribution and snr effects
130 # motivated by LIGO detections
133 bnsprob = 1. / (2 * numpy.pi * sigma**2)**.5 * numpy.exp(-(mchirp - mean)**2 / 2. / sigma**2)
139 bbhprob = schechter(mchirp, ligo_peak, ligo_alpha) / ligonorm
145 # make intrinsic BNS rate 7 times higher (it is actually probably 20 times higher)
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)
152 raise ValueError("Invalid mass model")
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])
163 coefficients[0,0,idx] = numpy.log(prob[tid]) - numpy.log(norm)
166 #matplotlib.use('agg')
167 #from matplotlib import pyplot
168 #print len(chirpmasses), coefficients.shape
169 #pyplot.semilogx(chirpmasses, coefficients[0,0,:-1], "*")
171 #pyplot.ylim([-20, 0])
172 #pyplot.savefig("blah.png")
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))