#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1694401452756/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# Copyright (C) 2013 Chad Hanna, Kipp Cannon
#
# 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 plot the likelihood distributions in noise of a gstlal inspiral analysis


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


import itertools
import math
from gstlal.plots import set_matplotlib_cache_directory
set_matplotlib_cache_directory()
import matplotlib
matplotlib.rcParams.update({
	"font.size": 10.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
})
import numpy
from optparse import OptionParser
import os
import sqlite3
import sys


from ligo.lw import dbtables
from ligo.lw import lsctables
from lal.utils import CacheEntry
from lalinspiral import thinca
from ligo.segments import utils as segmentsUtils


from gstlal import far
from gstlal import datafind
from gstlal.plots import far as plotfar


class SnrChiColourNorm(matplotlib.colors.Normalize):
	def __call__(self, value, clip = None):
		value, is_scalar = self.process_value(value)
		numpy.clip(value, 1e-200, 1e+200, value)

		self.autoscale_None(value)

		vmin = math.log(self.vmin)
		vmax = math.log(self.vmax)
		xbar = (vmax + vmin) / 2.
		delta = (vmax - vmin) / 2.
		pi_2 = math.pi / 2.

		value = (numpy.arctan((numpy.log(value) - xbar) * pi_2 / delta) + pi_2) / math.pi
		return value[0] if is_scalar else value

	def inverse(self, value):
		vmin = math.log(self.vmin)
		vmax = math.log(self.vmax)
		xbar = (vmax + vmin) / 2.
		delta = (vmax - vmin) / 2.
		pi_2 = math.pi / 2.

		value = numpy.exp(numpy.tan(value * math.pi - pi_2) * delta / pi_2 + xbar)
		numpy.clip(value, 1e-200, 1e+200, value)
		return value

	def _autoscale(self, vmin, vmax):
		vmin = math.log(vmin)
		vmax = math.log(vmax)
		xbar = (vmax + vmin) / 2.
		delta = (vmax - vmin) / 2.
		xbar += 2. * delta / 3.
		delta /= 4.
		vmin = math.exp(xbar - delta)
		vmax = math.exp(xbar + delta)
		return vmin, vmax

	def autoscale(self, A):
		self.vmin, self.vmax = self._autoscale(numpy.ma.min(A), numpy.ma.max(A))

	def autoscale_None(self, A):
		vmin, vmax = self._autoscale(numpy.ma.min(A), numpy.ma.max(A))
		if self.vmin is None:
			self.vmin = vmin
		if self.vmax is None:
			self.vmax = vmax


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


