#!/usr/bin/env python3
#
# Copyright (C) 2011--2013 Kipp Cannon, Chad Hanna, Drew Keppel
#
# 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.

### Compute FAR and FAP distributions from the likelihood CCDFs.

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


from optparse import OptionParser
try:
	import sqlite3
except ImportError:
	# pre 2.5.x
	from pysqlite2 import dbapi2 as sqlite3
sqlite3.enable_callback_tracebacks(True)
import sys


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 lalinspiral import thinca
from gstlal import far


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


def parse_command_line():
	parser = OptionParser()
	parser.add_option("--background-bins-file", metavar = "filename", help = "Set the name of the xml file containing the marginalized likelihood (required).")
	parser.add_option("--tmp-space", metavar = "dir", help = "Set the name of the tmp space if working with sqlite.")
	parser.add_option("--non-injection-db", metavar = "filename", default = [], action = "append", help = "Provide the name of a database from a non-injection run.  Can be given multiple times.")
	parser.add_option("--injection-db", metavar = "filename", default = [], action = "append", help = "Provide the name of a database from an injection run.  Can be given multiple times.  Databases are assumed to be over the same time period as the non injection databases using the same templates.  If not the results will be nonsense.")
	parser.add_option("--force", "-f", action = "store_true", help = "Force script to reevaluate FARs and FAPs.")
	parser.add_option("--verbose", "-v", action = "store_true", help = "Be verbose.")
	options, filenames = parser.parse_args()

	process_params = options.__dict__.copy()

	if options.background_bins_file is None:
		raise ValueError("must set --background-bins-file")

	if not options.non_injection_db + options.injection_db:
		raise ValueError("must provide at least one database file to process")

	if filenames:
		raise ValueError("unrecognized trailing arguments")

	return options, process_params, filenames


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


#
# Parse command line
#


options, process_params, filenames = parse_command_line()


#
# Retrieve distribution data
#


_, rankingstatpdf = far.parse_likelihood_control_doc(ligolw_utils.load_filename(options.background_bins_file, contenthandler = far.RankingStat.LIGOLWContentHandler, verbose = options.verbose))
if rankingstatpdf is None:
	raise ValueError("\"%s\" does not contain likelihood ratio PDFs" % options.background_bins_file)


#
# Histogram zero-lag likelihood ratios to construct extinction model.
# FIXME:  don't do this here.  write stand-alone tool to collect zero-lag
# counts and have this program require that as input data.  also, below,
# don't write any ranking statistic output file from this program.
#


if options.verbose:
	print("beginning count of above-threshold events", file=sys.stderr)

rankingstatpdf.zero_lag_lr_lnpdf.array[:] = 0.

for n, filename in enumerate(options.non_injection_db, start = 1):
	#
	# get working copy of database.  do not use scratch space for this,
	# query is very fast
	#

	if options.verbose:
		print("%d/%d: %s" % (n, len(options.non_injection_db), filename), file=sys.stderr)
	with dbtables.workingcopy(filename, discard = True, verbose = options.verbose) as working_filename:
		connection = sqlite3.connect(str(working_filename))

		#
		# update counts
		#

		xmldoc = dbtables.get_xml(connection)
		coinc_def_id = lsctables.CoincDefTable.get_table(xmldoc).get_coinc_def_id(thinca.InspiralCoincDef.search, thinca.InspiralCoincDef.search_coinc_type, create_new = False)
		xmldoc.unlink()
		rankingstatpdf.collect_zero_lag_rates(connection, coinc_def_id)

		#
		# done
		#

		connection.close()


#
# Apply density estimation to zero-lag rates
#


rankingstatpdf.density_estimate_zero_lag_rates()


#
# Now generate new ranking statistic PDFs by applying the clustering
# extinction model, and then initialize the FAP & FAR assignment machine
#


fapfar = far.FAPFAR(rankingstatpdf.new_with_extinction())


#
# Iterate over databases
#


if options.verbose:
	print("assigning FAPs and FARs", file=sys.stderr)

for n, filename in enumerate(options.non_injection_db + options.injection_db, start = 1):
	#
	# get working copy of database
	#

	if options.verbose:
		print("%d/%d: %s" % (n, len(options.non_injection_db + options.injection_db), filename), file=sys.stderr)
	if not options.force and sqlite3.connect(filename).cursor().execute("""SELECT EXISTS(SELECT * FROM process WHERE program == ?);""", (u"gstlal_compute_far_from_snr_chisq_histograms",)).fetchone()[0]:
		if options.verbose:
			print("already processed, skipping", file=sys.stderr)
		continue
	with dbtables.workingcopy(filename, tmp_path = options.tmp_space, verbose = options.verbose) as working_filename:
		connection = sqlite3.connect(str(working_filename))

		#
		# record our passage
		#

		xmldoc = dbtables.get_xml(connection)
		process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_compute_far_from_snr_chisq_histograms", process_params)

		#
		# assign FAPs and FARs
		#

		fapfar.assign_fapfars(connection)

		#
		# done, file is restored to original location
		#

		ligolw_process.set_process_end_time(process)
		connection.cursor().execute("UPDATE process SET end_time = ? WHERE process_id == ?", (process.end_time, process.process_id))

		connection.commit()
		connection.close()

if options.verbose:
	print("FAP and FAR assignment complete", file=sys.stderr)


#
# Write parameter and ranking statistic distribution file now with zero-lag
# counts populated.
#
# FIXME:  do not write this output file, rely on stand-alone tool to
# collect zero-lag counts before running this program, and make that
# information available to other tools that way
#


xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_compute_far_from_snr_chisq_histograms", process_params)
far.gen_likelihood_control_doc(xmldoc, None, rankingstatpdf)
ligolw_process.set_process_end_time(process)

outname = "post_%s" % options.background_bins_file
ligolw_utils.write_filename(xmldoc, outname, verbose = options.verbose)

if options.verbose:
	print("done", file=sys.stderr)
