#######################################
# Prasenjit Sen
#
# This script contains a RF regressor that
# predicts the magnetic anisotropy for the
# stable, magnetic compounds.
#########################################

import seaborn as sb
import numpy as np
from scipy.stats import pearsonr
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, explained_variance_score
from sklearn.model_selection import cross_val_score, GridSearchCV, train_test_split
from sklearn import preprocessing
from sklearn.feature_selection import SelectFromModel
from sklearn.inspection import plot_partial_dependence
import statistics
import pandas as pd
from math import sqrt

print('Loading dataset for magnetic anisotropy regression')
MAE_data = pd.read_csv('../../datasets/anisotropy/data-long2.csv',sep=',')
print(MAE_data.shape)

# Add derived features
MAE_data['log_MAE'] = np.log(np.abs(MAE_data[['E_zx', 'E_zy']].min(axis=1))/MAE_data['n_metal'])
print(MAE_data.shape)

# Drop unwanted features
MAE_data.drop(labels=['id','uu','ud','du','dd','mag_mom','E_zx','E_zy','n_metal',\
'H','He','Li','Be','B','C','N','O','F','Ne',\
'Na','Mg','Al','Si','P','S','Cl','Ar',\
'K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr',\
'Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I','Xe',\
'Cs','Ba','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu',\
'Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At'], axis=1, inplace=True)

#Keep those features with importance > 0.01
#MAE_data=MAE_data[['log_MAE', 'smeig12', 'smeig11', 'mean_Z', 'del_Z', 'mean_val', 'mean_group', 'del_group', 'smeig10', 'del_electroneg', 'd_elect', 'mode_group', 'acsf49', 'mode_val', 'mean_electroneg', 'mode_Z', 'acsf48', 'acsf46', 'mean_period', 'acsf47', 'cell_area', 'acsf43', 'acsf44', 'acsf215', 'acsf45', 'acsf212', 'acsf216', 'smeig9', 'acsf213', 'del_period', 'acsf39', 'mode_electroneg','del_val','acsf174','acsf42','acsf173', 'smeig8']]

print('Shape = ',MAE_data.shape)

#sb.distplot(MAE_data['log_MAE'])
#plt.show()

# Select rows after setting cutoff for the target variable
y_min = -6 # -6 for MAE, -10 for MAE/area, -7.5 for MAE/#metal
y_max = 6
MAE_data = MAE_data.loc[MAE_data['log_MAE'] >= y_min]
MAE_data = MAE_data.loc[MAE_data['log_MAE'] <= y_max]

Nsamples = MAE_data.shape[0]
print('log(MAE) selected between [', y_min, ':', y_max, ']')
print('No. of samples = ', Nsamples)

# open a file to append parameter values and scores
file1 = open("./stats/MAE-regRF-sp0.2-stat2.txt", "a")
#file1 = open("./stats/MAE-regRF-sp0.2-impgt0.01-stat2.txt", "a")
file1.write("# ccp_alpha,\tmax_depth,\tmax_samples,\tmin_samples_leaf,\tmin_samples_split,\tn_estimators,\tr2_train,\tr2_test,\tpearson_train,\tpearson_test,\texp_var_train,\texp_var_test,\tMAE_train,\tMAE_test,\tMAE_train_inv,\tMAE_test_inv #\n\n")

imp = pd.DataFrame()

Nruns = 100
# Import function to create training and test set splits
from sklearn.model_selection import train_test_split
# Scale the features and the target
from sklearn.preprocessing import QuantileTransformer, MinMaxScaler
from sklearn.model_selection import GridSearchCV

