r"""
Fuzzy neighborhood similarity: MDS, VAT and dendrogram
======================================================

The fuzzy neighborhood similarity replaces the crisp Jarvis--Patrick test by
the share of common neighbors, :math:`|A_i\cap A_j|/|A_i\cup A_j|`, and
spreads it over :math:`r`-order neighborhoods (neighbors of neighbors) with
a first-order filter. The resulting distance :math:`1-s_{ij}` can be fed to
any distance-based tool. Here MDS separates the three clusters and the
outlier, the VAT image shows three dark blocks and a single isolated sample,
and the single linkage dendrogram suggests the cut at :math:`d=0.75`.
"""

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

from graphclust import FuzzyNeighborhoodClustering, MetricMDS, fuzzy_neighborhood_similarity
from graphclust.datasets import make_variety
from graphclust.plotting import plot_dendrogram, plot_partition, plot_vat
from graphclust.validity import clustering_rate
from graphclust.vat import vat

X, y = make_variety()

# [snippet:fns]
S = fuzzy_neighborhood_similarity(X, k=6, r_max=3, alpha=0.2)
D = 1.0 - S
np.fill_diagonal(D, 0.0)
fnc = FuzzyNeighborhoodClustering(k=6, r_max=3, alpha=0.2, linkage="single", distance_threshold=0.75).fit(X)
print("clusters:", fnc.n_clusters_, " clustering rate:", clustering_rate(y, fnc.labels_))
# [/snippet:fns]

fig, axes = plt.subplots(1, 3, figsize=(13, 4))
Y = MetricMDS(dissimilarity="precomputed", random_state=0).fit_transform(D)
plot_partition(Y, y, ax=axes[0], title="MDS of the fuzzy neighborhood distances")
plot_vat(vat(D)[0], ax=axes[1], title="VAT of the fuzzy neighborhood distances")
plot_dendrogram(fnc.linkage_matrix_, ax=axes[2], threshold=0.75, title="single linkage dendrogram")
axes[0].set_xticks([])
axes[0].set_yticks([])
plt.tight_layout()

# %%
# The result is stable over a wide range of the three parameters.
for k in (3, 6, 10, 15):
    for r in (2, 3, 4):
        lab = fcluster(FuzzyNeighborhoodClustering(k=k, r_max=r, alpha=0.2).fit(X).linkage_matrix_, 4, "maxclust")
        print(f"k={k:2d} r_max={r}: rate with 4 groups {clustering_rate(y, lab):.2f}")
