import numpy as np
from CARTRegressionTree import bRegressionTree

f = open("AutodatenbankAllEntries.csv")
header = f.readline().rstrip('\n')  
featureNames = header.split(',')
dataset = np.loadtxt(f, delimiter=",", skiprows=4,usecols=range(2,9)) 
f.close()

Features = dataset[:,1:6]
y = dataset[:,0]
xbar = np.mean(Features,axis=0) 
sigma = np.std(Features,axis=0)
X = (Features - xbar) / sigma; print(X[450,:])

Sigma = np.cov(X.T)
(lamb, W) = np.linalg.eig(Sigma)

eigenVar = np.sort(lamb)[::-1]
sumEig = np.sum(lamb)
eigenVar = eigenVar/sumEig
cumVar= np.cumsum(eigenVar)

import matplotlib.pyplot as plt
plt.bar(range(1,len(eigenVar)+1),eigenVar, alpha=0.25, align='center', label='Varianzanteil', color='gray')
plt.step(range(1,len(eigenVar)+1),cumVar, where='mid', label='Kumulativer Varianzanteil', c='k')
plt.xlabel('Hauptkomponenten'); plt.ylabel('Prozentualer Anteil')
plt.legend()

eigenVarIndex = np.argsort(lamb)[::-1]
WP = W[:,eigenVarIndex[0:2]]
XProj = ( WP.T@X.T ).T

np.random.seed(42)
MainSet    = np.arange(0,XProj.shape[0])
TestSet    = np.random.choice(MainSet.shape[0],int(MainSet.shape[0]*0.25), replace=False)
TrainSet   = np.delete(MainSet, TestSet) 

pcaTree = bRegressionTree(minLeafNodeSize=40)
pcaTree.fit(XProj[TrainSet,:],y[TrainSet])
PreisApprox = pcaTree.predict(XProj[TestSet,:])
errorMean = np.mean(np.abs(PreisApprox - y[TestSet]))
print(errorMean)