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


### Generate an SNR PDF database file.


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


import itertools
import logging
import math
from optparse import OptionParser
import time


from ligo.lw import ligolw
from ligo.lw import utils as ligolw_utils
from ligo.lw.utils import process as ligolw_process
from glue.text_progress_bar import ProgressBar
from gstlal import reference_psd
from gstlal.stats import inspiral_extrinsics
import lal.series
from lal.utils import CacheEntry


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


def parse_command_line():
	parser = OptionParser(
		description = ""
	)

	parser.add_option("-f", "--full", action = "store_true", help = "Generate SNR PDFs for all possible horizon distance ratios as defined by the SNR PDF mechanism's internal quantization system.  Use --instruments to select the detector network to model (required).  A PDF will be constructed for every combination of --min-instruments or more instruments from the set.  When --full is enabled, any --horizon-distances options and/or PSD files are ignored.  See also --full-fragment for information on parallelization.")
	parser.add_option("--full-fragment", metavar = "n/m", default = "1/1", help = "Enable parallelization of --full by selecting a fragment of the full SNR PDFs sequence to generate.  When --full is enabled, the iteration over SNR PDFs employs a reproducible, deterministic, sequence.  That sequence is divided into m (m >= 1) approximately equal-sized intervals, and only the SNR PDFs from the n-th interval (1 <= n <= m) of the sequence will be constructed.  Afterwards, the files generated by several jobs can be combined by re-invoking the program using the --seed or --seed-cache options to obtain the complete SNR PDF collection.  The format of this option is \"n/m\", and the default is \"1/1\", which causes all SNR PDFs to be constructed.")
	parser.add_option("--horizon-distance-tolerance", metavar = "ratio", type = "float", default = 0.05, help = "Set the fractional amount by which two horizon distances must differ for them to be considered distinct (optional).  The default is 0.05, i.e., when two horizon distances differ by 5\% or more they are considered to be distinct, but less than that and they are considered to be equal.")
	parser.add_option("--horizon-distances", metavar = "instrument=distance[,instrument=distance,...]", action = "append", help = "Cache SNR PDFs for these instruments and horizon distances.  Format is, e.g., H1=120,L1=120,V1=48.  Units for distance are irrelevant (PDFs depend only on their ratios).  A PDF will be constructed for every combination of --min-instruments or more instruments from the set.  All --horizon-distances must list the same instruments (if an instrument is off set its horizon distance to 0).")
	parser.add_option("--horizon-distance-flow", metavar = "Hz", default = 10., type = "float", help = "When obtaining horizon distances from a collection PSD files, start horizon distance integral at this frequency in Hertz (default = 10 Hz).")
	parser.add_option("--horizon-distance-masses", metavar = "m1,m2", action = "append", help = "When obtaining horizon distances from a collection of PSD files, compute them for these masses in solar mass units (default = 1.4,1.4).  Can be given multiple times.")
	parser.add_option("--instruments", metavar = "name[,name,...]", help = "Set the instruments to include in the network.  If PSD files alone are to be used to provide horizon distances, or --full is selected, then this option is required, otherwise it is optional.  If both --instruments and --horizon-distances are given, they must list the same instruments.")
	parser.add_option("--min-instruments", metavar = "count", action = "append", type = "int", help = "Set the minimum number of instruments required to form a candidate;  can be given multiple times (default is 1 and 2).  Note that the probability that a recovered signal is recovered by a given set of instruments depends on how many instruments are required to participate.  The PDF cache must contain entries for every value of this parameter one will use to conduct searches.")
	parser.add_option("--output", "-o", metavar = "filename", help = "Write SNR PDF cache to this file (required).")
	parser.add_option("--seed", metavar = "filename", action = "append", default = [], help = "Seed the SNR PDF cache by loading pre-computed SNR PDFs from this file.  Can be given multiple times.")
	parser.add_option("--seed-cache", metavar = "filename", help = "Seed the SNR PDF cache by loading pre-computed SNR PDFs from the files named in this LAL cache.")
	parser.add_option("--verbose", "-v", action = "store_true", help = "Be verbose.")

	options, filenames = parser.parse_args()

	# defaults that can't be set in OptionParser because they would be
	# appended to instead of overridden
	if options.horizon_distance_masses is None:
		options.horizon_distance_masses = ["1.4,1.4"]
	if options.min_instruments is None:
		options.min_instruments = [1, 2]

	processparams = options.__dict__.copy()

	if options.verbose:
		logging.basicConfig(format = "%(message)s", level = logging.INFO)
	else:
		logging.basicConfig(format = "%(message)s", level = logging.WARNING)

	if options.seed_cache:
		options.seed += [CacheEntry(line).path for line in open(options.seed_cache)]

	if not options.full and not options.horizon_distances and not options.seed and not filenames:
		raise ValueError("must either enable --full, or provide one or more --horizon-distances, or one or more --seed and/or a --seed-cache, or provide the names of one or more PSD files")

	if options.full:
		if not options.instruments:
			raise ValueError("must set --instruments with --full enabled")

		#
		# disable PSD files and --horizon-distances options.  waste
		# of time if we're already going to generate all possible
		# PDFs
		#

		if filenames:
			logging.warning("--full enabled, ignoring PSD files")
		del filenames[:]
		if options.horizon_distances is not None:
			logging.warning("--full enabled, ignoring --horizon-distances")
		options.horizon_distances = None

	options.full_fragment = map(int, options.full_fragment.split("/"))
	if len(options.full_fragment) != 2 or options.full_fragment[1] < 1 or not 1 <= options.full_fragment[0] <= options.full_fragment[1]:
		raise ValueError("invalid --full-fragment")

	if options.horizon_distance_tolerance <= 0.:
		raise ValueError("invalid --horizon-distance-tolerance (%g), must be > 0." % options.horizon_distance_tolerance)

	if options.instruments:
		options.instruments = set(options.instruments.split(","))
		if len(options.instruments) < min(options.min_instruments):
			raise ValueError("--instruments must list at least --min-instruments (%d) instruments" % options.min_instruments)

	if options.horizon_distances is not None:
		options.horizon_distances = (items.split(",") for items in options.horizon_distances)
		options.horizon_distances = ([keyval.split("=") for keyval in items] for items in options.horizon_distances)
		options.horizon_distances = [dict((instrument, float(distance)) for instrument, distance in items) for items in options.horizon_distances]
		if not options.horizon_distances or not all(options.horizon_distances):
			raise ValueError("unknown failure parsing --horizon-distances")
		instruments = set(options.horizon_distances[0])
		if any(set(horizon_distances) != instruments for horizon_distances in options.horizon_distances):
			raise ValueError("all --horizon-distances must list the same instruments (if an instrument is off set its horizon distance to 0)")
		if not options.instruments:
			options.instruments = instruments
		elif instruments != options.instruments:
			raise ValueError("--instruments does not match --horizon-distances")
		if any(min(horizon_distances.values()) < 0. for horizon_distances in options.horizon_distances):
			raise ValueError("all --horizon-distances must be >= 0.")
	else:
		# we'll populate this later
		options.horizon_distances = []

	# if --full was given it has unset filenames;  if any
	# --horizon-distances were given then .instruments has been
	# populated from those if it wasn't already set
	if filenames and not options.instruments:
		raise ValueError("must set --instruments if PSD files alone are used for horizon distances")

	options.horizon_distance_masses = [map(float, s.split(",")) for s in options.horizon_distance_masses]
	if any(len(masses) != 2 for masses in options.horizon_distance_masses):
		raise ValueError("must provide exactly 2 masses for each --horizon-distance-masses")
	if any((m1 <= 0. or m2 <= 0.) for m1, m2 in options.horizon_distance_masses):
		raise ValueError("all --horizon-distances-masses must be > 0")

	if min(options.min_instruments) < 1:
		raise ValueError("--min-instruments must be >= 1")

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

	return options, processparams, filenames


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


