#!/home/conda/feedstock_root/build_artifacts/gstlal-inspiral_1674814439023/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_place/bin/python

# Copyright (C) 2019  Patrick Godwin
#
# 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.

__usage__ = "gstlal_ll_inspiral_event_uploader [--options]"
__description__ = "an executable to aggregate and upload GraceDB events from gstlal_inspiral jobs"
__author__ = "Patrick Godwin (patrick.godwin@ligo.org)"

#-------------------------------------------------
#				   Preamble
#-------------------------------------------------

from collections import deque, OrderedDict
import http.client as httplib
import gzip
import json
import logging
import math
from optparse import OptionParser
from io import BytesIO
import time
import yaml

import numpy
from scipy import random

from ligo.segments import segment
from ligo.gracedb.rest import GraceDb, HTTPError
from ligo.gracedb.rest import DEFAULT_SERVICE_URL as DEFAULT_GRACEDB_URL
from ligo.scald import utils
from ligo.scald.io import influx

from lal import LIGOTimeGPS

from gstlal import events
from gstlal import inspiral

from ligo.lw import ligolw
from ligo.lw import lsctables
from ligo.lw import utils as ligolw_utils

class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
    pass

lsctables.use_in(LIGOLWContentHandler)

#-------------------------------------------------
#				   Functions
#-------------------------------------------------

def parse_command_line():

	parser = OptionParser(usage=__usage__, description=__description__)
	parser.add_option("-v", "--verbose", default=False, action="store_true", help = "Be verbose.")
	parser.add_option("--rootdir", metavar = "path", default = ".", help = "Sets the root directory where logs and metadata are stored.")
	parser.add_option("--num-jobs", type = int, default = 10, help="number of jobs to listen to")
	parser.add_option("--tag", metavar = "string", default = "test", help = "Sets the name of the tag used. Default = 'test'")
	parser.add_option("--max-event-time", type = "int", default = 7200, help = "Maximum time to keep around an event. Default = 2 hours.")
	parser.add_option("--upload-cadence-type", metavar = "string", default = "geometric", help = "Choose the method [geometric|linear] in which the cadence of subsequent uploads are done. Default = geometric.")
	parser.add_option("--upload-cadence-factor", type = "float", default = 4, help = "Cadence factor T for sending out subsequent events for the same event window. For geometric cadence, first event gets sent T seconds later, second event gets sent T^2 seconds later, etc. For linear cadence, subsequent events get sent T seconds later. Default = 4.0.")
	parser.add_option("--far-threshold", type = "float", default = 3.84e-07, help = "FAR threshold considered for an event to be public, not including a trials factor. Default = 1 / month")
	parser.add_option("--far-trials-factor", type = "int", default = 1, help = "Trials factor for number of CBC pipelines uploading events to GraceDB. Default = 1.")
	parser.add_option("--processing-cadence", type = "float", default = 0.1, help = "Rate at which the event uploader acquires and processes data. Default = 0.1 seconds.")
	parser.add_option("--request-timeout", type = "float", default = 0.2, help = "Timeout for requesting messages from a topic. Default = 0.2 seconds.")
	parser.add_option("--kafka-server", metavar = "string", help = "Sets the server url that the kafka topic is hosted on. Required.")
	parser.add_option("--input-topic", metavar = "string", action="append", help = "Sets the input kafka topic(s). Required.")
	parser.add_option("--gracedb-group", metavar = "name", default = "Test", help = "Gracedb group to which to upload events (default is Test).")
	parser.add_option("--gracedb-pipeline", metavar = "name", default = "gstlal", help = "Name of pipeline to provide in GracedB uploads (default is gstlal).")
	parser.add_option("--gracedb-search", metavar = "name", default = "LowMass", help = "Name of search to provide in GracedB uploads (default is LowMass).")
	parser.add_option("--gracedb-service-url", metavar = "url", default = DEFAULT_GRACEDB_URL, help = "Override default GracedB service url (optional, default is {}).".format(DEFAULT_GRACEDB_URL))
	parser.add_option("--scald-config", metavar = "path", help = "sets ligo-scald options based on yaml configuration.")

	options, args = parser.parse_args()

	return options, args

