#!python
"""Calculate psd estimates for analysis segments"""

import argparse
import copy
import logging
import time

import numpy
from igwn_segments import segment, segmentlist
from six.moves import zip_longest

import pycbc
import pycbc.events
import pycbc.psd
import pycbc.strain
from pycbc.fft import ensure_fftw_planning_off
from pycbc.io import HFile
from pycbc.pool import BroadcastPool as Pool
from pycbc.workflow import resolve_td_option

logger = logging.getLogger(__name__)

ensure_fftw_planning_off()

parser = argparse.ArgumentParser(description=__doc__)
pycbc.add_common_pycbc_options(parser)
parser.add_argument(
    "--low-frequency-cutoff",
    type=float,
    required=True,
    help="The low frequency cutoff to use for filtering (Hz)",
)
parser.add_argument(
    "--analysis-segment-file",
    required=True,
    help="File defining the segments to estimate PSDs over",
)
parser.add_argument("--segment-name", help="Name of segment list to use")
parser.add_argument("--cores", default=1, type=int)
parser.add_argument("--output-file", required=True)
parser.add_argument("--num-data-retries", default=10, type=int)

pycbc.psd.insert_psd_option_group(parser, output=False)
pycbc.strain.insert_strain_option_group(parser, gps_times=False)
pycbc.strain.StrainSegments.insert_segment_option_group(parser)

args = parser.parse_args()
pycbc.init_logging(args.verbose)

pycbc.psd.verify_psd_options(args, parser)
pycbc.strain.StrainSegments.verify_segment_options(args, parser)


def grouper(n, iterable):
    args = [iter(iterable)] * n
    return [[e for e in t if e is not None] for t in zip_longest(*args)]


def get_psd(input_tuple):
    """
    Get the PSDs for the given data chunck. This follows the same rules
    as pycbc_inspiral for determining where to calculate PSDs
    """
    seg = input_tuple[0]
    i = input_tuple[1]

    logger.info(
        "%d: getting strain for %.1f-%.1f (%.1f s)", i, seg[0], seg[1], abs(seg)
    )
    argstmp = copy.deepcopy(args)
    argstmp.gps_start_time = int(seg[0]) + args.pad_data
    argstmp.gps_end_time = int(seg[1]) - args.pad_data
    tmp_segment = segment([argstmp.gps_start_time, argstmp.gps_end_time])
    # There may be cases where channel name or frame type change within an
    # analysis (noting that this could be an issue with significance
    # computation). If so, resolve them for each PSD block. This still
    # assumes that the channel and frame type are constant during a lock stretch.
    if args.channel_name:
        # Option may not have been given at all
        argstmp.channel_name = resolve_td_option(args.channel_name, tmp_segment)
    if args.frame_type:
        # Option is often not given.
        argstmp.frame_type = resolve_td_option(args.frame_type, tmp_segment)

    # This helps when the filesystem is unreliable
    for i in range(args.num_data_retries):
        try:
            gwstrain = pycbc.strain.from_cli(argstmp, pycbc.DYN_RANGE_FAC)
            break
        except RuntimeError:
            time.sleep(10)
            if i == (args.num_data_retries - 1):
                raise

    logger.info("%d: determining strain segmentation", i)
    strain_segments = pycbc.strain.StrainSegments.from_cli(args, gwstrain)

    flow = args.low_frequency_cutoff
    flen = strain_segments.freq_len
    delta_f = strain_segments.delta_f

    logger.info("%d: calculating psd", i)
    analysis_segments = [
        (seg.start, seg.stop, seg.start + ana.start, seg.start + ana.stop)
        for seg, ana in zip(
            strain_segments.segment_slices, strain_segments.analyze_slices, strict=True
        )
    ]
    psds_and_times = pycbc.psd.generate_segment_psds(
        args,
        gwstrain,
        analysis_segments,
        flen,
        delta_f,
        flow,
        dyn_range_factor=pycbc.DYN_RANGE_FAC,
    )

    lpsd = []
    seen = set()
    for start_idx, end_idx, psd in psds_and_times:
        if (start_idx, end_idx) in seen:
            continue
        seen.add((start_idx, end_idx))
        start_time = gwstrain.start_time + start_idx / gwstrain.sample_rate
        end_time = gwstrain.start_time + end_idx / gwstrain.sample_rate
        lpsd.append((psd.numpy(), psd.delta_f, int(start_time), int(end_time)))

    return lpsd


# Determine what times to calculate PSDs for
ifo = args.channel_name[0:2]
segments = pycbc.events.select_segments_by_definer(
    args.analysis_segment_file, args.segment_name, ifo=ifo
)

# get rid of duplicate segments which happen when splitting the bank
segments = segmentlist(frozenset(segments))

# Calculate the PSDs
logger.info("%d psds to calculate", len(segments))

if len(segments) > 0:
    pool = Pool(args.cores)
    psds = pool.map_async(get_psd, zip(segments, range(len(segments)), strict=True))
    psds = psds.get()
else:
    psds = []

# Store the PSDs in an hdf file, include some basic metadata
f = HFile(args.output_file, "w")
psd_group = f.create_group(ifo + "/psds")
inc, start, end = 0, [], []
for gpsd in psds:
    for psd_numpy, psd_delta_f, s, e in gpsd:
        logger.info("writing psd %d", inc)
        key = str(inc)
        start.append(int(s))
        end.append(int(e))
        psd_group.create_dataset(
            key, data=psd_numpy, compression="gzip", compression_opts=9, shuffle=True
        )
        psd_group[key].attrs["epoch"] = int(s)
        psd_group[key].attrs["delta_f"] = float(psd_delta_f)
        inc += 1

f[ifo + "/start_time"] = numpy.array(start, dtype=numpy.uint32)
f[ifo + "/end_time"] = numpy.array(end, dtype=numpy.uint32)
f.attrs["low_frequency_cutoff"] = args.low_frequency_cutoff
f.attrs["dynamic_range_factor"] = pycbc.DYN_RANGE_FAC

logger.info("Done!")
