#!python
# Copyright (C) 2016  Collin Capano
#
# 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.

__description__ = """"Loads a bank of waveforms and compresses them using the specified
compression algorithm. The resulting compressed waveforms are saved to an
hdf file."""

import argparse
import logging

import numpy

import pycbc
import pycbc.psd
from pycbc import waveform
from pycbc.pool import BroadcastPool
from pycbc.types import real_same_precision_as
from pycbc.waveform import compress

logger = logging.getLogger(__name__)


# --- WORKER FUNCTION ---
def _worker(ii):
    """Worker function to generate and compress a single template."""
    tmplt = bank_table[ii]
    if tmplt["approximant"] in do_not_compress:
        return None

    # Generate the waveform
    htilde = bank_obj[ii]
    fmin = tmplt.f_lower
    template_duration = htilde.chirp_length

    if template_duration is None:
        template_duration = seg_len // 2
        logger.info(
            "Warning: was not able to determine template duration, "
            "setting half segment length for template %s",
            tmplt.template_hash,
        )

    kmin = int(numpy.ceil(fmin / df_val))
    htilde[:kmin] = 0  # This ensures proper phase unwrapping
    if numpy.abs(htilde[kmin]) == 0:
        raise ValueError(
            "The amplitude of the waveform at the "
            "low_frequency_cutoff is zero. A non-zero value "
            "is required."
        )

    kmax = numpy.nonzero(abs(htilde))[0][-1]

    # Get the compressed sample points
    if alg == "mchirp":
        sample_points = compress.mchirp_compression(
            tmplt.mass1,
            tmplt.mass2,
            fmin,
            kmax * df_val,
            min_seglen=t_pad,
            df_multiple=df_val,
            scale=scale_val,
        ).astype(real_same_precision_as(htilde))
    elif alg == "spa":
        sample_points = compress.spa_compression(
            htilde, fmin, kmax * df_val, min_seglen=t_pad, scale=scale_val
        ).astype(real_same_precision_as(htilde))
    elif alg == "bounds":
        sample_points = numpy.array([fmin, kmax * df_val])
    else:
        raise ValueError(f"unrecognized compression algorithm {alg}")

    # Compress
    hcompressed = compress.compress_waveform(
        htilde, sample_points, tol, interp, "double", decomp_scratch=None, psd=psd_obj
    )

    return ii, tmplt.template_hash, hcompressed, template_duration