#
# parse command line
#


options, processparams, filenames = parse_command_line()


#
# initialize empty SNR PDF cache
#


snrpdf = inspiral_extrinsics.SNRPDF(snr_cutoff = 4., log_distance_tolerance = math.log(1.0 + options.horizon_distance_tolerance))
snrpdf.snr_joint_pdf_cache.clear()	# just in case


#
# now load seed files if requested.  all SNRPDF instances share a single
# global cache of PDFs, so loading one from disk has the effect of
# inserting its PDFs into our existing cache
#


for n, filename in enumerate(options.seed, 1):
	logging.info("loading seed PDFs %d/%d:" % (n, len(options.seed)))
	seed_snrpdf = inspiral_extrinsics.SNRPDF.load(open(filename), verbose = options.verbose)
	if seed_snrpdf.snr_cutoff != snrpdf.snr_cutoff:
		raise ValueError("incompatible SNR cut-offs")
	if seed_snrpdf.log_distance_tolerance != snrpdf.log_distance_tolerance:
		raise ValueError("incompatible horizon distance tolerance, found %g require %g" % (math.exp(seed_snrpdf.log_distance_tolerance) - 1., math.exp(snrpdf.log_distance_tolerance) - 1.))
	if seed_snrpdf.min_ratio != snrpdf.min_ratio:
		raise ValueError("incompatible minimum distance ratios")


