#!/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("--output-background-bins-file", metavar = "filename", help = "Set the name of post marginalized likelihood output file with zero-lag counts populated. If not set, creates a file of the form post_{background_bins_file}.")
	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("--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:
		raise ValueError("must provide noninj database file to process")

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

	if not options.output_background_bins_file:
		options.output_background_bins_file = "post_%s" % options.background_bins_file

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


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()


#
# Write parameter and ranking statistic distribution file now with zero-lag
# counts populated.
#


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)
process.set_end_time_now()
ligolw_utils.write_filename(xmldoc, options.output_background_bins_file, verbose = options.verbose)

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