3 # Copyright (C) 2016 Cody Messick
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 split a set of injections up into a smaller set of files grouped together by chirp mass
23 from optparse
import OptionParser
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
33 class ligolwcontenthandler(ligolw.LIGOLWContentHandler):
37 def mchirp_bounds(mchirp, which):
39 return {'lower': 0.65*mchirp, 'upper': 1.35*mchirp}[which]
41 return {'lower': 0.5*mchirp, 'upper': 1.5*mchirp}[which]
43 return {'lower': 0.5*mchirp, 'upper': 2*mchirp}[which]
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 )
54 def create_split_injection(processmap, process_params_dict, endtimesim_tuples, min_mchirp, max_mchirp, name, options):
56 xmldoc = ligolw.Document()
57 xmldoc.appendChild(ligolw.LIGO_LW())
59 processtable = lsctables.New(lsctables.ProcessTable)
60 processparamstable = lsctables.New(lsctables.ProcessParamsTable)
61 siminspiraltable = lsctables.New(lsctables.SimInspiralTable)
63 xmldoc.childNodes[-1].appendChild(processtable)
64 xmldoc.childNodes[-1].appendChild(processparamstable)
65 xmldoc.childNodes[-1].appendChild(siminspiraltable)
67 # FIXME add this to process params table
68 #process = ligolw_process.register_to_xmldoc(xmldoc, "gstlal_inspiral_combine_injection_sets", param_dict)
71 siminspiraltimemap = {}
72 end_times = numpy.array([])
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)
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)
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)
88 def parse_command_line():
89 parser = OptionParser()
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]")
98 # FIXME Add option checking so num-output and target-injection-rate cannot both be provided
100 options, filenames = parser.parse_args()
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)
104 return options, filenames, target_inj_rate_interval
106 options, filenames, target_inj_rate_interval = parse_command_line()
109 if options.generate_inj_string_only:
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)
115 # set up xmldoc structure to contain all of the injections
116 xmldoc = ligolw.Document()
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])
125 process_params_dict = {}
126 for param in lsctables.ProcessParamsTable.get_table(xmldoc):
127 process_params_dict.setdefault(param.process_id, []).append(param)
129 # close original xmldoc
132 # split injections up into X files with roughly equal injections each
134 avg_inj_rate = numpy.inf
137 if options.single_output:
138 split_keys = [siminspiralmchirps]
141 while avg_inj_rate > target_inj_rate_interval[1]:
144 split_keys = numpy.array_split(siminspiralmchirps, num_output)
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)
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")
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)
163 with open(options.injection_str_output, 'w') as f:
164 f.write(mchirp_str[:-1])