Algorithm Search⌘K

Techniquecore

Sakoe-Chiba band

Also called Sakoe-Chiba constraint.

Restrict the warping path of DTW to the cells within a fixed distance r of the diagonal. This saves time and stops degenerate alignments, but it can miss the optimum.

The Sakoe-Chiba band is a global constraint on dynamic time warping: a warping path may use only the cells (i,j)(i, j) with ∣i−j∣≤r|i - j| \le r, for a fixed band width rr. The dynamic program then fills about n(2r+1)n (2r + 1) cells in place of nmn m, and no element of one sequence can pair with a long run of the other. The price is that the best path inside the band can cost more than the best path overall. The Itakura parallelogram is a related constraint (Itakura 1975) that limits the slope of the path and so restricts it to a parallelogram around the diagonal.

In plain words

DTW lets one sequence wait while the other moves on, and it fills a table with one entry for each pair of positions. Most of that table is far from the diagonal, where one sequence is far ahead of the other. Such pairings are rarely right: two recordings of one word do not drift apart by half a second.

The band keeps only a strip of the table along the diagonal, and treats everything outside the strip as forbidden. The program fills only the strip, so it runs much faster on long sequences. It also cannot pick a strange pairing far from the diagonal. But if the true best pairing leaves the strip, the band gives a worse answer, so the width of the strip is a trade-off.

When it applies

The technique applies to a dynamic program over a two-dimensional table in which a path moves from the top left corner to the bottom right corner with monotone steps, and in which good paths stay near the diagonal. DTW is the first case. The same idea works for edit distance and for global alignment, where it is called banded alignment.

It fits when the two sequences have about the same speed, so the offset i−ji - j of a good path stays small, and when ∣n−m∣≤r|n - m| \le r. If the lengths differ a lot, use a band around the line from (1,1)(1, 1) to (n,m)(n, m) in place of the main diagonal, or rescale one sequence first.

The template

  1. BANDED-DTW(x, y, d, BAND) ▷ BAND(i) is the hole: the range of columns j allowed in row i
  2. 1if the cell (n, m) is not in BAND(n), or (1, 1) is not in BAND(1), then report "no path in the band"
  3. 2D[0][0] ← 0, and every cell outside the band counts as ∞
  4. 3for i ← 1 to n do
  5. 4for j in BAND(i), clipped to 1 .. m do
  6. 5D[i][j] ← d(x_i, y_j) + min(D[i-1][j-1], D[i-1][j], D[i][j-1])
  7. 6return D[n][m], and the path from the back pointers

The hole is BAND. The Sakoe-Chiba band of width rr is BAND(i)={i−r,…,i+r}\mathrm{BAND}(i) = \{ i - r, \ldots, i + r \}. With this band, a warping path exists if and only if ∣n−m∣≤r|n - m| \le r: the last cell must satisfy ∣n−m∣≤r|n - m| \le r, and if it does, the path that goes along the diagonal and then straight to (n,m)(n, m) stays in the band. Line L1 checks this. Line L5 is the recurrence of the symmetric1 pattern on the dynamic time warping page, and the other step patterns work the same way.

Walk through the template with x=(0,0,0,5)x = (0, 0, 0, 5), y=(0,5,5,5)y = (0, 5, 5, 5) and d(a,b)=∣a−b∣d(a, b) = |a - b|.

  • Without a band, the best path is (1,1),(2,1),(3,1),(4,2),(4,3),(4,4)(1, 1), (2, 1), (3, 1), (4, 2), (4, 3), (4, 4). It pairs the three zeros of xx with the zero of yy and the five of xx with the three fives of yy, and it costs 0. It uses the cells (3,1)(3, 1) and (4,2)(4, 2), which have ∣i−j∣=2|i - j| = 2.
  • With r=2r = 2 that path is in the band, and the cost is 0.
  • With r=1r = 1 it is not. The best path in the band is (1,1),(2,1),(3,2),(4,3),(4,4)(1, 1), (2, 1), (3, 2), (4, 3), (4, 4), which pairs the third zero of xx with a five and costs 5.
  • With r=0r = 0 only the diagonal is left, and the cost is 0+5+5+0=100 + 5 + 5 + 0 = 10.

