#!/usr/bin/python

# Copyright (c) 2011 Leif Johnson <leif@leifjohnson.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

'''A command-line script for plotting data from text files.'''

import bz2
import glob
import gzip
import logging
import numpy
import optparse
import os
import re
import sys

from matplotlib import pyplot

FLAGS = optparse.OptionParser('Usage: py-grep-plot [OPTIONS] [FILE...]')

FLAGS.add_option('-a', '--alpha', type=float, default=0.9, metavar='N',
                 help='plot series with alpha N (0.9)')
FLAGS.add_option('-b', '--batch', type=int, metavar='N',
                 help='batch data into groups of N points and plot mean + std')
FLAGS.add_option('-c', '--colors', default='k,r,#888,c,b,m,g,y', metavar='S,S,...',
                 help='cycle through the given colors (k,r,#888,c,b,m,g,y)')
FLAGS.add_option('-g', '--grid', default=False, action='store_true',
                 help='include a grid (False)')
FLAGS.add_option('-L', '--legend', metavar='[tl|cl|bl|tr|cr|br]',
                 help='include a legend (None)')
FLAGS.add_option('-l', '--log', default='', metavar='[x|y|xy]',
                 help='use a log scale on the specified axes')
FLAGS.add_option('-o', '--output', metavar='FILE',
                 help='save to FILE instead of displaying on screen')
FLAGS.add_option('-p', '--points', default='o-', metavar='S,S,...',
                 help='cycle through the given line/point styles (o-)')
FLAGS.add_option('-r', '--regex', default=r'([-+eE.\d]+)', metavar='RE',
                 help='extract data points from FILEs with RE ([-+eE.\d]+)')
FLAGS.add_option('-s', '--smooth', type=int, default=0, metavar='N',
                 help='smooth across N points before plotting (0)')
FLAGS.add_option('-t', '--title', metavar='S',
                 help='use S as the plot title')
FLAGS.add_option('-x', '--xlabel', metavar='S',
                 help='use S as the label for the x-axis')
FLAGS.add_option('-y', '--ylabel', metavar='S',
                 help='use S as the label for the y-axis')
FLAGS.add_option('-X', '--xlim', metavar='A,B',
                 help='use (A,B) as the range for the x-axis')
FLAGS.add_option('-Y', '--ylim', metavar='A,B',
                 help='use (A,B) as the range for the y-axis')


LEGEND = {
    'upper right': 1, 'ur': 1, 'tr': 1,
    'upper left': 2, 'ul': 2, 'tl': 2,
    'lower left': 3, 'll': 3, 'bl': 3,
    'lower right': 4, 'lr': 4, 'br': 4,
    'right': 5, 'r': 5,
    'center left': 6, 'cl': 6, 'ml': 6,
    'center right': 7, 'cr': 7, 'mr': 7,
    'lower center': 8, 'lc': 8, 'bc': 8,
    'upper center': 9, 'uc': 9, 'tc': 9,
    'center': 10, 'c': 10,
    }


def extract_groupdict(g, x, y, ey):
    '''We've matched a line with named groups. Extract data from them.'''
    logging.debug('group dict: %r', g)

    if 'x' in g:
        while len(x) < len(y):
            x.append(None)
        x.append(float(g['x']))

    y.append(float(g['y']))

    if 'ey' in g:
        while len(ey) < len(y):
            ey.append(None)
        ey.append(float(g['ey']))


def search_line(line, regex, x, y, ey):
    '''Search an input line for groups matching the given regex.

    Extracted data will be added to the mutable x, y, and/or ey sequences.
    '''
    m = regex.search(line)
    if not m:
        return

    g = m.groupdict()
    if g:
        return extract_groupdict(g, x, y, ey)

    g = m.groups()
    logging.debug('group matches: %r', g)
    if len(g) > 3:
        FLAGS.error('REGEX cannot match more than 3 values')
    elif len(g) == 3:
        while len(x) < len(y):
            x.append(None)
            ey.append(None)
        x.append(float(g[0]))
        y.append(float(g[1]))
        ey.append(float(g[2]))
    elif len(g) == 2:
        while len(x) < len(y):
            x.append(None)
            ey.append(None)
        x.append(float(g[0]))
        y.append(float(g[1]))
    elif len(g) == 1:
        y.append(float(g[0]))


