r"""
Zahn's MST clustering and the chaining effect
=============================================

Deleting the inconsistent edges of the minimal spanning tree separates
clusters of arbitrary shape. Zahn's global criterion calls an edge
inconsistent when it is λ times longer than the average tree edge; his local
criterion compares it with the edges around it, which also works for
clusters of different density. Neither can cut a *chain* of points between
two groups, because every edge of the chain is short: this is the chaining
effect known from single linkage.
"""

import matplotlib.pyplot as plt

from graphclust import MSTClustering
from graphclust.datasets import make_chainlink
from graphclust.plotting import plot_graph, plot_partition
from graphclust.validity import clustering_rate

X, y = make_chainlink()

# [snippet:zahn]
mst = MSTClustering(lambda_=2.0, criterion="both", min_cluster_size=3).fit(X)
print(f"{mst.n_clusters_} clusters, {len(mst.removed_edges_)} edges removed")
# [/snippet:zahn]

fig, axes = plt.subplots(1, 3, figsize=(12, 4))
plot_graph(X, mst.mst_, ax=axes[0], node_size=12, title="minimal spanning tree")
plot_partition(X, mst.labels_, ax=axes[1], title=f"global + local criterion, λ = 2 ({mst.n_clusters_} clusters)")
for lam in (1.5, 2, 3, 4, 6):
    m = MSTClustering(lambda_=lam, min_cluster_size=3).fit(X)
    print(f"lambda={lam}: {m.n_clusters_} clusters, clustering rate {clustering_rate(y, m.labels_):.2f}")
sl = MSTClustering(n_clusters=4, criterion=None).fit(X)
plot_partition(X, sl.labels_, ax=axes[2], title="four longest edges removed (single linkage)")
for ax in axes:
    ax.set_xticks([])
    ax.set_yticks([])
plt.tight_layout()
