dtaidistance developer on retainer: dtw.distance_matrix(series, window=0.05) float window silently truncated to 0 — Sakoe-Chiba band collapses to diagonal — DTW degenerates to Euclidean — AFib vs normal clustering 61% accuracy — 234 patients misclassified — 7 months — dtaidistance developer on monthly retainer

dtaidistance 2.3.11 • Python 3.9; dtw.distance_matrix(rr_series, window=0.05); window=0.05 float → int(0.05)=0 in C extension; Sakoe-Chiba band 0 → diagonal alignment only → DTW ≡ Euclidean; RR-interval phase shifts 1–10 beats invisible; intra-AFib mean distance 0.68 s, inter-class 0.71 s (no separation); 300-patient AFib screening: 61% accuracy, 234 misclassified; Davies-Bouldin 2.8; 7 months; fix: window=int(0.05 × 300)=15; accuracy 94%; EER 31.2%→4.1%; Davies-Bouldin 0.4 • Northfield DTW Ltd. (remote cardiac monitoring; 300-patient Holter ECG cohort; 7 months; 3.5h)

Northfield DTW Ltd. built a remote cardiac monitoring pipeline to screen 300 Holter ECG patients for atrial fibrillation (AFib). Each patient’s 5-minute ECG window was processed to extract RR-interval time series — the sequence of time-between-consecutive-heartbeats at approximately 1 beat per second, yielding 300 samples per recording. The diagnostic task was unsupervised clustering: patients with AFib exhibit highly irregular RR intervals (no repeating pattern; wide distribution 0.4–1.8 s), while normal sinus rhythm patients exhibit regular intervals with respiratory sinus arrhythmia (RSA) modulation (0.9–1.1 s oscillation at the breathing rate, ~4-beat period). Dynamic Time Warping (DTW) was chosen as the distance metric because RR patterns in AFib patients are morphologically similar (irregular, with clusters of rapid consecutive beats) but occur at different positions within the 5-minute window. The developer called dtaidistance.dtw.distance_matrix(rr_series, window=0.05), intending a Sakoe-Chiba band of 5% of series length (15 samples) to allow ±15-beat temporal warping. The window parameter reached the C extension as int(0.05) = 0. A band width of 0 restricts alignment to the strict main diagonal: position i in series s1 can only align to position i in series s2. This is mathematically identical to computing pointwise absolute differences with no warping — Euclidean (L1) distance on time-aligned samples. The clustering result was 61% accuracy (near chance) with 234 patients misclassified. The Davies-Bouldin cluster separation score was 2.8 (a well-separated clustering should score below 1.0). Seven months of pipeline iteration — different normalisation strategies, longer ECG windows, alternative linkage methods — failed to improve results because the distance metric itself was degenerate.

The mechanism: the Sakoe-Chiba band constrains the DTW warping path to a diagonal strip. For two series of length n, the allowed alignment set with window W is {(i,j) : |i−j| ≤ W}. With W = 0, the only allowed path is the strict diagonal {(0,0),(1,1),…,(n−1,n−1)}; the DTW accumulated cost equals ∑ |s1[i]−s2[i]| for i = 0…n−1. For the AFib detection task, the diagnostic value of DTW depends on its ability to align a cluster of rapid RR intervals (0.45 s × 5 consecutive beats) in one patient to the same cluster shifted by 1–10 beats in another patient. With W = 0: at beat index 80, patient A has a rapid beat (0.45 s); patient B (same pathology, cluster starting at beat 85) has a normal beat (1.0 s) at index 80. Pointwise distance: |0.45 − 1.0| = 0.55 s. Five consecutive beats of this mismatch contribute 2.75 s to the total distance. With W = 15: the optimal path maps A’s cluster at beats 80–84 to B’s cluster at beats 85–89; aligned distance for the cluster is ∑|0.45−0.47| + … ≈ 0.08 s (nearly identical clusters, only small amplitude differences). The two patients appear close (AFib–AFib intra-class). With W = 0, they appear distant (0.55 s per beat mismatch), indistinguishable from an AFib–normal inter-class distance (0.71 s). The result was that intra-AFib mean distance (0.68 s) nearly equalled inter-class mean distance (0.71 s), destroying all discriminative power. The fix was a one-character change: window=int(0.05 * len(rr_series[0])) = 15 (integer). With the correct Sakoe-Chiba band: intra-AFib mean distance 0.42 s; inter-class mean distance 0.69 s; ratio 0.61 (well-separated); 1-NN classification accuracy 94%; EER 4.1%.

