#!/usr/bin/env python
"""
Plot logs of variables saved in a text file by sfepy.base.log.Log class.

The plot should be almost the same as the plot that would be generated by the
Log directly.
"""
from __future__ import absolute_import
import sys
sys.path.append('.')
from argparse import ArgumentParser, Action, RawDescriptionHelpFormatter

import matplotlib.pyplot as plt

from sfepy.base.log import read_log, plot_log

class ParseRc(Action):
    def __call__(self, parser, namespace, values, option_string=None):
        pars = eval('{' + values + '}')
        setattr(namespace, self.dest, pars)

helps = {
    'groups' :
    'list of log data groups subplots (from 0) to plot - all groups are'
    ' plotted if not given',
    'output_filename' :
    'save the figure using the given file name',
    'rc' : 'matplotlib resources',
    'no_legends' :
    'do not show legends in the log plots',
    'nbins' :
    'the numbers of bins in x, y axes for all groups [default: %(default)s]',
    'swap_axes' :
    'swap the axes of the plots',
    'no_show' :
    'do not show the figure',
}

def main():
    parser = ArgumentParser(description=__doc__,
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('-g', '--groups', metavar='int[,int,...]',
                        action='store', dest='groups',
                        default=None, help=helps['groups'])
    parser.add_argument('-o', '--output', metavar='filename',
                        action='store', dest='output_filename',
                        default=None, help=helps['output_filename'])
    parser.add_argument('--rc', type=str, metavar='key:val,...',
                        action=ParseRc, dest='rc',
                        default={}, help=helps['rc'])
    parser.add_argument('--no-legends',
                        action='store_false', dest='show_legends',
                        default=True, help=helps['no_legends'])
    parser.add_argument('--nbins', metavar='nx1,ny1,...',
                        action='store', dest='nbins',
                        default=None, help=helps['nbins'])
    parser.add_argument('--swap-axes',
                        action='store_true', dest='swap_axes',
                        default=False, help=helps['swap_axes'])
    parser.add_argument('-n', '--no-show',
                        action='store_true', dest='no_show',
                        default=False, help=helps['no_show'])
    parser.add_argument('filename')
    options = parser.parse_args()

    filename = options.filename

    if options.groups is not None:
        options.groups = [int(ii) for ii in options.groups.split(',')]

    if options.nbins is not None:
        aux = [int(ii) if ii != 'None' else None
               for ii in options.nbins.split(',')]
        xnbins, ynbins = aux[::2], aux[1::2]

    else:
        xnbins = ynbins = None

    log, info = read_log(filename)

    plt.rcParams.update(options.rc)

    plot_log(None, log, info, groups=options.groups,
             xnbins=xnbins, ynbins=ynbins,
             show_legends=options.show_legends, swap_axes=options.swap_axes)

    if options.output_filename:
        plt.savefig(options.output_filename)

    if not options.no_show:
        plt.show()

if __name__ == '__main__':
    main()
