#!python
"""
Plots the recovered versus injected parameter values from a population
of injections.
"""

import logging
import sys

import matplotlib as mpl

mpl.use("Agg")
import matplotlib.colorbar as cbar
import matplotlib.pyplot as plt
import numpy
from matplotlib import cm

import pycbc
from pycbc.inference import io, option_utils
from pycbc.results import save_fig_with_metadata

logger = logging.getLogger(__name__)

# parse command line
parser = io.ResultsArgumentParser(description=__doc__)

pycbc.add_common_pycbc_options(parser)
parser.add_argument(
    "--output-file", required=True, type=str, help="Path to save output plot."
)
parser.add_argument(
    "--percentiles",
    nargs=2,
    type=float,
    default=[5, 95],
    help="Percentiles to use as limits.",
)
option_utils.add_scatter_option_group(parser)
option_utils.add_injsamples_map_opt(parser)
opts = parser.parse_args()

# set logging
pycbc.init_logging(opts.verbose)

# read results
fp, parameters, labels, samples = io.results_from_cli(opts)

# only plot one parameter
assert len(parameters) == 1
parameter = parameters[0]
label = labels[parameters[0]]

# create figure
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)

# typecast to list for iteratation
samples = [samples] if not isinstance(samples, list) else samples
fp = [fp] if not isinstance(fp, list) else fp
injs = io.injections_from_cli(opts)

# if user wants a colorbar

# if a z-arg is specified, load samples for it
if opts.z_arg is not None:
    logger.info("Getting samples for colorbar")
    zlbl = opts.z_arg_labels[opts.z_arg]
    zvals = []
    min_zval = max_zval = None
    for i, fpi in enumerate(fp):
        zsamples = fpi.samples_from_cli(opts, parameters=opts.z_arg)
        vals = zsamples[opts.z_arg]
        zvals.append(numpy.median(vals))

        # update range of colorbar
        min_zval = vals.min() if i == 0 else min(min_zval, vals.min())
        max_zval = vals.max() if i == 0 else max(max_zval, vals.max())

    # create colormap
    cmap = cm.get_cmap(opts.scatter_cmap)
    vmin = opts.vmin or min_zval
    vmax = opts.vmax or max_zval
    norm = mpl.colors.Normalize(vmin, vmax)

# loop over input files and its samples
logger.info("Plotting")
for i, input_samples in enumerate(samples):
    # get paramter values
    sampled_vals = input_samples[parameter]
    injected_vals = injs[parameter][i]
    # compute percentiles of sampled results
    percentiles = numpy.array(
        [numpy.percentile(sampled_vals, p) for p in opts.percentiles]
    )

    # get median and lowest and highest quntiles for plotting
    med = numpy.median(sampled_vals)
    high = percentiles.max()
    low = percentiles.min()

    # get color
    color = cmap(norm(zvals[i])) if opts.z_arg else "black"

    # plot a point for each injection
    ax.errorbar(
        [injected_vals],
        [med - injected_vals],
        yerr=[[(med - low)], [(high - med)]],
        ecolor=color,
        linestyle="None",
        zorder=10,
    )

# create a colorbar
if opts.z_arg:
    cax, _ = cbar.make_axes(ax)
    cb2 = cbar.ColorbarBase(cax, cmap=cmap, norm=norm)
    cb2.set_label(r"Recovered Median " + zlbl)

# set labels
ax.set_ylabel(r"Recovered " + label + r"- Injected " + label)
ax.set_xlabel(r"Injected " + rf"{label}")

# add grid to plot
ax.grid()

# add 1:1 line to plot
ax.axhline(0, linestyle="dashed", color="gray", zorder=9)

# save plot
caption = (
    "Difference in recovered value vs injected value vs injected value. "
    f"The vertical lines show the width of the {opts.percentiles[0]} to "
    f"{opts.percentiles[1]} percentile credible interval."
)
save_fig_with_metadata(
    fig,
    opts.output_file,
    caption=caption,
    cmd=" ".join(sys.argv),
    fig_kwds={"bbox_inches": "tight"},
)

# done
logger.info("Done")
