"""
Hierarchical clustering and distance maps
=========================================

Hierarchical clustering of a distance matrix shows the structure of a
collection at every level. Sammon mapping (Sammon, 1969) draws the matrix
in two dimensions while preserving small distances; the fuzzy Sammon
mapping (Feil, Balaskó and Abonyi, 2007) maps the objects relative to the cluster
prototypes using the fuzzy memberships, which makes the map of a large
collection fast and faithful to the clustering.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import clustering as cl
from mvtsa import pairwise_distances, viz
from mvtsa.datasets import make_cbf
from mvtsa.evaluation import clustering_scores

C, y = make_cbf(n_per_class=20, random_state=1)
D = pairwise_distances(C, metric="dtw", window=0.1)

# %%
# Dendrogram and ordered distance matrix
# --------------------------------------
hc = cl.HierarchicalClustering(
    n_clusters=3, linkage="average", metric="precomputed"
).fit(D)
print(clustering_scores(y, hc.labels_))
viz.plot_dendrogram(hc.linkage_matrix_, labels=y, truncate=30)
viz.plot_distance_matrix(D, hc.labels_)

# %%
# Sammon and fuzzy Sammon maps
# ----------------------------
fcm = cl.FuzzyCMedoids(3, metric="precomputed", random_state=0).fit(D)
Y_fuzzy, Z_proto = viz.fuzzy_sammon(D, fcm.memberships_, fcm.medoid_indices_)
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
viz.plot_embedding(D, y, method="sammon", ax=axes[0])
for k in np.unique(y):
    axes[1].scatter(*Y_fuzzy[y == k].T, s=22, label=str(k))
axes[1].scatter(*Z_proto.T, marker="*", s=200, color="k", label="prototypes")
axes[1].set_title("fuzzy Sammon mapping")
axes[1].legend(frameon=False)

# %%
# Parameter study: the linkage
# ----------------------------
# Cylinder and bell differ only in which side of the plateau rises slowly,
# so they are hard to separate without labels: the clustering task is much
# harder than 1-NN classification on the same distances.
for link in ("single", "complete", "average", "ward"):
    lab = (
        cl.HierarchicalClustering(3, linkage=link, metric="precomputed")
        .fit(D)
        .labels_
    )
    print(
        f"{link:8s} ARI {clustering_scores(y, lab)['ari']:.3f}  cluster sizes {np.bincount(lab).tolist()}"
    )
plt.show()