#-------------------------------------------------
#					Classes
#-------------------------------------------------

class EventUploader(events.EventProcessor):
	"""
	manages handling of incoming events, selecting the best and uploading to GraceDB.
	"""
	_name = 'event_uploader'

	def __init__(self, options):
		logging.info('setting up event uploader...')

		events.EventProcessor.__init__(
			self,
			process_cadence=options.processing_cadence,
			request_timeout=options.request_timeout,
			num_messages=options.num_jobs,
			kafka_server=options.kafka_server,
			input_topic=[f"gstlal.{options.tag}.{topic}" for topic in options.input_topic],
			tag=options.tag
		)

		### initialize timing options
		self.max_event_time = options.max_event_time
		self.retries = 5
		self.retry_delay = 1

		### initialize gracedb client
		if options.gracedb_service_url.startswith("file"):
			self.client = inspiral.FakeGracedbClient(options.gracedb_service_url)
		else:
			self.client = GraceDb(options.gracedb_service_url)

		### gracedb settings
		self.gracedb_group = options.gracedb_group
		self.gracedb_pipeline = options.gracedb_pipeline
		self.gracedb_search = options.gracedb_search

		### upload cadence settings
		self.upload_cadence_type = options.upload_cadence_type
		self.upload_cadence_factor = options.upload_cadence_factor

		### initialize event store
		self.events = OrderedDict()

		### favored event settings
		self.public_far_threshold = options.far_threshold / options.far_trials_factor
		self.favored_event_topic = f'gstlal.{self.tag}.favored_events'
		self.upload_topic = f'gstlal.{self.tag}.uploads'

		### heartbeat settings
		self.last_heartbeat = 0.0
		self.heartbeat_write = inspiral.now()

		### set up aggregator sink
		with open(options.scald_config, 'r') as f:
			agg_config = yaml.safe_load(f)
		self.agg_sink = influx.Aggregator(**agg_config["backends"]["default"])

		# register measurement schemas for aggregators
		self.agg_sink.load(path=options.scald_config)

	def ingest(self, message):
		"""
		parse a message containing a candidate event
		"""
		### process heartbeat messages
		if message.key() and 'heartbeat' == message.key().decode('UTF-8'):
			heartbeat = json.loads(message.value())
			if heartbeat['time'] > self.last_heartbeat:
				self.last_heartbeat = heartbeat['time']

		### process candidate event
		else:
			candidate = json.loads(message.value())
			candidate['time'] = LIGOTimeGPS(candidate['time'], candidate.pop('time_ns'))
			candidate.update(self.trigger_info(candidate))
			self.process_candidate(candidate)



	def process_candidate(self, candidate):
		"""
		handles the processing of a candidate, creating
		a new event if necessary
		"""
		key = self.event_window(candidate['time'])
		if key in self.events:
			logging.info('adding new candidate for event: [{:.1f}, {:.1f}]'.format(*key))
			self.events[key]['candidates'].append(candidate)
			self.update_trigger_history(key, candidate)
		else:
			new_event = True
			for seg, event in self.events.items():
				if segment(candidate['time'], candidate['time']) in seg:
					logging.info('adding new candidate for time window: [{:.1f}, {:.1f}]'.format(*seg))
					event['candidates'].append(candidate)
					self.update_trigger_history(seg, candidate)
					new_event = False

			### event not found, create a new event
			if new_event:
				logging.info('found new event: [{:.1f}, {:.1f}]'.format(*key))
				self.events[key] = self.new_event()
				self.events[key]['candidates'].append(candidate)
				self.update_trigger_history(key, candidate)

	def update_trigger_history(self, key, candidate):
		"""
		update trigger history dict for each candidate
		"""
		self.events[key]['trigger_history'].update(candidate['trigger_info'])

	def trigger_info(self, candidate):
		"""
		gather trigger information for each candidate,
		used for rtpe
		"""
		### parse candidate for SVD bin, masses, LR, and SNR
		svdbin, type = self.parse_job_tag(candidate["job_tag"])

		coinc = self.load_xmlobj(candidate["coinc"])
		coinc_row = lsctables.CoincTable.get_table(coinc)[0]
		snglinspiral_row = lsctables.SnglInspiralTable.get_table(coinc)[0]

		return {'trigger_info': {svdbin: {
				'snr': candidate["snr"],
				'likelihood': coinc_row.likelihood,
				'mass1': snglinspiral_row.mass1,
				'mass2': snglinspiral_row.mass2,
				'spin1z': snglinspiral_row.spin1z,
				'spin2z': snglinspiral_row.spin2z,
				'Gamma0': snglinspiral_row.Gamma0
				}
			}}

	def parse_job_tag(self, tag):
		"""
		get svd bin and job type from job tag
		"""
		svdbin = tag.split('_')[0]
		name = '_'.join(tag.split('_')[1:])
		return svdbin, tag

	def load_xmlobj(self, xmlobj):
		"""
		returns the coinc xml object from the kafka message
		"""
		if isinstance(xmlobj, str):
			xmlobj = BytesIO(xmlobj.encode("utf-8"))
		return ligolw_utils.load_fileobj(xmlobj, contenthandler = LIGOLWContentHandler)

	def event_window(self, t):
		"""
		returns the event window representing the event
		"""
		dt = 0.2
		return segment(utils.floor_div(t - dt, 0.5), utils.floor_div(t + dt, 0.5) + 0.5)


	def new_event(self):
		"""
		returns the structure that defines an event
		"""
		return {
			'num_sent': 0,
			'time_sent': None,
			'favored': None,
			'gid': None,
			'candidates': deque(maxlen = self.num_messages),
			'trigger_history': {}
		}


	def handle(self):
		"""
		handle events stored, selecting the best candidate.
		upload if a new favored event is found
		"""
		for key, event in sorted(self.events.items(), reverse=True):
			if event['num_sent'] == 0 or (
				event['candidates'] and utils.gps_now() >= self.next_event_upload(event)
			):
				self.process_event(event, key)

		# clean out old events
		current_time = utils.gps_now()
		for key in list(self.events.keys()):
			if current_time - key[0] >= self.max_event_time:
				logging.info('sending final trigger history for event [{:.1f}, {:.1f}]'.format(*key))
				self.upload_file(
					"Trigger history file for RTPE",
					"trigger_history.json",
					"trigger_history",
					json.dumps(self.events[key]["trigger_history"]),
					self.events[key]['gid']
				)
				logging.info('removing stale event [{:.1f}, {:.1f}]'.format(*key))
				self.events.pop(key)

		# has it been more than 15 minutes since last heartbeat
		# jobs should send heartbeats every 10 minutes
		now = inspiral.now()
		if now - self.heartbeat_write > 15*60:
			state = 0 if now - self.last_heartbeat > 15*60 else 1
			data = {'heartbeat': {'heartbeat_tag': {'time': [int(now)], 'fields': {'data': [state]}}}}

			logging.debug(f'Storing heartbeat state {state} to influx...')
			self.agg_sink.store_columns('heartbeat', data['heartbeat'], aggregate=None)
			self.heartbeat_write = now
			

	def process_event(self, event, window):
		"""
		handle a single event, selecting the best candidate.
		upload if a new favored event is found
		"""
		updated, event = self.process_candidates(event)
		if event['num_sent'] == 0:
			assert updated
		if updated:
			logging.info(
				'uploading {} candidate with FAR = {:.3E}, '
				'SNR = {:2.1f} for event: [{:.1f}, {:.1f}]'.format(
					self.to_ordinal(event['num_sent'] + 1),
					event['favored']['far'],
					event['favored']['snr'],
					window[0], window[1]
				)
			)
			self.send_favored_event(event, window)
			gid = self.upload_event(event)
			if gid:
				event['num_sent'] += 1
				event['gid'] = gid
				self.send_uploaded(event, gid)


	def process_candidates(self, event):
		"""
		process candidates and update the favored (maxsnr) event
		if needed

		returns event and whether the favored (maxsnr) event was updated
		"""
		if event['favored']:
			event['candidates'].append(event['favored'])

		### get overall max SNR
		maxsnr_candidate = self.select_maxsnr_candidate(event['candidates'])
		maxsnr = maxsnr_candidate['snr']

		### get overall min FAR
		minfar_candidate = self.select_minfar_candidate(event['candidates'])
		minfar = minfar_candidate['far']

		event['candidates'].clear()

		### not a better candidate
		if event['favored'] and maxsnr <= event['favored']['snr'] and minfar >= event['favored']['far']:

			return False, event

		### found a new or better candidate 
		else:
			logging.info(
				'found candidate with FAR: {:.3E}, '
				'SNR: {:2.3f}'.format(maxsnr_candidate['far'], maxsnr_candidate['snr'])
			)

			### composite event
			if maxsnr_candidate['far'] != minfar:
				logging.info(
					'construct new composite event with FAR: {:.3E}, '
					'SNR: {:2.3f}'.format(minfar, maxsnr_candidate['snr'])
				)
				maxsnr_candidate = self.composite_event(maxsnr_candidate, minfar_candidate, minfar)

			if event['favored']:
				assert maxsnr_candidate['far'] <= event['favored']['far'], "far should be smaller"
				assert maxsnr_candidate['snr'] >= event['favored']['snr'], "snr should be larger"

			event['favored'] = maxsnr_candidate 
				
			return True, event


	def composite_event(self, maxsnr_candidate, minfar_candidate, minfar):
		"""
		Consturct composite event. 

		Replace far, likelihood in maxsnr candidate with those in the minfar candidate.
		"""

		### replace far
		maxsnr_candidate['far'] = minfar
		
		### load coinc file
		maxsnr_candidate_coinc = self.load_xmlobj(maxsnr_candidate["coinc"])
		minfar_candidate_coinc = self.load_xmlobj(minfar_candidate["coinc"])

		### update likelihood in coinc file
		lsctables.CoincTable.get_table(maxsnr_candidate_coinc).getColumnByName("likelihood")[0] = lsctables.CoincTable.get_table(minfar_candidate_coinc).getColumnByName("likelihood")[0]

		### update combined_far in coinc file
		lsctables.CoincInspiralTable.get_table(maxsnr_candidate_coinc).getColumnByName("combined_far")[0] = minfar

		### save coinc file
		coinc_obj = BytesIO()
		ligolw_utils.write_fileobj(maxsnr_candidate_coinc, coinc_obj)
		maxsnr_candidate["coinc"] = coinc_obj.getvalue().decode("utf-8")
		
		return maxsnr_candidate


	def select_maxsnr_candidate(self, candidates):
		"""
		select the max snr candidate out of the candidates
		"""
		return max(candidates, key=self.rank_snr)

	def select_minfar_candidate(self, candidates):
		"""
		select the min far candidate out of the candidates
		"""
		return min(candidates, key=self.rank_far)


	def rank_snr(self, candidate): 
		return candidate['snr']

	def rank_far(self, candidate): 
		return candidate['far']

	def send_favored_event(self, event, event_window):
		"""
		send a favored event via Kafka
		"""
		favored_event = {
			'event_window': list(event_window),
			'time': event['favored']['time'].gpsSeconds,
			'time_ns': event['favored']['time'].gpsNanoSeconds,
			'snr': event['favored']['snr'],
			'far': event['favored']['far'],
			'coinc': event['favored']['coinc']
		}
		self.producer.produce(topic=self.favored_event_topic, value=json.dumps(favored_event))
		self.producer.poll(0)


	def send_uploaded(self, event, gid):
		"""
		send an uploaded event via Kafka
		"""
		uploaded = {
			'gid': gid,
			'time': event['favored']['time'].gpsSeconds,
			'time_ns': event['favored']['time'].gpsNanoSeconds,
			'coinc': event['favored']['coinc']
		}
		self.producer.produce(topic=self.upload_topic, value=json.dumps(uploaded))
		self.producer.poll(0)


	def upload_event(self, event):
		"""
		upload a new event + auxiliary files
		"""
		# upload event
		for attempt in range(1, self.retries + 1):
			try:
				resp = self.client.createEvent(
					self.gracedb_group,
					self.gracedb_pipeline,
					'coinc.xml',
					filecontents = event['favored']['coinc'],
					search = self.gracedb_search
				)
			except HTTPError as resp:
				logging.warning(resp)
			else:
				resp_json = resp.json()
				if resp.status == httplib.CREATED:
					graceid = resp_json['graceid']
					logging.info("event assigned grace ID {}".format(graceid))
					if not event['time_sent']:
						event['time_sent'] = utils.gps_now()
					break
			logging.warning(
				"gracedb upload of {} "
				"failed on attempt {:d}/{:d}".format('coinc.xml', attempt, self.retries)
			)
			time.sleep(random.lognormal(math.log(self.retry_delay), .5))
		else:
			logging.warning("gracedb upload of {} failed".format('coinc.xml'))
			return None

		self.upload_file(
			"Trigger history file for RTPE",
			"trigger_history.json",
			"trigger_history",
			json.dumps(event["trigger_history"]),
			graceid
		)

		return graceid


	def upload_file(self, message, filename, tag, contents, graceid):
		"""
		upload a file to gracedb
		"""
		logging.info("posting '{}' to gracedb ID {}".format(filename, graceid))
		for attempt in range(1, self.retries + 1):
			try:
				resp = self.client.writeLog(
					graceid,
					message,
					filename = filename,
					filecontents = contents,
					tagname = tag
				)
			except HTTPError as resp:
				logging.warning(resp)
			else:
				if resp.status == httplib.CREATED:
					break
			logging.info(
				"gracedb upload of {} for ID {} "
				"failed on attempt {:d}/{:d}".format(filename, graceid, attempt, self.retries)
			)
			time.sleep(random.lognormal(math.log(self.retry_delay), .5))
		else:
			logging.warning("gracedb upload of {} for ID {} failed".format(filename, graceid))

			return False



	def next_event_upload(self, event):
		"""
		check whether enough time has elapsed to send an updated event
		"""
		if self.upload_cadence_type == 'geometric':
			return event['time_sent'] + numpy.power(self.upload_cadence_factor, event['num_sent'])
		elif self.upload_cadence_type == 'linear':
			return event['time_sent'] + self.upload_cadence_factor * event['num_sent']

	def finish(self):
		"""
		send remaining events before shutting down
		"""
		for key, event in sorted(self.events.items(), reverse=True):
			if event['candidates']:
				self.process_event(event, key)


	@staticmethod
	def to_ordinal(n):
		"""
		given an integer, returns the ordinal number
		representation.

		this black magic is taken from
		https://stackoverflow.com/a/20007730
		"""
		return "%d%s" % (n,"tsnrhtdd"[(n/10%10!=1)*(n%10<4)*n%10::4])


#-------------------------------------------------
#					 Main
#-------------------------------------------------

if __name__ == '__main__':
	# parse arguments
	options, args = parse_command_line()

	# set up logging
	log_level = logging.DEBUG if options.verbose else logging.INFO
	logging.basicConfig(format = '%(asctime)s | event_uploader : %(levelname)s : %(message)s')
	logging.getLogger().setLevel(log_level)

	# create event uploader instance
	event_uploader = EventUploader(options)

	# start up
	event_uploader.start()
