#!/usr/bin/env python

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

"""
Aligned spin bank generator. Initial placement of template points, and
rejection of "too far away" templates is done in the code, but the final
translation between points in the chirp parameters parameter space is done
in a workflow.
"""

import argparse
import copy
import logging

import numpy
from igwn_ligolw import ligolw
from igwn_ligolw import utils as ligolw_utils
from scipy import spatial

import pycbc
import pycbc.psd
import pycbc.strain
import pycbc.tmpltbank
import pycbc.version
from pycbc.io import HFile
from pycbc.io.ligolw import create_process_table

logger = logging.getLogger(__name__)

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

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

# Begin with code specific options
pycbc.add_common_pycbc_options(parser)
parser.add_argument(
    "-s",
    "--stack-distance",
    action="store",
    type=float,
    default=0.2,
    help="Minimum metric spacing before we " + "stack.",
)
parser.add_argument(
    "-3",
    "--threed-lattice",
    action="store_true",
    default=False,
    help="Set this to use a 3D lattice. " + "OPTIONAL",
)
parser.add_argument(
    "-S",
    "--num-split-jobs",
    action="store",
    type=int,
    default=100,
    help="Number of parallel jobs to split the bank into. " + "OPTIONAL",
)
parser.add_argument(
    "-F",
    "--filter-points",
    action="store_true",
    default=False,
    help="Remove nearby points before generating the bank.",
)
parser.add_argument(
    "--random-seed",
    action="store",
    type=int,
    default=None,
    help="""Random seed to use whenever the numpy random
                            functions are called when doing the monte-carlo
                            for obtaining the principal components and when
                            translating all points back to physical space.
                            If this is used the code should give the same
                            output if run with the same random seed.""",
)
parser.add_argument(
    "--print-chi-points",
    action="store",
    default=None,
    metavar="FILENAME",
    help="Add a node to print off an ASCII list of mass "
    "parameters and corresponding location in the xi space "
    "using pycbc_tmpltbank_to_chi_params. This will be "
    "written to FILENAME. If this argument is not given, no "
    "chi points file will be written.",
)
parser.add_argument(
    "--metadata-file",
    type=str,
    required=True,
    help="Location of the output file containing the metadata "
    "that will be added to the final XML file.",
)
parser.add_argument(
    "--storage-path-base",
    default=None,
    help="If running this code as a sub-workflow then this "
    "path is pretended to all storage directories.",
)
parser.add_argument(
    "--supplement-config-file",
    action="append",
    help="This can be used to add additional options to those "
    "that this code will supply. If there are conflicts the "
    "code will fail. Can be supplied multiple times.",
)

pycbc.tmpltbank.insert_base_bank_options(parser)

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

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

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

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

# Workflow options


opts = parser.parse_args()
# Going to need this for setting up the dag later
orig_opts = copy.deepcopy(opts)

# Set up the process/process_params table and output xml document
outdoc = ligolw.Document()
outdoc.appendChild(ligolw.LIGO_LW())
create_process_table(outdoc, __program__, options=vars(opts))
ligolw_utils.write_filename(outdoc, opts.metadata_file)

pycbc.init_logging(opts.verbose)

opts.max_mismatch = 1 - opts.min_match

pycbc.tmpltbank.verify_metric_calculation_options(opts, parser)
metric_params = pycbc.tmpltbank.MetricParameters.from_argparse(opts)
pycbc.tmpltbank.verify_mass_range_options(opts, parser)
mass_range_params = pycbc.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:
    # FIXME: It would be nice if this was similar to psd.from_cli()
    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 = pycbc.tmpltbank.determine_eigen_directions(metric_params)

logger.info("Calculating covariance matrix")

vals = pycbc.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("Determining parameter space extent")

