r"""
Fuzzy neighborhood distances on the Wine data
=============================================

On the 13-dimensional Wine data, MDS of the Euclidean distances (after
standardization) shows three overlapping groups. MDS of the fuzzy
neighborhood distances pulls the cultivars apart, and an average-linkage
dendrogram of the same distances recovers them with few errors, whereas
Jarvis--Patrick clustering depends strongly on its parameters.
"""

import matplotlib.pyplot as plt
import numpy as np

from graphclust import FuzzyNeighborhoodClustering, JarvisPatrick, MetricMDS
from graphclust.datasets import load_wine
from graphclust.plotting import plot_dendrogram, plot_partition
from graphclust.validity import clustering_rate

X, y = load_wine()
X = (X - X.mean(0)) / X.std(0)

# [snippet:wine]
fnc = FuzzyNeighborhoodClustering(n_clusters=3, k=6, r_max=3, alpha=0.2, linkage="average").fit(X)
print("fuzzy neighborhood + average linkage:", round(clustering_rate(y, fnc.labels_), 4))
# [/snippet:wine]
for k, l in [(10, 5), (10, 3), (8, 3), (8, 2)]:
    print(f"Jarvis-Patrick k={k} l={l}:", round(clustering_rate(y, JarvisPatrick(k, l).fit(X).labels_), 4))

D = 1 - fnc.similarity_
np.fill_diagonal(D, 0)
fig, axes = plt.subplots(1, 3, figsize=(13, 4))
plot_partition(MetricMDS(random_state=0).fit_transform(X), y, ax=axes[0], title="MDS, Euclidean distances")
plot_partition(MetricMDS(dissimilarity="precomputed", random_state=0).fit_transform(D), y, ax=axes[1], title="MDS, fuzzy neighborhood distances")
plot_dendrogram(fnc.linkage_matrix_, ax=axes[2], title="average linkage dendrogram")
for ax in axes[:2]:
    ax.set_xticks([])
    ax.set_yticks([])
plt.tight_layout()
