from keras.models import model_from_yaml
import sys
import pandas as pd
import scipy.io
import numpy as np
import time
import os
import sys
import pandas as pd
import sklearn as sk
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
from sklearn import metrics
import numpy as np
import biosppy as bp
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Embedding
from keras.layers import Conv1D, GlobalAveragePooling1D, MaxPooling1D
from keras.layers.normalization import BatchNormalization

from keras.layers import LSTM
import scipy.io

yaml_file = open('model.yaml', 'r')
loaded_model_yaml = yaml_file.read()
yaml_file.close()
model = model_from_yaml(loaded_model_yaml)



def main():
    name = sys.argv[1]
    mat = scipy.io.loadmat('./validation/' + name + '.mat')
    
    mdata = mat['val']
    
    #print(mdata.shape)
    nd = np.asarray([mdata]).flatten()
    out = bp.ecg.ecg(signal=nd.astype(float), sampling_rate=300., show=False)

    ot = np.asarray(out[1])    


    
    length = ot.shape[0]
    #print("length of filtered signal is", length)
    maxLen = 18286
    
    if (length < maxLen):
        diff = maxLen - length
        ap = np.concatenate([ot, np.zeros(diff)])
    else:
        ap = ot[0 : maxLen]
        
    # print(ap.shape[0])
    cPD = pd.DataFrame(ap)
    
    la = cPD.diff()
    la = la.transpose()
    #print (la.shape)
    X = la.values.astype(np.float32)
    
    ## Set NaNs to 10e-6
    X[np.isnan(X)] = 0
    
    X_train = preprocessing.scale(X, axis=1)
    
    
    X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)

    
    # load weights into new model
    model.load_weights("./weights.best.hdf5")
    #print("Loaded model from disk")
    
    # evaluate loaded model on test data
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    
    y_pred = model.predict_on_batch(X_train)
    #print("prediction is ", y_pred)
    y_pred = y_pred.round().astype('int')
    #print("prediction is ", y_pred)
    # from categorial to lable indexing
    y_pred = y_pred.argmax(1)[0]
    
    print("The prediction for", name, " is: ", y_pred)
    return y_pred

if __name__ == "__main__":
    main()



