#!/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) 2020  Patrick Godwin (patrick.godwin@ligo.org)
#
# 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.


import argparse
import os
import shutil
import sys

from gstlal.config.inspiral import Config
from gstlal.dags.inspiral import DAG
from gstlal.datafind import DataCache, DataType
from gstlal.workflows import write_makefile


# set up command line options
parser = argparse.ArgumentParser()

subparser = parser.add_subparsers(title="commands", metavar="<command>", dest="command")
subparser.required = True

p = subparser.add_parser("init", help="generate a Makefile based on configuration")
p.add_argument("-c", "--config", help="Sets the path to read configuration from.")
p.add_argument("-w", "--workflow", default="full", help="Sets the type of workflow to run.")
p.add_argument("-f", "--force", action="store_true", help="If set, overwrites the existing Makefile")

p = subparser.add_parser("create", help="create a workflow DAG")
p.add_argument("-c", "--config", help="Sets the path to read configuration from.")
p.add_argument("-w", "--workflow", default="full", help="Sets the type of workflow to run.")


# load config
args = parser.parse_args()
config = Config.load(args.config)

# create makefile
if args.command == "init":
	if os.path.exists(os.path.join(os.getcwd(), "Makefile")) and not args.force:
		print("Makefile already exists. To overwrite, run with --force", file=sys.stderr)
	else:
		write_makefile(config, f"Makefile.offline_inspiral_{args.workflow}_template", workflow=args.workflow)

# generate dag
elif args.command == "create":
	config.setup()
	dag = DAG(config)
	dag.create_log_dir()

	# common paths
	filter_dir = os.path.join(config.data.analysis_dir, "filter")
	rank_dir = os.path.join(config.data.rerank_dir, "rank")

	# generate workflow
	if args.workflow in set(("full", "filter", "rerank")):
		if args.workflow in set(("full", "filter")):
			# input data products
			split_bank = DataCache.find(DataType.SPLIT_BANK, svd_bins="*", subtype="*")

			# generate filter dag layers
			ref_psd = dag.reference_psd()
			median_psd = dag.median_psd(ref_psd)
			svd_bank = dag.svd_bank(median_psd, split_bank)

			if config.filter.injections:
				injections = dag.split_injections()
				injections = dag.calc_expected_snr(median_psd, injections)
				lnlr_injections = dag.match_injections(injections)

			triggers, dist_stats = dag.filter(ref_psd, svd_bank)
			if config.filter.injections:
				inj_triggers = dag.filter_injections(ref_psd, svd_bank)
				triggers += inj_triggers

			triggers, dist_stats = dag.aggregate(triggers, dist_stats)

		else:
			# load filter data products
			ref_psd = DataCache.find(DataType.REFERENCE_PSD, root=config.data.analysis_dir)
			median_psd = DataCache.find(DataType.MEDIAN_PSD, root=config.data.analysis_dir)
			injections = DataCache.find(DataType.SPLIT_INJECTIONS, root=filter_dir, svd_bins="*", subtype="*")
			lnlr_injections = DataCache.find(DataType.MATCHED_INJECTIONS, root=filter_dir, svd_bins="*", subtype="*")
			svd_bank = DataCache.find(DataType.SVD_BANK, root=filter_dir, svd_bins="*")
			dist_stats = DataCache.find(DataType.DIST_STATS, root=filter_dir, svd_bins="*")
			triggers = DataCache.find(DataType.TRIGGERS, root=filter_dir, svd_bins="*", subtype="*")
			inj_triggers = DataCache.find(DataType.TRIGGERS, root=filter_dir, svd_bins="*")
			triggers += inj_triggers

		if args.workflow in set(("full", "rerank")):
			# generate rerank dag layers
			prior = dag.create_prior(svd_bank, median_psd, dist_stats)
			dist_stats = dag.marginalize(prior, dist_stats)

			pdfs = dag.calc_pdf(dist_stats)
			pdfs = dag.marginalize_pdf(pdfs)

			triggers = dag.calc_likelihood(triggers, dist_stats)
			triggers = dag.cluster(triggers, injections)

			if config.filter.injections:
				triggers, inj_triggers = dag.find_injections(triggers)
				lnlr_cdfs = dag.measure_lnlr_cdf(dist_stats, lnlr_injections)

			triggers, pdfs = dag.compute_far(triggers, pdfs)

			dag.plot_horizon_distance(dist_stats)
			dag.plot_summary(triggers, pdfs)
			dag.plot_background(triggers, pdfs)
			dag.plot_bin_background(dist_stats)
			dag.plot_sensitivity(triggers)

			if config.filter.injections:
				dag.plot_analytic_vt(triggers, pdfs, lnlr_cdfs)

	elif args.workflow == "injection":
		# input data products
		ref_psd = DataCache.find(DataType.REFERENCE_PSD, root=config.data.analysis_dir)
		median_psd = DataCache.find(DataType.MEDIAN_PSD, root=config.data.analysis_dir)
		svd_bank = DataCache.find(DataType.SVD_BANK, root=filter_dir, svd_bins="*")
		dist_stats = DataCache.find(DataType.MARG_DIST_STATS, root=rank_dir, svd_bins="*")
		pdfs = DataCache.find(DataType.DIST_STAT_PDFS, root=rank_dir)
		orig_zl_triggers = DataCache.find(DataType.TRIGGERS, root=rank_dir, extension="sqlite")

		# make a copy of zerolag triggers
		zerolag_triggers = orig_zl_triggers.copy(root="rank")
		for src_trg, dest_trg in zip(orig_zl_triggers.files, zerolag_triggers.files):
			shutil.copy2(src_trg, dest_trg)

		# generate injection-only dag layers
		injections = dag.split_injections()
		injections = dag.calc_expected_snr(median_psd, injections)
		lnlr_injections = dag.match_injections(injections)

		triggers = dag.filter_injections(ref_psd, svd_bank)
		triggers = dag.aggregate(triggers)
		triggers = dag.calc_likelihood(triggers, dist_stats)
		triggers = dag.cluster(triggers, injections)

		triggers, injections = dag.find_injections(triggers)
		lnlr_cdfs = dag.measure_lnlr_cdf(dist_stats, lnlr_injections)
		triggers += zerolag_triggers

		triggers, pdfs = dag.compute_far(triggers, pdfs)

		dag.plot_horizon_distance(dist_stats)
		dag.plot_summary(triggers, pdfs)
		dag.plot_background(triggers, pdfs)
		dag.plot_bin_background(dist_stats)
		dag.plot_sensitivity(triggers)
		dag.plot_analytic_vt(triggers, pdfs, lnlr_cdfs)

	else:
		raise ValueError(f"{args.workflow} is not a valid workflow option")

	# write dag/script to disk
	dag_name = f"{args.workflow}_inspiral_dag"
	dag.write_dag(f"{dag_name}.dag")
	dag.write_script(f"{dag_name}.sh")
