Note
Go to the end to download the full example code or to run this example in your browser via Binder.
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)
Euclidean 1.65 | DTW 0.09 | path length 147
<Figure size 540x500 with 3 Axes>
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),
)

window None : DTW 0.088
window 0.1 : DTW 0.088
window 0.05 : DTW 0.094
window ('itakura', 2.0): DTW 0.101
<Figure size 540x500 with 3 Axes>
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}"
)
LB_Kim 0.002 <= LB_Keogh 0.006 <= DTW(window=12) 0.088
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()
symmetric1 : 0.088
symmetric2 : 0.135
asymmetric : 0.052
penalty 0.0: path length 147
penalty 0.01: path length 128
penalty 0.05: path length 124
Total running time of the script: (0 minutes 0.940 seconds)

