#!/usr/bin/env python2
#-------------------------- =+- Python script -+= --------------------------
#
# @file      plot_test.py
# @date      Fri Apr  7 00:59:57 2006
# @brief
#
# CVS version control block - do not edit manually
#  $RCSfile: plot_test.py,v $
#  $Source: /home/cvs/yoh/progr/misc/netperf/plot_test.py,v $
#
# Created: Fri Apr  7 02:44:53 2006
#  Commited: $Date: 2006/04/10 20:17:49 $
#  Revision: $Revision: 1.7 $
#
#  Yaroslav Halchenko                                      CS@UNM, CS@NJIT
#  web:     http://www.onerussian.com                      & PSYCH@RUTGERS
#  e-mail:  yoh@onerussian.com                              ICQ#: 60653192
#
# DESCRIPTION (NOTES):
#  This script is to be used in conjunction with test_netperf.sh produced
#  output files. Use is quite simple. Please run with --help to see full
#  list of options.
# EXAMPLES:
#
#  To plot only selected items, where label field matches regexp specified with -r
#   plot_test.py -X MTU -Y "Throughput KBs" -t "Duplex Mode: Crossover" -r '.*/D.\+' directlink2*
#
# COPYRIGHT: Yaroslav Halchenko 2006
#
# LICENSE:
#
#  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 St, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
# On Debian system see /usr/share/common-licenses/GPL for the full license.
#
#-----------------\____________________________________/------------------

import re

from optparse import OptionParser

usage = "[options] inputfile1 inputfile2 ..."

parser = OptionParser(usage = usage)

parser.add_option("-v", "--verbose",
                  action="store", type="int", dest="verbose", default=1,
                  help="verbose")

parser.add_option("-r", "--regexp",
                  action="store", type="string", dest="labelRegex", default=None,
                  help="If we want to select a subset of plots")

parser.add_option("-p", "--plot-points",
                  action="store_true",  dest="plotPoints", default=False,
                  help="plot all data points")

parser.add_option("-x", "--x-column",
                  action="store", type="int", dest="xColumn", default=0,
                  help="which column to use as X")

parser.add_option("-X", "--x-label",
                  action="store", type="string", dest="xlabel", default=None,
                  help="Label for x axis")

parser.add_option("-y", "--y-column",
                  action="store", type="int", dest="yColumn", default=8,
                  help="which column to use as Y")

parser.add_option("-Y", "--y-label",
                  action="store", type="string", dest="ylabel", default=None,
                  help="Label for y axis")

parser.add_option("-l", "--label-column",
                  action="store", type="int", dest="labelColumn", default=3,
                  help="which column to use as label for the given plot")

parser.add_option("-s", "--subplotlegend",
                  action="store_true", dest="subplotlegend", default=False,
                  help="If plot legends (filenames)")

parser.add_option("-t", "--title",
                  action="store", dest="title", type="string", default=None,
                  help="Optional title for the plot")

parser.add_option("-o", "--output",
                  action="store", type="string", dest="ofilename", default="show",
                  help="Output filename where to store graphical version of the report"\
				  "('show' or 'display' displays it)")

try:
	import pylab
	import matplotlib.colors as colors
	from matplotlib.font_manager import FontProperties

except:
	print "Could not import pylab. Please have it (re)installed. No figure could be plotted"
	sys.exit(1)
from pylab import exp,arange,randn,std,mean
(options, inFiles) = parser.parse_args()
#setVerbosity(options.verbose)

graphs = {}
# Read In all the data
for inFile in inFiles:
	for line in file(inFile,'r').readlines():
		data = re.split("[ \t]+", line.strip())
		label = data[options.labelColumn]
		x = float(data[options.xColumn])
		y = float(data[options.yColumn])
		if not graphs.has_key(label):
			graphs[label]=[colors.cnames.values()[(len(graphs))%100+1],
						   {}]
		if not x in graphs[label][1]:
			graphs[label][1][x]=[]
		graphs[label][1][x].append(y)

lines = []
legends = []

if options.subplotlegend:
	options.legend = True
	pylab.subplot(211)
graphsitems = graphs.items()
graphsitems.sort()
for label,(color,data) in graphsitems:
	if options.labelRegex and not re.match(options.labelRegex, label):
		continue
	# we need error bars
	datalist = data.items()
	datalist.sort()
	x = map(lambda x: x[0], datalist)
	y = map(lambda x: pylab.mean(x[1]), datalist)
	N = map(lambda x:len(x), data.values())	# how many times each one was ran
	if min(N)>1:
		e = map(lambda x: pylab.std(x[1]), datalist)
		(ebl, ebb) = pylab.errorbar(x, y, e, fmt='-o', color=color, linewidth=3)
	else:
		ebl = pylab.plot(x, y, '-x', color=color, linewidth=3)
	if options.plotPoints:
		for x,data in datalist:
			pylab.plot([x]*len(data), data, '.', color=color, linewidth=1)

	lines.append(ebl)
	legends.append("%s (%d:%d runs)"%(label, min(N), max(N)) )

for op in ['title', 'xlabel', 'ylabel']:
	exec('if options.%s: pylab.%s(options.%s)'%(op, op, op))

if len(lines):
	# next line causes matplotlib barf whenever saving to a file
	#	leg = pylab.legend(lines, legends, loc=2, prop = FontProperties('smaller'))
	if options.subplotlegend:
		pylab.subplot(212)
		pylab.axis('off')

	leg = pylab.legend(lines, legends, loc=2, numpoints = 2)

	if options.ofilename in ["display", "show"]:
		pylab.show()
	else:
		pylab.savefig('%s'%options.ofilename, dpi=72)
else:
	print "Found no data -- nothing to plot"


