gstlal-inspiral  1.9.2
 All Classes Namespaces Files Functions
gstlal_inspiral_add_template_ids
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2018 Chad Hanna
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 # # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
12 # Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 
18 ### This program inputs a template bank from lalapps_tmpltbank, and returns
19 ### a template bank with a unique template_id row. Used to overcome the
20 ### "Asserion Error: assert row.template_id not in ids" error from
21 ### gstlal_inspiral_mass_model.
22 
23 import random
24 import sys
25 from ligo.lw import ligolw
26 from ligo.lw import lsctables, param as ligolw_param, array as ligolw_array
27 from ligo.lw import utils as ligolw_utils
28 
29 @ligolw_array.use_in
30 @ligolw_param.use_in
31 @lsctables.use_in
32 class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
33  pass
34 
35 # load all documents. stored as tuple of (name, xmldoc) pairs in the order
36 # provided on the command line
37 
38 documents = [(fname, ligolw_utils.load_filename(fname, verbose = True, contenthandler = LIGOLWContentHandler)) for fname in sys.argv[1:]]
39 
40 # count templates
41 
42 N = sum(len(lsctables.SnglInspiralTable.get_table(xmldoc)) for fname, xmldoc in documents)
43 
44 # generate template IDs by drawing N samples without replacement from the
45 # integers between 1 and some large number. for template bank sizes into
46 # the millions the probability of this process ever producing the same set
47 # of numbers twice is infinitessimally small. but its not 0. we don't let
48 # N get too close to the number of available IDs to keep the probability of
49 # two ID sequences being the same small.
50 
51 assert N < 5000000, "too many templates: increase size of draw space"
52 ids = sorted(random.sample(range(9999999), N))
53 
54 # assign the IDs and write back to disk
55 
56 next_id = iter(ids).__next__
57 for fname, xmldoc in documents:
58  for row in lsctables.SnglInspiralTable.get_table(xmldoc):
59  row.template_id = next_id()
60  ligolw_utils.write_filename(xmldoc, fname, verbose = True)