# -*- coding: utf-8 -*-
print(__doc__)

# Author: RACHED Anis <rachedanis94@gmail.com>
# License: MIT

# PREDICTION EN UTILISANT LA REGRESSION UTILISANT LA METHODE SVR (Support vector machine)

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import svm

# Simulation à etudier
SIM = 'SIM2'
TR_GEN_METH = 'GAUS'
STATE = 'INIT'

# Les N dernier individus à verifier ( tester si la fonction donne des valeurs proche de ceux de ces individus et calculer l'erreur )
TESTING_LEN = 10

# PREDICT Y = F(X)
# Telsque: F est inconnus

# X est
X_LAB = 'NumEssai'

# Y est
Y_LAB = 'Correct'


def mask(df, f):
  return df[f(df)]

# importer les données
DATA_TO_ANALYSE = TR_GEN_METH+'-TR_'+SIM+'_'+STATE
PATH_TO_DATA = './out/'+SIM+'/'+DATA_TO_ANALYSE+'.csv'
data = pd.read_csv(PATH_TO_DATA)

# Decommenter pour filtrer les données
#FILTER = 'Correct==1 and TR!=-1'
#data = data.query(FILTER)

X = data[X_LAB]
Y = data[Y_LAB]

X_train = X[:-TESTING_LEN].values.reshape((len(X)-TESTING_LEN),1)
X_test = X[-TESTING_LEN:].values.reshape((TESTING_LEN,1))

Y_train = Y[:-TESTING_LEN].values.reshape((len(Y)-TESTING_LEN),1)
Y_test = Y[-TESTING_LEN:].values.reshape((TESTING_LEN,1))

# Create SVR regression object
regr = svm.SVR()

# Train the model using the training sets
regr.fit(X_train, Y_train)

# Make predictions using the testing set
Y_pred = regr.predict(X_test)

# The mean squared error
err = "Mean squared error: %.2f" % mean_squared_error(Y_test, Y_pred)
print(err)

# Explained variance score: 1 is perfect prediction
var = 'Variance score: %.2f' % r2_score(Y_test, Y_pred)
print(var)

# Plot output
font = {'family': 'serif',
        'color':  'darkred',
        'weight': 'normal',
        'size': 9,
        }

outp = plt.figure(1)

LABEL = DATA_TO_ANALYSE+'_SVRReg_PREDICT:'+Y_LAB+'=F('+X_LAB+')'
plt.title(LABEL, fontdict=font)

plt.text(X_test[0], Y_pred[0], err + '\n' + var, fontdict=font)

plt.scatter(X_test, Y_test,  color='black')
plt.scatter(X_test, Y_pred, color='blue', linewidth=3)

plt.xlabel(X_LAB)
plt.ylabel(Y_LAB)

outp.show()

OUTPUT_FILE = 'out/'+SIM+'/'+LABEL+'.png'
outp.savefig(OUTPUT_FILE)
