#!/usr/bin/env python3
#
# 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 sys
import numpy
import h5py
from gstlal.stats.inspiral_extrinsics import TimePhaseSNR

# Read in and combine all of the input files
h5_covmat = h5py.File(sys.argv[1])
kwargs = {"SNR":h5_covmat["SNR"], "psd_fname":h5_covmat["psd"]}
h5_covmat.close()
files = sys.argv[2:]
TPS = TimePhaseSNR.from_hdf5(files[0], files[1:], **kwargs)

# compute the normalization
time, phase, deff = TimePhaseSNR.tile(NSIDE = 8, NANGLE = 17)
# This actually doesn't matter it is just needed to map from eff distance to
# snr, but the TimePhaseSNR code actually undoes this...
h = {"H1":1., "L1":1., "V1":1., "K1":1.}

# set the norm to 1
combos = TPS.combos + (("H1",),("L1",),("V1",),("K1",))
norm = dict((frozenset(k), 1.) for k in combos)
TPS.norm = norm

def extract_dict(DICT, keys):
	return dict((k,v) for k,v in DICT.items() if k in keys)

norm = dict((frozenset(k), 0.) for k in combos)
for i in range(len(time["H1"])):
	t = dict((k, v[i]) for k, v in time.items())
	p = dict((k, v[i]) for k, v in phase.items())
	s = dict((k, h[k] / v[i]) for k, v in deff.items())

	for ifos in combos:
		t2 = extract_dict(t, ifos)
		p2 = extract_dict(p, ifos)
		s2 = extract_dict(s, ifos)
		h2 = extract_dict(h, ifos)
		norm[frozenset(ifos)] += TPS(t2,p2,s2,h2) * (sum(x**2 for x in s2.values())**.5)**4 / len(time["H1"]) * 1. / (16. * numpy.pi**2)

TPS.norm = norm

# write the result to disk
TPS.to_hdf5("inspiral_dtdphi_pdf.h5")