# --- MAIN EXECUTION ---
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__description__)
    pycbc.add_common_pycbc_options(parser)
    parser.add_argument(
        "--bank-file", type=str, required=True, help="Bank hdf file to load."
    )
    parser.add_argument(
        "--output",
        type=str,
        required=True,
        help="The hdf file to save the templates and compressed waveforms to.",
    )
    parser.add_argument(
        "--low-frequency-cutoff",
        type=float,
        default=None,
        help="The low frequency cutoff to use for generating "
        "the waveforms (Hz). If this is not provided, the code "
        "will look for a low frequency cutoff corressponding "
        "to each template stored in the bank. If a "
        "--low-frequency-cutoff is provided and the bank stores "
        "a low frequency cutoff for each template as well, the "
        "former is used to generate the waveforms.",
    )
    pycbc.waveform.bank.add_approximant_arg(parser)
    parser.add_argument(
        "--sample-rate",
        type=int,
        required=True,
        help="Half this value sets the maximum frequency of "
        "the compressed waveforms. Must be a power of 2.",
    )
    parser.add_argument(
        "--segment-length",
        type=int,
        required=True,
        help="The segment length to use for generating the "
        "templates for compression, and for calculating "
        "overlap for tolerance. Must be a power of 2, "
        "and at least twice as long as the longest template "
        "in the bank.",
    )
    parser.add_argument(
        "--tmplt-index",
        nargs=2,
        type=int,
        default=None,
        help="Only generate compressed waveforms for the given "
        "indices in the bank file. Must provide both a start "
        "and a stop index. Default is to compress all of the "
        "templates in the bank file.",
    )
    parser.add_argument(
        "--compression-algorithm",
        type=str,
        required=True,
        choices=[*list(compress.compression_algorithms.keys()), "bounds"],
        help="The compression algorithm to use for selecting frequency points.",
    )
    parser.add_argument(
        "--nprocesses", type=int, default=1, help="Number of parallel processes to use."
    )
    parser.add_argument(
        "--t-pad",
        type=float,
        default=0.001,
        help="The minimum duration used for t(f) in seconds. "
        "The inverse of this gives the maximum frequency "
        "step that will be used in the compressed waveforms. "
        "Default is 0.001.",
    )
    parser.add_argument(
        "--tolerance",
        type=float,
        default=0.001,
        help="The maximum mismatch to allow between the "
        "interpolated waveform must and the full waveform. "
        "Points will be added to the compressed waveform "
        "until its interpolation has a mismatch <= this value. "
        "Default is 0.001.",
    )
    parser.add_argument(
        "--interpolation",
        type=str,
        default="inline_linear",
        help="The interpolation to use for decompressing the "
        "waveforms for checking tolerance. Options are "
        "'inline_linear', or any interpolation recognized by "
        "scipy's interp1d kind argument. Default is inline_linear.",
    )
    parser.add_argument(
        "--precision",
        type=str,
        choices=["double", "single"],
        default="single",
        help="What precision to generate and store the "
        "waveforms with; default is double.",
    )
    parser.add_argument(
        "--force",
        action="store_true",
        default=False,
        help="Overwrite the given hdf file if it exists. "
        "Otherwise, an error is raised.",
    )
    parser.add_argument(
        "--scale",
        type=float,
        default=1,
        help="Scale factor to apply to the courseness of the initial "
        "compression points. >1 means a courser set of initial "
        "points. The algorithm will still add points to meet"
        "the tolerance goals.",
    )
    parser.add_argument(
        "--do-not-compress",
        nargs="+",
        help="If given, will not compress waveforms using "
        "the given approximant. Recommended 'SPAtmplt TaylorF2'.",
    )

    pycbc.psd.insert_psd_option_group(parser, include_data_options=False)
    args = parser.parse_args()

    pycbc.init_logging(args.verbose)

    # Verify if the input options for calculating the psd are correct, if
    # a PSD is to be used while calculating the overlaps in compress.py . If
    # using a PSD is not desired, this check would prevent raising an error
    # asking for PSD options.
    if args.psd_model or args.psd_file or args.asd_file:
        pycbc.psd.verify_psd_options(args, parser)

    if args.sample_rate % 2 != 0:
        raise ValueError("sample rate must be a power of 2")
    if args.segment_length % 2 != 0:
        raise ValueError("segment length must be a power of 2")

    if args.do_not_compress is None:
        args.do_not_compress = []

    df_val = 1.0 / args.segment_length
    fmax = args.sample_rate / 2.0
    N = args.sample_rate * args.segment_length
    dtype = numpy.complex128

    logger.info("loading bank")
    # we'll do everything in double precision; if single is desired, we'll
    # cast to single when saving the waveforms
    bank_obj = waveform.FilterBank(
        args.bank_file,
        N // 2 + 1,
        df_val,
        dtype,
        low_frequency_cutoff=args.low_frequency_cutoff,
        approximant=args.approximant,
        enable_compressed_waveforms=False,
    )

    if args.tmplt_index is not None:
        imin, imax = args.tmplt_index
        bank_obj.table = bank_obj.table[imin:imax]

    # Map shared globals for workers
    bank_table = bank_obj.table
    do_not_compress = args.do_not_compress
    seg_len = args.segment_length
    tol = args.tolerance
    interp = args.interpolation
    alg = args.compression_algorithm
    t_pad = args.t_pad
    scale_val = args.scale

    logger.info("getting psd")
    psd_obj = pycbc.psd.from_cli(
        args,
        length=N // 2 + 1,
        delta_f=df_val,
        low_frequency_cutoff=bank_table.f_lower.min(),
        dyn_range_factor=pycbc.DYN_RANGE_FAC,
        precision="double",
    )

    logger.info("writing template info to output")
    output = bank_obj.write_to_hdf(
        args.output, force=args.force, write_compressed_waveforms=False
    )
    output.create_group("compressed_waveforms")

    logger.info("Starting compression with %d processes", args.nprocesses)

    pool = BroadcastPool(processes=args.nprocesses)
    results = pool.imap_unordered(_worker, range(bank_table.size))

    for result in results:
        if result is None:
            continue
        idx, tmplt_hash, hcompressed, duration = result

        # Verify segment length against duration one last time in main thread
        if args.segment_length < 2 * duration:
            raise ValueError(
                "segment length is < twice the duration "
                f"({duration}) of template {tmplt_hash}"
            )

        output["template_duration"][idx] = duration
        hcompressed.write_to_hdf(output, tmplt_hash, precision=args.precision)
        logger.info("Saved compressed template %s", tmplt_hash)

    pool.close()
    pool.join()
    output.close()
    logger.info("finished")