def parse_command_line():
	parser = OptionParser()
	parser.add_option("-d", "--database", metavar = "filename", action = "append", help = "Retrieve search results from this database (optional).  Can be given multiple times.")
	parser.add_option("-c", "--database-cache", metavar = "filename", help = "Retrieve search results from all databases in this LAL cache (optional).  See lalapps_path2cache.")
	parser.add_option("--max-snr", metavar = "SNR", default = 200., type = "float", help = "Plot SNR PDFs up to this value of SNR (default = 200).")
	parser.add_option("--max-log-lambda", metavar = "value", default = 40., type = "float", help = "Plot ranking statistic CCDFs, etc., up to this value of the natural logarithm of the likelihood ratio (default = 40).")
	parser.add_option("--min-log-lambda", metavar = "value", default = -5., type = "float", help = "Plot ranking statistic CCDFs, etc., down to this value of the natural logarithm of the likelihood ratio (default = -5).")
	parser.add_option("--scatter-log-lambdas", metavar = "[low]:[high][,[low]:[high]...]", help = "Overlay scatter plots of candidate parameter co-ordinates on various PDF plots, limiting the candidates to those whose log likelihood ratios are in the given range (default = don't overlay scatter plot).  Use a range of \":\" to plot all candidates.")
	parser.add_option("--output-dir", metavar = "output-dir", default = ".", help = "Write output to this directory (default = \".\").")
	parser.add_option("--output-format", metavar = "extension", default = ".png", help = "Select output format by setting the filename extension (default = \".png\").")
	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("--add-zerolag-to-background", action = "store_true", help = "Add zerolag events to background before populating coincident parameter PDF histograms.")
	parser.add_option("--user-tag", metavar = "user-tag", default = "ALL", help = "Set the adjustable component of the description fields in the output filenames (default = \"ALL\").")
	parser.add_option("--plot-snr-snr-pdfs", action = "store_true", help = "Plot the full cache of snr-snr-pdfs.")
	parser.add_option("--event-snr", metavar = "ifo:snr", action = "append", default=[], help = "SNR to plot on snr chisq plots. Pass as ifo:snr, e.g. H1:3.2. Can be passed multiple times, though only once for each ifo. Must also pass --event-chisq for ifo.")
	parser.add_option("--event-chisq", metavar = "ifo:chisq", action = "append", default=[], help = "chisq to plot on snr chisq plots. Pass as ifo:chisq, e.g. H1:1.1. Can be passed multiple times, though only once for each ifo. Must also pass --event-snr for ifo.")
	parser.add_option("--event-bankchisq", metavar = "ifo:chisq", action = "append", default=[], help = "chisq to plot on snr chisq plots. Pass as ifo:chisq, e.g. H1:1.1. Can be passed multiple times, though only once for each ifo. Must also pass --event-snr for ifo.")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	options, filenames = parser.parse_args()

	if options.database_cache is not None:
		if options.database is None:
			options.database = []
		options.database += [CacheEntry(line).path for line in open(options.database_cache)]

	valid_formats = (".png", ".pdf", ".svg")
	if options.output_format not in valid_formats:
		raise ValueError("invalid --output-format \"%s\", allowed are %s" % (options.output_format, ", ".join("\"%s\"" % fmt for fmt in valid_formats)))

	if options.scatter_log_lambdas is not None:
		options.scatter_log_lambdas = segmentsUtils.from_range_strings(options.scatter_log_lambdas.split(","), boundtype = float).coalesce()

	options.user_tag = options.user_tag.upper()

	options.event_snr_dict = {snr_str.split(":")[0] : float(snr_str.split(":")[1]) for snr_str in options.event_snr}
	options.event_chisq_dict = {chisq_str.split(":")[0] : float(chisq_str.split(":")[1]) for chisq_str in options.event_chisq}
	options.event_bankchisq_dict = {bankchisq_str.split(":")[0] : float(bankchisq_str.split(":")[1]) for bankchisq_str in options.event_bankchisq}
	for param in ("snr", "chisq", "bankchisq"):
		if not len(getattr(options, "event_%s_dict" % param)) == len(getattr(options, "event_%s" % param)):
			raise ValueError("--event-%s has duplicate ifo, --event-%s=%s" % (param, param, str(getattr(options, "event_%s" % param))))

	if not set(options.event_snr_dict) == (set(options.event_chisq_dict) | set(options.event_bankchisq_dict)):
		print("event_snr_dict : " + str(options.event_snr_dict), file=sys.stderr)
		print("event_chisq_dict : " + str(options.event_chisq_dict), file=sys.stderr)
		print("event_bankchisq_dict : " + str(options.event_bankchisq_dict), file=sys.stderr)
		raise ValueError("Each ifo provided to --event-snr must be mapped to ifos provided to either --event-chisq or --event-bankchisq")

	return options, filenames


#
# =============================================================================
#
#                                    Input
#
# =============================================================================
#


def load_distributions(filename, verbose = False):
	# Summing up RankingStat objects and RankingStatPDF objects for
	# the same template bank ID set is no longer done. It is assumed
	# that the files given as input correspond to different SVD bins,
	# otherwise their plots will have the same filenames.
	rankingstat, rankingstatpdf = far.parse_likelihood_control_doc(far.ligolw_utils.load_filename(filename, verbose = verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))
	if rankingstat is not None:
		if options.add_zerolag_to_background:
			rankingstat.denominator.lnzerolagdensity = rankingstat.zerolag
		rankingstat.finish()
	# the segment is only used to construct T050017-style filenames, so
	# just fake one if there's no livetime information
	seg = (0, 0)
	if rankingstatpdf is not None:
		seg = rankingstatpdf.segments.extent()
	elif rankingstat:
		try:
			seg = rankingstat.segmentlists.extent_all()
		except ValueError:
			pass
	return rankingstat, rankingstatpdf, seg


