#!/usr/bin/env python3
#
# Copyright (C) 2019-2020  Hiroaki Ohta
#
# 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.

try:
	from fpconst import NegInf
except ImportError:
	# not all machines have fpconst installed
	NegInf = float("-inf")
import itertools
import numpy as np
from optparse import OptionParser
import pickle
import time
np.random.seed(int(time.time()))
from tqdm import tqdm

from lalburst.snglcoinc import light_travel_time
from lalinspiral import inspinjfind
from ligo.lw import ligolw
from ligo.lw import lsctables
from ligo.lw import utils as ligolw_utils
from gstlal import far

@lsctables.use_in
class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
	pass

def build_tmplt_to_sim_index(xmldoc):
	coinc_def_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(inspinjfind.InspiralSTCoincDef.search, inspinjfind.InspiralSTCoincDef.search_coinc_type, create_new = False)
	coinc_event_ids = set(row.coinc_event_id for row in lsctables.CoincTable.get_table(xmldoc) if row.coinc_def_id == coinc_def_id)

	sim_index = dict((row.simulation_id, row) for row in lsctables.SimInspiralTable.get_table(xmldoc))

	# index maps template_id to list of simulation_ids for which that is the best template
	index = {}
	for coinc_event_id, coinc_event_maps in itertools.groupby(sorted(lsctables.CoincMapTable.get_table(xmldoc), key = lambda row: (row.coinc_event_id, row.table_name)), lambda row: row.coinc_event_id):
		# implicitly checks that there are only two rows in the coinc
		coinc_event_map_sim, coinc_event_map_sngl = coinc_event_maps
		# add to index
		index.setdefault(coinc_event_map_sngl.event_id, []).append(sim_index[coinc_event_map_sim.event_id])

	# done
	return index


def lnL_wrapper(rankingstat, params):
	# not all the triggers are above the SNR threshold.  they have been
	# left in the param stream so that calling codes can account for
	# the rate at which threshold crossing fails to occur in their
	# statistics.  which instruments are below threshold?
	blind = frozenset(instrument for instrument, snr in params["snrs"].items() if snr < rankingstat.snr_min)
	# remove them from params.  injection is missed if not enough
	# triggers remain
	for instrument in blind:
		del params["snrs"][instrument]
		del params["chi2s_over_snr2s"][instrument]
		del params["phase"][instrument]
		del params["dt"][instrument]
	if len(params["snrs"]) < rankingstat.min_instruments:
		return NegInf

	# the triggers are not neccessarily mutually coincident because the
	# time error distribution is unbounded.  as with the SNRs, these
	# noise-induced coincidence failures are left in the simulated
	# param stream so the rate at which they occur can be accounted for
	# in the statistics.
	#
	# dealing with this is tricky.	if we have a full n-way coincidence
	# then we compute the ranking statistic and we are done.  however,
	# if some pairs of triggers are not coincident, for example if we
	# have an {H1, L1, V1} network and the {H1, L1} and {H1, V1} pairs
	# are coincident but {L1, V1} is not, what the detection pipeline
	# would do is report this as two doubles.  the injection is found
	# if one of these yields a ranking statistic above the detection
	# threshold.  what we do is work our way down from the
	# largest number of available triggers to the smallest allowed by
	# min_instruments, until we find at least one coincidence with that
	# many triggers in it, then we report the largest ranking statistic
	# value for all the coincidences with that many
	# triggers (if more than one can be formed).  considering the {H1,
	# L1, V1} example above the sequence would be:
	#
	#	is {H1, L1, V1} coincident? --> no
	#	are any of the pairs coincident? --> yes
	#		compute ln L for all coincident pairs
	#		report largest value
	#		done
	#
	# if no doubles are coincident and min_instruments is 1 then we
	# would continue to singles, otherwise if min_instruments is 2 we
	# would stop at the doubles and report a missed injection

	for n in range(len(params["snrs"]), rankingstat.min_instruments - 1, -1):
		lnL = []
		for selected_instruments in itertools.combinations(params["snrs"], n):
			if len(selected_instruments) > 1:
				if max(abs(params["dt"][insta] - params["dt"][instb]) - light_travel_time(insta, instb) for insta, instb in itertools.combinations(selected_instruments, 2)) > rankingstat.delta_t:
					# this combo is not mutually coincident
					continue
			else:
				pass
			# make a new params object for just these
			# instruments
			selected_params = params.copy()
			for param in ("snrs", "chi2s_over_snr2s", "phase", "dt"):
				selected_params[param] = dict((instrument, val) for instrument, val in selected_params[param].items() if instrument in selected_instruments)
			# append ln L
			lnL.append(rankingstat(**selected_params))

		# if at least one combo was coincident, report largest ln
		# L, otherwise move on to next smaller n

		if lnL:
			return max(lnL)

	# if we get here, no set of instruments was actually coincident,
	# report a missed injection

	return NegInf

