"""
Dynamic time warping and global constraints
===========================================

DTW (Sakoe and Chiba, 1978) aligns two series by a monotone warping path
that minimizes the accumulated local cost. Global constraints -- the
Sakoe--Chiba band or the Itakura parallelogram -- limit how far the path may
leave the diagonal: they speed up the computation and prevent pathological
alignments. Lower bounds (Kim et al., 2001; Keogh, 2002) prune
nearest-neighbour searches.
"""

import matplotlib.pyplot as plt
import numpy as np

from mvtsa import viz
from mvtsa import warping as wp
from mvtsa.datasets import random_time_warp

rng = np.random.default_rng(0)
t = np.linspace(0, 1, 120)
x = (
    np.exp(-(((t - 0.3) / 0.06) ** 2))
    - 0.7 * np.exp(-(((t - 0.65) / 0.08) ** 2))
    + 0.03 * rng.normal(size=120)
)
y = random_time_warp(x, strength=0.25, random_state=1) + 0.03 * rng.normal(
    size=120
)

# %%
# Alignment and cost matrix
# -------------------------
res = wp.dtw_path(x, y)
print(
    f"Euclidean {np.linalg.norm(x - y) ** 2:.2f} | DTW {res.distance:.2f} "
    f"| path length {len(res.path)}"
)
viz.plot_alignment(x, y, res.path, every=3)
viz.plot_cost_matrix(x, y, res.path, cost=res.cost_matrix)

# %%
# Global constraints
# ------------------
for window in (None, 0.1, 0.05, ("itakura", 2.0)):
    r = wp.dtw_path(x, y, window=window)
    print(f"window {window!s:16s}: DTW {r.distance:.3f}")
r = wp.dtw_path(x, y, window=0.1)
viz.plot_cost_matrix(
    x,
    y,
    r.path,
    cost=r.cost_matrix,
    window_mask=wp.window_mask(len(x), len(y), 0.1),
)

# %%
# Lower bounds
# ------------
print(
    f"LB_Kim {wp.lb_kim(x, y):.3f} <= LB_Keogh {wp.lb_keogh(x, y, radius=12):.3f} "
    f"<= DTW(window=12) {wp.dtw(x, y, window=12):.3f}"
)
# %%
# Step patterns and penalties
# ---------------------------
for step in ("symmetric1", "symmetric2", "asymmetric"):
    print(f"{step:11s}: {wp.dtw(x, y, step=step):.3f}")
for pen in (0.0, 0.01, 0.05):
    r = wp.dtw_path(x, y, penalty=pen)
    print(f"penalty {pen}: path length {len(r.path)}")
plt.show()
