"""
Partitional clustering: k-means, k-Shape, k-medoids
===================================================

Partitional clustering needs a distance and a notion of a cluster centre.
:class:`~mvtsa.clustering.TimeSeriesKMeans` averages with the arithmetic
mean (Euclidean), DBA (DTW; Petitjean et al., 2011) or the soft-DTW
barycenter; k-Shape (Paparrizos and Gravano, 2015) uses the shape-based
distance and a centroid computed from the leading eigenvector; k-medoids and
fuzzy c-medoids only need a distance matrix, so any elastic measure works.
The synthetic control chart data (Alcock and Manolopoulos, 1999) have six
classes: normal, cyclic, increasing and decreasing trends, upward and
downward shifts.
"""

import matplotlib.pyplot as plt
import pandas as pd

from mvtsa import clustering as cl
from mvtsa import viz
from mvtsa.datasets import make_synthetic_control
from mvtsa.evaluation import clustering_scores

C, y = make_synthetic_control(n_per_class=15, random_state=0)

# %%
# Five algorithms
# ---------------
models = {
    "k-means (Euclidean)": cl.TimeSeriesKMeans(
        6, metric="euclidean", random_state=0
    ),
    "k-means (DBA)": cl.TimeSeriesKMeans(
        6, metric="dtw", window=0.1, max_iter=10, random_state=0
    ),
    "k-Shape": cl.KShape(6, random_state=0),
    "k-medoids (DTW)": cl.KMedoids(
        6, metric="dtw", metric_params={"window": 0.1}
    ),
    "fuzzy c-medoids (DTW)": cl.FuzzyCMedoids(
        6, metric="dtw", metric_params={"window": 0.1}, random_state=0
    ),
}
rows = []
for name, m in models.items():
    m.fit(C)
    rows.append({"algorithm": name, **clustering_scores(y, m.labels_)})
print(pd.DataFrame(rows).round(3).to_string(index=False))
dba = models["k-means (DBA)"]
viz.plot_cluster_prototypes(
    C, dba.labels_, centers=dba.cluster_centers_, ncols=3
)
plt.show()
