"""
Process-dynamics-aware warping: DPCA-CBDTW
==========================================

Bankó's second thesis extends CBDTW with dynamic PCA: the segments are
homogeneous in their *dynamics*, and the segment models are built on
lag-augmented data, so that series are compared by the sequence of their
input--output behaviour. Here the classes differ only in the order in which
the time constant of a first-order system changes; every series has three
regimes, so three segments are used.
"""

import matplotlib.pyplot as plt
import pandas as pd

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

C, y = make_dynamic_sequences(n_classes=3, n_per_class=10, random_state=0)
viz.plot_series(C[0], names=["u", "y"])

# %%
# Static versus dynamic segment models
# ------------------------------------
rows = []
for name, m in [
    (
        "DPCA-CBDTW (2 lags, 4 PCs)",
        wp.CBDTW(n_segments=3, n_components=4, lags=2).fit(C),
    ),
    ("CBDTW (1 PC)", wp.CBDTW(n_segments=3, n_components=1).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))
# %%
# The static correlation of :math:`u` and :math:`y` already reflects the
# time constant -- a slow system follows the input less closely -- so CBDTW
# is a strong baseline. The dynamic segment models capture the input--output
# relation itself.
#
# Parameter study: lags and principal components
# ----------------------------------------------
# With :math:`L` lags the segment models live in :math:`2(L+1)` dimensions.
# The dynamic relation :math:`y_k=a\,y_{k-1}+(1-a)\,u_{k-1}` and the
# near-relation of the piecewise constant input show up in the smallest
# directions: the best models keep all but the last one to three components,
# while too few components lose the structure.
for L in (1, 2, 3):
    res = []
    for q in range(1, 2 * (L + 1)):
        D = wp.CBDTW(n_segments=3, n_components=q, lags=L).fit(C).pairwise()
        res.append(f"{q}:{mean_average_precision(D, y):.2f}")
    print(f"lags {L}  mAP by number of PCs  " + "  ".join(res))
plt.show()
