gstlal-inspiral  1.9.3
 All Classes Namespaces Files Functions
gstlal_inspiral_combine_injection_sets
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2016 Cody Messick
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 split a set of injections up into a smaller set of files grouped together by chirp mass
21 
22 
23 from optparse import OptionParser
24 
25 from ligo.lw import ilwd, ligolw, lsctables
26 from ligo.lw import utils as ligolw_utils
27 from ligo.lw.utils import process as ligolw_process
28 from ligo.lw.utils import ligolw_add
29 
30 import numpy
31 
32 @lsctables.use_in
33 class ligolwcontenthandler(ligolw.LIGOLWContentHandler):
34  pass
35 
36 
37 def mchirp_bounds(mchirp, which):
38  if mchirp < 10:
39  return {'lower': 0.65*mchirp, 'upper': 1.35*mchirp}[which]
40  elif mchirp < 20:
41  return {'lower': 0.5*mchirp, 'upper': 1.5*mchirp}[which]
42  else:
43  return {'lower': 0.5*mchirp, 'upper': 2*mchirp}[which]
44 
45 
46 def mchirp_injection_str(keys, name):
47  # FIXME this could be done better by just looking for values that cross
48  # the boundaries defined in mchirp_bounds
49  lower_mchirp_bound = min([mchirp_bounds(mchirp, 'lower') for [mchirp, simulation_id] in keys])
50  upper_mchirp_bound = max([mchirp_bounds(mchirp, 'upper') for [mchirp, simulation_id] in keys])
51  return '%.2f:%.2f:%s ' % ( lower_mchirp_bound, upper_mchirp_bound, name )
52 
53 
54 def create_split_injection(processmap, process_params_dict, endtimesim_tuples, min_mchirp, max_mchirp, name, options):
55 
56  xmldoc = ligolw.Document()
57  xmldoc.appendChild(ligolw.LIGO_LW())
58 
59  processtable = lsctables.New(lsctables.ProcessTable)
60  processparamstable = lsctables.New(lsctables.ProcessParamsTable)
61  siminspiraltable = lsctables.New(lsctables.SimInspiralTable)
62 
63  xmldoc.childNodes[-1].appendChild(processtable)
64  xmldoc.childNodes[-1].appendChild(processparamstable)
65  xmldoc.childNodes[-1].appendChild(siminspiraltable)
66 
67  # FIXME add this to process params table
68  #process = ligolw_process.register_to_xmldoc(xmldoc, "gstlal_inspiral_combine_injection_sets", param_dict)
69 
70  process_ids = {}
71  siminspiraltimemap = {}
72  end_times = numpy.array([])
73 
74  for end_time, sim in sorted(endtimesim_tuples, key = lambda x: x[0]):
75  siminspiraltable.append(sim)
76  end_times = numpy.append(end_times, end_time)
77  process_ids.setdefault(sim.process_id, []).append(sim.simulation_id)
78 
79  for procid in sorted(process_ids.keys()):
80  processtable.append(processmap[procid])
81  for param in process_params_dict[procid]:
82  processparamstable.append(param)
83 
84  dt = end_times[1:] - end_times[:-1]
85  print("%s: avg injection rate = %f, min mchirp = %f, max mchirp = %f, min dt = %f" % (name, 1./dt.mean(), min_mchirp, max_mchirp, dt.min()))
86  ligolw_utils.write_filename(xmldoc, name)
87 
88 def parse_command_line():
89  parser = OptionParser()
90 
91  parser.add_option("--target-injection-rate", "-r", metavar = "s^-1", type = "float", default = 0.1, help = "Desired injection rate of output files (default: 0.01)")
92  parser.add_option("--output-tag", "-o", metavar = "filename", default = "split_injections", help = "Base of output file name (default: split_injections)")
93  parser.add_option("--injection-rate-tolerance", type = "float", default = 0.1, help = "Acceptable tolerance for target injection rate, files will be written to disk once a splitting has been found such that the injection rate is target-injection-rate +- (injection-rate-tolerance*target-injection-rate) (default: 0.1)")
94  parser.add_option("--generate-inj-string-only", action = "store_true", help = "Do not combine files, generate an injection string specifying which chirp mass bounds to use to search for the provided injection files")
95  parser.add_option("--single-output", action = "store_true", help = "Produce a single output file containing all injections")
96  parser.add_option("--injection-str-output", default = "injection_str.txt", help = "Write injection string used in analysis Makefile to this file. [Default: injection_str.txt]")
97 
98  # FIXME Add option checking so num-output and target-injection-rate cannot both be provided
99 
100  options, filenames = parser.parse_args()
101 
102  target_inj_rate_interval = (options.target_injection_rate - options.injection_rate_tolerance * options.target_injection_rate, options.target_injection_rate + options.injection_rate_tolerance * options.target_injection_rate)
103 
104  return options, filenames, target_inj_rate_interval
105 
106 options, filenames, target_inj_rate_interval = parse_command_line()
107 
108 mchirp_str = ''
109 if options.generate_inj_string_only:
110  for f in filenames:
111  xmldoc = ligolw_utils.load_filename(f, contenthandler = ligolwcontenthandler)
112  mchirp_str += mchirp_injection_str([(sim.mchirp, None) for sim in lsctables.SimInspiralTable.get_table(xmldoc)], f)
113  xmldoc.unlink()
114 else:
115  # set up xmldoc structure to contain all of the injections
116  xmldoc = ligolw.Document()
117 
118  # add all files together and create mappings needed to split the files up while
119  # conserving process ids
120  xmldoc = ligolw_add.ligolw_add(xmldoc, filenames, verbose = True, contenthandler = ligolwcontenthandler)
121  processmap = dict((proc.process_id, proc) for proc in lsctables.ProcessTable.get_table(xmldoc))
122  siminspiralmap = dict(((sim.mchirp, sim.simulation_id), (sim.geocent_end_time + 1e-9*sim.geocent_end_time_ns, sim)) for sim in lsctables.SimInspiralTable.get_table(xmldoc))
123  siminspiralmchirps = sorted(siminspiralmap.keys(), key = lambda k: k[0])
124 
125  process_params_dict = {}
126  for param in lsctables.ProcessParamsTable.get_table(xmldoc):
127  process_params_dict.setdefault(param.process_id, []).append(param)
128 
129  # close original xmldoc
130  xmldoc.unlink()
131 
132  # split injections up into X files with roughly equal injections each
133  num_output = 1
134  avg_inj_rate = numpy.inf
135  i=0
136 
137  if options.single_output:
138  split_keys = [siminspiralmchirps]
139 
140  else:
141  while avg_inj_rate > target_inj_rate_interval[1]:
142 
143  num_output += 1
144  split_keys = numpy.array_split(siminspiralmchirps, num_output)
145  avg_dts = []
146  for i, keys in enumerate(split_keys):
147  sorted_times = numpy.sort([siminspiralmap[tuple(k for k in key)][0] for key in keys])
148  if len(sorted_times) < 2:
149  raise ValueError("files need to be split too finely to hit target injection rate, try increasing target rate or tolerance (last splitting attempt: %d files)" % num_output)
150  avg_dts.append((sorted_times[1:] - sorted_times[:-1]).mean())
151  avg_inj_rate = 1/numpy.mean(avg_dts)
152 
153  if avg_inj_rate < target_inj_rate_interval[0]:
154  print(avg_inj_rate, num_output)
155  # the average injection rate cannot increase with more splittings, thus we can't hit this injection rate interval
156  raise ValueError("target injection rate not attainable, either increase the tolerance or decrease the target rate")
157 
158 
159  for i, keys in enumerate(split_keys):
160  create_split_injection(processmap, process_params_dict, [siminspiralmap[tuple(k for k in key)] for key in keys], keys[0][0], keys[-1][0], "%s_%04d.xml" %( options.output_tag, i) if not options.single_output else "%s.xml" % options.output_tag, options)
161  mchirp_str += mchirp_injection_str(keys, "%s_%04d.xml" %( options.output_tag, i) if not options.single_output else "%s.xml" % options.output_tag)
162 
163 with open(options.injection_str_output, 'w') as f:
164  f.write(mchirp_str[:-1])