#!python

# Copyright (C) 2019 Ian Harry
#
# 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 3 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.

"""
Reduce a template bank using some input parameter cuts
"""

import argparse
import logging

import pycbc
from pycbc import load_source
from pycbc.io import HFile

logger = logging.getLogger(__name__)

parser = argparse.ArgumentParser(description=__doc__)
pycbc.add_common_pycbc_options(parser)
parser.add_argument("--input-bank", required=True, help="Input template bank HDF file.")
parser.add_argument(
    "--output-bank", required=True, help="Output template bank HDF file."
)
parser.add_argument(
    "--filter-func-file",
    required=True,
    help="This can be provided to give a function to define "
    "which points are covered by the template bank "
    "bounds, and which are not. The file should contain "
    "a function called filter_tmpltbank, which should "
    "take as call profile the template bank HDF object "
    "and return a boolean (accept=1/reject=0) array.",
)


opt = parser.parse_args()
pycbc.init_logging(opt.verbose)

bank_fd = HFile(opt.input_bank, "r")

modl = load_source("filter_func", opt.filter_func_file)
func = modl.filter_tmpltbank
bool_arr = func(bank_fd)

logger.info(
    "Downselecting templates. Started with %s templates, now have %s "
    "after downselecting.",
    len(bool_arr),
    bool_arr.sum(),
)
bank_ofd = HFile(opt.output_bank, "w")
for name in bank_fd:
    bank_ofd[name] = bank_fd[name][:][bool_arr]
bank_ofd.close()
