"""
A multivariate mixed segment distance
=====================================

:class:`~mvtsa.warping.MixedSegmentDistance` generalizes MDPLA to
multivariate segment models: the dissimilarity of two segments is a
weighted sum of the differences of their levels, trends, correlation
structures, scales and durations. The weights are learned by
leave-one-out accuracy on a simplex grid. The example uses the BasicMotions
recordings (accelerometer and gyroscope, UEA archive).
"""

import matplotlib.pyplot as plt
import pandas as pd

from mvtsa import pairwise_distances
from mvtsa import warping as wp
from mvtsa.datasets import load_basic_motions
from mvtsa.evaluation import knn_accuracy, mean_average_precision

C, y = load_basic_motions()

# %%
# Learning the weights
# --------------------
model = wp.CBDTW(
    n_segments=6,
    n_components=2,
    local=wp.MixedSegmentDistance(
        {"level": 1, "trend": 1, "structure": 1, "scale": 1}
    ),
)
best, scores = wp.learn_segment_weights(model, C, y)
print("learned weights:", best)
top = sorted(scores.items(), key=lambda kv: -kv[1])[:5]
print(
    pd.DataFrame(
        [{**dict(zip(best, w, strict=True)), "accuracy": a} for w, a in top]
    ).round(3)
)
# %%
# Comparison
# ----------
rows = []
for name, m in [
    ("mixed (learned)", model),
    ("CBDTW, Krzanowski", wp.CBDTW(6, 2).fit(C)),
    ("CBDTW, Gaussian W2", wp.CBDTW(6, 2, local="gaussian_w2").fit(C)),
    ("DTW", "dtw"),
]:
    D = pairwise_distances(C, metric=m)
    rows.append(
        {
            "measure": name,
            "1-NN": knn_accuracy(D, y),
            "mAP": mean_average_precision(D, y),
        }
    )
print(pd.DataFrame(rows).round(3).to_string(index=False))

# %%
# Accuracy over the weight simplex
# --------------------------------
# Every point is one weighting of the four components; the structure weight
# on the horizontal axis.
fig, ax = plt.subplots(figsize=(5, 3.2))
w_struct = [w[2] for w in scores]
ax.scatter(
    w_struct,
    list(scores.values()),
    c=[w[3] for w in scores],
    cmap="viridis",
    s=28,
)
ax.set_xlabel("weight of the correlation structure")
ax.set_ylabel("LOO 1-NN accuracy")
ax.set_title("colour: weight of the scale", fontsize=9, loc="left")
plt.show()
