#!/usr/bin/env 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.

"""
Test that a template bank covers a provided parameter space using a provided
metric approximation to the parameter space.
"""

import argparse
import logging

import matplotlib
import numpy

matplotlib.use("Agg")
from igwn_ligolw import lsctables
from igwn_ligolw import utils as ligolw_utils
from matplotlib import pyplot as plt

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

logger = logging.getLogger(__name__)

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


# 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(
    "--histogram-output-file",
    action="store",
    default=None,
    help="Output a histogram of fitting factors to the "
    "supplied file. If not given no histogram is produced.",
)
parser.add_argument(
    "--print-distances",
    action="store_true",
    default=False,
    help="Print details about the match of each point.",
)
parser.add_argument(
    "-B",
    "--input-bank",
    action="store",
    required=True,
    help="The template bank to use an input.",
)
parser.add_argument(
    "-V",
    "--vary-fupper",
    action="store_true",
    default=False,
    help="Use a variable upper frequency cutoff in laying out the bank.  OPTIONAL.",
)
parser.add_argument(
    "--bank-fupper-step",
    type=float,
    default=10.0,
    help="Size of discrete frequency steps used when varying "
    "the fupper. This option will do "
    "nothing if the --vary-fupper flag is not given. "
    "OPTIONAL, default=10. Units=Hz",
)
parser.add_argument(
    "--bank-fupper-formula",
    default="SchwarzISCO",
    choices=["SchwarzISCO", "LightRing", "ERD"],
    help="Frequency cutoff formula for varying fupper. "
    "Frequencies will be rounded to the nearest discrete "
    "step. This option will do nothing if --vary-fupper is "
    "not given. OPTIONAL, default='SchwarzISCO'.",
)
parser.add_argument(
    "-N",
    "--num-points",
    action="store",
    type=int,
    default=100000,
    help="Number of points used to test ",
)
parser.add_argument(
    "-P",
    "--point-file",
    action="store",
    default=None,
    help="List of points to test bank against. Should be a "
    "space-separated ASCII file where the columns correspond "
    "to mass1, mass2, spin1z and spin2z respectively.",
)
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.",
)
parser.add_argument(
    "--bin-spacing",
    action="store",
    type=float,
    default=0.03,
    help="When read in, the template bank is placed into 2D "
    "bins according to the points' location in the 'natural' "
    "xi coordinate system. When computing matches points are "
    "only compared against points in their own bin and "
    "neighbouring bins. This argument specifies, in terms of "
    "mismatch, the width of these bins. Note that metric "
    "distance is proportional to the square root of the "
    "mismatch.",
)

# 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=opts.vary_fupper, vary_density=opts.bank_fupper_step
)

# Choose the frequency values to use for metric calculation
if not opts.vary_fupper:
    ref_freq = metric_params.f_upper
else:
    # determine upper frequency cutoffs corresponding to the min and max
    # total masses
    fs = numpy.array(list(metric_params.evals.keys()), dtype=float)
    fs.sort()
    low_eve, high_eve = tmpltbank.find_max_and_min_frequencies(
        opts.bank_fupper_formula, mass_range_params, fs
    )
    ref_freq = low_eve
    fs = fs[fs >= low_eve]
    fs = fs[fs <= high_eve]

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

# Initialize the class for generating the partitioned bank
logger.info("Initialize the PartitionedTmpltbank class")

partitioned_bank_object = tmpltbank.PartitionedTmpltbank(
    mass_range_params,
    metric_params,
    ref_freq,
    (opts.bin_spacing) ** 0.5,
    bin_range_check=1,
)

# Map the frequency values to idx if --vary-fupper is used
if opts.vary_fupper:
    partitioned_bank_object.get_freq_map_and_normalizations(
        fs, opts.bank_fupper_formula
    )

# Reading in the template bank
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)

    partitioned_bank_object.add_tmpltbank_from_xml_table(
        template_list, vary_fupper=opts.vary_fupper
    )

elif opts.input_bank.endswith((".h5", ".hdf", ".hdf5")):
    h5_fp = HFile(opts.input_bank, "r")
    partitioned_bank_object.add_tmpltbank_from_hdf_file(
        h5_fp, vary_fupper=opts.vary_fupper
    )
else:
    err_msg = f"Don't know how to read extension {opts.input_bank}."
    raise NotImplementedError(err_msg)

