#!/bin/env python
""" Make histograms of single detector triggers
"""
import numpy, argparse, h5py, logging, sys
import pycbc.version, pycbc.results, pycbc.io
from matplotlib import use; use('Agg')
from matplotlib import pyplot
from pycbc.events import veto

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--version', action='version', version=pycbc.version.git_verbose_msg)
parser.add_argument('--trigger-file', required=True,
                    help="Combined single detector hdf trigger file")
parser.add_argument('--veto-file',
                    help="segment xml file, indicates which triggers to ignore")
parser.add_argument('--segment-name',
                    help="name of segment list in the veto file")
parser.add_argument('--x-var',
                    help="name of value to histogram")
parser.add_argument('--output-file')
parser.add_argument('--bins', default=100, type=int,
                    help="number of bins in histogram")
parser.add_argument('--x-max', type=float)
parser.add_argument('--x-min', type=float, default=6,
                    help="Minimum x-value. Default 6")
parser.add_argument('--special-time', type=float,
                    help="plot triggers within +-1s of a given time in a "
                         "different color (black)")
parser.add_argument('--verbose')
args = parser.parse_args()

pycbc.init_logging(args.verbose)

f = h5py.File(args.trigger_file, 'r')
ifo = f.keys()[0]

trigs = pycbc.io.SingleDetTriggers(args.trigger_file, None, args.veto_file,
                                   args.segment_name, None, ifo)
val = getattr(trigs, args.x_var)
x_max = args.x_max if args.x_max else val.max() * 1.1

fig = pyplot.figure(0)

if args.special_time:
    time = getattr(trigs, 'end_time')
    val_special = val[abs(time-args.special_time) < 1]
    val_boring = val[abs(time-args.special_time) >= 1]
    binvals = numpy.linspace(args.x_min, x_max, args.bins, endpoint=True)
    pyplot.hist([val_boring, val_special], bins=binvals, histtype='stepfilled',
               stacked=True, color=[pycbc.results.ifo_color(ifo), 'k'],
          label=['Other times', 'Triggers near %i' % (int(args.special_time))])
    pyplot.legend(loc='upper right')
else:
    pycbc.results.hist_overflow(val, x_max, bins=args.bins,
                                  color=pycbc.results.ifo_color(ifo))

ax = pyplot.gca()
ax.set_yscale('log')
pyplot.ylabel('Number of triggers')
pyplot.xlabel(args.x_var)
pyplot.ylim(ymin=.1)

if args.x_min:
    pyplot.xlim(xmin=args.x_min)

if args.x_max:
    if len(numpy.where(val > args.x_max)[0]):
        overflow = 1
    else:
        overflow = 0

    pyplot.xlim(xmax=args.x_max + overflow)

pyplot.grid()
pycbc.results.save_fig_with_metadata(fig, args.output_file,
                title = '%s: %s histogram of single detector triggers' % (ifo, args.x_var),
                caption = 'Histogram of single detector triggers',
                cmd = ' '.join(sys.argv))

