"""
Diagnosing and tuning warping
=============================

How much warping does a data set need? Path statistics (the share of
diagonal steps, the longest horizontal or vertical run, the area between
the path and the diagonal) and the tightness of warping (ToW) describe the
alignments; the window that maximizes the leave-one-out accuracy can be
learned (Ratanamahatana and Keogh, 2004); and an elastic ensemble
(Lines and Bagnall, 2015) combines several measures.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import viz
from mvtsa import warping as wp
from mvtsa.datasets import make_cbf

C, y = make_cbf(n_per_class=12, length=96, random_state=2)

# %%
# Path statistics of a pair
# -------------------------
res = wp.dtw_path(C[0], C[1])
print({k: round(v, 3) for k, v in wp.path_statistics(res.path).items()})
paths = [wp.dtw_path(C[0], C[j]).path for j in (1, 2, 3)]
viz.plot_warping_function(paths, labels=["pair 0-1", "pair 0-2", "pair 0-3"])

# %%
# Learning the warping window
# ---------------------------
best, scores = wp.learn_window(
    C, y, candidates=(0.0, 0.02, 0.05, 0.1, 0.2, None)
)
print(
    "accuracy by window:",
    {str(k): round(v, 3) for k, v in scores.items()},
    "-> best",
    best,
)
# %%
# An elastic ensemble
# -------------------
rng = np.random.default_rng(0)
idx = rng.permutation(len(C))
train, test = idx[:24], idx[24:]
ee = wp.ElasticEnsemble(
    metrics=("dtw", "ddtw", "msm", ("lcss", {"epsilon": 0.5}))
).fit([C[i] for i in train], y[train])
pred = ee.predict([C[i] for i in test])
print(
    "weights:",
    {k: round(v, 2) for k, v in ee.weights_.items()},
    "| test accuracy:",
    np.mean(pred == y[test]),
)
plt.show()
