gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_injection_template_match
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2020 Hiroaki Ohta, Heather Fong
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 from optparse import OptionParser
20 import numpy as np
21 from tqdm import tqdm
22 
23 from lalinspiral import inspinjfind
24 from ligo.lw import ligolw
25 from ligo.lw import lsctables
26 from ligo.lw import utils as ligolw_utils
27 from ligo.lw.utils import ligolw_add
28 from ligo.lw.utils import coincs as ligolw_coincs
29 from ligo.lw.utils import process as ligolw_process
30 from gstlal import spawaveform
31 
32 
33 class ApproxID(object):
34  def __init__(self, sngl_inspiral_table):
35  self.sngls = dict((sngl.template_id, sngl) for sngl in sngl_inspiral_table)
36  self.bank = dict(
37  (tmplt_id, np.array([sngl.mchirp, sngl.chi])) for tmplt_id, sngl
38  in self.sngls.items()
39  )
40  self.multi_dim_bank = True if np.array(list(self.bank.values()))[:,1].any() else False
41  if self.multi_dim_bank:
42  self.boundary, self.vor = self.extended_templates(np.array(list(self.bank.values())))
43 
44  def __call__(self, inj):
45  #
46  # search almost proper template id for a injection
47  #
48  inj_point = np.array([inj.mchirp, spawaveform.computechi(inj.mass1, inj.mass2, np.sqrt(np.dot(inj.spin1, inj.spin1)), np.sqrt(np.dot(inj.spin2, inj.spin2)))])
49  if self.multi_dim_bank:
50  for i in range(len(self.vor.points)):
51  if self.vor.points[i] not in self.boundary: # Do not include boundary point regions, which have infinite volume
52  region = self.vor.vertices[self.vor.regions[self.vor.point_region[i]]]
53  if self.in_hull(inj_point, region):
54  best_tmplt = self.vor.points[i]
55  tmplt_id = list(self.bank.keys())[np.where(np.sum(np.array(list(self.bank.values()))==best_tmplt,axis=1)==2)[0][0]]
56  else:
57  tmplt_id = list(self.bank.keys())[np.argmin(abs(np.array(list(self.bank.values()))[:,0]-inj_point[0]))]
58  return tmplt_id
59 
60  def extended_templates(self, m, frac=0.01):
61  # Builds a buffered ConvexHull around the template to bound Voronoi regions
62  # Buffered ConvexHull is needed to avoid infinite volumes for edge points
63  # frac: fractional amount by which new hull points extend (fraction of radius)
64  inner_hull = ConvexHull(m)
65  inner_boundary = inner_hull.points[inner_hull.vertices]
66  v = inner_boundary-np.mean(inner_boundary, axis=0) # create vector from arithmetic centroid to convex hull point
67  outer_boundary = inner_boundary + v*( (1./(1-frac)) - 1.0 ) # define outer boundary points by expanding inner boundary points outwards
68  extended_m = np.concatenate((outer_boundary, m))
69  test_hull = ConvexHull(extended_m) # create convex hull for assert test
70  assert (test_hull.points[test_hull.vertices]==outer_boundary).all(), "Buffered hull points mismatch."
71  return outer_boundary, Voronoi(extended_m)
72 
73  def in_hull(self, p, hull):
74  # Returns a boolean array where True = point p is in hull
75  if not isinstance(hull, Delaunay):
76  try:
77  hull = Delaunay(hull)
78  except scipy.spatial.qhull.QhullError:
79  hull = Delaunay(hull, qhull_options=('Qs'))
80  return hull.find_simplex(p) >= 0
81 
82 
83 #
84 # =============================================================================
85 #
86 # Command Line
87 #
88 # =============================================================================
89 #
90 
91 def parse_command_line():
92  parser = OptionParser()
93 
94  # Input data options
95  parser.add_option("--comment", metavar = "message", help = "Set the string to be recorded in comment and tag columns in various places in the output file (optional).")
96  parser.add_option("--injection-file", metavar = "filename", help = "XML file containing injection list (required).")
97  parser.add_option("--output", metavar = "filename", default = None, help = "Set the name of the LIGO light-weight XML output file *.{xml,xml.gz} (optional). Document is written to stdout if this is not set.")
98  parser.add_option("--template-bank", metavar = "filename", help = "Set the template bank xml file. (required)")
99  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")
100 
101  options, filenames = parser.parse_args()
102 
103  process_params = options.__dict__.copy()
104 
105  required_options = ("injection_file", "template_bank")
106  missing_options = [option for option in required_options if not getattr(options, option)]
107  if missing_options:
108  raise ValueError("%s must be set" % ", ".join("--%s" % option.replace("_", "-") for option in missing_options))
109 
110  return options, process_params
111 
112 
113 #
114 # =============================================================================
115 #
116 # Main
117 #
118 # =============================================================================
119 #
120 
121 
122 #
123 # command line
124 #
125 
126 
127 options, process_params = parse_command_line()
128 
129 
130 #
131 # merge input documents into single XML document
132 #
133 
134 
135 xmldoc = ligolw_add.ligolw_add(ligolw.Document(), [options.injection_file, options.template_bank], verbose = options.verbose)
136 
137 
138 #
139 # add our process metadata
140 #
141 
142 
143 process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral_injection_template_match", paramdict = process_params, comment = options.comment)
144 
145 
146 #
147 # add required tables
148 #
149 
150 
151 coinc_def_id = ligolw_coincs.get_coinc_def_id(xmldoc, inspinjfind.InspiralSTCoincDef.search, inspinjfind.InspiralSTCoincDef.search_coinc_type, description = inspinjfind.InspiralSTCoincDef.description)
152 coinc_event_table = xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.CoincTable))
153 coinc_event_table.sync_next_id()
154 coinc_event_map_table = xmldoc.childNodes[-1].appendChild(lsctables.New(lsctables.CoincMapTable))
155 
156 
157 #
158 # for each injection find and record the matching template
159 #
160 
161 
162 approx_id = ApproxID(lsctables.SnglInspiralTable.get_table(xmldoc))
163 injs = lsctables.SimInspiralTable.get_table(xmldoc)
164 for inj in tqdm(injs, desc = "matching inj", disable = not options.verbose):
165  coinc_event_id = coinc_event_table.appendRow(
166  process_id = process.process_id,
167  coinc_def_id = coinc_def_id,
168  coinc_event_id = coinc_event_table.get_next_id(),
169  time_slide_id = None,
170  instruments = None,
171  nevents = 2,
172  likelihood = None
173  ).coinc_event_id
174 
175  coinc_event_map_table.appendRow(
176  coinc_event_id = coinc_event_id,
177  table_name = u"sim_inspiral",
178  event_id = inj.simulation_id
179  )
180 
181  coinc_event_map_table.appendRow(
182  coinc_event_id = coinc_event_id,
183  table_name = u"sngl_inspiral",
184  event_id = approx_id(inj)
185  )
186 
187 
188 #
189 # write output
190 #
191 
192 
193 ligolw_process.set_process_end_time(process)
194 ligolw_utils.write_filename(xmldoc, options.output, verbose = options.verbose)