#!/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) 2012  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.

### A program to plot the contents of a gstlal_svd_bank file by reconstructing the waveforms

from optparse import OptionParser

from gstlal.plots import set_matplotlib_cache_directory
set_matplotlib_cache_directory()
from gstlal import svd_bank
import numpy

import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot

from ligo.lw import lsctables

def parse_command_line():
	parser = OptionParser()
	parser.add_option("-v", "--verbose", action="store_true", help="Be verbose.")
	parser.add_option("--svd-bank-file", metavar = "filename", help="Specify svd bank file.")

	options, filenames = parser.parse_args()
	
	if options.svd_bank_file is None:
		raise ValueError("Must specify --svd-bank-file for plotting.")

	return options, filenames

options, filenames = parse_command_line()

for n, bank in enumerate(svd_bank.read_banks(options.svd_bank_file, contenthandler = svd_bank.DefaultContentHandler, verbose = True)):

	# get the template number
	tmps = int(bank.bank_fragments[0].mix_matrix.shape[1] / 2)
	row = bank.sngl_inspiral_table

	for n in range(tmps):
		mc, s1z, s2z = row[n].mchirp, row[n].spin1z, row[n].spin2z

		pyplot.figure(figsize=(18,6))
		pyplot.subplot(211)
		maxrate = 0
		mint = 0
		for frag in bank.bank_fragments:
			m = frag.mix_matrix
			s = frag.singular_values
			u = frag.orthogonal_template_bank
			h = numpy.dot(m.T, u)
			t = numpy.linspace(-frag.end, -frag.start, h.shape[1]+1)[1:]  # delta_t needs to be 1/2^n
			pyplot.plot(t, h[2 * n,:] * frag.rate**.5)
			pyplot.plot(t, h[2 * n + 1,:] * frag.rate**.5)
			maxrate = max(maxrate, frag.rate)
			mint = min(t[0], mint)
		pyplot.xlabel('waveform: time (s) mc:%.4f s1z:%.4f s2z:%.4f' % (mc, s1z, s2z))
		#pyplot.xlim([-.25, 0])

		pyplot.subplot(212)
		pyplot.xlabel('samples')
		l = len(bank.autocorrelation_bank[n,:])
		ts = l / float(maxrate)
		t = numpy.linspace(-ts, 0, l)
		pyplot.plot(numpy.real(bank.autocorrelation_bank[n,:]), label='autocorrelation real')
		pyplot.plot(numpy.imag(bank.autocorrelation_bank[n,:]), label='autocorrelation imag')
		pyplot.legend(loc='upper left', borderaxespad=0)

		pyplot.savefig(str(int(row[n].Gamma0)) + '_in_tmps.svg')

print('done plotting')