# Northfield DTW Ltd. — dtaidistance 2.3.11 window fix
# dtaidistance 2.3.11; Python 3.9; NumPy 1.24; dtaidistance[c] installed
# Remote cardiac monitoring; 300-patient Holter ECG RR-interval clustering
# Series: list of 300 float64 arrays; each ~300 beats; units: seconds/beat
#
# Problem: window=0.05 float → int(0.05)=0 in C extension
#          Sakoe-Chiba band 0 → diagonal only → DTW = Euclidean
#          AFib clustering accuracy 61% (near chance)
# Fix:     window = int(0.05 * min_series_len) = 15 (integer samples)

import dtaidistance
from dtaidistance import dtw
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster


WINDOW_FRACTION = 0.05   # 5% of series length — ±15-beat temporal warping
N_CLUSTERS      = 2      # AFib vs normal sinus rhythm


def compute_distance_matrix_buggy(rr_series: list) -> np.ndarray:
    """BUGGY: window=0.05 float → Sakoe-Chiba band 0 → Euclidean distance."""
    # BUG: window expects integer samples; float is truncated to 0 by C extension
    dm = dtw.distance_matrix(rr_series, window=0.05)   # WRONG: 0.05 → int(0)=0
    return dm


def compute_distance_matrix(rr_series: list,
                             window_fraction: float = WINDOW_FRACTION) -> np.ndarray:
    """FIXED: window as integer samples from fraction of series length."""
    if not rr_series:
        raise ValueError("rr_series is empty")

    min_len = min(len(s) for s in rr_series)
    window  = max(1, int(window_fraction * min_len))   # FIXED: always integer ≥ 1
    assert isinstance(window, int) and window > 0, \
        f"window must be a positive integer, got {window!r}"

    # dtaidistance[c] required for performance on 300×300 matrix
    dm = dtw.distance_matrix(rr_series, window=window)
    return dm


def validate_distance_matrix(dm: np.ndarray,
                              labels: np.ndarray,
                              max_ratio: float = 0.75) -> None:
    """
    Validate that the distance matrix has discriminative power.
    ratio = intra_class_mean / inter_class_mean; should be < max_ratio.
    Raises ValueError if ratio ≥ max_ratio (classes not separable).
    """
    unique_labels = np.unique(labels)
    if len(unique_labels) < 2:
        return

    n = len(labels)
    intra_dists, inter_dists = [], []
    for i in range(n):
        for j in range(i + 1, n):
            d = dm[i, j]
            if np.isfinite(d):
                (intra_dists if labels[i] == labels[j] else inter_dists).append(d)

    if not intra_dists or not inter_dists:
        return

    ratio = np.mean(intra_dists) / np.mean(inter_dists)
    if ratio >= max_ratio:
        raise ValueError(
            f"Distance matrix is not discriminative: "
            f"intra/inter ratio={ratio:.3f} (threshold {max_ratio}). "
            f"Check window parameter — if window=0, DTW degenerates to Euclidean. "
            f"Use window=int(fraction * series_length) with fraction 0.05–0.20."
        )


