r"""
Measuring the quality of a map
==============================

Distance-based measures (Sammon stress, metric MDS stress, residual variance)
ask whether the map distances reproduce the input distances. Rank-based
measures ask whether neighbors stay neighbors: *trustworthiness* penalizes
samples that look close in the map but are not, *continuity* penalizes
neighbors torn apart. Both are computed from the co-ranking matrix, which
also yields the :math:`R_{NX}(K)` curve and its area (AUC), the summary used
in most recent comparisons. On the swiss roll, PCA folds the roll (low
trustworthiness), whereas Isomap with geodesic distances unrolls it. Note
that the distance-based measures, computed against Euclidean input
distances, punish the unrolling: they should be computed against geodesic
distances when the aim is to unfold a manifold.
"""

import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA

from graphclust import Isomap, SammonMapping, metrics
from graphclust.datasets import make_swiss_roll
from graphclust.plotting import plot_quality_curves

X, t = make_swiss_roll(800, random_state=0)
maps = {
    "PCA": PCA(2).fit_transform(X),
    "Sammon": SammonMapping().fit_transform(X),
    "Isomap": Isomap(k=8).fit_transform(X),
}
ks = np.arange(1, 51)
T, C, R = {}, {}, {}
for name, Y in maps.items():
    # [snippet:quality]
    Q = metrics.coranking_matrix(X, Y)
    T[name], C[name] = metrics.trustworthiness_continuity(X, Y, ks, Q=Q)
    R[name] = metrics.rnx_curve(Q=Q)
    print(name, {k: round(v, 3) for k, v in metrics.mapping_quality(X, Y, k=(10,)).items()})
    # [/snippet:quality]

fig, axes = plt.subplots(1, 4, figsize=(15, 3.6))
axes[0].imshow(np.log1p(metrics.coranking_matrix(X, maps["PCA"])[:100, :100]), cmap="Greys")
axes[0].set_title("co-ranking matrix of PCA (first 100 ranks)")
axes[0].set_xlabel("rank in the map")
axes[0].set_ylabel("rank in the data")
plot_quality_curves(T, k=ks, ax=axes[1], ylabel="trustworthiness", title="trustworthiness")
plot_quality_curves(C, k=ks, ax=axes[2], ylabel="continuity", title="continuity")
plot_quality_curves(R, ax=axes[3], ylabel=r"$R_{NX}(K)$", title=r"$R_{NX}(K)$", logx=True)
axes[3].set_xlabel("K")
plt.tight_layout()