def load_search_results(filenames, tmp_path = None, verbose = False):
	timeslide_ln_lr = []
	zerolag_ln_lr = []
	timeslide_sngls = []
	zerolag_sngls = []

	for n, filename in enumerate(filenames, 1):
		if verbose:
			print("%d/%d: %s" % (n, len(filenames), filename), file=sys.stderr)
		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)

			cursor = connection.cursor()

			# subclass to allow it to carry extra attributes
			class snglsdict(dict):
				__slots__ = ("ln_likelihood_ratio", "fap")

			for coinc_event_id, rows in itertools.groupby(cursor.execute("""
SELECT
	coinc_event_map.coinc_event_id,
	coinc_event.likelihood,
	coinc_inspiral.false_alarm_rate,
	EXISTS (
		SELECT
			*
		FROM
			time_slide
		WHERE
			time_slide.time_slide_id == coinc_event.time_slide_id
			AND time_slide.offset != 0
	),
	sngl_inspiral.ifo,
	sngl_inspiral.snr,
	sngl_inspiral.chisq
FROM
	sngl_inspiral
	JOIN coinc_event_map ON (
		coinc_event_map.table_name == 'sngl_inspiral'
		AND coinc_event_map.event_id == sngl_inspiral.event_id
	)
	JOIN coinc_event ON (
		coinc_event.coinc_event_id == coinc_event_map.coinc_event_id
	)
	JOIN coinc_inspiral ON (
		coinc_inspiral.coinc_event_id == coinc_event.coinc_event_id
	)
WHERE
	coinc_event.coinc_def_id == ?
ORDER BY
	coinc_event_map.coinc_event_id
		""", (definer_id,)), lambda row: row[0]):
				rows = list(rows)
				is_timeslide = rows[0][3]
				# {instrument: (snr, chisq)} dictionary
				sngls = snglsdict((row[4], (row[5], row[6])) for row in rows)
				sngls.ln_likelihood_ratio = rows[0][1]
				sngls.fap = rows[0][2]
				if is_timeslide:
					timeslide_sngls.append(sngls)
				else:
					zerolag_sngls.append(sngls)

			cursor.close()
			connection.close()

	timeslide_ln_lr = sorted((sngls.ln_likelihood_ratio, sngls.fap) for sngls in timeslide_sngls)
	zerolag_ln_lr = sorted((sngls.ln_likelihood_ratio, sngls.fap) for sngls in zerolag_sngls)

	return timeslide_ln_lr, zerolag_ln_lr, timeslide_sngls, zerolag_sngls


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


#
# command line
#


options, filenames = parse_command_line()


#
# Create output directory if needed
#


os.makedirs(options.output_dir, exist_ok=True)


if options.database:
	timeslide_ln_lr, zerolag_ln_lr, timeslide_sngls, zerolag_sngls = load_search_results(options.database, tmp_path = options.tmp_space, verbose = options.verbose)
	if options.scatter_log_lambdas is not None:
		sngls = [sngl for sngl in timeslide_sngls + zerolag_sngls if sngl.ln_likelihood_ratio in options.scatter_log_lambdas]
	else:
		sngls = None
else:
	timeslide_ln_lr, zerolag_ln_lr, sngls = None, None, None


#
# plots
#


