#! /usr/bin/python3
import sys
import matplotlib.pyplot as plt
from math import *
from statistics import mean

def plot_from_file(ax,filename):
    # open file and remove newlines.
    f=open(filename)
    lines = [line.strip() for line in f.readlines()]
    f.close()

    # 1st column is DirectEvaluation
    # 2nd column is LUT without container
    # 3rd column is 0% out of bounds ...
    # last column is 100% out of bounds

    N = len(lines[2].split(" "))-2
    L = [[float(line.split(" ")[i]) for line in lines[2:]] for i in range(N+2)]
    proportions = [x/(N-1) for x in range(N)]

    # average each row
    avg_time = [mean(L[i]) for i in range(len(L))]

    #plt.plot(proportions,avg_time[2:])
    #plt.plot([1,0],avg_time[0:2])

    rel_slowdown = [t/(avg_time[0]+(avg_time[1]-avg_time[0])*(1-p)) for (p,t) in zip(proportions,avg_time[2:])]
    print(rel_slowdown[0])
    ax.plot(proportions,rel_slowdown)
    ax.set(title=filename.split(".")[0])


if len(sys.argv) <= 1:
    print("usage:", sys.argv[0], "<filename1> <filename2> ...")
    exit()


fig, axs = plt.subplots(1,3,sharex=True,sharey=True)
fig.set_size_inches(11, 3, forward=True)

axs[1].set(xlabel="Proportion of points sampled outside LUT domain")
axs[0].set(ylabel="Slowdown")

for ax in axs:
    ax.autoscale(enable=True, axis='both', tight=True)
    ax.grid(True, which='both',color='0.95')

for i in range(len(sys.argv)-1):
    plot_from_file(axs[i],sys.argv[i+1])

#loc={'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'}
plt.grid(True, which='both',color='0.95')
plt.subplots_adjust(left=0.05, right=0.995, top=0.92, bottom=0.145,
                    wspace=0.09)
plt.savefig("fail_proportions.eps", bbox_inches='tight')
plt.show()
#plt.savefig(outputname + ".png")

