import warnings
import numpy as np
from scipy.spatial.distance import pdist, squareform
from sklearn.manifold import Isomap, MDS
from sklearn.metrics import silhouette_score
from common import load_iris, SEED

warnings.filterwarnings("ignore")
X, y = load_iris()

# Step 1 of Isomap: geodesic distances from the 3-NN graph (sklearn's own matrix)
iso = Isomap(n_neighbors=3, n_components=2)
Z_iso = iso.fit_transform(X)
D = iso.dist_matrix_
print("geodesic distance matrix shape:", D.shape)
print("symmetric:", np.allclose(D, D.T), " all finite:", bool(np.isfinite(D).all()))
print()


def raw_stress(Z):
    # sum over pairs of (embedding distance - geodesic distance)^2
    return float(np.sum((pdist(Z) - squareform(D, checks=False)) ** 2))


# Step 2 done the way the assignment words it: iterative MDS (SMACOF) on D
mds = MDS(n_components=2, metric_mds=True, metric="precomputed",
          n_init=4, init="random", max_iter=300, random_state=SEED)
Z_mds = mds.fit_transform(D)
print("sklearn MDS (iterative, SMACOF) on the geodesic distances, seed %d" % SEED)
print("  iterations used in the best run:", mds.n_iter_)
print("  final stress reported by sklearn: %.4f" % mds.stress_)
print()
print("raw stress (sum over pairs of squared distance error), same formula for both")
print("  Isomap embedding (eigendecomposition): %.4f" % raw_stress(Z_iso))
print("  MDS embedding (iterative):             %.4f" % raw_stress(Z_mds))
print()
d_iso, d_mds = pdist(Z_iso), pdist(Z_mds)
print("correlation of pairwise distances, Isomap vs MDS embedding: %.4f" % np.corrcoef(d_iso, d_mds)[0, 1])
print("silhouette (true labels): Isomap %.4f, MDS %.4f" % (
    silhouette_score(Z_iso, y), silhouette_score(Z_mds, y)))
