r"""
Mapping real data: Wine and Wisconsin breast cancer
===================================================

On real data there is no manifold to unroll, but the comparison of the
mappings still tells which ones keep local neighborhoods (trustworthiness)
and which keep the global arrangement (continuity, stress). The data are
standardized, every method uses 20% of the samples as nodes, and the node
maps are evaluated against geodesic distances on the competitive Hebbian
graph of the nodes. UMAP and t-SNE, applied to all samples, are evaluated
against Euclidean distances.
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 GeodesicNLPNG, OnlineVisualizationNG, TRNMap, UMAPEmbedding, graphs, metrics, tsne
from graphclust.datasets import load_breast_cancer, load_wine
from graphclust.plotting import plot_embedding

fig, axes = plt.subplots(2, 4, figsize=(14, 6.8))
for row, (loader, name) in enumerate([(load_wine, "Wine"), (load_breast_cancer, "breast cancer")]):
    X, y = loader()
    X = (X - X.mean(0)) / X.std(0)
    n = int(0.2 * len(X))
    # [snippet:real]
    models = {
        "OVI-NG": OnlineVisualizationNG(n, random_state=0),
        "GNLP-NG": GeodesicNLPNG(n, random_state=0),
        "DP-TRNMap": TRNMap(n, normalize=False, random_state=0),
    }
    for mname, m in models.items():
        m.fit(X)
        D_ref = graphs.geodesic_distances(graphs.competitive_hebbian_graph(X, m.nodes_), points=m.nodes_, connect=True)
        q = metrics.mapping_quality(D_ref, m.embedding_, k=(5,), precomputed=True)
        print(f"{name:13s} {mname:10s} T(5) {q['trustworthiness@5']:.3f} C(5) {q['continuity@5']:.3f} Sammon {q['sammon_stress']:.4f}")
    # [/snippet:real]
    U = UMAPEmbedding(random_state=0).fit_transform(X)
    S = tsne(X, random_state=0)
    for mname, Y in (("UMAP", U), ("t-SNE", S)):
        T, C = metrics.trustworthiness_continuity(X, Y, 10)
        print(f"{name:13s} {mname:10s} T(10) {T:.3f} C(10) {C:.3f} (all samples)")
    for ax, (mname, m) in zip(axes[row, :2], list(models.items())[1:]):
        owner = np.argmin(((X[:, None] - m.nodes_[None]) ** 2).sum(-1), 1)
        lab = np.array([np.bincount(y[owner == i], minlength=y.max() + 1).argmax() if (owner == i).any() else -1 for i in range(n)])
        plot_embedding(m.embedding_, lab, ax=ax, s=18, title=f"{name}: {mname} (node majority class)")
    plot_embedding(U, y, ax=axes[row, 2], s=5, title=f"{name}: UMAP")
    plot_embedding(S, y, ax=axes[row, 3], s=5, title=f"{name}: t-SNE")
plt.tight_layout()
