r"""
HDBSCAN*: density-corrected spanning trees
==========================================

HDBSCAN* (Campello, Moulavi and Sander 2013) keeps the spanning tree of the
MST methods but measures distances in a density-aware way: the *mutual
reachability distance* of two samples is at least the distance of each to its
``min_samples``-th neighbor. Sparse regions are pushed apart, the MST of
these distances is turned into a hierarchy, and the clusters that persist
longest (largest stability) are selected. Samples in sparse regions become
noise. The density-based validity index DBCV, computed on mutual reachability
trees as well, scores the result without using labels.
"""

import matplotlib.pyplot as plt

from graphclust import HDBSCANStar, MSTClustering
from graphclust.datasets import make_variety
from graphclust.plotting import plot_graph, plot_partition
from graphclust.validity import clustering_rate, dbcv

X, y = make_variety()

# [snippet:hdbscan]
hdb = HDBSCANStar(min_cluster_size=8, min_samples=4).fit(X)
print("clusters:", hdb.n_clusters_, " noise samples:", (hdb.labels_ < 0).sum())
print("DBCV:", round(dbcv(X, hdb.labels_), 3))
# [/snippet:hdbscan]
zahn = MSTClustering(lambda_=2.0, min_cluster_size=2).fit(X)
print("Zahn  DBCV:", round(dbcv(X, zahn.labels_), 3), " rate", clustering_rate(y, zahn.labels_))
print("HDBSCAN rate (noise counted as error):", clustering_rate(y, hdb.labels_))

fig, axes = plt.subplots(1, 3, figsize=(13, 4.2))
plot_graph(X, hdb.mst_, ax=axes[0], node_size=8, title="MST of mutual reachability distances")
plot_partition(X, zahn.labels_, ax=axes[1], title=f"Zahn's criteria ({zahn.n_clusters_} clusters)")
plot_partition(X, hdb.labels_, ax=axes[2], title=f"HDBSCAN* ({hdb.n_clusters_} clusters, gray: noise)")
for ax in axes:
    ax.set_xticks([])
    ax.set_yticks([])
plt.tight_layout()
