"""
Correlation-based dynamic time warping
======================================

Bankó and Abonyi (2012) compare multivariate series by the *sequence of
their correlation structures*: every series is segmented bottom-up so that
the segments are homogeneous in the PCA sense, and DTW aligns the segment
sequences with the local dissimilarity :math:`1-s_{PCA}` (Krzanowski). The
warping runs over a few dozen segments instead of hundreds of samples, so
it is fast, and it ignores differences that do not change the correlation
of the variables. The example uses synthetic on-line signatures (pen
position, pressure and angles).
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import pairwise_distances, viz
from mvtsa import warping as wp
from mvtsa.datasets import make_signatures
from mvtsa.evaluation import (
    knn_accuracy,
    mean_average_precision,
    precision_recall_curve_knn,
)

data, writer = make_signatures(n_writers=6, n_per_writer=8, random_state=0)

# %%
# Segment-level alignment of two signatures of the same writer
# ------------------------------------------------------------
cb = wp.CBDTW(n_segments=10, n_components=2).fit(data)
path = cb.path(0, 1)
print(
    "segments:",
    len(cb.models_[0]),
    len(cb.models_[1]),
    "| CBDTW distance:",
    round(cb.distance(0, 1), 3),
)
viz.plot_segment_alignment(
    data[0], data[1], cb.models_[0], cb.models_[1], path, channel=0
)

# %%
# Retrieval: precision--recall curves
# -----------------------------------
# For every query the other signatures are ranked by distance (Bankó, 2015,
# Alg. 3.1).
std = [(x - np.vstack(data).mean(0)) / np.vstack(data).std(0) for x in data]
measures = {
    "CBDTW": cb.pairwise(),
    "SEGPCA (no warping)": wp.CBDTW(10, 2, warping=False).fit(data).pairwise(),
    "DTW": pairwise_distances(std, metric="dtw"),
    "DTW, 10% band": pairwise_distances(std, metric="dtw", window=0.1),
}
curves = {}
for name, D in measures.items():
    curves[name] = precision_recall_curve_knn(D, writer, r_items=7)
    print(
        f"{name:20s} 1-NN {knn_accuracy(D, writer):.3f}  "
        f"mAP {mean_average_precision(D, writer):.3f}"
    )
viz.plot_precision_recall(curves)

# %%
# Parameter study: the number of segments
# ---------------------------------------
for k in (4, 6, 10, 15, 25):
    D = wp.CBDTW(n_segments=k, n_components=2).fit(data).pairwise()
    print(f"{k:3d} segments: mAP {mean_average_precision(D, writer):.3f}")
plt.show()
