r"""
Neural gas learns the shape of the data
=======================================

Neural gas moves *all* representatives towards every drawn sample, with steps
that decay exponentially with their distance rank. Early on, when the
neighborhood range is large, the codebook contracts towards the data mean;
as the range shrinks the representatives spread out and finally cover the
data with roughly equal probability mass. The data set combines a noisy cube,
a bent line and a circle: shapes of three different intrinsic dimensions.
"""

import matplotlib.pyplot as plt
import numpy as np

from graphclust import NeuralGas
from graphclust.datasets import load_boxlinecircle

X = load_boxlinecircle()
rng = np.random.default_rng(0)
sub = X[rng.choice(len(X), 2000, replace=False)]

fig = plt.figure(figsize=(12, 7.5))
for i, t_max in enumerate([0, 100, 1000, 10000, 30000, 60000]):
    # [snippet:ng]
    ng = NeuralGas(n_nodes=300, max_iter=max(t_max, 1), random_state=0).fit(X)
    # [/snippet:ng]
    ax = fig.add_subplot(2, 3, i + 1, projection="3d")
    ax.scatter(*sub.T, s=1, c="#C9D3DD")
    ax.scatter(*ng.nodes_.T, s=6, c="#0072B2")
    ax.set_title("initialization" if t_max == 0 else f"{t_max} adaptation steps", fontsize=10)
    ax.view_init(20, -60)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
    print(f"t_max={t_max:6d}  quantization error {ng.quantization_error(X):.3f}")
plt.tight_layout()
