import os
import warnings
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy.sparse.csgraph import connected_components
from scipy.spatial.distance import pdist
from sklearn.decomposition import PCA
from sklearn.manifold import Isomap
from sklearn.neighbors import kneighbors_graph
from sklearn.metrics import silhouette_score
from common import load_iris, CLASSES, COLORS, MEDIA

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

X, y = load_iris()
K = 3  # number of neighbours, as the assignment asks

# Is the 3-nearest-neighbour graph connected? (edges treated as undirected)
G = kneighbors_graph(X, n_neighbors=K, mode="connectivity")
n_comp, labels = connected_components(G, directed=False)
print("3-NN graph: number of connected components =", n_comp)
print("component sizes:", np.bincount(labels))
print()

# Isomap with 3 nearest neighbours, 2 output dimensions
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    iso = Isomap(n_neighbors=K, n_components=2)
    Z_iso = iso.fit_transform(X)
print("Isomap warnings raised:", len(w))
for item in w:
    print("  ", str(item.message)[:150])
print("Isomap embedding shape:", Z_iso.shape)
print("Isomap reconstruction_error():  %.4f" % iso.reconstruction_error())

# Isomap has no random choices: a second fit should give the same embedding
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    Z_iso_again = Isomap(n_neighbors=K, n_components=2).fit_transform(X)
print("Isomap refit gives the same embedding:", np.allclose(Z_iso, Z_iso_again))
print()

# PCA with 2 components (same data, centered, no scaling)
pca = PCA(n_components=2)
Z_pca = pca.fit_transform(X)
print("PCA 2D variance explained:      %.4f" % pca.explained_variance_ratio_.sum())
print()

# How well do the 2D distances match the original 4D Euclidean distances?
d_orig = pdist(X)
for name, Z in [("PCA 2D", Z_pca), ("Isomap 2D", Z_iso)]:
    r = np.corrcoef(d_orig, pdist(Z))[0, 1]
    print("%-10s correlation of pairwise distances with original: %.4f" % (name, r))
print()

# Silhouette score with the true labels (the labels are only used to score)
print("silhouette score using the true labels")
for name, Z in [("original 4D", X), ("PCA 2D", Z_pca), ("Isomap 2D", Z_iso)]:
    print("  %-12s %.4f" % (name, silhouette_score(Z, y)))

# Fig 8: Isomap embedding, 3 nearest neighbours
fig, ax = plt.subplots(figsize=(6.5, 5))
for c in range(3):
    ax.scatter(Z_iso[y == c, 0], Z_iso[y == c, 1], s=22, color=COLORS[c],
               alpha=0.8, label=CLASSES[c])
ax.set_xlabel("Isomap dimension 1")
ax.set_ylabel("Isomap dimension 2")
ax.grid(alpha=0.25)
ax.legend(frameon=False, loc="best")
fig.tight_layout()
path = os.path.join(MEDIA, "p5_fig8_isomap_k3.png")
fig.savefig(path, dpi=200, bbox_inches="tight")
plt.close(fig)
print()
print("saved", path)