#
# obtain horizon distances from PSD files if requested
#


for n, filename in enumerate(filenames, 1):
	logging.info("loading PSD %d/%d:" % (n, len(filenames)))
	psd = lal.series.read_psd_xmldoc(ligolw_utils.load_filename(filename, contenthandler = lal.series.PSDContentHandler, verbose = options.verbose))
	for m1, m2 in options.horizon_distance_masses:
		horizon_distances = dict((instrument, (0. if instrument not in psd else reference_psd.HorizonDistance(options.horizon_distance_flow, psd[instrument].f0 + psd[instrument].data.length * psd[instrument].deltaF, psd[instrument].deltaF, m1, m2)(psd[instrument], 8.)[0])) for instrument in options.instruments)
		logging.info("\t%s" % ", ".join("%s = %.4g Mpc" % x for x in sorted(horizon_distances.items())))
		options.horizon_distances.append(horizon_distances)


#
# construct (fragment of) full spectrum of horizon distances if requested
#


if options.full:
	# the use of sorted() in both loops ensures the sequence is
	# reproducible from one job to the next.  this is required by the
	# --full-fragment feature.
	for loudest in sorted(options.instruments):
		other_instruments = sorted(options.instruments - set((loudest,)))
		for other_distances in itertools.product(*([snrpdf.quants] * len(other_instruments))):
			options.horizon_distances.append(snrpdf.quantized_horizon_distances([(loudest, 0.0)] + zip(other_instruments, other_distances)))
	options.horizon_distances.append(dict.fromkeys(options.instruments, 0.0))
	# clip total fragment count to total number of ratios
	n = len(options.horizon_distances)
	options.full_fragment[1] = min(options.full_fragment[1], n)
	# clip fragment index to clipped fragment count
	options.full_fragment[0] = min(*options.full_fragment)
	# mean horizon distance ratios per fragment
	ratios_per_fragment = n / float(options.full_fragment[1])
	# find start and end of interval to compute
	start = int(round(ratios_per_fragment * (options.full_fragment[0] - 1)))
	end = int(round(ratios_per_fragment * options.full_fragment[0]))
	# clip sequence
	options.horizon_distances = options.horizon_distances[start : end]


#
# populate SNR PDF cache
#


start_time = time.time()
for n, horizon_distances in enumerate(options.horizon_distances, 1):
	logging.info("Horizon distance ratio %d/%d, %g minutes elapsed:" % (n, len(options.horizon_distances), (time.time() - start_time) / 60.))
	for min_instruments in options.min_instruments:
		snrpdf.add_to_cache(horizon_distances, min_instruments, verbose = options.verbose)


#
# write to disk
#


xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = ligolw_process.register_to_xmldoc(xmldoc, "gstlal_inspiral_make_snr_pdf", processparams, instruments = options.instruments)
xmldoc.childNodes[0].appendChild(snrpdf.to_xml())
ligolw_utils.write_filename(xmldoc, options.output, verbose = options.verbose)
