r"""
Geodesic distances on a neighborhood graph
==========================================

On a curved manifold the Euclidean distance cuts through empty space. The
length of the shortest path in a neighborhood graph, with edges weighted by
their Euclidean length, follows the data instead: it approximates the
*geodesic* distance along the manifold. Too few neighbors split the graph,
too many create short-circuit edges between the windings of the swiss roll.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse.csgraph import connected_components

from graphclust import graphs
from graphclust.datasets import make_swiss_roll

X, t = make_swiss_roll(1000, random_state=0)

# [snippet:geodesic]
A = graphs.knn_graph(X, k=8)
D_geo = graphs.geodesic_distances(A, points=X, connect=True)
D_eu = np.linalg.norm(X[:, None] - X[None], axis=-1)
# [/snippet:geodesic]

src = int(np.argmin(t))
fig = plt.figure(figsize=(12, 4))
for i, (D, name) in enumerate([(D_eu, "Euclidean distance"), (D_geo, "geodesic distance (8-NN graph)")]):
    ax = fig.add_subplot(1, 3, i + 1, projection="3d")
    ax.scatter(*X.T, c=D[src], cmap="viridis", s=6)
    ax.scatter(*X[src], c="#D55E00", s=60, marker="*")
    ax.set_title(f"{name} from the marked sample", fontsize=10)
    ax.view_init(8, -70)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])
ax = fig.add_subplot(1, 3, 3)
ks = [2, 3, 4, 6, 8, 12, 16, 24, 32]
comps, corr = [], []
for k in ks:
    Ak = graphs.knn_graph(X, k)
    comps.append(connected_components(Ak)[0])
    Dk = graphs.geodesic_distances(Ak, points=X, connect=True)
    corr.append(np.corrcoef(Dk[src], t)[0, 1])
ax.plot(ks, corr, "o-", color="#0072B2", label="corr(geodesic, position on curve)")
ax2 = ax.twinx()
ax2.plot(ks, comps, "s--", color="#D55E00", label="graph components")
ax.set_xscale("log")
ax.set_xlabel("k")
ax.set_ylabel("correlation")
ax2.set_ylabel("components")
ax.set_title("choice of k", fontsize=10)
fig.legend(loc="lower right", fontsize=8, frameon=False)
plt.tight_layout()
for k, c, r in zip(ks, comps, corr):
    print(f"k={k:2d}: {c} component(s), correlation {r:.3f}")
