#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1674814439023/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# 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
import 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("--databases", metavar = "filename", default = [], action = "append", help = "Provide the name of a trigger database.  Can be given multiple times.")
	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.databases:
		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)
if (rankingstatpdf.zero_lag_lr_lnpdf.array==0).all():
	raise ValueError("A zerolag histogram is not stored in %s. Make sure to run gstlal_diststatpdf_collect_zerolag in advance and point to post dist-stat-pdf file." % options.background_bins_file)

# FIXME : add assert to make sure the zerolag histogram is populated.

#
# 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.databases, 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
		#

		process.set_end_time_now()
		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)


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