r"""
Volume-based splitting as initialization of Gaussian mixtures
=============================================================

Curved clusters cannot be described by one Gaussian each, but by several.
Run with a generous maximal number of clusters, the hybrid algorithm first
separates the curves (Zahn's criteria) and then keeps splitting the most
voluminous pieces, so that every piece is roughly ellipsoidal and contains
samples of one curve only. Gath--Geva started from this partition converges
to a clean mixture; started from random memberships it mixes the curves.
A dendrogram of the cluster centers shows which pieces belong together.
"""

import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import linkage

from graphclust import GathGeva, HybridMSTGG
from graphclust.datasets import make_curves
from graphclust.plotting import plot_dendrogram, plot_partition

X, y = make_curves()

# [snippet:curves]
hyb = HybridMSTGG(max_clusters=10, lambda_=2.5).fit(X)
Xs = (X - X.min(0)) / np.ptp(X, 0)
rnd = GathGeva(10, random_state=0).fit(Xs)
# [/snippet:curves]

def purity(lab):
    return np.mean([np.bincount(y[lab == c]).max() / (lab == c).sum() for c in np.unique(lab)])

print("criteria:", [s["criterion"] for s in hyb.split_history_])
print(f"purity of the pieces: hybrid initialization {purity(hyb.labels_):.3f}, random initialization {purity(rnd.labels_):.3f}")
fig, axes = plt.subplots(1, 3, figsize=(13, 4))
plot_partition(Xs, hyb.labels_, ax=axes[0], markers=False, title="hybrid MST-GG, 10 clusters")
plot_partition(Xs, rnd.labels_, ax=axes[1], markers=False, title="Gath--Geva from a random start")
for ax in axes[:2]:
    ax.set_xticks([])
    ax.set_yticks([])
Z = linkage(hyb.cluster_centers_, "single")
plot_dendrogram(Z, ax=axes[2], title="single linkage of the cluster centers")
plt.tight_layout()
