50 from ligo.lw
import ligolw
51 from ligo.lw
import lsctables
52 from ligo.lw
import array
as ligolw_array
53 from ligo.lw
import param
as ligolw_param
54 from ligo.lw
import utils
as ligolw_utils
55 from ligo.lw
import types
as ligolw_types
56 from ligo.lw.utils
import process
as ligolw_process
58 Attributes = ligolw.sax.xmlreader.AttributesImpl
60 from gstlal
import cbc_template_fir
61 from gstlal
import misc
as gstlalmisc
62 from gstlal
import templates
63 from gstlal
import reference_psd
68 ligolw_array.use_in(DefaultContentHandler)
69 ligolw_param.use_in(DefaultContentHandler)
70 lsctables.use_in(DefaultContentHandler)
85 def read_approximant(xmldoc, programs = (
"gstlal_bank_splitter",)):
87 for program
in programs:
88 process_ids |= lsctables.ProcessTable.get_table(xmldoc).get_ids_by_program(program)
90 raise ValueError(
"document must contain process entries from %s" %
", ".join(programs))
91 approximant = set(row.pyvalue
for row
in lsctables.ProcessParamsTable.get_table(xmldoc)
if (row.process_id
in process_ids)
and (row.param ==
"--approximant"))
93 raise ValueError(
"document must contain an 'approximant' process_params entry from %s" %
", ".join(
"'%s'" for program
in programs))
94 if len(approximant) > 1:
95 raise ValueError(
"document must contain only one approximant")
96 approximant = approximant.pop()
104 def check_ffinal_and_find_max_ffinal(xmldoc):
105 f_final = lsctables.SnglInspiralTable.get_table(xmldoc).getColumnByName(
"f_final")
107 raise ValueError(
"f_final column not populated")
115 def sum_of_squares_threshold_from_fap(fap, coefficients):
116 return gstlalmisc.max_stat_thresh(coefficients, fap)
130 def __init__(self, rate, start, end):
135 def set_template_bank(self, template_bank, tolerance, snr_thresh, identity_transform = False, verbose = False):
137 print(
"\t%d templates of %d samples" % template_bank.shape, file=sys.stderr)
141 if self.singular_values
is not None:
142 self.
sum_of_squares_weights = numpy.sqrt(self.chifacs.mean() * gstlalmisc.ss_coeffs(self.singular_values,snr_thresh))
146 print(
"\tidentified %d components" % self.orthogonal_template_bank.shape[0], file=sys.stderr)
147 print(
"\tsum-of-squares expectation value is %g" % self.chifacs.mean(), file=sys.stderr)
151 def __init__(self, bank_xmldoc, psd, time_slices, gate_fap, snr_threshold, tolerance, flow = 40.0, autocorrelation_length = None, logname = None, identity_transform = False, verbose = False, bank_id = None, fhigh = None):
157 if logname
is not None and not logname:
158 raise ValueError(
"logname cannot be empty if it is set")
164 lsctables.SnglInspiralTable.get_table(bank_xmldoc),
165 read_approximant(bank_xmldoc),
169 autocorrelation_length = autocorrelation_length,
174 sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(bank_xmldoc)
176 self.sngl_inspiral_table.extend(sngl_inspiral_table)
180 self.
newdeltaF = 1. / bank_workspace.working_duration
182 self.
f_low = bank_workspace.f_low
189 print(
"constructing template decomposition %d of %d: %g s ... %g s" % (i + 1, len(self.
bank_fragments), -bank_fragment.end, -bank_fragment.start), file=sys.stderr)
190 bank_fragment.set_template_bank(template_bank[i], tolerance, self.
snr_threshold, identity_transform = identity_transform, verbose = verbose)
192 if bank_fragment.sum_of_squares_weights
is not None:
193 self.
gate_threshold = sum_of_squares_threshold_from_fap(gate_fap, numpy.array([weight**2
for bank_fragment
in self.
bank_fragments for weight
in bank_fragment.sum_of_squares_weights], dtype =
"double"))
197 print(
"sum-of-squares threshold for false-alarm probability of %.16g: %.16g" % (gate_fap, self.
gate_threshold), file=sys.stderr)
200 return set(bank_fragment.rate
for bank_fragment
in self.
bank_fragments)
204 def set_template_bank_filename(self,name):
209 def build_bank(template_bank_url, psd, flow, ortho_gate_fap, snr_threshold, svd_tolerance, padding = 1.5, identity_transform = False, verbose = False, autocorrelation_length = 201, samples_min = 1024, samples_max_256 = 1024, samples_max_64 = 2048, samples_max = 4096, bank_id = None, contenthandler = None, sample_rate = None, instrument_override = None):
211 Return an instance of a Bank class.
213 @param template_bank_url The template bank filename or url containing a subbank of templates to decompose in a single inpsiral table.
214 @param psd A class instance of a psd.
215 @param flow The lower frequency cutoff.
216 @param ortho_gate_fap The FAP threshold for the sum of squares threshold, see http://arxiv.org/abs/1101.0584
217 @param snr_threshold The SNR threshold for the search
218 @param svd_tolerance The target SNR loss of the SVD, see http://arxiv.org/abs/1005.0012
219 @param padding The padding from Nyquist for any template time slice, e.g., if a time slice has a Nyquist of 256 Hz and the padding is set to 2, only allow the template frequency to extend to 128 Hz.
220 @param identity_transform Don't do the SVD, just do time slices and keep the raw waveforms
221 @param verbose Be verbose
222 @param autocorrelation_length The number of autocorrelation samples to use in the chisquared test. Must be odd
223 @param samples_min The minimum number of samples to use in any time slice
224 @param samples_max_256 The maximum number of samples to have in any time slice greater than or equal to 256 Hz
225 @param samples_max_64 The maximum number of samples to have in any time slice greater than or equal to 64 Hz
226 @param samples_max The maximum number of samples in any time slice below 64 Hz
227 @param bank_id The id of the bank in question
228 @param contenthandler The ligolw content handler for file I/O
232 bank_xmldoc = ligolw_utils.load_url(template_bank_url, contenthandler = contenthandler, verbose = verbose)
235 bank_sngl_table = lsctables.SnglInspiralTable.get_table(bank_xmldoc)
238 if instrument_override
is not None:
239 for row
in bank_sngl_table:
240 row.ifo = instrument_override
245 fhigh=check_ffinal_and_find_max_ffinal(bank_xmldoc),
248 samples_min = samples_min,
249 samples_max_256 = samples_max_256,
250 samples_max_64 = samples_max_64,
251 samples_max = samples_max,
252 sample_rate = sample_rate,
255 if sample_rate
is not None:
256 fhigh=check_ffinal_and_find_max_ffinal(bank_xmldoc)
263 psd[bank_sngl_table[0].ifo],
265 gate_fap = ortho_gate_fap,
266 snr_threshold = snr_threshold,
267 tolerance = svd_tolerance,
269 autocorrelation_length = autocorrelation_length,
270 identity_transform = identity_transform,
278 bank.set_template_bank_filename(ligolw_utils.local_path_from_url(template_bank_url))
282 def write_bank(filename, banks, psd_input, cliplefts = None, cliprights = None, verbose = False):
283 """Write SVD banks to a LIGO_LW xml file."""
286 xmldoc = ligolw.Document()
287 lw = xmldoc.appendChild(ligolw.LIGO_LW())
289 for bank, clipleft, clipright
in zip(banks, cliplefts, cliprights):
291 root = lw.appendChild(ligolw.LIGO_LW(Attributes({
u"Name":
u"gstlal_svd_bank_Bank"})))
295 clipright = len(bank.sngl_inspiral_table) - clipright
299 new_sngl_table = bank.sngl_inspiral_table.copy()
300 for row
in bank.sngl_inspiral_table[clipleft:clipright]:
302 row.Gamma1 = int(bank.bank_id.split(
"_")[0])
303 new_sngl_table.append(row)
306 root.appendChild(new_sngl_table)
309 root.appendChild(ligolw_param.Param.from_pyvalue(
'filter_length', bank.filter_length))
310 root.appendChild(ligolw_param.Param.from_pyvalue(
'gate_threshold', bank.gate_threshold))
311 root.appendChild(ligolw_param.Param.from_pyvalue(
'logname', bank.logname
or ""))
312 root.appendChild(ligolw_param.Param.from_pyvalue(
'snr_threshold', bank.snr_threshold))
313 root.appendChild(ligolw_param.Param.from_pyvalue(
'template_bank_filename', bank.template_bank_filename))
314 root.appendChild(ligolw_param.Param.from_pyvalue(
'bank_id', bank.bank_id))
315 root.appendChild(ligolw_param.Param.from_pyvalue(
'new_deltaf', bank.newdeltaF))
316 root.appendChild(ligolw_param.Param.from_pyvalue(
'working_f_low', bank.working_f_low))
317 root.appendChild(ligolw_param.Param.from_pyvalue(
'f_low', bank.f_low))
318 root.appendChild(ligolw_param.Param.from_pyvalue(
'sample_rate_max', int(bank.sample_rate_max)))
319 root.appendChild(ligolw_param.Param.from_pyvalue(
'gstlal_fir_whiten', os.environ[
'GSTLAL_FIR_WHITEN']))
322 bank.autocorrelation_bank = bank.autocorrelation_bank[clipleft:clipright,:]
323 bank.autocorrelation_mask = bank.autocorrelation_mask[clipleft:clipright,:]
324 bank.sigmasq = bank.sigmasq[clipleft:clipright]
328 root.appendChild(ligolw_array.Array.build(
'autocorrelation_bank_real', bank.autocorrelation_bank.real))
329 root.appendChild(ligolw_array.Array.build(
'autocorrelation_bank_imag', bank.autocorrelation_bank.imag))
330 root.appendChild(ligolw_array.Array.build(
'autocorrelation_mask', bank.autocorrelation_mask))
331 root.appendChild(ligolw_array.Array.build(
'sigmasq', numpy.array(bank.sigmasq)))
334 for i, frag
in enumerate(bank.bank_fragments):
336 el = root.appendChild(ligolw.LIGO_LW())
339 if frag.mix_matrix
is not None:
340 frag.mix_matrix = frag.mix_matrix[:,clipleft*2:clipright*2]
341 frag.chifacs = frag.chifacs[clipleft*2:clipright*2]
344 el.appendChild(ligolw_param.Param.from_pyvalue(
'rate', int(frag.rate)))
345 el.appendChild(ligolw_param.Param.from_pyvalue(
'start', frag.start))
346 el.appendChild(ligolw_param.Param.from_pyvalue(
'end', frag.end))
349 el.appendChild(ligolw_array.Array.build(
'chifacs', frag.chifacs))
350 if frag.mix_matrix
is not None:
351 el.appendChild(ligolw_array.Array.build(
'mix_matrix', frag.mix_matrix))
352 el.appendChild(ligolw_array.Array.build(
'orthogonal_template_bank', frag.orthogonal_template_bank))
353 if frag.singular_values
is not None:
354 el.appendChild(ligolw_array.Array.build(
'singular_values', frag.singular_values))
355 if frag.sum_of_squares_weights
is not None:
356 el.appendChild(ligolw_array.Array.build(
'sum_of_squares_weights', frag.sum_of_squares_weights))
361 psd = psd_input[bank.sngl_inspiral_table[0].ifo]
362 lal.series.make_psd_xmldoc({bank.sngl_inspiral_table[0].ifo: psd}, lw)
365 ligolw_utils.write_filename(xmldoc, filename, verbose = verbose)
368 def read_banks(filename, contenthandler, verbose = False):
369 """Read SVD banks from a LIGO_LW xml file."""
372 xmldoc = ligolw_utils.load_url(filename, contenthandler = contenthandler, verbose = verbose)
381 raw_psd = list(lal.series.read_psd_xmldoc(xmldoc).values())[0]
386 for root
in (elem
for elem
in xmldoc.getElementsByTagName(ligolw.LIGO_LW.tagName)
if elem.hasAttribute(
u"Name")
and elem.Name ==
"gstlal_svd_bank_Bank"):
389 bank = Bank.__new__(Bank)
392 bank.sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(root)
393 bank.sngl_inspiral_table.parentNode.removeChild(bank.sngl_inspiral_table)
396 bank.filter_length = ligolw_param.get_pyvalue(root,
'filter_length')
397 bank.gate_threshold = ligolw_param.get_pyvalue(root,
'gate_threshold')
398 bank.logname = ligolw_param.get_pyvalue(root,
'logname')
or None
399 bank.snr_threshold = ligolw_param.get_pyvalue(root,
'snr_threshold')
400 bank.template_bank_filename = ligolw_param.get_pyvalue(root,
'template_bank_filename')
401 bank.bank_id = ligolw_param.get_pyvalue(root,
'bank_id')
404 bank.newdeltaF = ligolw_param.get_pyvalue(root,
'new_deltaf')
405 bank.working_f_low = ligolw_param.get_pyvalue(root,
'working_f_low')
406 bank.f_low = ligolw_param.get_pyvalue(root,
'f_low')
407 bank.sample_rate_max = ligolw_param.get_pyvalue(root,
'sample_rate_max')
412 bank.autocorrelation_bank = ligolw_array.get_array(root,
'autocorrelation_bank_real').array + 1j * ligolw_array.get_array(root,
'autocorrelation_bank_imag').array
413 bank.autocorrelation_mask = ligolw_array.get_array(root,
'autocorrelation_mask').array
414 bank.sigmasq = ligolw_array.get_array(root,
'sigmasq').array
417 bank.horizon_factors = dict((row.template_id, sigmasq**.5)
for row, sigmasq
in zip(bank.sngl_inspiral_table, bank.sigmasq))
419 if raw_psd
is not None:
421 bank.processed_psd =
cbc_template_fir.condition_psd(raw_psd, bank.newdeltaF, minfs = (bank.working_f_low, bank.f_low), maxfs = (bank.sample_rate_max / 2.0 * 0.90, bank.sample_rate_max / 2.0))
424 bank.bank_fragments = []
425 for el
in (node
for node
in root.childNodes
if node.tagName == ligolw.LIGO_LW.tagName):
427 rate = ligolw_param.get_pyvalue(el,
'rate'),
428 start = ligolw_param.get_pyvalue(el,
'start'),
429 end = ligolw_param.get_pyvalue(el,
'end')
433 frag.chifacs = ligolw_array.get_array(el,
'chifacs').array
435 frag.mix_matrix = ligolw_array.get_array(el,
'mix_matrix').array
437 frag.mix_matrix =
None
438 frag.orthogonal_template_bank = ligolw_array.get_array(el,
'orthogonal_template_bank').array
440 frag.singular_values = ligolw_array.get_array(el,
'singular_values').array
442 frag.singular_values =
None
444 frag.sum_of_squares_weights = ligolw_array.get_array(el,
'sum_of_squares_weights').array
446 frag.sum_of_squares_weights =
None
447 bank.bank_fragments.append(frag)
450 template_id, func = horizon_distance_func(banks)
453 if template_id
in bank.horizon_factors:
454 assert horizon_norm
is None
455 horizon_norm = bank.horizon_factors[template_id]
457 bank.horizon_distance_func = func
458 bank.horizon_factors = dict((tid, f / horizon_norm)
for (tid, f)
in bank.horizon_factors.items())
463 def svdbank_templates_mapping(filenames, contenthandler, verbose = False):
465 From a list of the names of files containing SVD bank objects,
466 construct a dictionary mapping filename to list of sngl_inspiral
467 templates in that file. Typically this mapping is inverted through
468 the use of some sort of "template identity" function to map each
469 template to the filename that contains that template.
473 Assuming the (mass1, mass2) tuple is known to uniquely identify the
476 >>> def template_id(row):
477 ... return row.mass1, row.mass2
479 >>> mapping = svdbank_templates_mapping([], DefaultContentHandler)
480 >>> template_to_filename = dict((template_id(tempate), filename) for filename, templates in mapping.items() for template in templates)
483 for n, filename
in enumerate(filenames, start = 1):
485 print(
"%d/%d:" % (n, len(filenames)), file=sys.stderr)
486 mapping[filename] = sum((bank.sngl_inspiral_table
for bank
in read_banks(filename, contenthandler, verbose = verbose)), [])
489 def preferred_horizon_distance_template(banks):
490 template_id, m1, m2, s1z, s2z = min((row.template_id, row.mass1, row.mass2, row.spin1z, row.spin2z)
for bank
in banks
for row
in bank.sngl_inspiral_table)
491 return template_id, m1, m2, s1z, s2z
493 def horizon_distance_func(banks):
495 Takes a dictionary of objects returned by read_banks keyed by instrument
500 nyquists = set((max(bank.get_rates())/2.
for bank
in banks))
501 if len(nyquists) != 1:
502 warnings.warn(
"all banks should have the same Nyquist frequency to define a consistent horizon distance function (got %s)" %
", ".join(
"%g" % rate
for rate
in sorted(nyquists)))
509 template_id, m1, m2, s1z, s2z = preferred_horizon_distance_template(banks)
511 return template_id, reference_psd.HorizonDistance(15.0, 0.85 * max(nyquists), deltaF, m1, m2, spin1 = (0., 0., s1z), spin2 = (0., 0., s2z))
def gstlal_valid_approximant