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

### A program to marginalize the likelihood pdfs in noise across mass bins for a gstlal inspiral analysis.
###
### Review status
### -------------
###
### +-----------------------------+------------------------------------------+------------+
### | Names                       | Hash                                     | Date       |
### +=============================+==========================================+============+
### | Florent, Jolien, Kipp, Chad | 1dbbbd963c9dc076e1f7f5f659f936e44005f33b | 2015-05-14 |
### +-----------------------------+------------------------------------------+------------+
###  


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


from optparse import OptionParser


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


from gstlal import far


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


def parse_command_line():
	parser = OptionParser(
	)
	parser.add_option("--ignore-missing", action = "store_true", help = "Ignore and skip missing input documents.")
	parser.add_option("--marginalize", metavar = "{ranking-stat|ranking-stat-pdf}", default = "ranking-stat", help = "Set which set of PDFs to marginalize, the ranking statistics themselves, or the distributions of ranking statistic values (default: ranking-stat).")
	parser.add_option("--density-estimate-zero-lag", action = "store_true", help = "Apply density estimation algorithm to zero-lag PDFs (default: do not).  Requires --marginalize=ranking-stat-pdf.  In the online analysis, the ingested zero-lag histograms contain raw bin counts, but the consumer of this program's output requires the PDFs to be properly density-estimated, so we provide the option of performing that operation here as a courtesy.  This will probably work differently one day.")
	parser.add_option("-o", "--output", metavar = "filename", help = "Set the output file name (default = write to stdout).")
	parser.add_option("--likelihood-cache", metavar = "filename", help = "Set the cache file name from which to read likelihood files.")
	parser.add_option("--verbose", action = "store_true", help = "Be verbose.")

	options, urls = parser.parse_args()

	if options.marginalize not in ("ranking-stat", "ranking-stat-pdf"):
		raise ValueError("--marginalize must be one of 'ranking-stat' or 'ranking-stat-pdf'")
	if options.density_estimate_zero_lag and options.marginalize != "ranking-stat-pdf":
		raise ValueError("--density-estimate-zero-lag cannot be set unless --marginalize=ranking-stat-pdf")

	if options.likelihood_cache:
		urls += [CacheEntry(line).url for line in open(options.likelihood_cache)]
	if not urls and not options.ignore_missing:
		raise ValueError("no input documents")

	return options, urls


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


#
# parse command line
#


options, urls = parse_command_line()


#
# initialize output document
#


xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(xmldoc, u"gstlal_inspiral_marginalize_likelihood", options.__dict__)


#
# loop over input documents.  NOTE:  this process leaves the internal PDF
# metadata improperly normalized (the normalizations are not recomputed by
# the .__iadd__() methods for performance reasons).  The XML writing code,
# however, will ensure everything has been normalized properly before
# writing it to disk.
#


marginalized = far.marginalize_pdf_urls(
	urls,
	which = "RankingStat" if options.marginalize == "ranking-stat" else "RankingStatPDF",
	ignore_missing_files = options.ignore_missing,
	verbose = options.verbose
)


#
# Apply density estimation to zero-lag rates
#


if options.density_estimate_zero_lag:
	marginalized.density_estimate_zero_lag_rates()


#
# write output document
#


if options.marginalize == "ranking-stat":
	process.instruments = marginalized.instruments
	far.gen_likelihood_control_doc(xmldoc, marginalized, None)
else:
	far.gen_likelihood_control_doc(xmldoc, None, marginalized)
ligolw_process.set_process_end_time(process)
ligolw_utils.write_filename(xmldoc, options.output, verbose = options.verbose)
