r"""
Growing networks: GNG, GWR, DTRN and WINN
=========================================

Neural gas and the TRN need the number of nodes in advance. Growing networks
start small and insert nodes where the representation is poor:

* growing neural gas (GNG) inserts a node every λ steps near the node with
  the largest accumulated error;
* grow when required (GWR) inserts a node as soon as the winner of a sample
  is far away and already well trained;
* the dynamic TRN (DTRN) creates a node whenever a sample fails a vigilance
  test;
* the weighted incremental network (WINN) grows like GNG and also counts how
  often nodes and edges are used, which estimates the local density.
"""

import matplotlib.pyplot as plt

from graphclust import (
    DynamicTopologyRepresentingNetwork,
    GrowingNeuralGas,
    GrowWhenRequired,
    WeightedIncrementalNetwork,
)
from graphclust.datasets import make_swiss_roll, minmax_scale
from graphclust.plotting import plot_graph

X = minmax_scale(make_swiss_roll(2000, random_state=0)[0])

# [snippet:growing]
models = {
    "GNG": GrowingNeuralGas(max_nodes=200, max_age=30, random_state=0),
    "GWR": GrowWhenRequired(activity_threshold=0.86, n_epochs=3, random_state=0),
    "DTRN": DynamicTopologyRepresentingNetwork(max_iter=4000, rho=(None, 0.06), max_age=8, random_state=0),
    "WINN": WeightedIncrementalNetwork(n_nodes=200, max_age=5, random_state=0),
}
for m in models.values():
    m.fit(X)
# [/snippet:growing]

fig = plt.figure(figsize=(9, 7.5))
for i, (name, m) in enumerate(models.items()):
    ax = fig.add_subplot(2, 2, i + 1, projection="3d")
    plot_graph(m.nodes_, m.adjacency_, ax=ax, node_size=5, lw=0.5)
    ax.set_title(f"{name}: {m.n_nodes_} nodes, {m.n_edges_} edges", fontsize=9)
    ax.view_init(10, -70)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
    print(f"{name}: {m.n_nodes_} nodes, quantization error {m.quantization_error(X):.4f}")
plt.tight_layout()
