
import networkx as nx
import numpy as np
from timeawarepc.tpc import cfc_tpc
import time
from timeawarepc.find_cfc import *

import rpy2.robjects as ro
print("------------------------------------------------")
print("RUNNING R VERSION:")
print(ro.r('R.version.string')[0])
print("------------------------------------------------")

import rpy2
print(rpy2.__version__)


def get_confusion_matrix(true_graph,estimated_graph):
    num_nodes = true_graph.shape[0]
    TP = 0
    FP = 0
    TN = 0
    FN = 0
    for i in range(num_nodes):
        for j in range(num_nodes):
            if i!=j:
                if true_graph[i,j] == 1 and estimated_graph[i,j] == 1:
                    TP += 1
                if true_graph[i,j] == 1 and estimated_graph[i,j] == 0:
                    FN += 1
                if true_graph[i,j] == 0 and estimated_graph[i,j] == 1:
                    FP += 1
                if true_graph[i,j] == 0 and estimated_graph[i,j] == 0:
                    TN += 1

    return TP, FP, TN, FN


data = np.loadtxt('./river-runoff/river-runoff_N-12_T-4600/river-runoff_N-12_T-4600_0001.txt', delimiter=' ')
data = (data - np.mean(data, axis=0)) / np.std(data, axis=0)
print(type(data))
print(data.shape)
print(data[1:10,:])

true_ess_graph_t = np.array([[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                           [0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0],
                           [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
                           [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])

true_ess_graph = true_ess_graph_t.T


start_time = time.time()
adjmat = cfc_tpc(data, maxdelay=1, subsampsize=50, niter=50, alpha=0.1, thresh=0.01, isgauss=False)
end_time = time.time()
elapsed_time = end_time - start_time

[TP, FP, TN, FN] = get_confusion_matrix(true_ess_graph, adjmat[0])
TPR = TP/(TP+FN)
FPR = FP/(TN+FP)
precision = TP / (TP + FP)
recall    = TP / (TP + FN)
f1        = (2 * precision * recall) /(precision + recall)
print('F1 Score = ',f1)
print(f"TPR = {TPR}")
print(f"FPR = {FPR}")
print(f"Total algorithm run time = {elapsed_time}")