#!/usr/bin/env python3
#
# Copyright (C) 2018  Chad Hanna
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
# # This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

### This program inputs a template bank from lalapps_tmpltbank, and returns
### a template bank with a unique template_id row. Used to overcome the
### "Asserion Error: assert row.template_id not in ids" error from 
### gstlal_inspiral_mass_model.

import random
import sys
from ligo.lw import ligolw
from ligo.lw import lsctables, param as ligolw_param, array as ligolw_array
from ligo.lw import utils as ligolw_utils

@ligolw_array.use_in
@ligolw_param.use_in
@lsctables.use_in
class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
	pass

# load all documents.  stored as tuple of (name, xmldoc) pairs in the order
# provided on the command line

documents = [(fname, ligolw_utils.load_filename(fname, verbose = True, contenthandler = LIGOLWContentHandler)) for fname in sys.argv[1:]]

# count templates

N = sum(len(lsctables.SnglInspiralTable.get_table(xmldoc)) for fname, xmldoc in documents)

# generate template IDs by drawing N samples without replacement from the
# integers between 1 and some large number.  for template bank sizes into
# the millions the probability of this process ever producing the same set
# of numbers twice is infinitessimally small.  but its not 0.  we don't let
# N get too close to the number of available IDs to keep the probability of
# two ID sequences being the same small.

assert N < 5000000, "too many templates:  increase size of draw space"
ids = sorted(random.sample(range(9999999), N))

# assign the IDs and write back to disk

next_id = iter(ids).__next__
for fname, xmldoc in documents:
	for row in lsctables.SnglInspiralTable.get_table(xmldoc):
		row.template_id = next_id()
	ligolw_utils.write_filename(xmldoc, fname, verbose = True)
