# -*- coding: utf-8 -*-
"""
Created on Sat Feb  3 12:18:08 2018

@author: Lenovo
"""

#################################################################################################
#loading Libraries
import pandas as pd
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten	
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.utils import to_categorical
from pyts.transformation import StandardScaler
from pyts.transformation import GASF, GADF
from pyts import transformation, classification, visualization
from pyts.visualization import plot_gasf
from pyts.visualization import plot_gadf
from sklearn import  metrics
import numpy as np

################################################################################################



train =pd.read_csv('train_balanced.csv')
test=pd.read_csv('test_final.csv')
train=train.drop(train.columns[[0]], axis=1)
test=test.drop(test.columns[[0]],axis=1)

###########################################################################################

#loading Training Data
xtrain=train.iloc[:,1:62]
xtrain=xtrain.values
ytrain=train.iloc[:,0]
ytrain=ytrain.values

#loading Test data
xtest=test.iloc[:,3:64]
xtest=xtest.values
ytest=test.iloc[:,2]
ytest=ytest.values


y_train = to_categorical(ytrain)
y_test=to_categorical(ytest)

#reshaping time series window
standardscaler = StandardScaler(epsilon=1e-2)
X_standardized = standardscaler.transform(xtrain)
Xt_standardized = standardscaler.transform(xtest)

#gasf transformation
gasf = GASF(image_size=61, overlapping=False, scale='-1')
X_gasf = gasf.transform(X_standardized)
Xt_gasf=gasf.transform(Xt_standardized)


x_train =X_gasf.reshape(X_gasf.shape[0],61,61,1)
x_test =Xt_gasf.reshape(Xt_gasf.shape[0],61,61,1)

#shuffling the data set
idx = np.random.permutation(len(x_train))
x,y = x_train[idx], y_train[idx]



#defining custome metric
def auc_roc(y_true, y_pred):
    # any tensorflow metric
    value, update_op = tf.contrib.metrics.streaming_auc(y_pred, y_true)

    # find all variables created for this metric
    metric_vars = [i for i in tf.local_variables() if 'auc_roc' in i.name.split('/')[1]]

    # Add metric variables to GLOBAL_VARIABLES collection.
    # They will be initialized for new session.
    for v in metric_vars:
        tf.add_to_collection(tf.GraphKeys.GLOBAL_VARIABLES, v)

    # force to update metric values
    with tf.control_dependencies([update_op]):
        value = tf.identity(value)
        return value




#building sequential model
model = Sequential()
model.add(Convolution2D(61, kernel_size=(10, 10), strides=(1, 1),activation='relu',input_shape=(61,61,1)))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Convolution2D(61, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(100, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=[auc_roc,'accuracy'])


model.fit(x, y, batch_size=4, nb_epoch=6, verbose=1)


#predicting
score = model.evaluate(x_test, y_test, verbose=1)
yhat=model.predict_proba(x_test)
j=metrics.roc_auc_score(y_test, yhat)
j=np.array(j)
print(j)

roc_gasf=np.concatenate((y_test,yhat),axis=1)
np.savetxt("roc_gasf.csv", roc_gasf, delimiter=",")




#building model for gadf field

#######################################################################################################
#gadf transformation
gadf = GADF(image_size=61, overlapping=False, scale='-1')
X_gadf = gadf.transform(X_standardized)
Xt_gadf=gadf.transform(Xt_standardized)


x_train =X_gadf.reshape(X_gadf.shape[0],61,61,1)
x_test =Xt_gadf.reshape(Xt_gadf.shape[0],61,61,1)

#shuffling the data set
idx = np.random.permutation(len(x_train))
x,y = x_train[idx], y_train[idx]





#building sequential model
model = Sequential()
model.add(Convolution2D(61, kernel_size=(10, 10), strides=(1, 1),activation='relu',input_shape=(61,61,1)))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Convolution2D(61, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=[auc_roc,'accuracy'])


model.fit(x, y, batch_size=64, nb_epoch=2, verbose=1)


#predicting
score = model.evaluate(x_test, y_test, verbose=1)
yhat=model.predict_proba(x_test)
j=metrics.roc_auc_score(y_test, yhat)
j=np.array(j)
print(j)

roc_gadf=np.concatenate((y_test,yhat),axis=1)
np.savetxt("roc_gadf.csv", roc_gadf, delimiter=",")





##########################################################################################
#building model for mtf transformation
mtf = MTF(image_size=61, n_bins=4, quantiles='empirical', overlapping=False)
X_mtf = mtf.transform(X_standardized)
Xt_mtf=mtf.transform(Xt_standardized)

x_train =X_mtf.reshape(X_gadf.shape[0],61,61,1)
x_test =Xt_mtf.reshape(Xt_gadf.shape[0],61,61,1)

#shuffling the data set
#seeding 1001
idx = np.random.permutation(len(x_train))
x,y = x_train[idx], y_train[idx]







#building sequential model
model = Sequential()
model.add(Convolution2D(61, kernel_size=(10, 10), strides=(1, 1),activation='relu',input_shape=(61,61,1)))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Convolution2D(61, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=[auc_roc,'accuracy'])


model.fit(x, y, batch_size=16, nb_epoch=2, verbose=1)


#predicting
score = model.evaluate(x_test, y_test, verbose=1)
yhat=model.predict_proba(x_test)
j=metrics.roc_auc_score(y_test, yhat)
j=np.array(j)
print(j)

roc_mtf=np.concatenate((y_test,yhat),axis=1)
np.savetxt("roc_mtf.csv", roc_mtf, delimiter=",")