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

"""
Stochastic aligned spin bank generator.
"""

import argparse
import logging

import numpy

import pycbc
import pycbc.psd
import pycbc.strain

# Old ligolw output functions no longer imported at package level
import pycbc.tmpltbank.bank_output_utils as bank_output
from pycbc import tmpltbank
from pycbc.pnutils import named_frequency_cutoffs
from pycbc.types import positive_float

logger = logging.getLogger(__name__)

# Read command line option
_desc = __doc__[1:]
parser = argparse.ArgumentParser(
    description=_desc, formatter_class=tmpltbank.IndentedHelpFormatterWithNL
)

# Begin with code specific options
pycbc.add_common_pycbc_options(parser)
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=positive_float,
    default=10.0,
    help="Size of discrete frequency steps used when varying "
    "the fupper. OPTIONAL. Units=Hz",
)
parser.add_argument(
    "--bank-fupper-formula",
    default="SchwarzISCO",
    choices=named_frequency_cutoffs.keys(),
    help="Frequency cutoff formula for varying fupper. "
    "Frequencies will be rounded to the nearest discrete "
    "step. OPTIONAL.",
)
parser.add_argument(
    "-N",
    "--num-seeds",
    action="store",
    type=int,
    default=5000000,
    help="Number of seed points used in bank construction.  OPTIONAL.",
)
parser.add_argument(
    "-n",
    "--num-failed-cutoff",
    action="store",
    type=int,
    default=1000000000,
    help="Maximum number of consecutive, not-accepted test "
    "points after which bank generation will be stopped.  "
    "OPTIONAL.  Default value is really large as --num-seeds"
    " is intended to provide the termination condition.",
)
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.",
)

tmpltbank.insert_base_bank_options(parser)

# 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)

# delete defaults for redundant options if not varying fupper
if not opts.vary_fupper:
    opts.bank_fupper_step = None
    opts.bank_fupper_formula = None
opts.max_mismatch = 1 - opts.min_match
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)
pycbc.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 if opts.vary_fupper else None,
)

logger.info("Identifying limits of frequency")

# 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)
evecs_cv_dict = {}
evecs_cv_dict[ref_freq] = evecs_cv
metric_params.evecs_cv = evecs_cv_dict

logger.info("Initialize the PartitionedTmpltbank class")

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

# Initialise counters
N = 0
Np = 0
Ns = 0
Nr = 0

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

logger.info("Starting bank placement")

while True:
    if not (Ns % 100000):
        # For optimization we generate points in sets of 100000
        r_mass1, r_mass2, r_spin1z, r_spin2z = tmpltbank.get_random_mass(
            100000, mass_range_params
        )
        if opts.vary_fupper:
            mass_dict = {
                "mass1": r_mass1,
                "mass2": r_mass2,
                "spin1z": r_spin1z,
                "spin2z": 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 = [tmpltbank.get_mu_params(lambdas, metric_params, freq) for freq in fs]
            mus = numpy.array(mus)
        vecs = tmpltbank.get_cov_params(
            r_mass1, r_mass2, r_spin1z, r_spin2z, metric_params, ref_freq
        )
        vecs = numpy.array(vecs)
        Ns = 0
    # Then we check each point for acceptance
    if not (Np % 100000):
        logger.info("%d seeds", Np)
    vs = vecs[:, Ns]
    Np = Np + 1
    # Stop if we hit break condition
    if Np > opts.num_seeds:
        break
    # Calculate if any existing point is too close (set store to False)
    if opts.vary_fupper:
        reject = partitioned_bank_object.test_point_distance_vary(
            vs, ref_eve[Ns], mus[:, :, Ns], opts.max_mismatch
        )
    else:
        reject = partitioned_bank_object.test_point_distance(vs, opts.max_mismatch)
    # Increment counters, check for break condition and continue if rejected
    if reject:
        Ns = Ns + 1
        Nr = Nr + 1
        if Nr > opts.num_failed_cutoff:
            break
        continue
    # Add point, increment counters and continue if accepted
    Nr = 0
    if opts.vary_fupper:
        curr_mus = mus[:, :, Ns]
        point_fupper = ref_eve[Ns]
    else:
        curr_mus = None
        point_fupper = None
    partitioned_bank_object.add_point_by_chi_coords(
        vs,
        r_mass1[Ns],
        r_mass2[Ns],
        r_spin1z[Ns],
        r_spin2z[Ns],
        point_fupper=point_fupper,
        mus=curr_mus,
    )
    N = N + 1
    if not (N % 100000):
        logger.info("%d templates", N)
    Ns = Ns + 1

logger.info("Outputting bank")

# Put the whole template bank in one list
mass1, mass2, spin1z, spin2z = partitioned_bank_object.output_all_points()
temp_bank = zip(mass1, mass2, spin1z, spin2z, strict=True)

# Output to file
bank_output.output_bank_to_file(
    opts.output_file,
    temp_bank,
    program_name="pycbc_aligned_stoch_bank",
    opt_dict=opts.__dict__,
)

logger.info("Done")
