"""
Looking inside alignments and collections
=========================================

Warping paths, the accumulated cost and the uncertainty of an alignment
explain *why* two series are similar; maps of a distance matrix show the
structure of a whole collection; prototypes summarize the clusters. The
example uses GunPoint (two classes of hand movements, UEA & UCR archive).
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import pairwise_distances, viz
from mvtsa import warping as wp
from mvtsa.datasets import load_gunpoint

G, y = load_gunpoint()
rng = np.random.default_rng(0)
idx = rng.choice(len(G), 60, replace=False)
G, y = [G[i] for i in idx], y[idx]

# %%
# An alignment and its uncertainty
# --------------------------------
a, b = G[0], G[int(np.flatnonzero(y == y[0])[1])]
res = wp.dtw_path(a, b, window=0.1)
_, E = wp.soft_dtw_alignment(a, b, gamma=0.05)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4))
viz.plot_alignment(a, b, res.path, every=4, ax=axes[0])
viz.plot_alignment_uncertainty(E, path=res.path, ax=axes[1])

# %%
# The collection: distance matrix, Sammon map and prototypes
# ----------------------------------------------------------
D = pairwise_distances(G, metric="dtw", window=0.1)
viz.plot_distance_matrix(D, y)
viz.plot_embedding(D, y, method="sammon")
centers = [
    wp.dba([G[i] for i in np.flatnonzero(y == k)], n_iter=8, window=0.1)
    for k in np.unique(y)
]
viz.plot_cluster_prototypes(G, y, centers=centers, ncols=2)
plt.show()
