#!/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 = {}
        for pair in values.split(','):
            key, val = pair.split('=')
            pars[key] = eval(val)
        setattr(namespace, self.dest, pars)

helps = {
    'output_filename' :
    'save the figure using the given file name',
    'rc' : 'matplotlib resources',
    'no_show' :
    'do not show the figure',
}

def main():
    parser = ArgumentParser(description=__doc__,
                            formatter_class=RawDescriptionHelpFormatter)
    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('-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

    log, info = read_log(filename)

    plt.rcParams.update(options.rc)

    plot_log(1, log, info)

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

    if not options.no_show:
        plt.show()

if __name__ == '__main__':
    main()
