"""
Piecewise linear warping: MPLA, SPLA and MDPLA
==============================================

Bankó and Abonyi (2015) warp piecewise linear approximations. A segment is
described by its mean and by the angle of its slope; MPLA compares means,
SPLA the slope angles, and the mixed MDPLA measure their weighted sum. The
tightness of warping (ToW) -- the average warping path length relative to
the segment count -- shows that the mixed measure warps less, i.e. its
alignments are more natural.
"""

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

from mvtsa import pairwise_distances
from mvtsa import warping as wp
from mvtsa.datasets import load_gunpoint, make_cbf
from mvtsa.evaluation import knn_accuracy

datasets = {"CBF": make_cbf(n_per_class=15, random_state=0)}
G, g = load_gunpoint()
rng = np.random.default_rng(0)
sel = rng.choice(len(G), 60, replace=False)
datasets["GunPoint"] = ([G[i] for i in sel], g[sel])

# %%
# Accuracy and tightness of warping
# ---------------------------------
rows = []
for dname, (C, y) in datasets.items():
    for kind in ("mpla", "spla", "mdpla"):
        p = wp.PLADistance(n_segments=12, kind=kind).fit(C)
        tow = wp.tightness_of_warping(
            list(range(len(C))), p.path, max_pairs=200, random_state=0
        )
        rows.append(
            {
                "data": dname,
                "measure": kind.upper(),
                "1-NN": knn_accuracy(p.pairwise(), y),
                "ToW": tow,
            }
        )
    rows.append(
        {
            "data": dname,
            "measure": "DTW",
            "1-NN": knn_accuracy(pairwise_distances(C, metric="dtw"), y),
            "ToW": np.nan,
        }
    )
print(pd.DataFrame(rows).round(3).to_string(index=False))
# %%
# Learning the weights of MDPLA
# -----------------------------
C, y = datasets["CBF"]
best, scores = wp.learn_segment_weights(wp.PLADistance(12), C, y)
print(
    "best (w_M, w_S):",
    tuple(round(w, 2) for w in best),
    "accuracy",
    round(scores[best], 3),
)
# %%
# On CBF the level of the segments carries most of the information, on
# GunPoint the mixed measure is the best of the three and warps the least:
# the right weighting depends on the data, which is why it is learned.
fig, ax = plt.subplots(figsize=(4.8, 3))
ax.plot([w[0] for w in scores], list(scores.values()), "o-", color="#285780")
ax.set_xlabel("$w_M$ (weight of the mean; $w_S = 1 - w_M$)")
ax.set_ylabel("LOO 1-NN accuracy")
plt.show()