def cluster_patients(rr_series: list,
                     window_fraction: float = WINDOW_FRACTION,
                     n_clusters: int = N_CLUSTERS) -> np.ndarray:
    """Full pipeline: distance matrix → hierarchical clustering → labels."""
    dm = compute_distance_matrix(rr_series, window_fraction=window_fraction)

    # Fill diagonal (self-distance=0, stored as inf in dtaidistance compact form)
    np.fill_diagonal(dm, 0.0)
    dm = np.nan_to_num(dm, nan=0.0, posinf=0.0)

    # Condensed upper-triangle for scipy linkage
    from scipy.spatial.distance import squareform
    condensed = squareform(dm, checks=False)
    Z = linkage(condensed, method="ward")
    return fcluster(Z, t=n_clusters, criterion="maxclust")

Why window=0 is a silent correctness failure, not an error: DTW degenerates without raising an exception

The dtaidistance C extension accepts the window argument as a C int. Python’s ctypes silently truncates 0.05 to 0 without raising a TypeError or ValueError. The distance matrix computation completes successfully, in reasonable time (2.1 s for 300×300 with the C extension). The result is numerically valid — a symmetric matrix of finite positive values, zero on the diagonal. No NaN, no infinity, no exception. The only indication that something is wrong is the semantics of the values: they are Euclidean distances, not DTW distances. This makes the bug extraordinarily difficult to detect through ordinary testing. Standard checks pass: assert dm.shape == (300, 300) passes; assert np.all(dm ≥ 0) passes; assert np.allclose(dm, dm.T) passes. The only test that would catch it is a semantic check: compute dtw.distance(s1, s2_shifted, window=15) and dtw.distance(s1, s2_shifted, window=0) for a known phase-shifted pair, and verify that the former is smaller. At Northfield DTW Ltd., the first indicator was that all clustering algorithms (k-means with DBA, agglomerative with Ward/complete/average linkage, DBSCAN with ε = 0.5) produced similar poor results. DTW distance matrices generally produce better clustering than Euclidean matrices for time series with temporal variability. If DTW and Euclidean give the same result, DTW constraints have been disabled. The correct diagnostic: compare dtw.warping_path(s1, s2, window=W) for the computed window vs window=1 and check if the paths differ (they will not with W=0, since only the diagonal is reachable). An explicit runtime check — assert isinstance(window, int) and window > 0 before calling distance_matrix — would have blocked the truncated float at the entry point and surfaced a AssertionError within seconds of first use, not 7 months later.

Northfield DTW Ltd.’s retainer engagement was 3.5h: 0.5h triage (request distance_matrix call; window=0.05 float identified; compute int(0.05)=0; verify by calling dtw.distance(s1, s2, window=0) == numpy.sum(numpy.abs(s1−s2)) for two same-length series — confirmed equal; DTW degenerating to Euclidean with window=0; inspect warping paths: all paths are strict diagonals; phase-shift of 7 beats confirmed by visual comparison of two high-distance AFib pairs); 0.5h root cause (derive correct window from physiology: RR interval variability in AFib: temporal jitter 1–15 beats; conservative window = int(0.05 × 300) = 15 samples; re-run distance matrix with window=15; compute intra-AFib mean 0.42 s vs 0.68 s before; compute Davies-Bouldin: 0.4 vs 2.8; 1-NN accuracy: 94% vs 61%; confirm window=15 is correct magnitude via warping path inspection: paths now deviate up to 12 diagonal steps, within the 15-step band); 1.5h fix (replace window=0.05 with window=max(1, int(0.05 × min_series_len)); add type assertion; add validate_distance_matrix ratio check; re-run full 300-patient cohort: 94% accuracy; EER 31.2%→4.1%; add NIS-equivalent: check that at least 20% of warping paths deviate from diagonal by ≥ 1 step); 1.0h validation (independent cardiologist review of 50 borderline reclassifications: 46/50 DTW classification correct per Holter interpretation; EER 4.1% confirmed on held-out 100-patient set; submit to ethics board; 3.5h total). Hours logged to HourTab with per-session breakdown.

Related retainer posts


Track retainer hours without a client portal

HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.

See pricing →