"""
Real data: Japanese vowels and Riemannian local distances
=========================================================

Twelve LPC cepstrum coefficients of nine speakers uttering the vowel pair
/ae/ (Kudo, Toyama and Shimbo, 1999; UEA archive). The series are short (7
to 29 frames), so a segment carries few samples. The correlation structure
alone (Krzanowski) separates the speakers poorly; local dissimilarities
that compare whole Gaussian segment models -- mean *and* covariance -- work
as well as sample-level DTW at a fraction of the cost.
"""

import time

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_japanese_vowels
from mvtsa.evaluation import knn_accuracy, mean_average_precision

C, y = load_japanese_vowels()
rng = np.random.default_rng(0)
idx = np.concatenate(
    [
        rng.choice(np.flatnonzero(y == k), 20, replace=False)
        for k in np.unique(y)
    ]
)
C, y = [C[i] for i in idx], y[idx]
print(len(C), "utterances, lengths", min(map(len, C)), "-", max(map(len, C)))

# %%
# Local dissimilarities of segment models
# ---------------------------------------
rows = []
for name, m in [
    ("DTW", "dtw"),
    ("DTW_I", "dtw_i"),
    ("CBDTW, Krzanowski", wp.CBDTW(n_segments=1, n_components=2)),
    (
        "CBDTW, log-Euclidean",
        wp.CBDTW(n_segments=1, n_components=3, local="log_euclidean"),
    ),
    (
        "CBDTW, Jeffreys",
        wp.CBDTW(n_segments=1, n_components=3, local="jeffreys"),
    ),
    (
        "CBDTW, Gaussian W2",
        wp.CBDTW(n_segments=1, n_components=3, local="gaussian_w2"),
    ),
    (
        "CBDTW, Gaussian W2, 2 segments",
        wp.CBDTW(
            n_segments=2, n_components=3, local="gaussian_w2", initial_size=6
        ),
    ),
]:
    t0 = time.perf_counter()
    D = pairwise_distances(C, metric=m if isinstance(m, str) else m.fit(C))
    rows.append(
        {
            "measure": name,
            "1-NN": knn_accuracy(D, y),
            "mAP": mean_average_precision(D, y),
            "seconds": time.perf_counter() - t0,
        }
    )
print(pd.DataFrame(rows).round(3).to_string(index=False))
# %%
# Accuracy and cost at a glance
# -----------------------------
table = pd.DataFrame(rows)
fig, ax = plt.subplots(figsize=(6, 3.2))
ax.barh(
    table["measure"],
    table["1-NN"],
    color=["#999999"] * 2 + ["#285780"] * (len(table) - 2),
)
ax.invert_yaxis()
ax.set_xlim(0.5, 1.0)
ax.set_xlabel("leave-one-out 1-NN accuracy (9 speakers)")
plt.show()
