import numpy as np

X = np.array([[-2, -1], [-1, 0], [0, 1], [1, 2], [2, 3]], dtype=float)
n = X.shape[0]

mean = X.mean(axis=0)
Xc = X - mean
print("mean:", mean)
print("centered data:")
print(Xc)

# covariance of the centered data (divide by n-1)
C = Xc.T @ Xc / (n - 1)
print("covariance matrix:")
print(C)

vals, vecs = np.linalg.eigh(C)
order = np.argsort(vals)[::-1]
vals, vecs = vals[order], vecs[:, order]
w = vecs[:, 0]
if w[0] < 0:
    w = -w  # sign is arbitrary, make the first entry positive
print("eigenvalues:", np.round(vals, 10))
print("first PC w:", w, " norm:", np.linalg.norm(w))

for p in [np.array([3.0, 3.0]), np.array([3.0, 4.0])]:
    pc = p - mean
    coef = pc @ w
    recon_c = coef * w
    recon = recon_c + mean
    err_vec = p - recon
    print()
    print("point:", p)
    print("  centered:", pc)
    print("  coefficient w.(x - mean):", coef)
    print("  reconstruction (original coords):", recon)
    print("  error vector:", err_vec)
    print("  L2 reconstruction error:", np.linalg.norm(err_vec))

# cross-check with sklearn
from sklearn.decomposition import PCA
pca = PCA(n_components=1).fit(X)
print()
print("sklearn components_:", pca.components_[0])
for p in [np.array([[3.0, 3.0]]), np.array([[3.0, 4.0]])]:
    r = pca.inverse_transform(pca.transform(p))
    print("sklearn error for", p[0], ":", np.linalg.norm(p - r))