def read_input(args):
    '''Given input pattern arguments, open up corresponding files.'''
    if not args:
        args.append('-')
    for pattern in args:
        if pattern == '-':
            yield 'stdin', sys.stdin
            continue
        for filename in glob.glob(pattern):
            if filename.endswith('.gz'):
                handle = gzip.open(filename)
            elif filename.endswith('.bz2'):
                handle = bz2.BZ2File(filename)
            else:
                handle = open(filename)
            yield os.path.splitext(os.path.basename(filename))[0], handle


def compile_regex(opts):
    '''Compile a regular expression pattern.'''
    logging.debug('compiling REGEX %r', opts.regex)
    try:
        return re.compile(opts.regex)
    except:
        logging.critical('cannot compile REGEX %r', opts.regex)
        sys.exit(-2)


def make_axes(opts):
    '''Create an axes object to hold our plots.'''
    X, Y = opts.ylabel and 0.12 or 0.1, opts.xlabel and 0.13 or 0.1
    ax = pyplot.axes([X, Y, 0.95 - X, 0.95 - Y])
    ax.xaxis.tick_bottom()
    ax.yaxis.tick_left()
    if 'x' in opts.log:
        ax.set_xscale('log')
    if 'y' in opts.log:
        ax.set_yscale('log')
    return ax


def format_axes(ax, opts):
    '''Format our plotting axes using the script options.'''
    logging.debug('using legend: %s' % opts.legend)
    loc = LEGEND.get(opts.legend)
    if loc is not None:
        ax.legend(loc=loc)

    logging.debug('using grid: %s' % opts.grid)
    ax.grid(opts.grid)

    if opts.title:
        logging.debug('using title: %r', opts.title)
        ax.set_title(opts.title)
    if opts.xlabel:
        logging.debug('using x label: %r', opts.xlabel)
        ax.set_xlabel(opts.xlabel)
    if opts.xlim:
        logging.debug('using x limit: %r', opts.xlim)
        ax.set_xlim(eval(opts.xlim))
    if opts.ylabel:
        logging.debug('using y label: %r', opts.ylabel)
        ax.set_ylabel(opts.ylabel)
    if opts.ylim:
        logging.debug('using y limit: %r', opts.ylim)
        ax.set_ylim(eval(opts.ylim))


def main(opts, args):
    colors = [c.strip() for c in opts.colors.split(',')]
    points = [s.strip() for s in opts.points.split(',')]

    regex = compile_regex(opts)
    ax = make_axes(opts)

    plot_kwargs = dict(alpha=opts.alpha, aa=True)

    c = p = 0

    def plot(label, x, y, ey):
        if opts.smooth:
            y = numpy.convolve(y, [1. / opts.smooth] * opts.smooth, 'same')

        if opts.batch:
            n = opts.batch
            count = int(numpy.ceil(float(len(y)) / n))
            batches = lambda: (y[i * n:(i + 1) * n] for i in range(count))
            means = [numpy.array(b).mean() for b in batches()]
            stds = [numpy.array(b).std() for b in batches()]
            y, ey = means, stds

        x = x or range(len(y))

        ax.plot(x, y, points[p], c=colors[c],
                mec=colors[c], mfc=(1, 1, 1, 1), mew=1.,
                label=label, **plot_kwargs)

        if ey:
            ax.errorbar(x, y, fmt=None, yerr=ey, ecolor=colors[c], **plot_kwargs)

    for label, lines in read_input(args):
        x, y, ey = [], [], []
        for line in lines:
            search_line(line, regex, x, y, ey)
        plot(label, x, y, ey)
        c = (c + 1) % len(colors)
        p = (p + 1) % len(points)

    format_axes(ax, opts)

    if opts.output:
        logging.info('%s: saving plot', opts.output)
        return pyplot.savefig(opts.output)

    quit = lambda e=None: sys.exit(0)
    try:
        pyplot.connect('close_event', quit)
    except ValueError:
        pass
    try:
        pyplot.show()
    except KeyboardInterrupt:
        quit()


if __name__ == '__main__':
    logging.basicConfig(
        stream=sys.stdout,
        level=logging.INFO,
        format='%(levelname).1s %(asctime)s %(message)s')
    main(*FLAGS.parse_args())
