#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os, sys
sys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(__file__))+"/../scripts"))

import fileinput
import numpy as np
import matplotlib as mpl

show = len(sys.argv) > 1 and sys.argv[1] == 'show'
if not show:
	mpl.use('pgf')

import matplotlib.pyplot as plt
import matplotlib.lines as lines
from common import set_size, config_plt, get_colors, fix_log_rects

config_plt()


def toFloat(s):
	return float(s.split(' ')[1].replace(',', '.'))


def loadData(fn):
	content = []

	with open(fn) as f:
		content = f.readlines()

	values = {}
	for line in content:
		n, real, user, sys, _ = [x for x in line.split(':')]
		time = toFloat(user) + toFloat(sys)
		if not n in values:
			values[n] = []
		values[n].append(time);

	if "5" in values:
		values.pop("5")

	return values


def figCT(title, xlabel, xticks, output, datasrcs, legendOutside=False, error=False, log=False):
	fig = plt.figure()

	plt.title(title)
	plt.xlabel(xlabel)
	plt.ylabel(u"temps (s)")
	plt.xticks(xticks)

	if log:
		plt.yscale('log')

	nd = len(datasrcs)

	width = 1.5
	pos = .5-.5*nd
	for f, label in datasrcs:
		values = loadData(f)
		barcolor, errcolor = get_colors(['dep/fixed', 'indep/fixed', 'dep/rand', 'indep/rand'], label)

		for k, a in values.items():
			x = int(k)
			m = np.mean(a)
			s = 2.5758 * np.std(a) / np.sqrt(len(a))

			x = x + pos*width

			bar = plt.bar(x, m, width=width, color=barcolor, label=label)
			if log:
				fix_log_rects(bar, 1e-4)
			if error:
				plt.errorbar(x, m, s, elinewidth=.8, capsize=1, ecolor=errcolor)
			label=''

		pos = pos + 1

	bbox=(1, 1)
	if not legendOutside:
		bbox=(.38, 1)
	plt.legend(bbox_to_anchor=bbox)

	fig.set_size_inches(set_size(455.24408, .8))
	if not show:
		plt.savefig(output, format='pdf', bbox_inches='tight')
	return plt


# script
plts = []

plt = figCT(u"", u"nombre de boucles", [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
		"plots/fixediv.pdf", [
			['data/ct_fixediv_dep_fixedi', 'dep/fixed'],
			['data/ct_fixediv_indep_fixedi', 'indep/fixed'],
			['data/ct_fixediv_dep_randi', 'dep/rand'],
			['data/ct_fixediv_indep_randi', 'indep/rand'],
			],
		legendOutside=True,
		error=True
		)
plts.append(plt)

plt = figCT(u"", u"nombre d'instructions", [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
		"plots/fixedv.pdf", [
			['data/ct_fixedv_dep_fixedi', 'dep/fixed'],
			['data/ct_fixedv_indep_fixedi', 'indep/fixed'],
			['data/ct_fixedv_dep_randi', 'dep/rand'],
			['data/ct_fixedv_indep_randi', 'indep/rand'],
			],
		error=True,
		log=True
		)
plts.append(plt)

if show:
	for plt in plts:
		plt.show()
