gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_create_prior_diststats
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2010--2014 Kipp Cannon, 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 
20 ### A program to create some prior likelihood data to seed an offline analysis
21 
22 #
23 # =============================================================================
24 #
25 # Preamble
26 #
27 # =============================================================================
28 #
29 
30 
31 from optparse import OptionParser
32 import numpy
33 import scipy
34 
35 from lal import series
36 
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
43 
44 
45 from gstlal import far
46 from gstlal import svd_bank
47 from gstlal import templates
48 
49 @ligolw_array.use_in
50 @ligolw_param.use_in
51 @lsctables.use_in
52 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
53  pass
54 
55 __author__ = "Chad Hanna <chad.hanna@ligo.org>"
56 __version__ = "git id %s" % "" # FIXME
57 __date__ = "" # FIXME
58 
59 
60 #
61 # =============================================================================
62 #
63 # Command Line
64 #
65 # =============================================================================
66 #
67 
68 
69 def parse_command_line():
70  parser = OptionParser(
71  version = "Name: %%prog\n%s" % "" # FIXME
72  )
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()
89 
90  process_params = dict(options.__dict__)
91 
92  if not options.instrument:
93  raise ValueError("must specify at least one --instrument")
94  options.instrument = set(options.instrument)
95 
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")
100 
101  if filenames:
102  raise ValueError("unrecognized arguments after options: %s" % " ".join(filenames))
103 
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")
106  psd = {}
107  if options.psd_xml:
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)
111 
112 
113  template_ids = []
114  horizon_factors = {}
115  bandwidths = []
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":
121  for ifo in psd:
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
126  import json
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())]
132  else:
133  raise ValueError("svd file cannot be read")
134 
135  if options.df == "bandwidth":
136  # don't let the bandwidth get too small
137  options.df = max(int(min(bandwidths)) + 1, 10) * 3
138 
139  return options, process_params, filenames, template_ids, horizon_factors
140 
141 
142 #
143 # =============================================================================
144 #
145 # Main
146 #
147 # =============================================================================
148 #
149 
150 
151 #
152 # command line
153 #
154 
155 
156 options, process_params, filenames, template_ids, horizon_factors = parse_command_line()
157 
158 
159 #
160 # initialize output document (records process start time)
161 #
162 
163 
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)
167 
168 
169 #
170 # create parameter distribution priors
171 #
172 
173 
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)
175 
176 if options.background_prior > 0:
177  rankingstat.denominator.add_noise_model(number_of_events = options.background_prior)
178 
179 # Add the numerator
180 rankingstat.numerator.add_signal_model(df = int(options.df))
181 
182 
183 #
184 # record results in output file
185 #
186 
187 
188 far.gen_likelihood_control_doc(xmldoc, rankingstat, None)
189 
190 
191 #
192 # done
193 #
194 
195 
196 ligolw_process.set_process_end_time(process)
197 ligolw_utils.write_filename(xmldoc, options.write_likelihood, verbose = options.verbose)