r"""
Quantitative comparison of topology-based maps
==============================================

OVI-NG, GNLP-NG, the two TRNMap variants and CDA are run on the swiss roll
with 150 nodes and identical common parameters; each learns its own nodes,
and every node map is evaluated against geodesic distances on the competitive
Hebbian graph of its nodes. Isomap is applied to the TRNMap nodes for
reference. Methods that
use geodesic distances reach trustworthiness and continuity close to one at
all neighborhood sizes; OVI-NG, which uses Euclidean distances, keeps the
roll folded and loses continuity.
TRNMap is run without its internal rescaling (``normalize=False``) so that
all maps live in the same distance scale.
"""

import matplotlib.pyplot as plt
import numpy as np

from graphclust import (
    CurvilinearComponentAnalysis,
    GeodesicNLPNG,
    Isomap,
    OnlineVisualizationNG,
    TRNMap,
    graphs,
    metrics,
)
from graphclust.datasets import make_swiss_roll
from graphclust.plotting import plot_quality_curves

X, t = make_swiss_roll(2000, random_state=0)
n = 150
ks = np.arange(1, 31)

# [snippet:compare]
models = {
    "OVI-NG": OnlineVisualizationNG(n, random_state=0),
    "GNLP-NG": GeodesicNLPNG(n, random_state=0),
    "DP-TRNMap": TRNMap(n, mapping="metric", normalize=False, random_state=0),
    "NP-TRNMap": TRNMap(n, mapping="nonmetric", normalize=False, random_state=0),
    "CDA": CurvilinearComponentAnalysis(geodesic=True, n_nodes=n, k=6, n_epochs=40, random_state=0),
}
T, C, table = {}, {}, {}
for name, m in models.items():
    m.fit(X)
    W = m.nodes_
    D_ref = graphs.geodesic_distances(graphs.competitive_hebbian_graph(X, W), points=W, connect=True)
    T[name], C[name] = metrics.trustworthiness_continuity(D_ref, m.embedding_, ks, precomputed=True)
    table[name] = metrics.mapping_quality(D_ref, m.embedding_, k=(5,), precomputed=True)
# [/snippet:compare]
W = models["DP-TRNMap"].nodes_
iso = Isomap(graph=graphs.competitive_hebbian_graph(X, W)).fit(W)
D_ref = graphs.geodesic_distances(graphs.competitive_hebbian_graph(X, W), points=W, connect=True)
T["Isomap (TRN nodes)"], C["Isomap (TRN nodes)"] = metrics.trustworthiness_continuity(D_ref, iso.embedding_, ks, precomputed=True)
table["Isomap (TRN nodes)"] = metrics.mapping_quality(D_ref, iso.embedding_, k=(5,), precomputed=True)

print(f"{'method':20s} {'Sammon':>8s} {'MDS':>8s} {'1-R^2':>8s} {'T(5)':>7s} {'C(5)':>7s} {'AUC':>6s}")
for name, q in table.items():
    print(f"{name:20s} {q['sammon_stress']:8.4f} {q['mds_stress']:8.4f} {q['residual_variance']:8.4f} "
          f"{q['trustworthiness@5']:7.3f} {q['continuity@5']:7.3f} {q['auc_rnx']:6.3f}")
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
plot_quality_curves(T, k=ks, ax=axes[0], ylabel="trustworthiness", title="trustworthiness, swiss roll")
plot_quality_curves(C, k=ks, ax=axes[1], ylabel="continuity", title="continuity, swiss roll")
plt.tight_layout()
