#!/bin/env python3

import numpy as np
import pickle
from scipy.io import loadmat, savemat
from optparse import OptionParser
from util import nested_to_matrix, matrix_to_nested

def normalize_train(fts):
    
    ftsarray, indices = nested_to_matrix(fts)
    
    maxs = np.amax(ftsarray, axis=0)
    mins = np.amin(ftsarray, axis=0)
    
    return (mins, maxs)

def normalize(fts, mins, maxs):
    
    ftsarray, indices = nested_to_matrix(fts)

    diff = maxs-mins
    ftsarray = np.array([(fv-mins)/diff for fv in ftsarray])

    res = matrix_to_nested(ftsarray, indices)

    return res
    


if __name__ == '__main__':
    
    parser = OptionParser()
    parser.add_option("-i", "--input", dest="input_filename", help="Load feature vectors from FILE", metavar="FILE")
    parser.add_option("-o", "--output", dest="output_filename", help="Store dimension-reduced feature vectors in FILE", metavar="FILE")
    parser.add_option("-p", "--params", dest="params_filename", help="Save PCA to file", metavar="PCAFILE")
    parser.add_option("-t", "--training", action="store_true", dest="training", default=False, help="Operate in training mode.")

    (options, args) = parser.parse_args()
    
    if options.input_filename is None:
        print('Path to .mat file is required.')
        exit(1)
    
    if options.output_filename is None:
        print('Output file name is required.')
        exit(1)

    if options.params_filename is None:
        print('Parameter file name is required.')
        exit(1)

    infilename = options.input_filename
    outfilename = options.output_filename
    trainingmode = options.training
   
    testpatients = loadmat(infilename)
    testpatients = testpatients["features"][0]

    if (trainingmode):
        mins, maxs = normalize_train(testpatients)
        pickle.dump((mins, maxs), open(options.params_filename, 'wb'))
    else:
        mins, maxs = pickle.load(open(options.params_filename, 'rb'))
    
    normalized = normalize(testpatients, mins, maxs)

    savemat(outfilename, {'features': [normalized]})

    


