#!/bin/env python3

"""
Apply OLS dimensionality reduction to (single) test example
"""

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

try:
    # Storage for huge lists.
    import h5py
    hdf5_enabled = True
except:
    hdf5_enabled = False

def _reduce_dimension(redidx, patients):
    reduced_patients = [np.array(p)[np.array(redidx,dtype=bool)].tolist() for p in patients]
    return np.array(reduced_patients)

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", "--paramfilename", dest="paramfilename", help="Indices of selected feature coordinates", metavar="PARAMFILE")
    
    (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.paramfilename is None:
        print('Parameter file name is required.')
        exit(1)

    infilename = options.input_filename
    outfilename = options.output_filename
    
    
    print('loading data...')
    if hdf5_enabled and h5py.is_hdf5(infilename):
        # Load HDF5 file
        print('Loading data from HDF5 file...')
        f = h5py.File(infilename, 'r')
        patients = hdf5_load_patients(f)
    else:
        # Load mat file
        matfile = loadmat(infilename)
        patients = matfile["scattered"][0]


    # Load pca from file.
    redidx = loadmat(options.paramfilename)
    redidx = np.squeeze(redidx['redidx'])

    fv_reduced = _reduce_dimension(redidx, patients)
    
    print("Dimensionality reduction complete, exporting reduced data...")
    savemat(outfilename, {'features': [[fv_reduced]]})