import numpy as np

from DeepGate import DeepGate
from preprocess import approximate_weights
from preprocess import generate_dataset
from train import train
from test import test
from datetime import datetime

# Set up the path, dictionary, and sample sets.
path = "speech_recordings/"
dictionary = list(range(10)) + ["east", "north", "south", "west"]
    
# Set the number of input nodes, hidden nodes per layer, output nodes, and the
# learning rate.
#input_nodes = len(training_data[0].split(",")) - 1
input_nodes = 516
hidden_nodes = [100, 50]
output_nodes = len(dictionary)


#learning_rate = np.linspace(0.01, 0.1, 10)

people = ["michael_1", "michael_2", "michael_3", "michael_4", "michael_5",
          "cedric_1", "cedric_2", "cedric_3", "cedric_4", "cedric_5",
          "estella_1", "estella_2", "estella_3", "estella_4", "estella_5",
          "iyan_1", "iyan_2", "iyan_3", "iyan_4", "iyan_5",
          "sophia_1"]

# Track the average classification performance for a particular learning rate.
average_performance = []

# Set the number of training epochs.
epochs = list(range(70))
    
learning_rate = [0.05] 

# Shuffle the order of the sample sets.
#temp = people[:-1]
#np.random.shuffle(temp)
#people = np.append(temp, people[-1])

cutoff = 0.4

# Generate the training and testing sets.
generate_dataset(path, dictionary, people[:-1], "training", cutoff)
generate_dataset(path, dictionary, [people[-1]], "testing", cutoff)

# Open and read the training and testing sets.
with open(path + "training_set.csv", "r") as training_file:
    training_data = training_file.readlines()
with open(path + "testing_set.csv", "r") as testing_file:
    testing_data = testing_file.readlines()

#for lr in learning_rate:
performance = []
for i in range(1):
    
    # Create, train, and test an instance of the network.
    dnn = DeepGate(input_nodes, hidden_nodes, output_nodes, 0.05)
    startTime = datetime.now()
    train(path, dnn, training_data, epochs)
    print(datetime.now() - startTime) 
    
    # Discretize the weight matrices.
#    for matrix in range(dnn.depth-1):
#        for i in range(dnn.weights[matrix].shape[0]):
#            dnn.weights[matrix][i] = approximate_weights(dnn.weights[matrix][i])
    
    (outputs, scorecard) = test(path, dnn, testing_data, show=True)       
    
    # Compute the average classification performance of the network.
    performance.append(np.sum(scorecard) / len(scorecard))
    #print(people[-1])
    #print("Performance:", np.sum(scorecard) / len(scorecard))
    
average_performance.append(np.sum(performance) / len(performance))
