'''
lecture21_pca_cov_template.py
PCA dimension reduction on and plotting
Oliver W. Layton
CS251: Data Analysis and Visualization
Spring 2019
'''
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("darkgrid")

# Load in diamond data, sample 1000 points
# print(data[:3])

# Assign data variables x (price),y (carat),z (z) and n

# 1) Center data: xc, yc, zc

# Make data matrix

# Compute data ranges of each variable

# 2) Normalize so range is 1
# print('Centered variable mins:\n', np.min(dataMat, axis=0))
# print('Centered variable maxs:\n', np.max(dataMat, axis=0))


# 3) Compute covariance matrix
# print('Covariance matrix:\n', sigma)


# 4) Compute eigenvalues and eigenvectors
# print('Eigenvalues:\n', eVals)
# print('Eigenvectors:\n', eVecs)

# 5) Sort eigenvalues (already done)

# 6) Compute portion of variance accounted for by each eigenvalue
# print('Proportion variance accounted for:', propVar)

# 7) Remove eigenvectors based on eigenvalue portion variance scores (Step 6)

# 8) Project into PCA space.
# Convert to ndarray for plotting

# Plot data in original space
sns.scatterplot(x='carat', y='price', data=data)
plt.show()
sns.scatterplot(x='z', y='price', data=data)
plt.show()

# Plot data in PCA space
# plt.scatter(dataPCAProj[:, 0].flatten(), dataPCAProj[:, 1].flatten())
# plt.title('data in PCA space')
# plt.xlabel('PC1')
# plt.ylabel('PC2')
# plt.show()

# Price dominates eVals so we conclude that PC0 mostly corresponds to price.
# It accounts for most of the variance out of (price, carat, z) vars.

# 9) (optional) Reconstruct data based on top PCs.
# In this case, we have to comment out the normalization step above (#2)
# otherwise the shape of the reconstructed data will look ok, but at unit scale.

# plt.scatter([data2[:, 1]], [data2[:, 0]])
# plt.title('Reconstructed data')
# plt.xlabel('carat')
# plt.ylabel('price')
# plt.show()
