r"""
Number of nodes in TRNMap and the mapping quality
=================================================

The most influential parameter of TRNMap is the number of nodes. With too few
nodes the node spacing exceeds the gap between the windings of the roll, the
competitive Hebbian links bridge the gap, and the map folds; with enough nodes
the links stay on the sheet and the roll is unrolled. Trustworthiness and
continuity of the node maps, computed with geodesic distances as the
reference, quantify the result.
"""

import matplotlib.pyplot as plt
import numpy as np

from graphclust import TRNMap, metrics
from graphclust.datasets import make_swiss_roll
from graphclust.plotting import plot_graph, plot_quality_curves

X, t = make_swiss_roll(2000, random_state=0)
ks = np.arange(1, 21)
fig, axes = plt.subplots(1, 4, figsize=(15, 3.6))
T, C = {}, {}
for ax, n in zip(axes[:3], [50, 150, 400]):
    # [snippet:nodes]
    tm = TRNMap(n_nodes=n, random_state=0).fit(X)
    Tn, Cn = metrics.trustworthiness_continuity(tm.dist_matrix_, tm.embedding_, ks, precomputed=True)
    # [/snippet:nodes]
    T[f"trust., n = {n}"], C[f"cont., n = {n}"] = Tn, Cn
    owner = tm.trn_.labels_
    t_node = np.array([t[owner == i].mean() if (owner == i).any() else np.nan for i in range(n)])
    plot_graph(tm.embedding_, tm.adjacency_, ax=ax, node_size=0, lw=0.5, title=f"DP-TRNMap, n = {n} ({tm.trn_.n_edges_} edges)")
    ax.scatter(*tm.embedding_.T, c=t_node, cmap="viridis", s=10, zorder=3)
    ax.set_xticks([])
    ax.set_yticks([])
    print(f"n={n}: trustworthiness(5) {Tn[4]:.3f}, continuity(5) {Cn[4]:.3f}")
plot_quality_curves({**T, **C}, k=ks, ax=axes[3], title="quality of the node maps")
plt.tight_layout()