vals = pycbc.tmpltbank.estimate_mass_range(
    1000000, 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

logger.info("Calculating lattice")

if not opts.threed_lattice:
    v1s, v2s = pycbc.tmpltbank.generate_hexagonal_lattice(
        chi1_max + (0.02 * chi1_diff),
        chi1_min - (0.02 * chi1_diff),
        chi2_max + (0.02 * chi2_diff),
        chi2_min - (0.02 * chi2_diff),
        opts.max_mismatch,
    )
else:
    chi3_max = vals[2].max()
    chi3_min = vals[2].min()
    chi3_diff = chi3_max - chi3_min
    v1s, v2s, v3s = pycbc.tmpltbank.generate_anstar_3d_lattice(
        chi1_max + (0.02 * chi1_diff),
        chi1_min - (0.02 * chi1_diff),
        chi2_max + (0.02 * chi2_diff),
        chi2_min - (0.02 * chi2_diff),
        chi3_max + (0.02 * chi3_diff),
        chi3_min - (0.02 * chi3_diff),
        opts.max_mismatch,
    )
    chi3_max = vals[2].max()
    chi3_min = vals[2].min()
    chi3_diff = chi3_max - chi3_min

logger.info("Lattice contains %d points", len(v1s))

# Now remove points that are too far from edges of parameter space

if opts.filter_points:
    logger.info("Removing lattice points too far from physical space.")
    # Create a large set of points and map to xi_i to give a starting point when
    # mapping from xi_i to masses and spins
    # Use the EM constraint only if asked to do so
    r_mass1, r_mass2, r_spin1z, r_spin2z = pycbc.tmpltbank.get_random_mass(
        2000000, mass_range_params
    )

    r_xis = pycbc.tmpltbank.get_cov_params(
        r_mass1, r_mass2, r_spin1z, r_spin2z, metric_params, metric_params.f_upper
    )

    xis = (numpy.array(r_xis)).T
    f0 = opts.f0
    order = opts.pn_order
    maxmass1 = opts.max_mass1
    maxmass2 = opts.max_mass2
    minmass1 = opts.min_mass1
    minmass2 = opts.min_mass2
    max_ns_spin = opts.max_ns_spin_mag
    max_bh_spin = opts.max_bh_spin_mag

    new_v1s = []
    new_v2s = []
    if opts.threed_lattice:
        new_v3s = []

    # Use scipy's KDtree to quickly calculate Euclidean distances
    logger.info("Setting up KDtree to compute distances.")
    if opts.threed_lattice:
        tree = spatial.KDTree(xis[:, :3])
        xi_points = list(zip(v1s, v2s, v3s, strict=True))
    else:
        tree = spatial.KDTree(xis[:, :2])
        xi_points = list(zip(v1s, v2s, strict=True))

    logger.info("Computing distances using KDtree.")
    dists, pointargs = tree.query(xi_points)

    logger.info("Removing far-away points.")

    for i in range(len(v1s)):
        if dists[i] < 2.0:
            new_v1s.append(v1s[i])
            new_v2s.append(v2s[i])
            if opts.threed_lattice:
                new_v3s.append(v3s[i])

    logger.info("Filtered lattice contains %d points", len(new_v1s))
else:
    new_v1s = v1s
    new_v2s = v2s
    if opts.threed_lattice:
        new_v3s = v3s

# Now begin to generate the dag

h5file = HFile(opts.output_file, "w")
# Dump the full bank in \xi_i coordinates
h5file["full_bank/v1s"] = new_v1s
h5file["full_bank/v2s"] = new_v2s
if opts.threed_lattice:
    h5file["full_bank/v3s"] = new_v3s

# Now store split banks
bank_num = 0

logger.info("Printing split banks to HDF file.")
v1s = []
v2s = []
v3s = []
total_points = len(new_v1s)
points_per_job = (
    int(numpy.ceil(total_points / float(opts.num_split_jobs)))
    if total_points > 0 and opts.num_split_jobs > 0
    else 1
)

for i in range(len(new_v1s)):
    v1s.append(new_v1s[i])
    v2s.append(new_v2s[i])
    if opts.threed_lattice:
        v3s.append(new_v3s[i])
    if not (i + 1) % points_per_job:
        h5file[f"split_banks/split_bank_{bank_num:05d}/v1s"] = v1s
        h5file[f"split_banks/split_bank_{bank_num:05d}/v2s"] = v2s
        v1s = []
        v2s = []
        if opts.threed_lattice:
            h5file[f"split_banks/split_bank_{bank_num:05d}/v3s"] = v3s
            v3s = []
        bank_num = bank_num + 1

if v1s:
    # There are still templates to dump
    h5file[f"split_banks/split_bank_{bank_num:05d}/v1s"] = v1s
    h5file[f"split_banks/split_bank_{bank_num:05d}/v2s"] = v2s
    if opts.threed_lattice:
        h5file[f"split_banks/split_bank_{bank_num:05d}/v3s"] = v3s

logger.info("Adding metric information to HDF file.")
h5file["cov_evecs"] = metric_params.evecs_cv[metric_params.f_upper]
h5file["metric_evals"] = metric_params.evals[metric_params.f_upper]
h5file["metric_evecs"] = metric_params.evecs[metric_params.f_upper]

h5file.close()