for cnt in range(Nruns):
	print("Run count : ", cnt+1)
	
	#Shuffle rows randomly
	MAE_data = MAE_data.sample(frac=1, axis=0).reset_index(drop=True)
	'''	
	area = MAE_data[['cell_area']].values
	total_area = 0.0
	for i in range(MAE_data.shape[0]):
		total_area += float(area[i])
	
	av_area = total_area/(MAE_data.shape[0])
	print('Average cell area ',av_area)
	'''
	
	y = MAE_data[['log_MAE']].values
	X = MAE_data.drop(labels=['log_MAE'], axis=1, inplace=False).to_numpy()
	
	X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
	
	y_test_data = y_test[:,0]
	Ntrain = np.shape(y_train)[0] # no. of training examples
	
	# Scaling feature data
	Xscaler = QuantileTransformer(n_quantiles=Ntrain, output_distribution='normal').fit(X_train) # Handles outliers better
	X_train = Xscaler.transform(X_train)
	X_test = Xscaler.transform(X_test)
	
	# Scaling target data
	y_train = y_train.reshape(-1,1)
	y_test = y_test.reshape(-1,1)
	Yscaler = QuantileTransformer(n_quantiles=Ntrain, output_distribution='normal').fit(y_train)
	#Yscaler = MinMaxScaler(feature_range=(-1, 1)).fit(y_train)
	y_train = Yscaler.transform(y_train)
	y_test = Yscaler.transform(y_test)
	#######################
	
	#Create random forest classifier
	N_CV = 5
	estimators = [100,125,150,175,200,225]
	depth = np.linspace(15,25,11, dtype=int, endpoint=True)
	min_split = np.linspace(5,15,11, dtype=int, endpoint=True)
	#min_leaf = np.linspace(1,10,9, dtype=int, endpoint=True) # 'min_samples_leaf':min_leaf
	min_leaf = [1]
	#max_sample = np.linspace(0.6,0.6,1, endpoint=True)  # 'max_samples':max_sample
	max_sample = [0.6]
	max_features = 'sqrt'
	#max_leaf = np.linspace(50,600,10, dtype=int, endpoint=True) # max_leaf_nodes
	#alphas = np.linspace(0.0,0.3,4, endpoint=True)
	alphas = [0]
	
	parameters = {'n_estimators':estimators, 'max_depth':depth, 'max_samples':max_sample,\
	       'min_samples_leaf':min_leaf, 'min_samples_split':min_split, 'ccp_alpha':alphas}
	rf = GridSearchCV(RandomForestRegressor(criterion='mae',max_features='sqrt'), parameters, cv=N_CV, n_jobs=-1, verbose=0)
	
	#krr.fit(X_train,y_train)
	opt = rf.fit(X_train,np.ravel(y_train))
	
	# append to file
	row = []
	for k,v in opt.best_params_.items():
	    row.append(v)
	
	y_pred = opt.best_estimator_.predict(X_test)
	y_pred_train = opt.best_estimator_.predict(X_train)
	
	# R^2 for training set
	row.append(r2_score(y_train, y_pred_train))
	# R^2 for test set 
	row.append(r2_score(y_test, y_pred))
	
	y_train_data = y_train[:,0]
	
	# Pearson's correlation coefficient
	r = np.corrcoef(y_train_data, y_pred_train)
	row.append(r[0,1])
	r = np.corrcoef(y_test_data, y_pred)
	row.append(r[0,1])
	
	
	# Explained variance
	row.append(explained_variance_score(y_train,y_pred_train))
	row.append(explained_variance_score(y_test,y_pred))
	
	# The mean squared error
	#print('RMSE for train y: %.4f'
	#        % np.sqrt(mean_squared_error(y_train, y_pred_train)))
	#print('RMSE for test y: %.4f '
	#        % np.sqrt(mean_squared_error(y_test, y_pred)))
	#print()
	
	#Mean absolute error
	row.append(mean_absolute_error(y_train, y_pred_train))
	row.append(mean_absolute_error(y_test, y_pred))
	
	# Perform the inverse scaling transormations
	X_test_inv = Xscaler.inverse_transform(X_test)
	y_test_inv = Yscaler.inverse_transform(y_test.reshape(-1,1))
	y_train_inv = Yscaler.inverse_transform(y_train.reshape(-1,1))
	y_pred_inv = Yscaler.inverse_transform(y_pred.reshape(-1,1))
	y_pred_train_inv = Yscaler.inverse_transform(y_pred_train.reshape(-1,1))
	
	#Mean absolute error
	row.append(mean_absolute_error(y_train_inv, y_pred_train_inv))
	row.append(mean_absolute_error(y_test_inv, y_pred_inv))
	
	file1.write(','.join(map(str,row)))
	file1.write('\n')
	# Append the feature rankings to a dataframe
	imp = imp.append([opt.best_estimator_.feature_importances_])

imp.columns = MAE_data.drop('log_MAE', axis=1, inplace=False).columns	

# write the feature importance table to a file
imp.to_csv(r'./stats/MAE-regRF-sp0.2-2.csv')
#imp.to_csv(r'./stats/MAE-regRF-sp0.2-impgt0.01-2.csv')
