#!/usr/bin/env python3
#
# Copyright (C) 2017  Sarah Caudill, Shasvath Kapadia
#
# 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 produce a variety of plots from the template bank and svd banks

#
# =============================================================================
#
#				    Preamble
#
# =============================================================================
#

from optparse import OptionParser

import numpy

from ligo.lw import ligolw
from ligo.lw import lsctables
from ligo.lw import utils as ligolw_utils
from lal import CacheEntry

from gstlal import svd_bank
from gstlal import dagparts
from gstlal.plots import bank as plotbank

#
# =============================================================================
#
#				  Command Line
#
# =============================================================================
#

def parse_command_line():
	parser = OptionParser(description = __doc__)
	parser.add_option("--output-dir", metavar = "output-dir", default = ".", help = "Provide an output directory.")
	parser.add_option("--plot-svd-bank", default = False, action = "store_true", help = "Make svd bank plots.")
	parser.add_option("--svd-bank-cache", metavar = "filename", help = "Set the path to the svd bank cache file.")
	parser.add_option("--plot-template-bank", default = False, action = "store_true", help = "Make template bank plots.")
	parser.add_option("--template-bank-file", metavar = "filename", help = "Path to the template bank file.")

	options, filenames = parser.parse_args()

	if options.plot_template_bank:
		if options.template_bank_file is None:
			raise ValueError("Must specify --template-bank-file for template bank plotting.")

	if options.plot_svd_bank:
		if options.svd_bank_cache is None:
			raise ValueError("Must specify --svd-bank-cache for SVD bank plots.")

	return options, filenames

###################################
#
#	    Main
#
###################################

# Content Handler
class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
	pass
lsctables.use_in(LIGOLWContentHandler)

options, filenames = parse_command_line()

filename_template = dagparts.T050017_filename('H1L1V1', 'GSTLAL_INSPIRAL_PLOTBANKS_%s', (0, 0), '.png',  path = options.output_dir)

# Make svd bank plots
if options.plot_svd_bank:

	# First, read in the svd bank cache files
	svd_bank_files = [CacheEntry(line) for line in open(options.svd_bank_cache)]

	# Then, read in the svd banks
	svd_banks = {cacheentry.description: svd_bank.read_banks(cacheentry.path, svd_bank.DefaultContentHandler) for cacheentry in svd_bank_files}

	# Determine the min and max mchirp and chi values in each split bank. Store the values
	# as tuples in a list. The tuple will be (file_tag, min_mchirp, max_mchirp, min_chi, max_chi)
	edgevalues = []
	for tag, sngl_table_list in svd_banks.items():

		for bank in sngl_table_list:
			rows = bank.sngl_inspiral_table
			chirpmasses = [row.mchirp for idx,row in enumerate(rows)]
			chivals = [chi(row) for idx,row in enumerate(rows)]
			edgevalues.append((tag, min(chirpmasses), max(chirpmasses), min(chivals), max(chivals)))

	# Exract the list of file_tags for easier handling
	file_tags = [params[0] for params in edgevalues]

	tag_num = [int(''.join(c for c in tag if c.isdigit())) for tag in file_tags]

	# Create plots
	plotbank.color_split_bank_by_svd(filename_template, tag_num,
			[params[1] for params in edgevalues], [params[2] for params in edgevalues],
			[params[3] for params in edgevalues], [params[4] for params in edgevalues])

# Make template bank plots
if options.plot_template_bank:

	# Read template bank file
	tmpltxmldoc = ligolw_utils.load_filename(options.template_bank_file, verbose = True, contenthandler = LIGOLWContentHandler)
	# Extract sngl_inspiral table
	sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(tmpltxmldoc)

	# Create plots
	plotbank.plot_template_bank(filename_template, sngl_inspiral_table)
