import os
import math
import sys
import common as com

t_values_directory = "t_test_results/"
num_hpc = 6
num_indicator = 5

t_critical = 3.86460985 #(98, 0.0001)

Matrix = [[0 for x in range(num_hpc)] for y in range(num_indicator)]

def select_column(mat, i):
    return [row[i] for row in mat]

def mean_var(d):
    m = sum(d) / float(len(d))
    var = sum([(x - m)**2 for x in d]) / float(len(d))
    return m, var

def create_t_values():
    if not os.path.exists(t_values_directory):
        os.makedirs(t_values_directory)
    with open("base.txt", "r") as base:
        benign = base.readlines()
    with open("input.txt", "r") as tar:
        target = tar.readlines()
    loopcount = 0
    for b in benign:
        for t in target:
            loopcount += 1
            sys.stdout.write('\r')
            sys.stdout.write("[%-20s] %d%%" % ('*'*int((20*loopcount)/(len(benign)*len(target))), ((100*loopcount)/(len(benign)*len(target)))))
            sys.stdout.flush()
            b_name = b.split("/")[-1].split(".")[0]
            t_name = t.split("/")[-1].split(".")[0]
            data1 = com.load_matrix(b.strip())
            data2 = com.load_matrix(t.strip())
            for c in range(num_hpc):
                    for r in range(num_indicator):
                        dis1 = select_column(data1, c + r)
                        dis2 = select_column(data2, c + r)
                        m1, v1 = mean_var(dis1)
                        m2, v2 = mean_var(dis2)
                        t_val = (m1 - m2) / float((math.sqrt((v1 + v2)/float(len(dis1)))))
                        Matrix[r][c] = t_val
            com.save_matrix(t_values_directory+b_name+"_"+t_name+".txt", Matrix)

def create_t_values_single_file(t):
    if not os.path.exists(t_values_directory):
        os.makedirs(t_values_directory)
    with open("base.txt", "r") as base:
        benign = base.readlines()
    for b in benign:
        b_name = b.split("/")[-1].split(".")[0]
        t_name = t.split("/")[-1].split(".")[0]
        data1 = com.load_matrix(b.strip())
        data2 = com.load_matrix(t.strip())
        for c in range(num_hpc):
            for r in range(num_indicator):
                dis1 = select_column(data1, c + r)
                dis2 = select_column(data2, c + r)
                m1, v1 = mean_var(dis1)
                m2, v2 = mean_var(dis2)
                t_val = (m1 - m2) / float((math.sqrt((v1 + v2)/float(len(dis1)))))
                Matrix[r][c] = t_val
        com.save_matrix(t_values_directory+b_name+"_"+t_name+".txt", Matrix)