for num, filename in enumerate(filenames):
	if options.verbose:
		print("%d/%d:" % (num, len(filenames)), file=sys.stderr)
	rankingstat, rankingstatpdf, seg = load_distributions(filename, verbose = options.verbose)

	if rankingstat is not None:
		# FIXME bin index is inferred from filename
		# instead, store bin_index in rankingstat object and load here
		bin_index = int(filename.split('-')[1][:4])

		# SNR and \chi^2
		for instrument in rankingstat.instruments:
			for chi_type in ("chi", "bankchi"):
				for plot_type in ("background_pdf", "injection_pdf", "zero_lag_pdf", "LR"):
					if instrument in getattr(options, "event_%ssq_dict" % chi_type).keys():
						fig = plotfar.plot_snr_chi_pdf(rankingstat,
										instrument,
										plot_type,
										chi_type,
										options.max_snr,
										sngls = sngls,
										event_snr = options.event_snr_dict[instrument],
										event_chisq = getattr(options, "event_%ssq_dict" % chi_type)[instrument] if getattr(options, "event_%ssq" % chi_type) else None,
										)
					else:
						fig = plotfar.plot_snr_chi_pdf(rankingstat,
										instrument,
										plot_type,
										chi_type,
										options.max_snr,
										sngls = sngls
										)
					if fig is None:
						continue
					plotname = datafind.T050017_filename(instrument, "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%04d_%s_SNR%s2" % (options.user_tag, bin_index, plot_type.upper(), chi_type.upper()), seg, options.output_format, path = options.output_dir)
					if options.verbose:
						print("writing %s" % plotname, file=sys.stderr)
					fig.savefig(plotname)

		# candidate rates
		fig = plotfar.plot_rates(rankingstat)
		plotname = datafind.T050017_filename("H1L1V1", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%04d_RATES" % (options.user_tag, bin_index), seg, options.output_format, path = options.output_dir)
		if options.verbose:
			print("writing %s" % plotname, file=sys.stderr)
		fig.savefig(plotname)

		# SNR PDFs
		if options.plot_snr_snr_pdfs:
			# assume PDFs are identical for all template bank bins, and plot
			# only the first one
			if num == 0:
				for (instruments, horizon_distances) in sorted(rankingstat.numerator.SNRPDF.snr_joint_pdf_cache.keys(), key = lambda x: sorted(x[1])):
					# they're stored as a frozen set of quantized key/value
					# pairs, need to unquantize them and get a dictionary back
					horizon_distances = rankingstat.numerator.SNRPDF.quantized_horizon_distances(horizon_distances)
					fig = plotfar.plot_snr_joint_pdf(rankingstat.numerator.SNRPDF, instruments, horizon_distances, rankingstat.min_instruments, options.max_snr, sngls = sngls)
					if fig is not None:
						plotname = datafind.T050017_filename(instruments, "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_SNR_PDF_%s" % (options.user_tag, "_".join(["%s_%s" % (k, horizon_distances[k]) for k in sorted(horizon_distances)]) ), seg, options.output_format, path = options.output_dir)
						if options.verbose:
							print("writing %s" % plotname, file=sys.stderr)
						fig.savefig(plotname)

	# ranking statistic PDFs and CCDFs
	if rankingstatpdf is not None:
		for Title, which, NAME in (("Noise", "noise", "NOISE"), ("Signal", "signal", "SIGNAL")):
			fig = plotfar.plot_likelihood_ratio_pdf(rankingstatpdf, (options.min_log_lambda, options.max_log_lambda), Title, which = which)
			plotname = datafind.T050017_filename("COMBINED", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_%s_LIKELIHOOD_RATIO_PDF" % (options.user_tag, NAME), seg, options.output_format, path = options.output_dir)
			if options.verbose:
				print("writing %s" % plotname, file=sys.stderr)
			fig.savefig(plotname)

	if rankingstatpdf is not None and rankingstatpdf.zero_lag_lr_lnpdf.array.any():
		fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())
		if zerolag_ln_lr is not None:
			xhi = max(zerolag_ln_lr + timeslide_ln_lr)[0]
			xhi = 5. * math.ceil(xhi / 5.)
			xhi = max(xhi, options.max_log_lambda)
		else:
			xhi = options.max_log_lambda
		fig = plotfar.plot_likelihood_ratio_ccdf(fapfar, (options.min_log_lambda, xhi), observed_ln_likelihood_ratios = zerolag_ln_lr, is_open_box = True)
		plotname = datafind.T050017_filename("COMBINED", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_NOISE_LIKELIHOOD_RATIO_CCDF_OPEN_BOX" % options.user_tag, seg, options.output_format, path = options.output_dir)
		if options.verbose:
			print("writing %s" % plotname, file=sys.stderr)
		fig.savefig(plotname)

		fig = plotfar.plot_likelihood_ratio_ccdf(fapfar, (options.min_log_lambda, xhi), observed_ln_likelihood_ratios = timeslide_ln_lr, is_open_box = False)
		plotname = datafind.T050017_filename("COMBINED", "GSTLAL_INSPIRAL_PLOT_BACKGROUND_%s_NOISE_LIKELIHOOD_RATIO_CCDF_CLOSED_BOX" % options.user_tag, seg, options.output_format, path = options.output_dir)
		if options.verbose:
			print("writing %s" % plotname, file=sys.stderr)
		fig.savefig(plotname)
