"""Dynamic time warping and its variants.
DTW is "not a simple similarity measure, rather a framework" (Bankó,
2015): it combines a local dissimilarity of the samples, admissible steps
(the local constraint), an admissible region of the warping path (the
global constraint) and possibly a penalty of warping. All variants below
use the same compiled dynamic-programming kernel.
* :func:`dtw`, :func:`dtw_path` -- classical DTW (Sakoe and Chiba, 1978)
with Sakoe--Chiba band, Itakura parallelogram or a custom window, three
step patterns and dependent (vector) multivariate local costs;
* :func:`dtw_independent` -- the sum of univariate DTW distances
(Shokoohi-Yekta et al., 2017);
* :func:`ddtw` -- derivative DTW (Keogh and Pazzani, 2001);
* :func:`wdtw` -- weighted DTW with a logistic weight of the phase
difference (Jeong, Jeong and Omitaomu, 2011);
* :func:`adtw` -- amerced DTW, an additive penalty for every warping step
(Herrmann and Webb, 2023);
* :func:`shape_dtw` -- DTW of local shape descriptors (Zhao and Itti, 2018);
* :func:`fast_dtw` -- multi-resolution approximation (Salvador and Chan, 2007);
* :func:`lb_kim`, :func:`lb_keogh` -- lower bounds for fast search
(Kim et al., 2001; Keogh and Ratanamahatana, 2005);
* :func:`subsequence_dtw` -- best match of a query anywhere inside a long
series (open-begin, open-end DTW).
"""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
from .._base import as_series
from ..preprocessing import keogh_derivative
from . import _dp
__all__ = [
"local_cost_matrix",
"window_mask",
"DTWResult",
"dtw",
"dtw_path",
"dtw_independent",
"ddtw",
"wdtw",
"adtw",
"shape_dtw",
"fast_dtw",
"lb_kim",
"lb_keogh",
"subsequence_dtw",
"STEP_PATTERNS",
]
STEP_PATTERNS = {"symmetric1": _dp.SYMMETRIC1, "symmetric2": _dp.SYMMETRIC2, "asymmetric": _dp.ASYMMETRIC}
[docs]
def local_cost_matrix(x, y, metric="sqeuclidean") -> np.ndarray:
"""Local cost matrix ``C[i, j] = d(x_i, y_j)``.
``metric``: ``"sqeuclidean"`` (default), ``"euclidean"``, ``"abs"``
(city block), ``"cosine"`` or a callable ``f(x_i, y_j)``.
"""
X, Y = as_series(x), as_series(y)
if X.shape[1] != Y.shape[1]:
raise ValueError("the two series must have the same number of variables")
if callable(metric):
return np.array([[metric(a, b) for b in Y] for a in X], dtype=float)
if metric in ("sqeuclidean", "euclidean"):
sx, sy = (X**2).sum(1), (Y**2).sum(1)
C = np.maximum(sx[:, None] + sy[None, :] - 2 * X @ Y.T, 0.0)
return np.sqrt(C) if metric == "euclidean" else C
if metric in ("abs", "cityblock", "manhattan"):
return np.abs(X[:, None, :] - Y[None, :, :]).sum(-1)
if metric == "cosine":
nx = np.linalg.norm(X, axis=1)
ny = np.linalg.norm(Y, axis=1)
nx, ny = np.where(nx < 1e-12, 1.0, nx), np.where(ny < 1e-12, 1.0, ny)
return 1.0 - (X / nx[:, None]) @ (Y / ny[:, None]).T
raise ValueError(f"unknown metric {metric!r}")
[docs]
def window_mask(n: int, m: int, window=None) -> np.ndarray:
"""Admissible cells of the warping path.
``window`` may be ``None`` (no constraint), an int or float ``r``
(Sakoe--Chiba band of half-width ``r`` samples, or ``r`` times the
length if ``r < 1``), ``("sakoe_chiba", r)``, ``("itakura", s)`` with
maximal slope ``s`` (Itakura parallelogram), or a boolean array.
The band follows the diagonal of the rectangular ``n x m`` grid.
"""
if window is None:
return np.ones((n, m), dtype=bool)
if isinstance(window, np.ndarray):
if window.shape != (n, m):
raise ValueError("window mask has the wrong shape")
return window.astype(bool)
kind, val = ("sakoe_chiba", window) if np.isscalar(window) else window
i = np.arange(n)[:, None] / max(n - 1, 1)
j = np.arange(m)[None, :] / max(m - 1, 1)
if kind in ("sakoe_chiba", "band"):
r = float(val)
r = r if r >= 1 else r * max(n, m)
width = (r + 0.5) / max(n - 1, m - 1, 1)
M = np.abs(i - j) <= width + 1e-12
elif kind == "itakura":
s = float(val)
M = (j <= s * i + 1e-12) & (j >= i / s - 1e-12) & (1 - j <= s * (1 - i) + 1e-12) & (1 - j >= (1 - i) / s - 1e-12)
else:
raise ValueError(f"unknown window {window!r}")
M[0, 0] = M[-1, -1] = True
return M
[docs]
@dataclass
class DTWResult:
"""Distance, warping path and accumulated cost matrix of one alignment."""
distance: float
path: np.ndarray
cost_matrix: np.ndarray
accumulated: np.ndarray
@property
def normalized_distance(self) -> float:
"""Distance divided by the warping path length."""
return float(self.distance / max(len(self.path), 1))
def _run(C, window, step, penalty, open_begin=False, need_path=True):
n, m = C.shape
mask = window_mask(n, m, window)
st = STEP_PATTERNS[step] if isinstance(step, str) else int(step)
D = _dp.accumulate(np.ascontiguousarray(C, dtype=np.float64), mask, st, float(penalty), bool(open_begin), False)
path = _dp.backtrack(D, np.ascontiguousarray(C, dtype=np.float64), st, float(penalty), bool(open_begin)) \
if need_path else None
return D, path
[docs]
def dtw(x, y, window=None, metric="sqeuclidean", step: str = "symmetric1", penalty: float = 0.0,
normalize: bool = False) -> float:
"""DTW distance of two (multivariate) series.
Parameters
----------
x, y : arrays (T_x, n), (T_y, n)
window : see :func:`window_mask`
metric : local cost (see :func:`local_cost_matrix`), or ``"precomputed"``
if ``x`` is already the cost matrix.
step : {"symmetric1", "symmetric2", "asymmetric"}
Local constraint (``"symmetric1"`` is type I of Rabiner and Juang).
penalty : float
Additive cost of every non-diagonal step.
normalize : bool
Divide by ``T_x + T_y`` (symmetric2) or by the path length.
Examples
--------
>>> x = np.array([0., 0, 1, 2, 1, 0]); y = np.array([0., 1, 2, 1, 0, 0])
>>> float(dtw(x, y))
0.0
"""
C = np.asarray(x, float) if metric == "precomputed" else local_cost_matrix(x, y, metric)
D, path = _run(C, window, step, penalty, need_path=normalize and step != "symmetric2")
d = float(D[-1, -1])
if normalize:
d = d / (C.shape[0] + C.shape[1]) if step == "symmetric2" else d / len(path)
return d
[docs]
def dtw_path(x, y, window=None, metric="sqeuclidean", step: str = "symmetric1", penalty: float = 0.0) -> DTWResult:
"""Full DTW result: distance, optimal warping path ``(L, 2)``, local and
accumulated cost matrices."""
C = np.asarray(x, float) if metric == "precomputed" else local_cost_matrix(x, y, metric)
D, path = _run(C, window, step, penalty)
return DTWResult(float(D[-1, -1]), path, C, D[1:, 1:])
[docs]
def dtw_independent(x, y, window=None, metric="sqeuclidean", step: str = "symmetric1") -> float:
"""Independent multivariate DTW: the sum of the DTW distances of the
variables, each warped separately (DTW_I)."""
X, Y = as_series(x), as_series(y)
return float(sum(dtw(X[:, k], Y[:, k], window, metric, step) for k in range(X.shape[1])))
[docs]
def ddtw(x, y, window=None, metric="sqeuclidean", step: str = "symmetric1") -> float:
"""Derivative DTW: DTW of the Keogh--Pazzani derivative estimates."""
return dtw(keogh_derivative(x), keogh_derivative(y), window, metric, step)
[docs]
def wdtw(x, y, g: float = 0.05, w_max: float = 1.0, metric="sqeuclidean") -> float:
"""Weighted DTW: the local cost of cell ``(i, j)`` is multiplied by
:math:`w_{max}/(1+\\exp(-g(|i-j|-m_c)))`, where :math:`m_c` is half of
the length; large phase differences are penalized smoothly."""
C = local_cost_matrix(x, y, metric)
n, m = C.shape
mc = max(n, m) / 2.0
d = np.abs(np.arange(n)[:, None] - np.arange(m)[None, :])
W = w_max / (1.0 + np.exp(-g * (d - mc)))
return dtw(C * W, None, metric="precomputed")
[docs]
def adtw(x, y, penalty: float = 1.0, metric="sqeuclidean") -> float:
"""Amerced DTW: every non-diagonal (warping) step costs an additional
``penalty`` (Herrmann and Webb, 2023). ``penalty=0`` is DTW, a very
large penalty approaches the lock-step (Euclidean) distance."""
return dtw(x, y, metric=metric, penalty=penalty)
def _shape_descriptors(x, width: int, descriptor: str):
X = as_series(x)
T, n = X.shape
h = width // 2
P = np.vstack([np.repeat(X[:1], h, 0), X, np.repeat(X[-1:], h, 0)])
win = np.stack([P[t:t + 2 * h + 1] for t in range(T)]) # (T, w, n)
if descriptor == "raw":
return win.reshape(T, -1)
if descriptor == "derivative":
return np.diff(win, axis=1).reshape(T, -1)
if descriptor == "slope":
k = 3
parts = np.array_split(np.arange(2 * h + 1), k)
out = []
for idx in parts:
tt = idx - idx.mean()
seg = win[:, idx, :]
den = (tt**2).sum() or 1.0
out.append((seg * tt[None, :, None]).sum(1) / den)
return np.concatenate(out, axis=1)
if descriptor == "paa":
parts = np.array_split(np.arange(2 * h + 1), 3)
return np.concatenate([win[:, idx, :].mean(1) for idx in parts], axis=1)
raise ValueError(f"unknown descriptor {descriptor!r}")
[docs]
def shape_dtw(x, y, width: int = 9, descriptor: str = "slope", window=None, return_path: bool = False):
"""shapeDTW: DTW on local shape descriptors of every sample; the optimal
path is used to accumulate the *raw* sample distances (Zhao and Itti,
2018). Descriptors: ``"raw"``, ``"derivative"``, ``"slope"``, ``"paa"``."""
Dx, Dy = _shape_descriptors(x, width, descriptor), _shape_descriptors(y, width, descriptor)
res = dtw_path(Dx, Dy, window)
C = local_cost_matrix(x, y)
d = float(C[res.path[:, 0], res.path[:, 1]].sum())
return (d, res.path) if return_path else d
def _coarsen(X):
T = len(X) // 2 * 2
if T < 2:
return X
return (X[:T:2] + X[1:T:2]) / 2.0
[docs]
def fast_dtw(x, y, radius: int = 1, metric="sqeuclidean", min_size: int | None = None):
"""FastDTW (Salvador and Chan, 2007): project the path found at a coarser
resolution, expand it by ``radius`` cells and refine. Returns
``(distance, path)``; an approximation of DTW in linear time."""
X, Y = as_series(x), as_series(y)
min_size = max(radius + 2, 4) if min_size is None else min_size
if len(X) <= min_size or len(Y) <= min_size:
r = dtw_path(X, Y, metric=metric)
return r.distance, r.path
_, path = fast_dtw(_coarsen(X), _coarsen(Y), radius, metric, min_size)
n, m = len(X), len(Y)
M = np.zeros((n, m), dtype=bool)
for i, j in path:
i0, j0 = 2 * i, 2 * j
M[max(0, i0 - radius): min(n, i0 + 2 + radius), max(0, j0 - radius): min(m, j0 + 2 + radius)] = True
M[0, 0] = M[-1, -1] = True
# make sure the window connects the corners
M[-1, :] |= np.arange(m) >= m - 2 - radius
M[:, -1] |= np.arange(n) >= n - 2 - radius
r = dtw_path(X, Y, window=M, metric=metric)
if not np.isfinite(r.distance):
r = dtw_path(X, Y, metric=metric)
return r.distance, r.path
[docs]
def lb_kim(x, y) -> float:
"""LB_Kim lower bound of DTW (squared Euclidean local cost): first and
last samples."""
X, Y = as_series(x), as_series(y)
return float(np.sum((X[0] - Y[0]) ** 2) + (np.sum((X[-1] - Y[-1]) ** 2) if len(X) > 1 and len(Y) > 1 else 0.0))
[docs]
def lb_keogh(query, candidate, radius: int) -> float:
"""LB_Keogh lower bound of band-constrained DTW (squared Euclidean cost,
equal lengths): the distance of the candidate from the envelope of the
query."""
from scipy.ndimage import maximum_filter1d, minimum_filter1d
Q, Cn = as_series(query), as_series(candidate)
if len(Q) != len(Cn):
raise ValueError("LB_Keogh needs series of equal length")
size = 2 * int(radius) + 1
U = maximum_filter1d(Q, size, axis=0, mode="nearest")
L = minimum_filter1d(Q, size, axis=0, mode="nearest")
above = np.maximum(Cn - U, 0.0)
below = np.maximum(L - Cn, 0.0)
return float(np.sum(above**2 + below**2))
[docs]
def subsequence_dtw(query, series, metric="sqeuclidean", step: str = "symmetric1"):
"""Best warped match of ``query`` inside a longer ``series``.
Returns ``(distance, start, stop, distance_profile)``: the match covers
``series[start:stop]``; ``distance_profile[j]`` is the cost of the best
match ending at ``j``.
"""
C = local_cost_matrix(query, series, metric)
D, _ = _run(C, None, step, 0.0, open_begin=True, need_path=False)
prof = D[-1, 1:]
stop = int(np.argmin(prof))
path = _dp.backtrack(D[:, : stop + 2], np.ascontiguousarray(C[:, : stop + 1]), STEP_PATTERNS[step], 0.0, True)
start = int(path[0, 1])
return float(prof[stop]), start, stop + 1, prof