#!/usr/bin/python3
"""
Python Script to plot values obtained by the rmit.py script
Runs a R.I.P.L.

./plot.py
-t trials
-o option:values
"""

import argparse
import itertools
import json
import math
import numpy
import re
import sys

import matplotlib.pyplot as plt
from matplotlib.ticker import EngFormatter

class Field:
	def __init__(self, unit, _min):
		self.unit = unit
		self.min  = _min

field_names = {
	"ns per ops"           : Field('ns'    , 0),
	"Number of processors" : Field(''      , 1),
	"Ops per procs"        : Field('Ops'   , 0),
	"Ops per threads"      : Field('Ops'   , 0),
	"ns per ops/procs"     : Field('ns'    , 0),
	"Number of threads"    : Field('thrd'  , 1),
	"Total Operations(ops)": Field('Ops'   , 0),
	"Ops/sec/procs"        : Field('Ops'   , 0),
	"Total blocks"         : Field('Blocks', 0),
	"Ops per second"       : Field('Ops'   , 0),
	"Cycle size (# thrds)" : Field('thrd'  , 1),
	"Duration (ms)"        : Field('ms'    , 0),
}

def plot(data, x, y):
	fig, ax = plt.subplots()
	colors = itertools.cycle(['#0095e3','#006cb4','#69df00','#0aa000','#fb0300','#e30002','#fd8f00','#ff7f00','#8f00d6','#4b009a','#ffff00','#b13f00'])
	series = {}
	for entry in data:
		if not entry[0] in series:
			series[entry[0]] = {'x':[], 'y':[]}

		if x in entry[2] and y in entry[2]:
			series[entry[0]]['x'].append(entry[2][x])
			series[entry[0]]['y'].append(entry[2][y])

	for name, data in series.items():
		plt.scatter(data['x'], data['y'], color=next(colors), label=name, marker='x')

	mx = max([max(s['x']) for s in series.values()])
	my = max([max(s['y']) for s in series.values()])

	plt.ylabel(y)
	plt.xlim(field_names[x].min, mx + 0.25)
	plt.xticks(range(1, math.ceil(mx) + 1))
	plt.xlabel(x)
	plt.ylim(field_names[y].min, my*1.2)
	plt.grid(b = True)
	ax.xaxis.set_major_formatter( EngFormatter(unit=field_names[x].unit) )
	ax.yaxis.set_major_formatter( EngFormatter(unit=field_names[y].unit) )
	plt.legend(loc='upper left')
	plt.show()


if __name__ == "__main__":
	# ================================================================================
	# parse command line arguments
	parser = parser = argparse.ArgumentParser(description='Python Script to draw R.M.I.T. results')
	parser.add_argument('-f', '--file', nargs='?', type=argparse.FileType('r'), default=sys.stdin)

	try:
		options =  parser.parse_args()
	except:
		print('ERROR: invalid arguments', file=sys.stderr)
		parser.print_help(sys.stderr)
		sys.exit(1)

	# ================================================================================
	# load data
	try :
		data = json.load(options.file)
	except :
		print('ERROR: could not read input', file=sys.stderr)
		parser.print_help(sys.stderr)
		sys.exit(1)

	# ================================================================================
	# identify the keys

	series = set()
	fields = set()

	for entry in data:
		series.add(entry[0])
		for label in entry[2].keys():
			fields.add(label)

	print(series)
	print("fields")
	for f in fields:
		print("{}".format(f))

	plot(data, "Number of processors", "ns per ops")
