#!/usr/bin/env python3
#
# Copyright (C) 2013,2014  Kipp Cannon, Chad Hanna, Jacob Peoples
#
# 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 2 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.

### A program to comput the signal and noise rate posteriors of a gstlal inspiral analysis


#
# =============================================================================
#
#                                   Preamble
#
# =============================================================================
#


import bisect
try:
	from fpconst import NegInf
except ImportError:
	NegInf = float("-inf")
import h5py
import matplotlib
matplotlib.rcParams.update({
	"font.size": 8.0,
	"axes.titlesize": 10.0,
	"axes.labelsize": 10.0,
	"xtick.labelsize": 8.0,
	"ytick.labelsize": 8.0,
	"legend.fontsize": 8.0,
	"figure.dpi": 600,
	"savefig.dpi": 600,
	"text.usetex": True
})
from matplotlib import figure
from matplotlib import ticker
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy
from optparse import OptionParser
import sqlite3
import sys


from ligo import segments
from ligo.lw import ligolw
from ligo.lw import dbtables
from ligo.lw import lsctables
from ligo.lw import utils as ligolw_utils
from ligo.lw.utils import process as ligolw_process
from glue.text_progress_bar import ProgressBar
from lal.utils import CacheEntry
from lalinspiral import thinca


from gstlal import far
from gstlal import rate_estimation
from gstlal.plotutil import golden_ratio


process_name = u"gstlal_inspiral_rate_posterior"


__author__ = "Kipp Cannon <kipp.cannon@ligo.org>"
__version__ = ""	# FIXME
__date__ = ""	# FIXME


#
# =============================================================================
#
#                                 Command Line
#
# =============================================================================
#


def parse_command_line():
	parser = OptionParser(
		version = "Name: %%prog\n%s" %  __version__,
		usage = "%prog [options] candidates_database [...]"
	)
	parser.add_option("-c", "--credible-intervals", metavar = "credibility[,...]", default = "0.68,0.95,0.999999", help = "Compute and report credible intervals in the signal count for these credibilities (default = \".68,.95,.999999\", clear to disable).")
	parser.add_option("-i", "--input-cache", metavar = "filename", help = "Also process the candidate databases named in this LAL cache.  See lalapps_path2cache for information on how to produce a LAL cache file.")
	parser.add_option("--chain-file", metavar = "filename", help = "Read chain from this file, save chain to this file.")
	parser.add_option("--ranking-stat-pdf", metavar = "filename", action = "append", help = "Load ranking statistic PDFs for the signal and noise models from this file.  Can be given multiple times.")
	parser.add_option("--ranking-stat-pdf-cache", metavar = "filename", help = "Load ranking statistic PDFs for the signal and noise models from the files in this LAL cache.")
	parser.add_option("--ranking-stat-threshold", metavar = "value", type = "float", help = "Only consider candidates at or above this value of the ranking statistic.  The default is to set the threshold automatically from the extinction model's domain of validity.")
	parser.add_option("-t", "--tmp-space", metavar = "path", help = "Path to a directory suitable for use as a work area while manipulating the database file.  The database file will be worked on in this directory, and then moved to the final location when complete.  This option is intended to improve performance when running in a networked environment, where there might be a local disk with higher bandwidth than is available to the filesystem on which the final output will reside.")
	parser.add_option("--with-background", action = "store_true", help = "Show background posterior on plot.")
	parser.add_option("--samples", metavar = "count", type = "int", help = "Run this many samples.  Set to 0 to load and plot the contents of a previously-recorded chain file without doing any additional samples.")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	options, filenames = parser.parse_args()

	paramdict = options.__dict__.copy()

	options.credible_intervals = map(float, options.credible_intervals.split(","))

	if options.samples is not None and options.samples < 0:
		raise ValueError("--samples cannot be negative")

	if options.ranking_stat_pdf_cache is not None:
		if options.ranking_stat_pdf is None:
			options.ranking_stat_pdf = []
		options.ranking_stat_pdf += [CacheEntry(line).path for line in open(options.ranking_stat_pdf_cache)]
	if not options.ranking_stat_pdf and options.samples > 0:
		raise ValueError("must provide ranking statistic PDF data if --samples is non-zero")

	if options.input_cache:
		filenames += [CacheEntry(line).path for line in open(options.input_cache)]

	return options, paramdict, filenames


