3 # Copyright (C) 2010--2014 Kipp Cannon, 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.
20 ### A program to create some prior likelihood data to seed an offline analysis
23 # =============================================================================
27 # =============================================================================
31 from optparse
import OptionParser
35 from lal
import series
37 from ligo.lw
import ligolw
38 from ligo.lw
import lsctables
39 from ligo.lw
import array as ligolw_array
40 from ligo.lw
import param as ligolw_param
41 from ligo.lw
import utils as ligolw_utils
42 from ligo.lw.utils
import process as ligolw_process
45 from gstlal
import far
46 from gstlal
import svd_bank
47 from gstlal
import templates
52 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
55 __author__ = "Chad Hanna <chad.hanna@ligo.org>"
56 __version__ = "git id %s" % "" # FIXME
61 # =============================================================================
65 # =============================================================================
69 def parse_command_line():
70 parser = OptionParser(
71 version = "Name: %%prog\n%s" % "" # FIXME
73 parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
74 # FIXME: default must be identical to gstlal_inspiral's default
75 parser.add_option("--coincidence-threshold", metavar = "value", type = "float", default = 0.005, help = "Set the coincidence window in seconds (default = 0.005). The light-travel time between instruments will be added automatically in the coincidence test.")
76 # FIXME: default must be identical to gstlal_inspiral's default
77 parser.add_option("--min-instruments", metavar = "count", type = "int", default = 2, help = "Set the minimum number of instruments that must contribute triggers to form a candidate (default = 2).")
78 parser.add_option("--write-likelihood", metavar = "filename", help = "Write merged raw likelihood data to this file.")
79 parser.add_option("--instrument", action = "append", help = "Append to a list of instruments to create dist stats for. List must be whatever instruments you intend to analyze.")
80 parser.add_option("-p", "--background-prior", metavar = "N", default = 1, type = "float", help = "Include an exponential background prior with the maximum bin count = N, default 1")
81 parser.add_option("--df", metavar = "N", default = 40, help = "set the degrees of freedom for the background chisq prior: default 40. You can also use template bandwidth to set this by setting it to 'bandwidth'")
82 parser.add_option("--svd-file", metavar = "filename", help = "The SVD file to read the template ids from")
83 parser.add_option("--svd-bin", metavar = "%04d", help = "The bin that this is, required if giving json manifest for --svd-file")
84 parser.add_option("--mass-model-file", metavar = "filename", help = "The mass model file to read from (hdf5 format)")
85 parser.add_option("--dtdphi-file", metavar = "filename", help = "dtdphi snr ratio pdfs to read from (hdf5 format). Default passed by gstlal_inspiral_pipe, but not when run as a standalone program.")
86 parser.add_option("--idq-file", metavar = "filename", help = "idq glitch file (hdf5 format)")
87 parser.add_option("--psd-xml", type = "string", help = "Specify a PSD to use for computing template bandwidth. Required if df is bandwidth")
88 options, filenames = parser.parse_args()
90 process_params = dict(options.__dict__)
92 if not options.instrument:
93 raise ValueError("must specify at least one --instrument")
94 options.instrument = set(options.instrument)
96 if options.min_instruments < 1:
97 raise ValueError("--min-instruments must be >= 1")
98 if options.min_instruments > len(options.instrument):
99 raise ValueError("--min-instruments is greater than the number of unique --instrument's")
102 raise ValueError("unrecognized arguments after options: %s" % " ".join(filenames))
104 if options.df == "bandwidth" and options.psd_xml is None:
105 raise ValueError("Must specify psd xml file if using bandwidth to set degrees of freedom")
108 for ifo, p in series.read_psd_xmldoc(ligolw_utils.load_filename(options.psd_xml, verbose = options.verbose, contenthandler = series.PSDContentHandler)).items():
109 f = numpy.arange(len(p.data.data)) * p.deltaF
110 psd[ifo] = scipy.interpolate.interp1d(f, p.data.data)
116 if options.svd_file.endswith(
".xml") or options.svd_file.endswith(
".xml.gz"):
117 for n, bank in enumerate(svd_bank.read_banks(options.svd_file, contenthandler = LIGOLWContentHandler, verbose = options.verbose)):
118 template_ids += [row.template_id
for row in bank.sngl_inspiral_table]
119 # FIXME don
't hard code
120 if options.df == "bandwidth":
122 bandwidths += [templates.bandwidth(row.mass1, row.mass2, row.spin1z, row.spin2z, f_min = 10.0, f_max = row.f_final, delta_f = 0.25, psd = psd[ifo]) for row in bank.sngl_inspiral_table]
123 horizon_factors.update(bank.horizon_factors)
124 elif options.svd_file.endswith(".json"):
125 assert options.svd_bin is not None
127 with open(options.svd_file) as f:
128 manifest = json.loads(f.read())
129 bandwidths = [manifest[options.svd_bin]["min_bw"], manifest[options.svd_bin]["max_bw"]]
130 horizon_factors.update(manifest[options.svd_bin]["horizon_factors"])
131 template_ids = [int(template_id) for template_id in list(manifest[options.svd_bin]["horizon_factors"].keys())]
133 raise ValueError("svd file cannot be read")
135 if options.df == "bandwidth":
136 # don't let the bandwidth
get too small
137 options.df = max(
int(min(bandwidths)) + 1, 10) * 3
139 return options, process_params, filenames, template_ids, horizon_factors
143 # =============================================================================
147 # =============================================================================
156 options, process_params, filenames, template_ids, horizon_factors = parse_command_line()
160 # initialize output document (records process start time)
164 xmldoc = ligolw.Document()
165 xmldoc.appendChild(ligolw.LIGO_LW())
166 process = ligolw_process.register_to_xmldoc(xmldoc, u
"gstlal_inspiral_create_prior_diststats", instruments = options.instrument, paramdict = process_params)
170 # create parameter distribution priors
174 rankingstat = far.RankingStat(template_ids = template_ids, instruments = options.instrument, delta_t = options.coincidence_threshold, min_instruments = options.min_instruments, population_model_file = options.mass_model_file, dtdphi_file = options.dtdphi_file, horizon_factors = horizon_factors, idq_file = options.idq_file)
176 if options.background_prior > 0:
177 rankingstat.denominator.add_noise_model(number_of_events = options.background_prior)
180 rankingstat.numerator.add_signal_model(df =
int(options.df))
184 # record results in output file
188 far.gen_likelihood_control_doc(xmldoc, rankingstat, None)
196 ligolw_process.set_process_end_time(process)
197 ligolw_utils.write_filename(xmldoc, options.write_likelihood, verbose = options.verbose)