So the band missed the optimum for r≤1r \le 1. The test test_band_misses_the_optimum checks these values.

Cost. Row ii has at most 2r+12r + 1 cells, so the template fills at most n(2r+1)n (2r + 1) cells, and exactly n(2r+1)−r(r+1)n (2r + 1) - r (r + 1) when n=m>rn = m > r. The time and the memory are O(nr)O(n r) for r≥1r \ge 1, against Θ(nm)\Theta(n m) without the band. The code stores only the cells of the band.

What the band guarantees. The banded cost is the least cost over the warping paths inside the band (a theorem, from the same induction as for DTW, applied to the cells of the band). It is at least the unconstrained cost, it does not increase as rr grows, and it equals the unconstrained cost when r≥max⁡(n,m)−1r \ge \max(n, m) - 1. The tests check all three. The banded cost is exact only if some optimal path stays in the band, and the band has no way to check this.

Classic examples

  • Isolated word recognition. Sakoe and Chiba 1978 compared spoken words with stored templates by dynamic time warping under an adjustment window ∣i−j∣≤r|i - j| \le r, together with a slope constraint. The window cut the cost of each comparison and removed alignments that were not plausible for speech.
  • Banded alignment of strings. For edit distance and global alignment of similar strings, banded alignment fills only the diagonals near the main one. For unit costs, the band can be doubled until its width exceeds the cost found, which makes the result exact.
  • Nearest neighbor search over time series. A nearest neighbor search that compares a query with many stored series uses a band of a few percent of the length. The band cuts the cost of each comparison, and its width becomes a parameter of the classifier, chosen on held-out data like any other.
  • Alignment with a known transcript. The limits lotlo_t and hithi_t of forced alignment are a band in the frame and state table, but there they are exact: they only drop cells that no complete path can use.

Variations

  • Itakura parallelogram. Itakura 1975 limited the local slope of the path, so that each sequence advances at most twice as fast as the other. Together with the fixed ends, this keeps the path in a parallelogram with corners (1,1)(1, 1) and (n,m)(n, m) and sides of slope 1/21/2 and 22, so a path exists only if m/2≤n≤2mm/2 \le n \le 2m, roughly. The parallelogram is narrow near the ends and wide in the middle, while the band has the same width everywhere.
  • Slope constraints. Sakoe and Chiba 1978 also gave step patterns that allow at most a few horizontal or vertical steps in a row. A slope constraint acts on each step, while a band acts on the position.
  • A band around the scaled diagonal. For sequences of different lengths, allow the cells with ∣j−im/n∣≤r|j - i m / n| \le r, so the band follows the line from (1,1)(1, 1) to (n,m)(n, m).
  • Data-dependent bands. Compute the path at a coarse resolution, project it to the fine resolution, and fill only a band around it. This is fast, but it is a heuristic and not exact.
  • Beam pruning. A time-synchronous beam search keeps the cells whose score is close to the best one in each column. The beam adapts to the data, but like the band it can lose the best path.

Pitfalls

  • A band that is too narrow. The banded cost is only an upper bound on the true DTW cost. If the sequences have a large time offset, every path in the band is poor. The band width is a heuristic, to be set on development data, often as a percentage of the length.
  • Different lengths. With ∣n−m∣>r|n - m| > r there is no path. The code raises an error, and a silent ∞\infty could look like a very bad match.
  • Mixing constraints. The band and a slope limit together can leave no path, even when each one alone leaves one.
  • Comparing costs across widths. The banded cost depends on rr. Use the same width for all the comparisons of one task.
  • Assuming exactness. Lower bounds and pruning rules that are proved for the banded cost do not bound the unconstrained cost from the same side.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

sakoe_chiba_band.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sakoe-chiba-band/. The authors are listed in prov/HMGHCC.jsonl.