#
# =============================================================================
#
#                              Support Functions
#
# =============================================================================
#


def load_ranking_data(filenames, ln_likelihood_ratio_threshold, verbose = False):
	if not filenames:
		raise ValueError("no likelihood files!")
	rankingstatpdf = far.marginalize_pdf_urls(filenames, "RankingStatPDF", verbose = verbose)

	if ln_likelihood_ratio_threshold is None:
		# determine the treshold below which the extinction model
		# will be invalid.  FIXME:  this shouldn't have to be
		# repeated in code like this, the extinction model itself
		# should provide this information somehow.
		zl = rankingstatpdf.zero_lag_lr_lnpdf.copy()
		zl.array[:40] = 0.
		if not zl.array.any():
			raise ValueError("zero-lag counts are all zero")
		ln_likelihood_ratio_threshold, = zl.argmax()

	# apply the extinction model
	rankingstatpdf = rankingstatpdf.new_with_extinction()

	# affect the zeroing of the PDFs below threshold by hacking the
	# histograms.  do the indexing ourselves to not 0 the bin @
	# threshold
	rankingstatpdf.noise_lr_lnpdf.array[:rankingstatpdf.noise_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
	rankingstatpdf.noise_lr_lnpdf.normalize()
	rankingstatpdf.signal_lr_lnpdf.array[:rankingstatpdf.signal_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
	rankingstatpdf.signal_lr_lnpdf.normalize()
	rankingstatpdf.zero_lag_lr_lnpdf.array[:rankingstatpdf.zero_lag_lr_lnpdf.bins[0][ln_likelihood_ratio_threshold]] = 0.
	rankingstatpdf.zero_lag_lr_lnpdf.normalize()

	return rankingstatpdf, ln_likelihood_ratio_threshold


def load_search_results(filenames, ln_likelihood_ratio_threshold, tmp_path = None, verbose = False):
	zerolag_ln_likelihood_ratios = []

	for n, filename in enumerate(filenames, 1):
		if verbose:
			print >>sys.stderr, "%d/%d: %s" % (n, len(filenames), filename)
		with dbtables.workingcopy(filename, tmp_path = tmp_path, discard = True, verbose = verbose) as working_filename:
			connection = sqlite3.connect(str(working_filename))

			xmldoc = dbtables.get_xml(connection)
			definer_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)

			for ln_likelihood_ratio in connection.cursor().execute("""
SELECT
	coinc_event.likelihood,
FROM
	coinc_event
	JOIN coinc_inspiral ON (
		coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
	)
WHERE
	coinc_event.coinc_def_id == ?
	AND NOT EXISTS (
		SELECT
			*
		FROM
			time_slide
		WHERE
			time_slide.time_slide_id == coinc_event.time_slide_id
			AND time_slide.offset != 0
	)
	AND coinc_event.likelihood >= ?"""
	, (definer_id, (ln_likelihood_ratio_threshold if ln_likelihood_ratio_threshold is not None else NegInf))):
				zerolag_ln_likelihood_ratios.append(ln_likelihood_ratio)

			connection.close()

	return zerolag_ln_likelihood_ratios


def plot_rates(signal_rate_ln_pdf, credible_intervals = None):
	fig = figure.Figure()
	FigureCanvas(fig)
	fig.set_size_inches((4., 4. / golden_ratio))
	axes = fig.gca()

	x, = signal_rate_ln_pdf.centres()
	y = numpy.exp(signal_rate_ln_pdf.at_centres())
	line1, = axes.plot(x, y, color = "k", linestyle = "-", label = "Signal")
	axes.set_title("Event Rate Posterior Probability Density")
	axes.set_xlabel("Event Rate ($\mathrm{signals} / \mathrm{experiment}$)")
	axes.set_ylabel(r"$P(\mathrm{signals} / \mathrm{experiment})$")

	axes.semilogy()
	#axes.set_ylim((1e-8, 1.))
	axes.set_xlim((0., axes.get_xlim()[1]))

	axes.yaxis.set_minor_locator(ticker.LogLocator(10., subs = (0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9)))
	axes.minorticks_on()
	axes.grid(which = "both", linestyle = "-", linewidth = 0.2)

	if credible_intervals is not None:
		alphas = dict(zip(sorted(credible_intervals), [.6, .4, .2]))

		# convert lo and hi bounds to co-ordinate index segments
		credible_intervals = sorted((cred, segments.segmentlist([segments.segment(bisect.bisect_left(x, lo), bisect.bisect_right(x, hi))])) for cred, (mode, lo, hi) in credible_intervals.items())

		# remove from each the indexes spanned by lower credible regions
		credible_intervals = [(cred, indexes - sum((segs for cred, segs in credible_intervals[:i]), segments.segmentlist())) for i, (cred, indexes) in enumerate(credible_intervals)]

		for cred, segs in credible_intervals:
			for lo, hi in segs:
				axes.fill_between(x[lo:hi+1], y[lo:hi+1], 1e-8, color = "k", alpha = alphas[cred])

	fig.tight_layout()
	return fig


#
# =============================================================================
#
#                                     Main
#
# =============================================================================
#


#
# command line
#


options, paramdict, filenames = parse_command_line()


#
# load ranking statistic PDFs
#


if options.ranking_stat_pdf:
	rankingstatpdf, ln_likelihood_ratio_threshold = load_ranking_data(options.ranking_stat_pdf, options.ln_likelihood_ratio_threshold, verbose = options.verbose)
else:
	rankingstatpdf, ln_likelihood_ratio_threshold = None, None


#
# load search results
#


zerolag_ln_likelihood_ratios = load_search_results(filenames, ln_likelihood_ratio_threshold = ln_likelihood_ratio_threshold, tmp_path = options.tmp_space, verbose = options.verbose)


#
# calculate rate posteriors
#


if options.verbose:
	print >>sys.stderr, "calculating rate posteriors using %d likelihood ratios ..." % len(zerolag_ln_likelihood_ratios)
	progressbar = ProgressBar()
else:
	progressbar = None
kwargs = {}
if options.chain_file is not None:
	kwargs["chain_file"] = h5py.File(options.chain_file)
if options.samples is not None:
	kwargs["nsample"] = options.samples
signal_rate_ln_pdf, noise_rate_ln_pdf = rate_estimation.calculate_rate_posteriors(rankingstatpdf, zerolag_ln_likelihood_ratios, progressbar = progressbar, **kwargs)
#p_signal = rate_estimation.calculate_psignal_posteriors_from_rate_samples(rankingstatpdf, zerolag_ln_likelihood_ratios, progressbar = progressbar)
#while open("p_signal.txt", "w") as f:
#	for vals in zip(zerolag_ln_likelihood_ratios, p_signal):
#		print >>f, "%.17g %.17g" % vals
del progressbar


#
# find credible intervals
#


if options.credible_intervals:
	if options.verbose:
		print >>sys.stderr, "determining credible intervals ..."
	credible_intervals = dict((cred, rate_estimation.confidence_interval_from_lnpdf(signal_rate_ln_pdf, cred)) for cred in options.credible_intervals)
else:
	credible_intervals = None
if options.verbose and credible_intervals is not None:
	print >>sys.stderr, "rate posterior mean = %g signals/experiment" % rate_estimation.mean_from_lnpdf(signal_rate_ln_pdf)
	print >>sys.stderr, "rate posterior median = %g signals/experiment" % rate_estimation.median_from_lnpdf(signal_rate_ln_pdf)
	# all modes are the same, pick one and report it
	print >>sys.stderr, "maximum-likelihood rate = %g signals/experiment" % credible_intervals.values()[0][0]
	for cred, (mode, lo, hi) in sorted(credible_intervals.items()):
		print >>sys.stderr, "%g%% credible interval = [%g, %g] signals/experiment" % (cred * 100., lo, hi)


#
# save results
#


filename = "rate_posteriors.xml.gz"
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(xmldoc, process_name, paramdict)
xmldoc.childNodes[-1].appendChild(signal_rate_ln_pdf.to_xml(u"%s:signal_ln_pdf" % process_name))
xmldoc.childNodes[-1].appendChild(noise_rate_ln_pdf.to_xml(u"%s:noise_ln_pdf" % process_name))
ligolw_utils.write_filename(xmldoc, filename, verbose = options.verbose)


fig = plot_rates(signal_rate_ln_pdf, credible_intervals = credible_intervals)
for filename in ("rate_posteriors.png", "rate_posteriors.pdf"):
	if options.verbose:
		print >>sys.stderr, "writing %s ..." % filename
	fig.savefig(filename)

if options.verbose:
	print >>sys.stderr, "done"
