"""
A family of elastic measures on Cylinder--Bell--Funnel
======================================================

The CBF problem (Saito, 1994) is the classic test of elastic measures: the
three classes differ in shape, but the onset and length of the events vary.
The leave-one-out 1-nearest-neighbour accuracy compares Euclidean distance,
DTW and its variants (derivative, weighted, amerced, shape-based) and the
edit-type measures (LCSS, EDR, ERP, TWED, MSM).
"""

import time

import matplotlib.pyplot as plt
import pandas as pd

from mvtsa import pairwise_distances, viz
from mvtsa.datasets import make_cbf
from mvtsa.evaluation import knn_accuracy

C, y = make_cbf(n_per_class=15, length=96, random_state=0)
viz.plot_cluster_prototypes(C, y, ncols=3)

# %%
# Leave-one-out 1-NN accuracy
# ---------------------------
measures = {
    "euclidean": {},
    "dtw": {},
    "dtw (10% band)": {"metric": "dtw", "window": 0.1},
    "ddtw": {},
    "wdtw": {"g": 0.05},
    "adtw": {"penalty": 0.5},
    "shape_dtw": {"width": 9},
    "lcss": {"epsilon": 0.5, "delta": 10},
    "edr": {"epsilon": 0.25},
    "erp": {},
    "twed": {},
    "msm": {"c": 0.5},
    "sbd": {},
}
rows = []
for name, kw in measures.items():
    kw = dict(kw)
    metric = kw.pop("metric", name)
    t0 = time.perf_counter()
    D = pairwise_distances(C, metric=metric, **kw)
    rows.append(
        {
            "measure": name,
            "1-NN accuracy": knn_accuracy(D, y),
            "seconds": time.perf_counter() - t0,
        }
    )
table = pd.DataFrame(rows).sort_values("1-NN accuracy", ascending=False)
print(table.round(3).to_string(index=False))
fig, ax = plt.subplots(figsize=(6, 3.2))
ax.barh(table["measure"], table["1-NN accuracy"], color="#285780")
ax.invert_yaxis()
ax.set_xlabel("leave-one-out 1-NN accuracy")
ax.set_xlim(0.5, 1.0)
plt.show()
