#!/usr/bin/env python3
#
# Copyright (C) 2010--2015  Kipp Cannon, Chad Hanna
#
# 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 compute the noise probability distributions of likehood ratios for inspiral triggers

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


from optparse import OptionParser
import sys


from ligo.lw import ligolw
from ligo.lw import utils as ligolw_utils
from ligo.lw.utils import process as ligolw_process
from gstlal import far
from lal.utils import CacheEntry


__author__ = "Kipp Cannon <kipp.cannon@ligo.org>"
__version__ = "git id %s" % ""	# FIXME
__date__ = ""	# FIXME


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


def parse_command_line():
	parser = OptionParser(
		version = "Name: %%prog\n%s" % "" # FIXME
	)
	parser.add_option("--likelihood-cache", metavar = "filename", help = "Also load the likelihood ratio data files listsed in this LAL cache.  See lalapps_path2cache for information on how to produce a LAL cache file.")
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	parser.add_option("--ranking-stat-samples", metavar = "N", default = 2**24, type = "int", help = "Construct ranking statistic histograms by drawing this many samples from the ranking statistic generator (default = 2^24).")
	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("--output", metavar = "filename", help = "Write merged raw likelihood data and likelihood ratio histograms to this LIGO Light-Weight XML file.")
	options, urls = parser.parse_args()

	paramdict = options.__dict__.copy()

	if options.likelihood_cache is not None:
		urls += [CacheEntry(line).url for line in open(options.likelihood_cache)]
	if not urls:
		raise ValueError("must provide some likelihood files")

	if options.output is None:
		raise ValueError("must set --output")

	return options, urls, paramdict


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


#
# command line
#


options, urls, paramdict = parse_command_line()


#
# load parameter distribution data
#


rankingstat = far.marginalize_pdf_urls(urls, "RankingStat", verbose = options.verbose)


#
# invoke .finish() to apply density estimation kernels and correct the
# normalization.  preserve the original, raw data, so we can write it do
# disk later with the ranking stat PDF obtained from it.  if we wish to
# draw samples from a population that includes the zero-lag, then we also
# construct a separate, sampler, PDF object.
#


lr_rankingstat = rankingstat.copy()
lr_rankingstat.finish()
if options.add_zerolag_to_background:
	signal_noise_pdfs = rankingstat.copy()
	signal_noise_pdfs.denominator.lnzerolagdensity = signal_noise_pdfs.zerolag
	signal_noise_pdfs.finish()
else:
	signal_noise_pdfs = None


#
# generate likelihood ratio histograms
#


rankingstatpdf = far.RankingStatPDF(lr_rankingstat, signal_noise_pdfs = signal_noise_pdfs, nsamples = options.ranking_stat_samples, verbose = options.verbose)


#
# Write the parameter and ranking statistic distribution data to a file
#


xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral_calc_rank_pdfs", paramdict = paramdict, instruments = rankingstat.instruments)
far.gen_likelihood_control_doc(xmldoc, rankingstat, rankingstatpdf)
ligolw_process.set_process_end_time(process)
ligolw_utils.write_filename(xmldoc, options.output, verbose = options.verbose)
