3 # Copyright (C) 2012 Stephen Privitera
4 # Copyright (C) 2011-2014 Chad Hanna
5 # Copyright (C) 2010 Melissa Frei
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.
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.
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.
24 from optparse
import OptionParser
25 from gstlal
import spawaveform
26 from ligo.lw
import ligolw
27 from ligo.lw
import lsctables
28 from ligo.lw
import utils as ligolw_utils
29 from ligo.lw.utils
import process as ligolw_process
30 from gstlal
import templates
31 from gstlal
import inspiral_pipe
32 from gstlal
import dagparts
33 from gstlal
import chirptime
35 from lal.utils
import CacheEntry
36 import numpy, scipy.interpolate
38 from lal
import series
40 ### This program splits template banks into sub banks suitable for singular value decomposition; see gstlal_bank_splitter for more information
45 ### 1. split up bank file for H1; sort by mchirp; add final frequency and specify a maximum frequency::
47 ### gstlal_bank_splitter --overlap 10 --instrument H1 --n 100 --sort-by mchirp --add-f-final --max-f-final 2048 H1-TMPLTBANK-871147516-2048.xml
49 ### 2. Please add more!
54 ### 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)::
56 ### ligolw_print -t sngl_inspiral -c mass1 -c mass2 ../H1-TMPLTBANK-871147516-2048.xml | sort -u | wc
57 ### ligolw_print -t sngl_inspiral -c mass1 -c mass2 test.xml.gz | sort -u | wc
59 ### +-------------------------------------------------+------------------------------------------+------------+
60 ### | Names | Hash | |
61 ### +=================================================+==========================================+============+
62 ### | Florent, Sathya, Duncan Me., Jolien, Kipp, Chad | 7536db9d496be9a014559f4e273e1e856047bf71 | 2014-04-28 |
63 ### +-------------------------------------------------+------------------------------------------+------------+
64 ### | Sathya, Duncan Me., Jolien, Kipp, Chad | 72875f5cb241e8d297cd9b3f9fe309a6cfe3f716 | 2015-11-06 |
65 ### +-------------------------------------------------+------------------------------------------+------------+
68 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
70 lsctables.use_in(LIGOLWContentHandler)
73 def group_templates(templates, n, overlap = 0):
75 break up the template table into sub tables of length n with overlap
76 overlap. n must be less than the number of templates and overlap must be less
79 if n >= len(templates):
82 n = len(templates) / round(len(templates) / float(n))
84 for i in itertools.count():
85 start = int(round(i * n)) - overlap
86 end = int(round((i + 1) * n)) + overlap
87 yield templates[max(start, 0):end]
88 if end >= len(templates):
91 def parse_command_line():
92 parser = OptionParser()
93 parser.add_option("--output-path", metavar = "path", default = ".", help = "Set the path to the directory where output files will be written. Default is \".\".")
94 parser.add_option("--output-full-bank-file", metavar = "path", help = "Set the path to output the bank.")
95 parser.add_option("--output-cache", metavar = "file", help = "Set the file name for the output cache.")
96 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.")
97 parser.add_option("--overlap", default = 0, metavar = "count", type = "int", help = "overlap the templates in each file by this amount, must be even")
98 parser.add_option("--sort-by", metavar = "column", default="mchirp", help = "Select the template sort column, default mchirp")
99 parser.add_option("--min-f-final", metavar = "float", type="float", help = "Min f_final to populate table with; if f_final under min, use min.")
100 parser.add_option("--max-f-final", metavar = "float", type="float", help = "Max f_final to populate table with; if f_final over max, use max.")
101 parser.add_option("--instrument", metavar = "ifo", type="string", help = "override the instrument, required")
102 parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
103 parser.add_option("--psd-xml", type = "string", help = "Specify a PSD to use for computing template bandwidth. Required if sort-by is bandwidth")
104 parser.add_option("--approximant", type = "string", action = "append", help = "Must specify an approximant given as mchirp_min:mchirp_max:string")
105 parser.add_option("--f-low", type = "float", metavar = "frequency", help = "Lower frequency cutoff. Required")
106 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")
107 parser.add_option("--write-svd-caches", action = "store_true", help = "output a cache file of cache files, each of which correspond to the banks meant to be in a single SVD bank (disabled by default)")
108 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 if --write-svd-caches invoked)") # FIXME The second half of this help message is incomprehensible
109 options, filenames = parser.parse_args()
111 required_options = ("n", "instrument", "sort_by", "output_cache", "approximant", "f_low")
112 missing_options = [option for option in required_options if getattr(options, option) is None]
114 raise ValueError("missing required option(s) %s" % ", ".join("--%s" % option.replace("_", "-") for option in missing_options))
116 if options.write_svd_caches and not options.num_banks:
117 raise ValueError("missing --num-banks, required if invoking --write-svd-caches")
119 if options.overlap % 2:
120 raise ValueError("overlap must be even")
122 if len(filenames) !=1:
123 raise ValueError("Must give exactly one file name")
125 if options.sort_by == "bandwidth" and not options.psd_xml:
126 raise ValueError("must specify psd-xml if sort-by is bandwidth")
129 for appx in options.approximant:
130 mn, mx, appxstring = appx.split(":")
131 approximants.append((float(mn), float(mx), appxstring))
132 options.approximant = approximants
134 if options.num_banks:
135 options.num_banks = [int(v) for v in options.num_banks.split(",")]
137 # FIXME don't hard code L1
139 psd = series.read_psd_xmldoc(ligolw_utils.load_filename(options.psd_xml, verbose = options.verbose, contenthandler = series.PSDContentHandler))["L1"]
140 f = numpy.arange(len(psd.data.data)) * psd.deltaF
141 psd = scipy.interpolate.interp1d(f, psd.data.data)
144 return options, filenames[0], psd
146 options, filename, psd = parse_command_line()
148 def assign_approximant(mchirp, approximants = options.approximant):
149 for lo, hi, appx in approximants:
150 if lo <= mchirp < hi:
152 raise ValueError("Valid approximant not given for this chirp mass")
157 xmldoc = ligolw_utils.load_filename(filename, verbose = options.verbose, contenthandler = LIGOLWContentHandler)
158 sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
159 # Add a fake bandwidth column
160 if options.sort_by == "bandwidth":
161 for count, row in enumerate(sngl_inspiral_table):
162 # FIXME don't hard code
163 row.bandwidth = templates.bandwidth(row.mass1, row.mass2, row.spin1z, row.spin2z, f_min = 10.0, f_max = 1024., delta_f = 0.25, psd = psd)
164 print(count, len(sngl_inspiral_table), row.bandwidth)
166 #process = ligolw_process.register_to_xmldoc(xmldoc, program = "gstlal_bank_splitter", paramdict = options.__dict__, comment = "Assign template IDs")
167 if options.output_full_bank_file is not None:
168 ligolw_utils.write_filename(xmldoc, options.output_full_bank_file, verbose = options.verbose)
171 sngl_inspiral_table.sort(key = lambda row: spawaveform.computechi(row.mass1, row.mass2, row.spin1z, row.spin2z))
172 for chirows in group_templates(sngl_inspiral_table, len(sngl_inspiral_table) / options.group_by_chi, overlap = 0):
174 def sort_func(row, column = options.sort_by):
175 return getattr(row, column)
177 chirows.sort(key=sort_func, reverse = True if options.sort_by == "template_duration" else False)
179 for numrow, rows in enumerate(group_templates(chirows, options.n, options.overlap)):
180 assert len(rows) >= options.n/2, "There are too few templates in this chi interval. Requested %d: have %d" % (options.n, len(rows))
181 # Pad the first group with an extra overlap / 2 templates
183 rows = rows[:options.overlap
184 outputrows.append((rows[0], rows))
185 # Pad the last group with an extra overlap / 2 templates
186 outputrows[-1] = (rows[0], rows + rows[-options.overlap
188 # A sort of the groups of templates so that the sub banks are ordered.
189 def sort_func(input_tuple, column = options.sort_by):
190 row, rows = input_tuple
191 return getattr(row, column)
193 outputrows.sort(key=sort_func, reverse = True if options.sort_by == "template_duration" else False)
196 with open(options.output_cache, "w") as output_cache_file:
198 for bank_count, (_, rows) in enumerate(outputrows):
199 # just choose the first row to get mchirp
200 # FIXME this could certainly be better
201 approximant = assign_approximant(rows[0].mchirp)
203 # Make an output document
204 xmldoc = ligolw.Document()
205 lw = xmldoc.appendChild(ligolw.LIGO_LW())
206 sngl_inspiral_table = lsctables.New(lsctables.SnglInspiralTable)
207 lw.appendChild(sngl_inspiral_table)
208 # Override the approximant
209 options.approximant = approximant
210 # store the process params
211 process = ligolw_process.register_to_xmldoc(xmldoc, program = "gstlal_bank_splitter", paramdict = options.__dict__, comment = "Split bank into smaller banks for SVD")
215 m1_SI, m2_SI = lal.MSUN_SI * row.mass1, lal.MSUN_SI * row.mass2
216 # Find the total spin magnitudes
217 spin1, spin2 = (row.spin1x**2 + row.spin1y**2 + row.spin1z**2)**.5, (row.spin2x**2 + row.spin2y**2 + row.spin2z**2)**.5
219 if approximant in templates.gstlal_IMR_approximants:
220 # make sure to go a factor of 2 above the ringdown frequency for safety
221 row.f_final = 2 * chirptime.ringf(m1_SI + m2_SI, chirptime.overestimate_j_from_chi(max(spin1, spin2)))
223 # otherwise choose a suitable high frequency
225 row.f_final = spawaveform.ffinal(row.mass1, row.mass2, 'bkl_isco')
227 # Override the high frequency with the max if appropriate
228 if options.max_f_final and (row.f_final > options.max_f_final):
229 row.f_final = options.max_f_final
230 # Override the high frequency with the min if appropriate
231 if options.min_f_final and (row.f_final < options.min_f_final):
232 row.f_final = options.min_f_final
233 row.process_id = process.process_id
236 # Record the conservative template duration
237 row.template_duration = chirptime.imr_time(options.f_low, m1_SI, m2_SI, spin1, spin2, f_max = row.f_final)
239 # Make sure ifo and total mass is stored
240 row.ifo = options.instrument
241 row.mtotal = row.mass1 + row.mass2
243 sngl_inspiral_table[:] = rows
244 output = dagparts.T050017_filename(options.instrument, "%04d_GSTLAL_SPLIT_BANK" % bank_count, (0, 0), ".xml.gz", path = options.output_path)
245 if not options.write_svd_caches:
246 output_cache_file.write("%s\n" % CacheEntry.from_T050017("file:
248 svd_caches.append((bank_count, "%s\n" % CacheEntry.from_T050017("file:
249 ligolw_utils.write_filename(xmldoc, output, verbose = options.verbose)
251 if options.write_svd_caches:
252 cache_path = os.path.join(options.output_path, "cache")
256 # cache directory already exists
259 for svd_cache_group in inspiral_pipe.group(svd_caches, options.num_banks):
260 output = dagparts.T050017_filename(options.instrument, "%04d_%04d_GSTLAL_SPLIT_BANK" % (svd_cache_group[0][0], svd_cache_group[-1][0]), (0, 0), ".cache", path = cache_path)
261 with open(output, 'w') as svd_cache:
262 for bank_count, split_bank_cache_entry in svd_cache_group:
263 svd_cache.write(split_bank_cache_entry)
265 output_cache_file.write("%s\n" % CacheEntry.from_T050017("file: