#!/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 Leo Tsukada
#
# 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.stats import inspiral_extrinsics, inspiral_lr


parser = argparse.ArgumentParser(description = 'generate a dt dphi covariance matrix and tree data to replace share/inspiral_dtdphi_pdf.h5')
parser.add_argument('--snr-thresh', type=float, default = inspiral_lr.LnLRDensity.snr_min, help = 'set the snr minimum to define found')
parser.add_argument('--instruments', type=str, help='add instruments. Separate tham with comma, does not have to be alphabetical.', required = True)
args = parser.parse_args()

instruments = "".join(sorted(args.instruments.split(",")))

dag = DAG(f"p_of_I_{instruments}")
dag.create_log_dir()

requirements = {
	"want_graceful_removal": "True",
	"kill_sig": "15",
	"accounting_group_user": getpass.getuser(),
	"accounting_group": "ligo.prod.o3.cbc.uber.gstlaloffline",
}

marg_layer = Layer(
	"gstlal_inspiral_create_p_of_ifos_given_horizon",
	requirements={"request_cpus": 1, "request_memory": 4000, **requirements},
)
add_layer = Layer(
	"gstlal_inspiral_add_p_of_ifos_given_horizon",
	requirements={"request_cpus": 1, "request_memory": 4000, **requirements},
)


num = 41
marg_files = []
for start in range(0, 41**(len(instruments) / 2 - 1), num):
	stop = start + num
	marg_file = f"{''.join(instruments)}_{start:d}_{stop:d}.h5"
	marg_layer += Node(
		arguments = [
			Option("start", start),
			Option("stop", stop),
			Option("instruments", args.instruments)
		],
		outputs = Option("output-file", marg_file),
	)
	marg_files.append(marg_file)
dag.attach(marg_layer)

add_layer += Node(
	arguments = Option("instruments", args.instruments),
	inputs = Argument("inputs", marg_files),
	outputs = Argument(f"{''.join(instruments)}_p_of_instruments_given_H_d.h5", suppress=True)
)
dag.attach(add_layer)

dag.write_dag(f"p_of_I_{instruments}.dag")
dag.write_script(f"p_of_I_{instruments}.sh")
