import numpy as np

from preprocess import approximate_weights

def train(dnn, training_data, epochs, show=False, discrete=True):
    
    # Iterate through all training epochs.
    for epoch in epochs:

        # Train the network.
        for data in training_data:
            
            # Convert the training data into an array, removing commas.
            data_array = data.split(',')
            input_layer = np.asfarray(data_array[1:])
            
            # Scale and shift the input so that it lies within [0.01, 1.00].            
            input_layer[input_layer == 0] = 0.01
                
            # Shift the target so that it lies within [0.01, 0.99].
            target = np.zeros(dnn.output_nodes) + 0.01
            
            # Set the target label for this example.
            target[int(data_array[0])] = 0.99
    
            # Begin training.                
            if show == True:
                print("Training: " + str(data_array[0]))
                dnn.train(input_layer, target)
                print("Done!")
            else:
                dnn.train(input_layer, target)

    # Discretize the weight matrices.
    if discrete == True:
        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])
