r"""
Combining quantization, distance and mapping
============================================

A graph-based map is assembled from three choices: how the data are reduced
to representatives (k-means or neural gas), how dissimilarities between them
are measured (Euclidean, geodesic on a kNN graph, or geodesic on the TRN), and
how the dissimilarities are mapped (metric MDS, non-metric MDS or Sammon).
On the swiss roll, every combination with Euclidean distances folds the roll;
geodesic distances unfold it, and the TRN graph is as good as a carefully
chosen kNN graph without a neighborhood size to tune.
"""

import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans

from graphclust import MetricMDS, NeuralGas, NonMetricMDS, SammonMapping, graphs, metrics
from graphclust.datasets import make_swiss_roll

X, t = make_swiss_roll(2000, random_state=0)
n = 150

# [snippet:combine]
codebooks = {
    "k-means": KMeans(n, n_init=1, random_state=0).fit(X).cluster_centers_,
    "NG": NeuralGas(n, random_state=0).fit(X).nodes_,
}
mappers = {
    "metric MDS": lambda D: MetricMDS(dissimilarity="precomputed", random_state=0).fit_transform(D),
    "non-metric MDS": lambda D: NonMetricMDS(dissimilarity="precomputed", random_state=0).fit_transform(D),
    "Sammon": lambda D: SammonMapping(dissimilarity="precomputed").fit_transform(D),
}
rows = []
for vq, W in codebooks.items():
    D_eu = np.linalg.norm(W[:, None] - W[None], axis=-1)
    D_knn = graphs.geodesic_distances(graphs.knn_graph(W, 5), points=W, connect=True)
    D_trn = graphs.geodesic_distances(graphs.competitive_hebbian_graph(X, W), points=W, connect=True)
    for dist, D in [("Euclidean", D_eu), ("kNN graph", D_knn), ("TRN graph", D_trn)]:
        for mp, f in mappers.items():
            Y = f(D)
            T, C = metrics.trustworthiness_continuity(D_trn, Y, 5, precomputed=True)
            rows.append((vq, dist, mp, T, C))
# [/snippet:combine]

print(f"{'VQ':8s} {'distance':10s} {'mapping':15s} trust(5) cont(5)")
for r in rows:
    print(f"{r[0]:8s} {r[1]:10s} {r[2]:15s} {r[3]:.3f}    {r[4]:.3f}")
M = np.array([[r[3] for r in rows[i * 3:(i + 1) * 3]] for i in range(6)])
fig, ax = plt.subplots(figsize=(6.5, 4.2))
im = ax.imshow(M, cmap="viridis", vmin=0.8, vmax=1.0)
ax.set_xticks(range(3), list(mappers))
ax.set_yticks(range(6), [f"{a} / {b}" for a in codebooks for b in ("Euclidean", "kNN graph", "TRN graph")])
for i in range(6):
    for j in range(3):
        ax.text(j, i, f"{M[i, j]:.3f}", ha="center", va="center", color="w" if M[i, j] < 0.93 else "k", fontsize=8)
ax.set_title("trustworthiness (k = 5) of the node maps")
fig.colorbar(im, ax=ax, shrink=0.8)
plt.tight_layout()