"""DTW restricted to a Sakoe-Chiba band.

x = x_1 ... x_n and y = y_1 ... y_m. A warping path from (1, 1) to (n, m) uses
the steps (1, 0), (0, 1) and (1, 1). The band of width r keeps only the cells
with |i - j| <= r, so a path in the band exists if and only if |n - m| <= r.
The recurrence is the symmetric1 pattern of the dynamic-time-warping page:

    D[i][j] = d(x_i, y_j) + min(D[i-1][j-1], D[i-1][j], D[i][j-1]),

with D[0][0] = 0 and every other cell outside the band at infinity. Only the
cells of the band are stored, so time and memory are O(n r) for r >= 1.
"""

import math
from typing import Callable, Dict, Sequence, Tuple

INF = math.inf


def abs_dist(a, b) -> float:
    return abs(a - b)


def band_dtw(x: Sequence, y: Sequence, r: int, dist: Callable = abs_dist):
    """Return (cost, path, cells): the best cost in the band, a best path, and the number of cells filled.

    Ties in the traceback go to the diagonal, then (i - 1, j), then (i, j - 1).
    Raise ValueError if no warping path fits in the band (|n - m| > r).
    """
    n, m = len(x), len(y)
    if n == 0 or m == 0 or r < 0:
        raise ValueError("need non-empty sequences and r >= 0")
    if abs(n - m) > r:  # @line L1
        raise ValueError("no warping path fits in the band: |n - m| > r")
    D: Dict[Tuple[int, int], float] = {(0, 0): 0.0}  # @line L2
    back: Dict[Tuple[int, int], Tuple[int, int]] = {}
    for i in range(1, n + 1):  # @line L3
        for j in range(max(1, i - r), min(m, i + r) + 1):  # @line L4
            best, arg = D.get((i - 1, j - 1), INF), (i - 1, j - 1)  # @line L5
            for cell in ((i - 1, j), (i, j - 1)):
                v = D.get(cell, INF)
                if v < best:
                    best, arg = v, cell
            D[(i, j)] = dist(x[i - 1], y[j - 1]) + best
            back[(i, j)] = arg
    path = [(n, m)]
    while path[-1] != (1, 1):
        path.append(back[path[-1]])
    path.reverse()
    return D[(n, m)], path, len(D) - 1  # @line L6


def full_dtw(x: Sequence, y: Sequence, dist: Callable = abs_dist) -> float:
    """The unconstrained symmetric1 DTW cost, O(n m), for comparison."""
    n, m = len(x), len(y)
    D = [[INF] * (m + 1) for _ in range(n + 1)]
    D[0][0] = 0.0
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            D[i][j] = dist(x[i - 1], y[j - 1]) + min(D[i - 1][j - 1], D[i - 1][j], D[i][j - 1])
    return D[n][m]
test_sakoe_chiba_band.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sakoe-chiba-band/. The authors are listed in prov/HMGHCC.jsonl.

import random

import pytest

from sakoe_chiba_band import band_dtw, full_dtw


def all_paths(n, m):
    out = []

    def go(path):
        i, j = path[-1]
        if (i, j) == (n, m):
            out.append(list(path))
            return
        for di, dj in ((1, 1), (1, 0), (0, 1)):
            if i + di <= n and j + dj <= m:
                path.append((i + di, j + dj))
                go(path)
                path.pop()

    go([(1, 1)])
    return out


def cost(x, y, path):
    return sum(abs(x[i - 1] - y[j - 1]) for i, j in path)


def test_against_brute_force_inside_the_band():
    rng = random.Random(1)
    cache = {}
    for _ in range(200):
        n, m = rng.randint(1, 6), rng.randint(1, 6)
        r = rng.randint(abs(n - m), 5)
        x = [rng.randint(0, 9) for _ in range(n)]
        y = [rng.randint(0, 9) for _ in range(m)]
        if (n, m) not in cache:
            cache[(n, m)] = all_paths(n, m)
        inside = [p for p in cache[(n, m)] if all(abs(i - j) <= r for i, j in p)]
        c, path, _ = band_dtw(x, y, r)
        assert c == min(cost(x, y, p) for p in inside)
        assert path in inside and cost(x, y, path) == c


