import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from common import load_iris, MEDIA

os.makedirs(MEDIA, exist_ok=True)
plt.rcParams.update({"font.family": ["Arial", "DejaVu Sans"], "font.size": 11})

X, y = load_iris()
n = X.shape[0]
Xc = X - X.mean(axis=0)  # centered data matrix

# SVD of the centered data matrix: Xc = U S Vt
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)

# Frobenius norm and variance: ||Xc||_F^2 = sum of squared entries = sum of s_i^2
fro2 = np.linalg.norm(Xc, "fro") ** 2
print("||Xc||_F^2 from the entries:        %.4f" % fro2)
print("sum of s_i^2 from the SVD:          %.4f" % np.sum(s ** 2))
print("total variance = ||Xc||_F^2/(n-1):  %.4f" % (fro2 / (n - 1)))
print("sum of per-feature variances (ddof=1): %.4f" % np.sum(X.var(axis=0, ddof=1)))
print()

# Variance along each PC, ratio and cumulative
var_pc = s ** 2 / (n - 1)
ratio = s ** 2 / np.sum(s ** 2)
cum = np.cumsum(ratio)
np.set_printoptions(precision=4, suppress=True)
print("singular values:", s)
print("variance per PC:", var_pc)
print("ratio per PC:   ", ratio)
print("cumulative:     ", cum)
print()

# Q1: two-dimensional representation (rank-2 approximation of Xc)
X2 = (U[:, :2] * s[:2]) @ Vt[:2]
num = np.linalg.norm(X2, "fro") ** 2
res = np.linalg.norm(Xc - X2, "fro") ** 2
print("Q1: rank-2 approximation")
print("  ||X2||_F^2 / ||Xc||_F^2     = %.4f" % (num / fro2))
print("  (s1^2 + s2^2) / sum(s_i^2)  = %.4f" % ((s[0] ** 2 + s[1] ** 2) / np.sum(s ** 2)))
print("  residual ||Xc - X2||_F^2 / ||Xc||_F^2 = %.4f" % (res / fro2))
print()

# Q2: number of PCs needed for 50% of the variance
k50 = int(np.argmax(cum >= 0.5)) + 1
print("Q2: smallest k with cumulative ratio >= 0.5: k = %d (cumulative = %.4f)" % (k50, cum[k50 - 1]))
print()

# cross-check with sklearn
pca = PCA(n_components=4).fit(X)
print("sklearn explained_variance_ratio_:", pca.explained_variance_ratio_)
print("sklearn cumulative:               ", np.cumsum(pca.explained_variance_ratio_))
print("max abs difference from SVD ratios: %.2e" % np.max(np.abs(pca.explained_variance_ratio_ - ratio)))

# Fig 7: variance explained per PC with cumulative curve
fig, ax = plt.subplots(figsize=(6.5, 4.2))
pcs = np.arange(1, 5)
ax.bar(pcs, ratio, color="#4a9d9c", width=0.55, label="per PC")
ax.plot(pcs, cum, "o-", color="#d95f02", label="cumulative")
ax.axhline(0.5, color="gray", linestyle="--", linewidth=1)
ax.text(4.45, 0.51, "50%", ha="right", va="bottom", color="gray")
for p, r in zip(pcs, ratio):
    if p == 1:
        ax.text(p, r - 0.03, "%.3f" % r, ha="center", va="top", fontsize=9, color="white")
    else:
        ax.text(p, r + 0.02, "%.3f" % r, ha="center", va="bottom", fontsize=9)
ax.set_xticks(pcs)
ax.set_xticklabels(["PC1", "PC2", "PC3", "PC4"])
ax.set_ylabel("fraction of total variance")
ax.set_ylim(0, 1.1)
ax.legend(frameon=False, loc="upper right", bbox_to_anchor=(1.0, 0.82))
fig.tight_layout()
path = os.path.join(MEDIA, "p4_fig7_variance_explained.png")
fig.savefig(path, dpi=200, bbox_inches="tight")
plt.close(fig)
print("saved", path)