logger.info("Bank read in and sorted")
# Okay, now lets test a bunch of matches
points_mass1 = []
points_mass2 = []
points_spin1z = []
points_spin2z = []
points_xis = []
points_fittingfactor = []
points_closestidxes = []
outbins = [[0, 0], [0, 1], [1, 0], [0, -1], [-1, 0], [1, 1], [1, -1], [-1, 1], [-1, -1]]

if opts.point_file:
    temp_data = numpy.loadtxt(opts.point_file)
    r_mass1 = temp_data[:, 0]
    r_mass2 = temp_data[:, 1]
    r_spin1z = temp_data[:, 2]
    r_spin2z = temp_data[:, 3]
    opts.num_points = len(r_mass1)
else:
    r_mass1, r_mass2, r_spin1z, r_spin2z = tmpltbank.get_random_mass(
        100000, mass_range_params
    )

if opts.vary_fupper:
    mass_dict = {}
    mass_dict["m1"] = r_mass1
    mass_dict["m2"] = r_mass2
    mass_dict["s1z"] = r_spin1z
    mass_dict["s2z"] = r_spin2z
    ref_eve = tmpltbank.return_nearest_cutoff(opts.bank_fupper_formula, mass_dict, fs)
    lambdas = tmpltbank.get_chirp_params(
        r_mass1, r_mass2, r_spin1z, r_spin2z, metric_params.f0, metric_params.pn_order
    )
    mus = []
    for freq in fs:
        if freq >= low_eve and freq <= high_eve:
            mus.append(tmpltbank.get_mu_params(lambdas, metric_params, freq))
    mus = numpy.array(mus)
else:
    ref_eve = numpy.zeros(100000)
    mus = numpy.zeros([1, 1, 100000])
vecs = tmpltbank.get_cov_params(
    r_mass1, r_mass2, r_spin1z, r_spin2z, metric_params, ref_freq
)
vecs = numpy.array(vecs)

for idx_curr in range(opts.num_points):
    vs = vecs[:, idx_curr]
    if opts.vary_fupper:
        min_mismatch, idxes = partitioned_bank_object.calc_point_distance_vary(
            vs, ref_eve[idx_curr], mus[:, :, idx_curr]
        )
    else:
        min_mismatch, idxes = partitioned_bank_object.calc_point_distance(vs)

    # Store the data
    points_mass1.append(r_mass1[idx_curr])
    points_mass2.append(r_mass2[idx_curr])
    points_spin1z.append(r_spin1z[idx_curr])
    points_spin2z.append(r_spin2z[idx_curr])
    points_xis.append(vs)
    min_mismatch = min(min_mismatch, 1)
    points_fittingfactor.append(1 - min_mismatch)
    points_closestidxes.append(idxes)

# Convert to numpy arrays
points_mass1 = numpy.array(points_mass1)
points_mass2 = numpy.array(points_mass2)
points_spin1z = numpy.array(points_spin1z)
points_spin2z = numpy.array(points_spin2z)
points_fittingfactor = numpy.array(points_fittingfactor)

logger.info("Distances calculated.")

if opts.histogram_output_file:
    plt.hist(points_fittingfactor, 100)
    plt.xlabel("Fitting factor")
    plt.ylabel("# of signals")
    plt.savefig(opts.histogram_output_file)

if opts.print_distances:
    print()  # noqa: T201
    for idx in range(len(points_mass1)):
        print("The test point with the following parameters (m1,m2,S1z,S2z)")  # noqa: T201
        print(  # noqa: T201
            f"{points_mass1[idx]:e} {points_mass2[idx]:e} {points_spin1z[idx]:e} "
            f"{points_spin2z[idx]:e}"
        )
        print(f"Was recovered with an overlap of {points_fittingfactor[idx]:e}")  # noqa: T201
        if points_closestidxes[idx] is None:
            print("No template was within a metric distance of 1.\n")  # noqa: T201
            continue
        print("The point in the bank with this overlap had (m1,m2,S1z,S2z)")  # noqa: T201
        curr_m1, curr_m2, curr_spin1, curr_spin2 = (
            partitioned_bank_object.get_point_from_bins_and_idx(
                points_closestidxes[idx][0],
                points_closestidxes[idx][1],
                points_closestidxes[idx][2],
            )
        )
        print(f"{curr_m1:e} {curr_m2:e} {curr_spin1:e} {curr_spin2:e}\n")  # noqa: T201
