#######################################
# Prasenjit Sen
#
# This script contains a RF Classifier that
# classifies stable, magnetic compounds in to
# two classes: having 'HIGH' or 'LOW' magnetic
# anisotropy energy (MAE). The cutoff for 
# LOW-HIGH classification is taken as the median
# value of the training set MAE.
#########################################

import seaborn as sb
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_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 classification')
MAE_data = pd.read_csv('../../datasets/anisotropy/data-long2.csv',sep=',')
print(MAE_data.shape)

# Add derived features
# Scale MAE to per metal atom
#MAE_data['MAE'] = MAE_data['MAE']/MAE_data['n_metal']
# Scale moment to per metal atom
#MAE_data['mom'] = MAE_data['mag_mom']/MAE_data['n_metal']

#MAE_data['log_MAE'] = np.log(MAE_data['MAE'])
#MAE_data['gap'] = MAE_data[['uu','dd','ud','du']].min(axis=1)
#MAE_data['gap_inv'] = 1.0 / MAE_data['gap']
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', 'mean_Z', 'mean_val', 'smeig11', 'smeig10', 'del_group', 'del_Z','mean_group', 'mode_group', 'del_electroneg', 'acsf46', 'acsf49', 'd_elect', 'mode_val', 'acsf47', 'acsf48', 'acsf44', 'acsf45', 'acsf43', 'cell_area', 'acsf212', 'acsf215', 'smeig9', 'acsf216', 'mode_Z', 'mean_period','acsf213','mean_electroneg','mode_electroneg','smeig8','smeig7','del_period', 'acsf42']]

print(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-clRF-sp0.2-impgt0.01-stat.txt", "a")
file1 = open("./stats/MAE-clRF-sp0.2-impgt0.01-stat2.txt", "a")
file1.write("# ccp_alpha,\tmax_depth,\tmax_samples,\tmin_samples_leaf,\tmin_samples_split,\tn_estimators,\ttn_train,\tfp_train,\tfn_train,\ttp_train,\tf1_train,\ttn_test,\tfp_test,\tfn_test,\ttp_test,\tf1_test #\n\n")

imp = pd.DataFrame()

Nruns = 100
# Import function to create training and test set splits
from sklearn.model_selection import train_test_split
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
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score

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)
	
	
	MAE_log = MAE_data[['log_MAE']].values # Just to find the length, below.
	X = MAE_data.drop(labels=['log_MAE'], axis=1, inplace=False).to_numpy()
	
	#X = MAE_data.to_numpy()
	# This test/train split is to find the median of the train MAE values
	X_train, X_test, y_train, y_test = train_test_split(X, MAE_log, test_size=0.2, random_state=1)
	
	med = statistics.median(y_train)
	print('Median log MAE = ',med)
	
	y = []
	for i in range(len(MAE_log)):
		if (MAE_log[i][0] <= med ): y.append(0)
		else: y.append(1)
	#print(y)
	
	
	#sb.stplot(y)
	#t.show()
	
	#MAE_data.drop(labels=['log_MAE'], axis=1, inplace=True)
	#X = MAE_data.to_numpy()
	# Test/train split, again for classification model. Note, we will have exactly
	# the same train-test split as before because we set the same value for random_state.
	# Else, this would have led to data leakage.
	X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
	print('Shape ',X_train.shape)
	
	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
	#Xscaler = MinMaxScaler(feature_range=(-1,1)).fit(X_train)
	X_train = Xscaler.transform(X_train)
	X_test = Xscaler.transform(X_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(RandomForestClassifier(criterion='gini',max_features='sqrt'), parameters, cv=N_CV, n_jobs=-1, scoring='f1', verbose=0)
	
	#krr.fit(X_train,y_train)
	opt = rf.fit(X_train,y_train)
	
	# append to file
	row = []
	for k,v in opt.best_params_.items():
	    row.append(v)
	
	print('Best parameters : ', opt.best_params_)
	print('Scorer f1 :\t', 'best score : ', opt.best_score_)
	
	print('Training results:\n')
	y_train_pred = opt.best_estimator_.predict(X_train)
	print(confusion_matrix(y_train,y_train_pred))
	for v in confusion_matrix(y_train,y_train_pred).flatten():
		row.append(v)
	row.append(opt.best_score_)
	
	print('\nTest results:\n')
	y_pred = opt.best_estimator_.predict(X_test)
	print(confusion_matrix(y_test,y_pred))
	for v in confusion_matrix(y_test,y_pred).flatten():
		row.append(v)
	
	print('Precision=',precision_score(y_test, y_pred, pos_label=1))
	print('Recall=',recall_score(y_test, y_pred, pos_label=1))
	print('f1=',f1_score(y_test, y_pred, pos_label=1))
	row.append(f1_score(y_test, y_pred, pos_label=1))
	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-clRF-sp0.2-impgt0.01.csv')
imp.to_csv(r'./stats/MAE-clRF-sp0.2-impgt0.01-imp2.csv')