def parse_command_line():
	parser = OptionParser(description = __doc__)

	# Basic option
	parser.add_option("--f-low", metavar = "Hertz", default = 15., type = "float", help = "Low frequency cutoff.  Default is 15 Hz")
	parser.add_option("--trials-per-injection", metavar = "count", default = 1000, type = "int", help = "Set the number of trials to run per injection.  Default is 1000.")
	parser.add_option("--xaxis-points", metavar = "count", default = 100, type = "int", help = "Specify the number of false-alarm rates for which to compute the search volume.  Default is 100.")

	# Input data options
	parser.add_option("--injection-template-match-file", metavar = "filename", help = "XML file containing injection template match (required).")
	parser.add_option("-l", "--likelihood-url", metavar = "URL", action = "append", help = "Set the name of the likelihood ratio data file to use.  Can be given more than once.  Filenames and URLs are accepted. (required).")

	# Output data options
	parser.add_option("--output-file", metavar = "URL", help = "Text file of factored lnlrcdf_signal")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose (optional).")

	options, filenames = parser.parse_args()

	required_options = ("injection_template_match_file", "likelihood_url", "output_file")
	missing_options = [option for option in required_options if not getattr(options, option)]
	if missing_options:
		raise ValueError("%s must be set" % ", ".join("--%s" % option.replace("_", "-") for option in missing_options))

	return options

##############
#MAIN PROGRAM#
##############

options = parse_command_line()

#
# create output factor
#

# Should choose a sufficiently large interval and small density for false alarm rate
lnL_th = np.linspace(-75, 75, options.xaxis_points)

lnlrcdfsignals = {"lnlrcdf": [], "lnL_th": lnL_th}


#
# read and index injection<-->template mapping
#


tmplt_to_sim = build_tmplt_to_sim_index(ligolw_utils.load_filename(options.injection_template_match_file, contenthandler = LIGOLWContentHandler, verbose = options.verbose))


#
# iterate over ranking stat files
#

for filename in tqdm(options.likelihood_url, desc = "opening likelihood", disable = not options.verbose):
	rankingstat = far.marginalize_pdf_urls([filename], "RankingStat", verbose = options.verbose)
	rankingstat.finish()

	#
	# iterate over templates covered by this ranking stat object
	#

	for template_id in tqdm(rankingstat.template_ids, desc = "expanding rankingstat.template_ids", disable = not options.verbose):
		#
		# iterate over injections for which that is the best match (if any)
		#

		if template_id not in tmplt_to_sim:
			continue

		for inj in tqdm(tmplt_to_sim[template_id], leave = False, desc = "calculating lnL cdf", disable = not options.verbose):
			#
			# draw ln L's for this injection
			#

			lnL = [lnL_wrapper(rankingstat, params) for params in itertools.islice(rankingstat.numerator.random_sim_params(inj, f_low = options.f_low), options.trials_per_injection)]

			#
			# calc P(lnL >= threshold | candidate) and estimate its uncertainty
			#

			lnlrcdf = np.array([sum(x >= threshold for x in lnL) for threshold in lnL_th]) / float(options.trials_per_injection)
			lnlrcdfsignals["lnlrcdf"].append(((inj.distance, inj.mchirp), lnlrcdf))


#
# save the data
#

if options.verbose:
	print("saving lnL CDF")

with open(options.output_file, "wb") as f:
	pickle.dump(lnlrcdfsignals, f)
