#!/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) 2018, 2019 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.

import argparse
import getpass
import os

from gstlal.dags import Argument, Option, DAG
from gstlal.dags.layers import Layer, Node
from gstlal.dags import profiles


parser = argparse.ArgumentParser(description = 'generate a dt dphi covariance matrix and tree data to replace share/inspiral_dtdphi_pdf.h5')
parser.add_argument('--psd-xml', help = 'XML containing HLVK psd')
parser.add_argument('--H-snr', type = float, help = 'H characteristic SNR')
parser.add_argument('--L-snr', type = float, help = 'L characteristic SNR')
parser.add_argument('--V-snr', type = float, help = 'V characteristic SNR')
parser.add_argument('--K-snr', type = float, help = 'K characteristic SNR')
parser.add_argument('--m1', type = float, default = 1.4, help = 'primary component mass')
parser.add_argument('--m2', type = float, default = 1.4, help = 'secondary component mass')
parser.add_argument('--s1', type = float, default = 0., help = 'primary (z) spin')
parser.add_argument('--s2', type = float, default = 0., help = 'secondary (z) spin')
parser.add_argument('--flow', type = float, default = 10., help = 'Low frequency cut-off. Default 10 Hz')
parser.add_argument('--fhigh', type = float, default = 1024., help = 'High frequency cut-off. Default 1024 Hz')
parser.add_argument('--profile', type = str, help = 'The site profile to use for condor submit requirements')
parser.add_argument('--singularity-image', metavar = "filename", help = 'If set, uses the Singularity image provided as the build environment and sets Singularity-specific condor options.')
parser.add_argument('--NSIDE', type = int, default = 16, help = 'NSIDE of healpix decomposition used for RA and DEC. There will be 12 x NSIDE^2 pixels')
parser.add_argument('--n-inc-angle', type = int, default = 33, help = 'Number of discrete inclination angles')
parser.add_argument('--n-pol-angle', type = int, default = 33, help = 'Number of discrete polarization angles')
args = parser.parse_args()

if args.flow >= args.fhigh:
	raise ValueError("flow must be less than fhigh")

dag = DAG("dt_dphi")
dag.create_log_dir()

requirements_list = []
submit_opts = {
	"want_graceful_removal": "True",
	"kill_sig": "15",
	"accounting_group_user": getpass.getuser(),
	"accounting_group": "ligo.prod.o4.cbc.uber.gstlaloffline",
	"environment": '"HDF5_USE_FILE_LOCKING=FALSE"'
}

if args.profile:
	profile_dict = profiles.load_profile(profile=args.profile)
	requirements_list.extend(profile_dict['requirements'])

if args.singularity_image:
	submit_opts['+SingularityImage'] = f'"{args.singularity_image}"'
	submit_opts['transfer_executable'] = False
	submit_opts['get_env'] = False
	requirements_list.append("(HAS_SINGULARITY=?=True)")

if len(requirements_list) > 0:
	submit_opts['requirements'] = " && ".join(requirements_list)

cov_layer = Layer(
	"gstlal_inspiral_compute_dtdphideff_cov_matrix",
	requirements={"request_cpus": 1, "request_memory": "1GB", "request_disk": "1GB", **submit_opts},
)
marg_layer = Layer(
	"gstlal_inspiral_create_dt_dphi_snr_ratio_pdfs",
	requirements={"request_cpus": 1, "request_memory": "5GB", "request_disk": "1GB",**submit_opts},
)
add_round_one_layer = Layer(
	"gstlal_inspiral_add_dt_dphi_snr_ratio_pdfs",
	name="add_pdfs_round_one",
	requirements={"request_cpus": 1, "request_memory": "4GB", "request_disk": "5GB",**submit_opts},
)
add_round_two_layer = Layer(
	"gstlal_inspiral_add_dt_dphi_snr_ratio_pdfs",
	name="add_pdfs_round_two",
	requirements={"request_cpus": 1, "request_memory": "4GB", "request_disk": "6GB",**submit_opts},
)

cov_layer += Node(
	arguments = [
		Option("H-snr", args.H_snr),
		Option("L-snr", args.L_snr),
		Option("V-snr", args.V_snr),
		Option("K-snr", args.K_snr),
		Option("flow", args.flow),
		Option("fhigh", args.fhigh),
		Option("m1", args.m1),
		Option("m2", args.m2),
		Option("s1", args.s1),
		Option("s2", args.s2),
		Option("NSIDE", args.NSIDE),
		Option("n-inc-angle", args.n_inc_angle),
		Option("n-pol-angle", args.n_pol_angle),
	],
	inputs = Option("psd-xml", args.psd_xml),
	outputs = Option("output", "covmat.h5"),
)
dag.attach(cov_layer)

num = 1000
marg_files = []
# FIXME dont hardcode 3345408, it comes from number of tiles in TimePhaseSNR
for start in range(0, 12*(args.NSIDE)**2 * args.n_inc_angle * args.n_pol_angle, num):
	stop = start + num
	marg_file = f"inspiral_dtdphi_pdf_{start:d}_{stop:d}.h5"
	marg_layer += Node(
		arguments = [Option("start", start), Option("stop", stop)],
		inputs = Option("cov-mat-h5", "covmat.h5"),
		outputs = Option("output", marg_file),
	)
	marg_files.append(marg_file)
dag.attach(marg_layer)

# Add dtdphi pdfs in chunks of 50
files_per_job = 50
intermediate_files = []
for i in range(0, len(marg_files), files_per_job):
	output_filename = f"inspiral_dtdphi_pdf_combined_{i}_to_{i+files_per_job}"
	add_round_one_layer += Node(
		inputs = Argument("inputs", marg_files[i:i+files_per_job]),
		outputs = Option("output", output_filename)
	)
	intermediate_files.append(output_filename)
dag.attach(add_round_one_layer)

# Add intermediate dtdphi pdfs
add_round_two_layer += Node(
	inputs = Argument("inputs", intermediate_files),
	outputs = Option("output", "inspiral_dtdphi_pdf.h5")
)
dag.attach(add_round_two_layer)

dag.write_dag("dt_dphi.dag")
dag.write_script("dt_dphi.sh")
