#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1694401452756/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python
#
# Copyright (C) 2023 Leo Tsukada, Kipp Cannon
#
# 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 listen to lvalerts, download the coinc.xml from gstlal gracedb events, plot it, and upload the dtdphi plots


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


import logging
from optparse import OptionParser
import os.path
import sys
import urllib.parse as urlparse
import json


import lal


from ligo.lw import utils as ligolw_utils
from ligo.lw import lsctables
from gstlal.plots import set_matplotlib_cache_directory
set_matplotlib_cache_directory()
from gstlal import far
from gstlal import lvalert_helper
from gstlal.plots import dtdphi as plotdtdphi
from ligo.gracedb import rest as gracedb


import matplotlib
matplotlib.rcParams.update({
	"font.size": 10.0,
	"axes.titlesize": 10.0,
	"axes.labelsize": 10.0,
	"xtick.labelsize": 8.0,
	"ytick.labelsize": 8.0,
	"legend.fontsize": 8.0,
	"figure.dpi": 100,
	"savefig.dpi": 100,
	"text.usetex": True,
	"path.simplify": True
})


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


def parse_command_line():
	parser = OptionParser()
	parser.add_option("--format", default = "png", help = "Set file format by selecting the extention (default = \"png\").")
	parser.add_option("--no-upload", action = "store_true", help = "Write plots to disk.")
	parser.add_option("--output-dir", default = "./", help = "Set the directory to save the result plots to.")
	parser.add_option("--add-subthresh", action = "store_true", help = "Add sub-threshold ifos whose SNR < 4 for dtdphi plots")
	parser.add_option("--skip-404", action = "store_true", help = "Skip events that give 404 (file not found) errors (default is to abort).")
	parser.add_option("--gracedb-service-url", default="%s" % gracedb.DEFAULT_SERVICE_URL, help = "GraceDb service url to upload to (default: %s)" % gracedb.DEFAULT_SERVICE_URL)
	parser.add_option("-v", "--verbose", action = "store_true", help = "Be verbose.")
	options, graceids = parser.parse_args()

	if not graceids:
		# FIXME:  lvalert_listen doesn't allow command-line
		# options, enable logging for online analysis
		options.verbose = True

	# can only call basicConfig once (otherwise need to switch to more
	# complex logging configuration)
	if options.verbose:
		logging.basicConfig(format = "%(asctime)s:%(message)s", level = logging.INFO)
	else:
		logging.basicConfig(format = "%(asctime)s:%(message)s")

	return options, graceids


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


options, graceids = parse_command_line()

gracedb_client = gracedb.GraceDb(service_url = options.gracedb_service_url)


for graceid in graceids:
	coinc_xmldoc = lvalert_helper.get_coinc_xmldoc(gracedb_client, graceid)
	rankingstat_xmldoc = ligolw_utils.load_fileobj(lvalert_helper.get_filename(gracedb_client, graceid, filename = 'ranking_data.xml.gz'), contenthandler = far.RankingStat.LIGOLWContentHandler)

	#
	# dtdphi plot
	#

	sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(coinc_xmldoc)
	offset_vectors = lsctables.TimeSlideTable.get_table(coinc_xmldoc).as_dict()
	assert len(offset_vectors) == 1, "the time slide table has to have exactly one time-slide entry."
	offset_vector = offset_vectors[list(offset_vectors)[0]]
	rankingstat, _ = far.parse_likelihood_control_doc(rankingstat_xmldoc)

	### FIXME : ugly hack to add sub-threshold triggers
	if options.add_subthresh:
		amp_factor = (rankingstat.snr_min) / min(row.snr for row in sngl_inspiral_table)
		for row in sngl_inspiral_table:
			row.snr *= amp_factor
			row.chisq = 1
	event_kwargs = rankingstat.kwargs_from_triggers(sngl_inspiral_table, offset_vector)
	ifos = sorted(event_kwargs["snrs"])
	ifo1 = ifos.pop(0)
	snrs = event_kwargs["snrs"]
	# remove segments for ifos not having horizon distance after
	# compression, which would cause an error inside
	# local_mean_horizon_distance()
	segs_nonzero = {ifo:seg for ifo, seg in event_kwargs["segments"].items() if len(rankingstat.numerator.horizon_history[ifo]) > 0}
	horizons = rankingstat.numerator.local_mean_horizon_distance(segs_nonzero, template_id = event_kwargs["template_id"])

	### generate and upload plots
	for ifo2 in ifos:
		ifo_pair = ifo1[0] + ifo2[0]
		dt_ref = event_kwargs["dt"][ifo2] - event_kwargs["dt"][ifo1]
		dphi_ref = event_kwargs["phase"][ifo2] - event_kwargs["phase"][ifo1]

		fig = plotdtdphi.plots_dtdphi(ifo1, ifo2, snrs, horizons, sngl={"dt":dt_ref, "dphi":dphi_ref})
		filename = "%s/%s_dtdphi_%s.%s" % (options.output_dir, graceid, ifo_pair, options.format)
		if options.no_upload:
			logging.info("writing %s ..." % filename)
			fig.savefig(filename)
		else:
			lvalert_helper.upload_fig(fig, gracedb_client, graceid, filename = filename, log_message = '{} dtdphi 2D pdf plot'.format(ifo_pair), tagname = ('dtdphi', 'background'))

