#!/usr/bin/env python

# Copyright (C) 2013 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.

"""
Template bank generator for placing a bank of non-spinning templates.
"""

import argparse
import copy
import logging
import math

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
import pycbc.version
from pycbc import pnutils, tmpltbank

logger = logging.getLogger(__name__)

__author__ = "Ian Harry <ian.harry@ligo.org>"
__version__ = pycbc.version.git_verbose_msg
__date__ = pycbc.version.date
__program__ = "pycbc_geom_nonspinbank"

# Read command line options
_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(
    "--random-seed",
    action="store",
    type=int,
    default=None,
    help="""Random seed to use when calling numpy.random
                            functions used in obtaining the principal
                            components 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, non_spin=True)

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

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, non_spin=True)
mass_range_params = tmpltbank.MassRangeParameters.from_argparse(opts, non_spin=True)
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")
# FIXME: Revisit the following!
# 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

logger.info("Calculating metric")

# Begin by calculating a metric
metric_params = tmpltbank.determine_eigen_directions(metric_params)

# This is used to calculate evals_cv and evecs_cv with describe the rotations
# needed to move into the principal component directions. evals_cv will be 1s.
logger.info("Calculating covariance matrix")

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


logger.info("Estimating extent of parameter space")

# This is to get an estimate of the largest values of \chi1 and \chi2
vals = tmpltbank.estimate_mass_range(
    5000000, mass_range_params, metric_params, metric_params.f_upper, covary=True
)

chi1_max = vals[0].max()
chi1_min = vals[0].min()
chi1_diff = chi1_max - chi1_min
chi2_max = vals[1].max()
chi2_min = vals[1].min()
chi2_diff = chi2_max - chi2_min

# Generate a lattice of points in \chi1 \chi2 coordinates
logger.info("Calculating lattice")

# When placing the lattice we transition from 1D lattice to a hexagonal
# lattice and then back to 1D lattice
# Assume that once 2D is needed it will be needed until the end.
# Ie. We have 1D region then 2D region then 1D region. Nothing else
# Length of the 1D region can be 0

# We start by figuring out the 1D lattice regions and placing these 1D lattices
# Start from the start going forward.

lower_1d_boundary = None
spacing_1d = opts.max_mismatch**0.5 * 2
v1s = []
v2s = []
for i in range(100):
    temp_chi1_lower = chi1_min + i * chi1_diff / 100.0
    temp_chi1_upper = chi1_min + (i + 1) * chi1_diff / 100.0
    lgc = (vals[0] > temp_chi1_lower) & (vals[0] < temp_chi1_upper)
    temp_chi1 = vals[0][lgc]
    temp_chi2 = vals[1][lgc]
    temp_chi2_max = temp_chi2.max()
    temp_chi2_min = temp_chi2.min()
    if (temp_chi2_max - temp_chi2_min) < 0.2:
        # 1D lattice through here
        chi2_loc = (temp_chi2_max + temp_chi2_min) / 2.0
        curr_iter = 0
        start_point = chi1_min - 0.02 * chi1_diff
        while 1:
            curr_chi1 = start_point + curr_iter * spacing_1d
            if (curr_chi1 < temp_chi1_lower) and (i != 0):
                curr_iter = curr_iter + 1
                continue
            elif (
                (curr_chi1 > temp_chi1_upper) and (i != 99)
            ) or curr_chi1 > temp_chi1_upper + 0.02 * chi1_diff:
                break
            v1s.append(curr_chi1)
            v2s.append(chi2_loc)
            curr_iter = curr_iter + 1
    else:
        # Now we need 2D lattice
        lower_1d_boundary = i
        break

# Next we start from the end and work backwards
for i in range(99, -1, -1):
    # Only need to do this if there is a lower boundary
    if lower_1d_boundary is None:
        break
    # FIXME: Move this to a function, duplicated above!
    # FIXME: Maybe move all this to a generate_NS_lattice function
    temp_chi1_lower = chi1_min + i * chi1_diff / 100.0
    temp_chi1_upper = chi1_min + (i + 1) * chi1_diff / 100.0
    lgc = (vals[0] > temp_chi1_lower) & (vals[0] < temp_chi1_upper)
    temp_chi1 = vals[0][lgc]
    temp_chi2 = vals[1][lgc]
    temp_chi2_max = temp_chi2.max()
    temp_chi2_min = temp_chi2.min()
    if (temp_chi2_max - temp_chi2_min) < 0.2:
        # 1D lattice through here
        chi2_loc = (temp_chi2_max + temp_chi2_min) / 2.0
        curr_iter = 0
        start_point = chi1_min - 0.02 * chi1_diff
        while 1:
            curr_chi1 = start_point + curr_iter * spacing_1d
            if (curr_chi1 < temp_chi1_lower) and (i != 0):
                curr_iter = curr_iter + 1
                continue
            elif (
                (curr_chi1 > temp_chi1_upper) and (i != 99)
            ) or curr_chi1 > temp_chi1_upper + 0.02 * chi1_diff:
                break
            v1s.append(curr_chi1)
            v2s.append(chi2_loc)
            curr_iter = curr_iter + 1
    else:
        # Now we need 2D lattice
        upper_1d_boundary = i + 1
        break

# Anything left is covered with a 2D hexagonal array
if lower_1d_boundary is not None:
    # Need some 2D parts in the bank
    if lower_1d_boundary == 0:
        lower_chi1 = chi1_min - 0.02 * chi1_diff
    else:
        lower_chi1 = chi1_min + lower_1d_boundary * chi1_diff / 100.0
    if upper_1d_boundary == 100:
        upper_chi1 = chi1_max + 0.02 * chi1_diff
    else:
        upper_chi1 = chi1_min + upper_1d_boundary * chi1_diff / 100.0
    tempv1s, tempv2s = tmpltbank.generate_hexagonal_lattice(
        upper_chi1,
        lower_chi1,
        chi2_max + 0.02 * chi2_diff,
        chi2_min - 0.02 * chi2_diff,
        opts.max_mismatch,
    )
    v1s.extend(tempv1s)
    v2s.extend(tempv2s)

v1s = numpy.array(v1s)
v2s = numpy.array(v2s)

logger.info("%d points in the lattice", len(v1s))

# What follows is used to
#   1) Check if the points are close to the physical space, if not reject
#   2) If the point is *within* the physical space find a physical point that
#      matches the position.
#   3) If the point is "close" to the physical space find a "close" physical
#      point within the allowed range. Close means within the specified
#      minimal mismatch.

# FIXME: Most of this should probably move to a function in pycbc.tmpltbank

# Choose an initial set of points to begin comparing points to physical space
r_mass1, r_mass2, r_spin1z, r_spin2z = tmpltbank.get_random_mass(
    2000000, mass_range_params
)
r_totmass, r_eta = pnutils.mass1_mass2_to_mtotal_eta(r_mass1, r_mass2)
# Here we have a set of m1s,m2s and mapped to Xis below
r_xis = tmpltbank.get_cov_params(
    r_mass1, r_mass2, r_spin1z, r_spin2z, metric_params, metric_params.f_upper
)

xis = (numpy.array(r_xis)).T
phys_masses = numpy.array([r_totmass, r_eta, r_spin1z, r_spin2z])
phys_masses = phys_masses.T

# Sort the xis for easy access
v1smin = v1s.min()
v1smax = v1s.max()
v1sdiff = v1smax - v1smin
numv1bins = int(math.ceil(v1sdiff / 1.0))
v2smin = v2s.min()
v2smax = v2s.max()
v2sdiff = v2smax - v2smin
numv2bins = int(math.ceil(v2sdiff / 1.0))

sorted_bins = {}

logger.info("Sorting guide points")

bin_size = (opts.max_mismatch) ** 0.5 * 6.0

for iter, curr_xi in enumerate(xis):
    xi1 = curr_xi[0]
    xi2 = curr_xi[1]
    x1bin = int((xi1 - v1smin) / bin_size)
    x2bin = int((xi2 - v2smin) / bin_size)
    if x1bin not in sorted_bins:
        sorted_bins[x1bin] = {}
    if x2bin not in sorted_bins[x1bin]:
        sorted_bins[x1bin][x2bin] = []
    if len(sorted_bins[x1bin][x2bin]) < 100:
        sorted_bins[x1bin][x2bin].append((iter, xi1, xi2))

logger.info("Converting to physical points")

# Now we start looping through all the points and either accept it, with a
# physical representation *or* accept it nudged toward the physical space
# *or* reject it if it is outside the physically allowed region.

temp_bank = []
temp_number = 0
req_match = 0.0001
for v1, v2 in zip(v1s, v2s, strict=True):
    # First check if point is within the physical space
    # and find some example nearby physical points if it is.
    v1bin = int((v1 - v1smin) / bin_size)
    v2bin = int((v2 - v2smin) / bin_size)
    phys_bin = None
    for i in [v1bin, v1bin + 1, v1bin - 1]:
        if i not in sorted_bins:
            continue
        for j in [v2bin, v2bin + 1, v2bin - 1]:
            if j not in sorted_bins[i]:
                continue
            phys_bin = [i, j]
            points = numpy.array(sorted_bins[phys_bin[0]][phys_bin[1]])
            dist = (v1 - points[:, 1]) ** 2 + (v2 - points[:, 2]) ** 2
            break
        if phys_bin:
            break
    else:
        # No nearby physical points found: continue
        continue
    iters = points[:, 0]
    best_xis = points[dist.argmin(), 1:]
    best_masses = phys_masses[int(points[dist.argmin(), 0] + 0.5)]

    # Reject point if it is too far from physical space
    masses = tmpltbank.get_physical_covaried_masses(
        [v1, v2],
        copy.deepcopy(best_masses),
        copy.deepcopy(best_xis),
        req_match,
        mass_range_params,
        metric_params,
        metric_params.f_upper,
        give_up_thresh=20,
    )

    # If point is still not close enough to desired space, remove it
    if masses[5] > opts.max_mismatch:
        continue
    # Add the two masses (masses[0],masses[1]) to the list. For consistency
    # we also add spin1z and spin2z (masses[2] and masses[3]) but here these
    # will always be 0.

    temp_bank.append([masses[0], masses[1], masses[2], masses[3]])

logger.info("Writing output to file %s", opts.output_file)

bank_output.output_bank_to_file(
    opts.output_file, temp_bank, program_name=__program__, opt_dict=opts.__dict__
)

logger.info("Done")
