r"""
Hybrid MST--Gath--Geva clustering cuts the chain
================================================

The hybrid algorithm always splits the cluster with the largest hypervolume
:math:`\sqrt{\det\mathbf{F}_i}`. If Zahn's criteria find an inconsistent
edge in it, that edge goes; otherwise the edge whose removal gives the
smallest total fuzzy hypervolume is cut. Two compact groups joined by a chain
have a far larger volume than the groups and the chain separately, so the
volume criterion breaks the chain. The crisp partition then initializes
Gath--Geva clustering, which returns memberships and a Gaussian description
of every cluster.
"""

import matplotlib.pyplot as plt
import numpy as np

from graphclust import HybridMSTGG
from graphclust.datasets import make_chainlink
from graphclust.plotting import PALETTE, plot_partition
from graphclust.validity import clustering_rate

X, y = make_chainlink()

# [snippet:hybrid]
model = HybridMSTGG(max_clusters=4, lambda_=2.5, m=2.0).fit(X)
for step in model.split_history_:
    print(step["criterion"], "cut of cluster", step["cluster"], "volumes", np.round(step["volumes"], 4))
print("clustering rate:", clustering_rate(y, model.labels_))
# [/snippet:hybrid]

fig, axes = plt.subplots(1, 2, figsize=(10, 4.3))
plot_partition(X, model.tree_labels_, ax=axes[0], title="MST cut by the hybrid criterion")
Xs = (X - X.min(0)) / np.ptp(X, 0)
gx, gy = np.meshgrid(np.linspace(-0.05, 1.05, 220), np.linspace(-0.05, 1.05, 220))
U = model.gath_geva_.predict_proba(np.c_[gx.ravel(), gy.ravel()])
for i in range(U.shape[1]):
    axes[1].contour(gx, gy, U[:, i].reshape(gx.shape), levels=[0.5, 0.7, 0.9], colors=PALETTE[i], linewidths=0.8)
plot_partition(Xs, model.labels_, ax=axes[1], title="Gath--Geva memberships (contours 0.5, 0.7, 0.9)")
axes[1].scatter(*model.cluster_centers_.T, marker="+", s=120, c="k")
for ax in axes:
    ax.set_xticks([])
    ax.set_yticks([])
plt.tight_layout()
