gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_bank_splitter
1 #! /usr/bin/env python3
2 #
3 # Copyright (C) 2012 Stephen Privitera
4 # Copyright (C) 2011-2014 Chad Hanna
5 # Copyright (C) 2010 Melissa Frei
6 #
7 # This program is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by the
9 # Free Software Foundation; either version 2 of the License, or (at your
10 # option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
15 # Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with this program; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 
21 
22 import json
23 import itertools
24 import os
25 import shutil
26 from optparse import OptionParser
27 from gstlal import spawaveform
28 from ligo.lw import ligolw
29 from ligo.lw import lsctables
30 from ligo.lw import utils as ligolw_utils
31 from ligo.lw.utils import process as ligolw_process
32 from gstlal import templates
33 from gstlal import inspiral_pipe
34 from gstlal import dagparts
35 from gstlal import chirptime
36 from gstlal import reference_psd
37 from gstlal import svd_bank
38 import lal
39 from lal.utils import CacheEntry
40 import numpy, scipy.interpolate
41 import lalsimulation
42 from lal import series
43 
44 ### This program splits template banks into sub banks suitable for singular value decomposition; see gstlal_bank_splitter for more information
45 ###
46 ### Usage examples
47 ### --------------
48 ###
49 ### 1. split up bank file for H1; sort by mchirp; add final frequency and specify a maximum frequency::
50 ###
51 ### gstlal_bank_splitter --overlap 10 --instrument H1 --n 100 --sort-by mchirp --add-f-final --max-f-final 2048 H1-TMPLTBANK-871147516-2048.xml
52 ###
53 ### 2. Please add more!
54 ###
55 ### Review status
56 ### -------------
57 ###
58 ### Compared original bank with the split banks. Verified that they are the same, e.g., add sub bank files into test.xml.gz and run (except that lalapps_tmpltbank adds redundant templates)::
59 ###
60 ### ligolw_print -t sngl_inspiral -c mass1 -c mass2 ../H1-TMPLTBANK-871147516-2048.xml | sort -u | wc
61 ### ligolw_print -t sngl_inspiral -c mass1 -c mass2 test.xml.gz | sort -u | wc
62 ###
63 ### +-------------------------------------------------+------------------------------------------+------------+
64 ### | Names | Hash | |
65 ### +=================================================+==========================================+============+
66 ### | Florent, Sathya, Duncan Me., Jolien, Kipp, Chad | 7536db9d496be9a014559f4e273e1e856047bf71 | 2014-04-28 |
67 ### +-------------------------------------------------+------------------------------------------+------------+
68 ### | Sathya, Duncan Me., Jolien, Kipp, Chad | 72875f5cb241e8d297cd9b3f9fe309a6cfe3f716 | 2015-11-06 |
69 ### +-------------------------------------------------+------------------------------------------+------------+
70 ###
71 
72 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
73  pass
74 lsctables.use_in(LIGOLWContentHandler)
75 
76 
77 def group_templates(templates, n, overlap = 0):
78  """
79  break up the template table into sub tables of length n with overlap
80  overlap. n must be less than the number of templates and overlap must be less
81  than n
82  """
83  if n >= len(templates):
84  yield templates
85  else:
86  n = len(templates) / round(len(templates) / float(n))
87  assert n >= 1
88  for i in itertools.count():
89  start = int(round(i * n)) - overlap // 2
90  end = int(round((i + 1) * n)) + overlap // 2
91  yield templates[max(start, 0):end]
92  if end >= len(templates):
93  break
94 
95 def parse_command_line():
96  parser = OptionParser()
97  parser.add_option("--output-path", metavar = "path", default = ".", help = "Set the path to the directory where output files will be written. Default is \".\".")
98  parser.add_option("--output-stats-file", metavar = "file", help = "Set the path to the directory where output files will be written. Required")
99  parser.add_option("--output-full-bank-file", metavar = "path", help = "Set the path to output the bank.")
100  parser.add_option("--n", metavar = "count", type = "int", help = "Set the number of templates per output file (required). It will be rounded to make all sub banks approximately the same size.")
101  parser.add_option("--overlap", default = 0, metavar = "count", type = "int", help = "overlap the templates in each file by this amount, must be even")
102  parser.add_option("--sort-by", metavar = "column", default="mchirp", help = "Select the template sort column, default mchirp")
103  parser.add_option("--f-final", metavar = "float", type="float", help = "f_final to populate table with")
104  parser.add_option("--instrument", metavar = "ifo", type="string", help = "override the instrument, required")
105  parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
106  parser.add_option("--psd-xml", type = "string", help = "Specify a PSD to use for computing template bandwidth. Required.")
107  parser.add_option("--approximant", type = "string", action = "append", help = "Must specify an approximant given as mchirp_min:mchirp_max:string")
108  parser.add_option("--f-low", type = "float", metavar = "frequency", help = "Lower frequency cutoff. Required")
109  parser.add_option("--group-by-chi", type = "int", metavar = "N", default = 1, help = "group templates into N groups of chi - helps with SVD. Default 1")
110  parser.add_option("--num-banks", metavar = "str", help = "The number of parallel subbanks per SVD bank. can be given as a list like 1,2,3,4 then it will split up the bank into N groups with M banks each. (required)") # FIXME The second half of this help message is incomprehensible
111  options, filenames = parser.parse_args()
112 
113  required_options = ("n", "instrument", "sort_by", "approximant", "f_low", "num_banks", "output_stats_file", "psd_xml")
114  missing_options = [option for option in required_options if getattr(options, option) is None]
115  if missing_options:
116  raise ValueError("missing required option(s) %s" % ", ".join("--%s" % option.replace("_", "-") for option in missing_options))
117 
118  if options.overlap % 2:
119  raise ValueError("overlap must be even")
120 
121  if len(filenames) !=1:
122  raise ValueError("Must give exactly one file name")
123 
124  if options.sort_by == "bandwidth" and not options.psd_xml:
125  raise ValueError("must specify psd-xml if sort-by is bandwidth")
126 
127  approximants = []
128  for appx in options.approximant:
129  mn, mx, appxstring = appx.split(":")
130  approximants.append((float(mn), float(mx), appxstring))
131  options.approximant = approximants
132 
133  if options.num_banks:
134  options.num_banks = [int(v) for v in options.num_banks.split(",")]
135 
136  if options.psd_xml:
137  psd = reference_psd.harmonic_mean(series.read_psd_xmldoc(ligolw_utils.load_filename(options.psd_xml, verbose = options.verbose, contenthandler = series.PSDContentHandler)))
138  f = numpy.arange(len(psd.data.data)) * psd.deltaF
139  psdinterp = scipy.interpolate.interp1d(f, psd.data.data)
140  else:
141  psd = None; psdinterp = None
142  return options, filenames[0], psd, psdinterp
143 
144 options, filename, psd, psdinterp = parse_command_line()
145 
146 def assign_approximant(mchirp, approximants = options.approximant):
147  for lo, hi, appx in approximants:
148  if lo <= mchirp < hi:
149  return appx
150  raise ValueError("Valid approximant not given for this chirp mass")
151 
152 
153 outputrows = []
154 
155 xmldoc = ligolw_utils.load_filename(filename, verbose = options.verbose, contenthandler = LIGOLWContentHandler)
156 sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
157 # Add a fake bandwidth column
158 for count, row in enumerate(sngl_inspiral_table):
159  # FIXME don't hard code
160  row.f_final = options.f_final
161  row.bandwidth = templates.bandwidth(row.mass1, row.mass2, row.spin1z, row.spin2z, f_min = options.f_low, f_max = row.f_final, delta_f = 0.25, psd = psdinterp)
162  row.horizon = reference_psd.HorizonDistance(options.f_low, row.f_final, row.mass1, row.mass2, 0.25, (0.,0.,row.spin1z), (0.,0.,row.spin2z))(psd)[0]
163 
164 # FIXME
165 #process = ligolw_process.register_to_xmldoc(xmldoc, program = "gstlal_bank_splitter", paramdict = options.__dict__, comment = "Assign template IDs")
166 if options.output_full_bank_file is not None:
167  ligolw_utils.write_filename(xmldoc, options.output_full_bank_file, verbose = options.verbose)
168 
169 # Bin by Chi
170 sngl_inspiral_table.sort(key = lambda row: spawaveform.computechi(row.mass1, row.mass2, row.spin1z, row.spin2z))
171 for chirows in group_templates(sngl_inspiral_table, len(sngl_inspiral_table) / options.group_by_chi, overlap = 0):
172 
173  def sort_func(row, column = options.sort_by):
174  return getattr(row, column)
175 
176  chirows.sort(key=sort_func, reverse = True if options.sort_by == "template_duration" else False)
177 
178  for numrow, rows in enumerate(group_templates(chirows, options.n, options.overlap)):
179  assert len(rows) >= options.n/2, "There are too few templates in this chi interval. Requested %d: have %d" % (options.n, len(rows))
180  # Pad the first group with an extra overlap / 2 templates
181  if numrow == 0:
182  rows = rows[:options.overlap//2] + rows
183  outputrows.append((rows[0], rows))
184  # Pad the last group with an extra overlap / 2 templates
185  outputrows[-1] = (rows[0], rows + rows[-options.overlap//2:])
186 
187 # A sort of the groups of templates so that the sub banks are ordered.
188 def sort_func(row_rows_tup, column = options.sort_by):
189  return getattr(row_rows_tup[0], column)
190 
191 outputrows.sort(key=sort_func, reverse = True if options.sort_by == "template_duration" else False)
192 svd_dirs = []
193 metadata = {}
194 
195 for bank_count, (_, rows) in enumerate(outputrows):
196  # just choose the first row to get mchirp
197  # FIXME this could certainly be better
198  approximant = assign_approximant(rows[0].mchirp)
199 
200  # Make an output document
201  xmldoc = ligolw.Document()
202  lw = xmldoc.appendChild(ligolw.LIGO_LW())
203  sngl_inspiral_table = lsctables.New(lsctables.SnglInspiralTable)
204  lw.appendChild(sngl_inspiral_table)
205  # Override the approximant
206  options.approximant = approximant
207  # store the process params
208  process = ligolw_process.register_to_xmldoc(xmldoc, program = "gstlal_bank_splitter", paramdict = options.__dict__, comment = "Split bank into smaller banks for SVD")
209 
210  for row in rows:
211  row.process_id = process.process_id
212 
213  # Record the conservative template duration
214  row.template_duration = chirptime.imr_time(options.f_low,
215  lal.MSUN_SI * row.mass1,
216  lal.MSUN_SI * row.mass2,
217  (row.spin1x**2 + row.spin1y**2 + row.spin1z**2)**.5,
218  (row.spin2x**2 + row.spin2y**2 + row.spin2z**2)**.5,
219  f_max = min(row.f_final, 2 * chirptime.ringf(lal.MSUN_SI * row.mass1 + lal.MSUN_SI * row.mass2, chirptime.overestimate_j_from_chi(max((row.spin1x**2 + row.spin1y**2 + row.spin1z**2)**.5, (row.spin2x**2 + row.spin2y**2 + row.spin2z**2)**.5))) if approximant in templates.gstlal_IMR_approximants else spawaveform.ffinal(row.mass1, row.mass2, 'bkl_isco')))
220 
221  # Make sure ifo and total mass is stored
222  row.ifo = options.instrument
223  row.mtotal = row.mass1 + row.mass2
224 
225  sngl_inspiral_table[:] = rows
226  output = dagparts.T050017_filename(options.instrument, "%04d_GSTLAL_SPLIT_BANK" % bank_count, (0, 0), ".xml.gz", path = options.output_path)
227  metadata[output] = rows
228  svd_dirs.append(output)
229  ligolw_utils.write_filename(xmldoc, output, verbose = options.verbose)
230 
231 svd_groups = list(inspiral_pipe.group(svd_dirs, options.num_banks))
232 outjson = {}
233 for n, svd in enumerate(svd_groups):
234  outdir = os.path.join(options.output_path, "%04d" % n)
235  try:
236  os.mkdir(outdir)
237  except OSError:
238  # svd directory already exists
239  pass
240  svd_mchirps = []
241  svd_durs = []
242  svd_bw = []
243  ref_hd = []
244  clipleft = options.overlap // 2
245  clipright = options.overlap // 2
246  for m, split_file in enumerate(svd):
247  svd_mchirps.extend([r.mchirp for r in metadata[split_file][clipleft:-clipright]])
248  svd_durs.extend([r.template_duration for r in metadata[split_file][clipleft:-clipright]])
249  svd_bw.extend([r.bandwidth for r in metadata[split_file][clipleft:-clipright]])
250  outfile = os.path.join(outdir, os.path.split(split_file)[1])
251  shutil.move(split_file, outfile)
252  xmldoc = ligolw_utils.load_url(outfile, contenthandler = LIGOLWContentHandler, verbose = options.verbose)
253  process = ligolw_process.register_to_xmldoc(xmldoc, program = "gstlal_inspiral_bank_splitter", paramdict = {"clipleft": clipleft, "clipright": clipright, "bank-id": "%d_%d" % (n,m)}, comment = "Add some extra metadata for the SVD")
254  ligolw_utils.write_filename(xmldoc, outfile, verbose = options.verbose)
255 
256  # some gymnastics to get the fiducial horizon template in the LR calculation
257  rows = metadata[svd[0]][clipleft:-clipright]
258  for split_file in svd[1:]:
259  rows += metadata[split_file][clipleft:-clipright]
260  class fakebank(object):
261  def __init__(self, sngl_inspiral_table = rows):
262  self.sngl_inspiral_table = sngl_inspiral_table
263  fb = fakebank()
264  tid,_,_,_,_ = svd_bank.preferred_horizon_distance_template([fb])
265  ref_hd = [r.horizon for split_file in svd for r in metadata[split_file][clipleft:-clipright] if r.template_id == tid][0]
266  outjson["%04d" % n] = {
267  "mean_mchirp": numpy.mean(svd_mchirps),
268  "median_mchirp": numpy.median(svd_mchirps),
269  "min_mchirp": numpy.min(svd_mchirps),
270  "max_mchirp": numpy.max(svd_mchirps),
271  "mean_dur": numpy.mean(svd_durs),
272  "median_dur": numpy.median(svd_durs),
273  "min_dur": numpy.min(svd_durs),
274  "max_dur": numpy.max(svd_durs),
275  "min_bw": numpy.min(svd_bw),
276  "max_bw": numpy.max(svd_bw),
277  "horizon_factors": dict((r.template_id, r.horizon/ref_hd) for m, split_file in enumerate(svd) for r in metadata[split_file][clipleft:-clipright])
278  }
279 
280 #with open(dagparts.T050017_filename(options.instrument, "%04d_%04d_GSTLAL_INSPIRAL_SVD_BANK_METADATA" % (0, n), (0, 0), ".json", path = options.output_path), "w") as jsf:
281 with open(options.output_stats_file, "w") as jsf:
282  jsf.write(json.dumps(outjson, sort_keys = True, indent = 4))