#!/usr/bin/env python

# Copyright (C) 2016 Christopher M. Biwer
#
# 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 3 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.
""" Plots samples from inference sampler.
"""

import argparse
import logging
from matplotlib import use
use('agg')
from matplotlib import pyplot as plt
from matplotlib import rc
import numpy
import pycbc
from pycbc import results
from pycbc import __version__
from pycbc.inference import (option_utils, io)
import sys

# command line usage
parser = argparse.parser = io.ResultsArgumentParser(skip_args=['walkers'])
parser.add_argument("--verbose", action="store_true", default=False,
                    help="Print logging info.")
parser.add_argument("--version", action="version", version=__version__,
                    help="show version number and exit")
parser.add_argument("--walkers", nargs='+', default=None,
                    help="Walker indices to plot. Options are 'all' or one "
                         "or more walker indices. Default is to plot the "
                         "average of all walkers for the input "
                         "`--parameters`.")
parser.add_argument("--output-file", type=str, required=True,
                    help="Path to output plot.")

# parse the command line
opts = parser.parse_args()

# setup log
pycbc.init_logging(opts.verbose)

# load the results
fp, parameters, labels, _ = io.results_from_cli(opts, load_samples=False)

# get number of dimensions
ndim = len(parameters)

# get walker indices
if opts.walkers == ['all'] or opts.walkers == None:
    walkers = range(fp.nwalkers)
else:
    walkers = list(map(int, opts.walkers))

# plot samples
# plot each parameter as a different subplot
logging.info("Plotting samples")
fig, axs = plt.subplots(ndim, figsize=(10,8), sharex=True)
plt.xlabel("Iteration")

# loop over parameters
axs = [axs] if not hasattr(axs, "__iter__") else axs

if opts.thin_start is not None:
    xmin = opts.thin_start
else:
    try:
        xmin = fp.attrs['thin_start']
    except KeyError:
        xmin = 0

if opts.thin_interval is not None:
    xint = opts.thin_interval
else:
    try:
        xint = fp.attrs['thin_interval']
    except KeyError:
        xint = 1

thinned_by = fp.thinned_by*xint
xmin = xmin*fp.thinned_by

# add the temperature args if it exists
additional_args = {}
try:
    additional_args['temps'] = opts.temps
except AttributeError:
    pass

for i, arg in enumerate(parameters):
    chains_arg = []
    for widx in walkers:
        chain = fp.read_samples(parameters, walkers=widx,
                                thin_start=opts.thin_start,
                                thin_interval=opts.thin_interval,
                                thin_end=opts.thin_end, **additional_args)
        chains_arg.append(chain[arg])
    if opts.walkers is not None:
        for chain in chains_arg:
            # plot each walker as a different line on the subplot
            axs[i].plot((numpy.arange(len(chain)))*thinned_by + xmin, chain, alpha=0.6)
    else:
        # plot the average of all walkers for the parameter on the subplot
        chains_arg = numpy.array(chains_arg)
        avg_chain = [chains_arg[:, j].sum()/fp.nwalkers
                     for j in range(len(chains_arg[0]))]
        axs[i].plot((numpy.arange(len(avg_chain)))*thinned_by + xmin, avg_chain)
    # Set y labels
    axs[i].set_ylabel(labels[arg])
fp.close()

# save figure with meta-data
caption_kwargs = {
    "parameters" : ", ".join(sorted(list(labels.values()))),
}
caption = r"""Parameter samples from the walker chains whose indices were
provided as inputs. Each line is a different chain of walker samples in that
case. If no walker indices were provided, the plot shows the variation of the
parameter sample values averaged over all walkers."""
title = "Samples for {parameters}".format(**caption_kwargs)
results.save_fig_with_metadata(fig, opts.output_file,
                               cmd=" ".join(sys.argv),
                               title=title,
                               caption=caption)
plt.close()

# exit
logging.info("Done")
