#!/usr/bin/python3.13 -s
# Copyright (C) 2020 Josh Willis
#
# 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.
"""Plot histograms of IFAR and ranking statistic of injections missed
in only one of two comparable runs
"""

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import argparse

from pycbc import add_common_pycbc_options, init_logging
from pycbc.io.hdf import HFile

parser = argparse.ArgumentParser(description=__doc__)
add_common_pycbc_options(parser)
parser.add_argument('--combined-comparison-file', required=True,
                    help="HDF file holding output of"
                    " 'pycbc_combine_injection_comparisons'")
parser.add_argument('--outfile', type=str, required=True,
                    help='Output file to save to')
parser.add_argument('--plot-title', type=str, required=True,
                    help='(Possibly) quoted string to be title of plot')
parser.add_argument('--found-category', type=str, required=True,
                    choices=['found', 'found_after_vetoes'],
                    help='Which class of found injections to plot')
parser.add_argument('--missed-run', type=str, required=True,
                    choices=['reference', 'comparison'],
                    help='Which run missed the injections to plot')
parser.add_argument('--nbins', type=int, default=10,
                    help='Number of bins to use for template duration (x-axis)')
parser.add_argument('--log-y', action='store_true', default=False,
                    help='Use logarithmic y-axis')
args = parser.parse_args()

init_logging(args.verbose)

# Load in the two datasets
f = HFile(args.combined_comparison_file)

conversion_dict = { 'reference' : 'found_comparison_only',
                    'comparison' : 'found_reference_only'}

ifar = f[args.found_category][conversion_dict[args.missed_run]]['ifar'][:]
stat = f[args.found_category][conversion_dict[args.missed_run]]['stat'][:]

nbins = args.nbins

fig, (ax_ifar, ax_stat) = plt.subplots(1, 2, sharey=True)

stitle = fig.suptitle(args.plot_title)

_, bins = np.histogram(np.log10(ifar), bins=nbins)
ax_ifar.hist(ifar, bins=10.0**bins)
ax_ifar.set_xscale('log')
ax_ifar.set(xlabel='IFAR in found run')

ax_stat.hist(stat, bins=nbins)
ax_stat.set(xlabel='Ranking Statistic in found run')

ax_ifar.set(ylabel='Count')

for ax in [ax_ifar, ax_stat]:
    if args.log_y:
        ax.set_yscale('log')

fig.savefig(args.outfile)
plt.close()
