#!python

# Copyright (C) 2011 Ian W. 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.

"""
Read in a tmpltbank and create a file containing the list of chi parameters
"""

import pycbc
import pycbc.version

__author__ = "Ian Harry <ian.harry@astro.cf.ac.uk>"
__version__ = pycbc.version.git_verbose_msg
__date__ = pycbc.version.date
__program__ = "pycbc_bank_verification"

import argparse
import logging

import numpy
from igwn_ligolw import lsctables
from igwn_ligolw import utils as ligolw_utils

from pycbc import psd, strain, tmpltbank
from pycbc.io.hdf import HFile
from pycbc.io.ligolw import LIGOLWContentHandler

logger = logging.getLogger(__name__)

# Read command line option
parser = argparse.ArgumentParser(
    description=__doc__, formatter_class=tmpltbank.IndentedHelpFormatterWithNL
)

# Begin with code specific options
pycbc.add_common_pycbc_options(parser)
parser.add_argument(
    "--input-bank",
    action="store",
    required=True,
    help="The template bank to use an input.",
)
parser.add_argument(
    "--output-file",
    action="store",
    required=True,
    help="The ASCII file to create as output. The columns in "
    "this file will hold: mass1, mass2, spin1z, spin2z, chi_1, "
    "chi_2, ....",
)
parser.add_argument(
    "--random-seed",
    action="store",
    type=int,
    default=None,
    help="Random seed to use when calling numpy.random "
    "functions used in obtaining the principal components in "
    "parameter space and when translating points back to "
    "physical space.  If given, the code should give the "
    "same output when run with the same random seed.",
)

# Insert the metric calculation options
tmpltbank.insert_metric_calculation_options(parser)

# Insert the mass range options
tmpltbank.insert_mass_range_option_group(parser)

# Insert the PSD options
pycbc.psd.insert_psd_option_group(parser)

# Insert the data reading options
pycbc.strain.insert_strain_option_group(parser)

opts = parser.parse_args()

pycbc.init_logging(opts.verbose)

# Sanity check options
tmpltbank.verify_metric_calculation_options(opts, parser)
metric_params = tmpltbank.MetricParameters.from_argparse(opts)
tmpltbank.verify_mass_range_options(opts, parser)
mass_range_params = tmpltbank.MassRangeParameters.from_argparse(opts)
psd.verify_psd_options(opts, parser)
if opts.psd_estimation:
    pycbc.strain.verify_strain_options(opts, parser)

# Set random seed if needed
if opts.random_seed is not None:
    numpy.random.seed(opts.random_seed)

# If we are going to use h(t) to estimate a PSD we need h(t)
if opts.psd_estimation:
    logger.info("Obtaining h(t) for PSD generation")
    strain = pycbc.strain.from_cli(opts, pycbc.DYN_RANGE_FAC)
else:
    strain = None

# Get the PSD using the pycbc interface
logger.info("Obtaining PSD")
# Want the number of samples to be a binary number and Nyquist must be above
# opts.f_upper. All this assumes that 1 / delta_f is a binary number
nyquist_freq = 2 ** numpy.ceil(numpy.log2(opts.f_upper))
num_samples = int(round(nyquist_freq / opts.delta_f)) + 1
psd = pycbc.psd.from_cli(
    opts,
    length=num_samples,
    delta_f=opts.delta_f,
    low_frequency_cutoff=opts.f_low,
    strain=strain,
    dyn_range_factor=pycbc.DYN_RANGE_FAC,
)
metric_params.psd = psd

# Begin by calculating a metric
logger.info("Calculating metric")
metric_params = tmpltbank.determine_eigen_directions(
    metric_params, vary_fmax=False, vary_density=None
)

# Choose the frequency values to use for metric calculation
ref_freq = metric_params.f_upper

logger.info("Calculating covariance matrix")

vals = tmpltbank.estimate_mass_range(
    1000000, mass_range_params, metric_params, ref_freq, covary=False
)
cov = numpy.cov(vals)
evals_cv, evecs_cv = numpy.linalg.eig(cov)
metric_params.evecs_cv = {}
metric_params.evecs_cv[ref_freq] = evecs_cv

logger.info("Reading template bank.")
if opts.input_bank.endswith((".xml", ".xml.gz", ".xmlgz")):
    indoc = ligolw_utils.load_filename(
        opts.input_bank, contenthandler=LIGOLWContentHandler
    )
    template_list = lsctables.SnglInspiralTable.get_table(indoc)
    mass1 = [template.mass1 for template in template_list]
    mass2 = [template.mass2 for template in template_list]
    spin1z = [template.spin1z for template in template_list]
    spin2z = [template.spin2z for template in template_list]
elif opts.input_bank.endswith((".h5", ".hdf", ".hdf5")):
    h5_fp = HFile(opts.input_bank, "r")
    mass1 = h5_fp["mass1"][:]
    mass2 = h5_fp["mass2"][:]
    spin1z = h5_fp["spin1z"][:]
    spin2z = h5_fp["spin2z"][:]
else:
    err_msg = f"Don't know how to read extension {opts.input_bank}."
    raise NotImplementedError(err_msg)

with open(opts.output_file, "w") as fp:
    for idx in range(len(mass1)):
        chi_coords = tmpltbank.get_cov_params(
            mass1[idx], mass2[idx], spin1z[idx], spin2z[idx], metric_params, ref_freq
        )
        vals = " ".join(
            [str(mass1[idx]), str(mass2[idx]), str(spin1z[idx]), str(spin2z[idx])]
        )
        vals += " "
        vals += " ".join([str(i) for i in chi_coords])
        fp.write(f"{vals}\n")
