#!/usr/bin/env python3
#
# Copyright (C) 2010--2014  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 reset likelihood data after a burn in


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


import sys
import warnings
import numpy
from gstlal import far
from ligo.lw import utils as ligolw_utils
from ligo.lw.utils import process as ligolw_process
from ligo.lw import ligolw
from ligo import segments
from lal import LIGOTimeGPS
from optparse import OptionParser


def parse_command_line():
	parser = OptionParser(
		version = "Name: %%prog\n%s" % "" # FIXME
	)
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	parser.add_option("--background-ranking-file", metavar = "filename", help = "Write likelihood files to disk and include the names in this cachefile file.")

	parser.add_option("--zerolag-ranking-file", metavar = "filename", help = "Write zerolag likelihood files to disk and include the names in this cachefile file.")
	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("--skip-seg-and-rd-reset", action = "store_true", help = "Skip adjusting the segments and ranking data. This would make the entire use of this program a no op unless --add-zerolag-to-background is used.  So you have to do that.")
	parser.add_option("--segment-and-horizon", action = "append", help = "Append to a list of segments and horizon distances for a given instrument.  Argument specified as IFO:start:end:horizon, e.g., H1:1000000000:1000000100:120 ")
	options, filenames = parser.parse_args()

	process_params = dict(options.__dict__)

	def parse_segment_and_horizon(options = options):
		seglistdict = segments.segmentlistdict()
		for x in options.segment_and_horizon:
			ifo, start, stop, horizon = x.split(":")
			seglistdict.setdefault(ifo, segments.segmentlist()).append(segments.segment([LIGOTimeGPS(start), LIGOTimeGPS(stop)]))
		return seglistdict

	if options.segment_and_horizon is None:
		raise ValueError("--segment-and-horizon required")
	seglistdict = parse_segment_and_horizon(options)

	if options.skip_seg_and_rd_reset and not options.add_zerolag_to_background:
		raise ValueError("if using --skip-seg-and-rd-reset you must use --add-zerolag-to-background or else this program will do nothing")

	return options, process_params, seglistdict


options, process_params, segs = parse_command_line()

if options.verbose:
	print >> sys.stderr, "Livetime: ", abs(segs.extent_all())
	print >> sys.stderr, "Extent: ", segs.extent_all()

like_cpd, like_rd = far.parse_likelihood_control_doc(ligolw_utils.load_filename(options.background_ranking_file, verbose = options.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))

_, zlike_rd = far.parse_likelihood_control_doc(ligolw_utils.load_filename(options.zerolag_ranking_file, verbose = options.verbose, contenthandler = far.RankingStat.LIGOLWContentHandler))

# optionally add the zero lag SNR/chi counts to the background
# FIXME:  this is busted.  needs to be updated following the re-write
if options.add_zerolag_to_background:
	raise ValueError("not implemented")

if not options.skip_seg_and_rd_reset:
	# replace thae live time with the user specified live time
	new_like_segs = segs
	new_zlike_segs = segs

	# Make the observed counts match the background sample but with the correct normalization
	num_zero_lag = zlike_rd.zero_lag_lr_lnpdf.array.sum() * float(abs(new_like_segs)) / float(abs(like_rd.segments))
	if num_zero_lag <= 100 or numpy.isnan(num_zero_lag):
		warnings.warn("found %f zero lag counts, replacing with 100" % num_zero_lag)
		num_zero_lag = 100
	zlike_rd.zero_lag_lr_lnpdf.array[:] = like_rd.noise_lr_lnpdf.array[:]
	zlike_rd.zero_lag_lr_lnpdf.array *= num_zero_lag / zlike_rd.zero_lag_lr_lnpdf.array.sum()
	# make the counts integers
	if options.verbose:
		print >> sys.stderr, "replacing with %f zero lag counts" % zlike_rd.zero_lag_lr_lnpdf.array.sum()


# write out the background file
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(xmldoc, sys.argv[0], instruments = like_cpd.instruments, paramdict = process_params)
far.gen_likelihood_control_doc(xmldoc, like_cpd, like_rd)
ligolw_utils.write_filename(xmldoc, options.background_ranking_file, verbose = options.verbose)

# write out the zerolag file
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(xmldoc, sys.argv[0], instruments = like_cpd.instruments, paramdict = process_params)
far.gen_likelihood_control_doc(xmldoc, None, zlike_rd)
ligolw_utils.write_filename(xmldoc, options.zerolag_ranking_file, verbose = options.verbose)