def test_wide_band_equals_full_dtw():
    rng = random.Random(2)
    for _ in range(100):
        x = [rng.randint(0, 9) for _ in range(rng.randint(1, 12))]
        y = [rng.randint(0, 9) for _ in range(rng.randint(1, 12))]
        r = max(len(x), len(y)) - 1
        assert band_dtw(x, y, r)[0] == full_dtw(x, y)


def test_band_misses_the_optimum():
    x, y = [0, 0, 0, 5], [0, 5, 5, 5]
    assert full_dtw(x, y) == 0
    assert band_dtw(x, y, 2)[0] == 0
    c1, path, _ = band_dtw(x, y, 1)
    assert c1 == 5 and path == [(1, 1), (2, 1), (3, 2), (4, 3), (4, 4)]
    assert band_dtw(x, y, 0)[0] == 10


def test_cost_does_not_increase_with_r():
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randint(1, 10)
        x = [rng.randint(0, 9) for _ in range(n)]
        y = [rng.randint(0, 9) for _ in range(n)]
        costs = [band_dtw(x, y, r)[0] for r in range(n)]
        assert all(costs[k + 1] <= costs[k] for k in range(n - 1))
        assert costs[-1] == full_dtw(x, y)


def test_cells_filled():
    x = list(range(100))
    for r in (0, 1, 5, 10):
        _, _, cells = band_dtw(x, x, r)
        assert cells == sum(min(100, i + r) - max(1, i - r) + 1 for i in range(1, 101))
        assert cells <= 100 * (2 * r + 1)


def test_no_path_in_a_narrow_band():
    with pytest.raises(ValueError):
        band_dtw([1, 2, 3, 4], [1, 2], 1)
    assert band_dtw([1, 2, 3, 4], [1, 2], 2)[0] == full_dtw([1, 2, 3, 4], [1, 2])

Exercises

  1. Prove that a warping path with ∣i−j∣≤r|i - j| \le r in every cell exists if and only if ∣n−m∣≤r|n - m| \le r.
  2. Show that the band of width rr has exactly n(2r+1)−r(r+1)n (2r + 1) - r (r + 1) cells when n=m>rn = m > r, and check it against the test test_cells_filled.
  3. Prove that the banded cost does not increase when rr grows, and that it equals the unconstrained DTW cost for r≥max⁡(n,m)−1r \ge \max(n, m) - 1.
  4. Find two sequences of length 3 whose banded cost with r=0r = 0 is larger than with r=1r = 1, and two sequences for which the two costs are equal although the best paths differ.
  5. In one form of the Itakura constraint, each step advances ii by 1 and jj by 0, 1 or 2, and no two consecutive steps advance jj by 0. Show that a path from (1,1)(1, 1) to (n,m)(n, m) exists only if m−1≤2(n−1)m - 1 \le 2 (n - 1) and m−1≥⌊(n−1)/2⌋m - 1 \ge \lfloor (n - 1) / 2 \rfloor.

References

  1. Hiroaki Sakoe and Seibi Chiba, Dynamic programming algorithm optimization for spoken word recognition, IEEE Transactions on Acoustics, Speech, and Signal Processing 26(1), 1978, pages 43 to 49, the adjustment window condition on the warping path and the slope constraint
  2. Fumitada Itakura, Minimum prediction residual principle applied to speech recognition, IEEE Transactions on Acoustics, Speech, and Signal Processing 23(1), 1975, pages 67 to 72, the local slope constraint of the warping path, which gives the parallelogram
  3. Lawrence Rabiner and Biing-Hwang Juang, Fundamentals of Speech Recognition, Prentice Hall, 1993, Chapter 4 (pattern comparison techniques, time alignment and normalization)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises