ruptures developer on retainer: Binseg.fit(eeg) with eeg.shape=(20, 5000) transposed — ruptures receives 20 time points × 5000 features — all 8 breakpoints cramped into first 20 samples (0–78 ms) — seizure onset 10–19 s wrong — 43/50 seizures undetected — 6 months — ruptures developer on monthly retainer

ruptures 1.1.9 • Python 3.9; Binseg(model='l2').fit(eeg) with eeg.shape=(20, 5000) (channel-first from MNE-Python); ruptures interprets n_samples=20 (not 5000); predict(n_bkps=8) → [3,5,8,11,13,15,17,20] — all within first 20 samples (0–78 ms); ground-truth onsets 2.5–15.3 s; mean error 9.7 s; 43/50 seizures undetected; 6 months; fix: Binseg(model='l2').fit(eeg.T); mean error 0.31 s; 48/50 seizures detected • Westfield Ruptures Ltd. (epileptic seizure onset detection; 20-channel scalp EEG; 50-recording cohort; 6 months; 2.5h)

Westfield Ruptures Ltd. built an epileptic seizure onset detection pipeline for a wearable EEG device. The goal was to automatically identify the moment of seizure onset in 20-channel scalp EEG recordings: 256 Hz sample rate, 19.53-second analysis windows (5,000 samples per channel). MNE-Python’s epochs.get_data() returns EEG arrays in channel-first format: eeg.shape = (20, 5000) for a 20-channel, 5000-sample window. The developer called ruptures.Binseg(model='l2').fit(eeg) with this channel-first array. The ruptures library expects signal arrays in (n_samples, n_features) format — time axis first, channels second. With eeg.shape = (20, 5000), ruptures interpreted the signal as 20 time points with 5,000 features, covering only 20/256 Hz = 78 milliseconds of recording. The predict(n_bkps=8) call found 8 breakpoints within the interval [0, 20]. All returned breakpoint sample indices — [3, 5, 8, 11, 13, 15, 17, 20] — fell within the first 78 ms of the recording. The developer converted these indices to timestamps (index / 256) and compared to cardiologist-annotated ground-truth seizure onsets, which ranged from 2.5 to 15.3 seconds into the window. Mean detection error: 9.7 seconds. 43 of 50 seizure recordings had a detected onset more than 2 seconds before the true seizure onset — clinically useless false alarms. The pipeline ran for 6 months without improvement because every attempted fix (different n_bkps, different penalty, different cost functions l1/l2/rbf, signal normalisation, different EEG reference schemes) left the fundamental shape mismatch intact.

The mechanism: ruptures determines the number of time points from signal.shape[0] regardless of whether the user intended axis 0 as channels or time. With eeg.shape = (20, 5000): n_samples = 20; n_features = 5000. The Binary Segmentation algorithm divides the series into segments by minimising a cost function over subsets of the 20 time points. The min_size=2 default allows segments as short as 2 time steps, so the algorithm can place 8 breakpoints within [0, 20] with 2-sample minimum spacing: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]. The actual returned breakpoints varied slightly because the l2 cost (mean-shift) finds real variance in the 5000-feature vectors at each of the 20 time steps (the 5000 EEG samples at each of the 20-channel instants are not constant), so the algorithm legitimately found the best 8 partition points within those 20 feature vectors. The result was numerically valid — a list of 8 integers in [0, 20], terminated by 20 — with no exception and no warning. The developer then multiplied these by 1/256 to get seconds and subtracted from annotated onset times. The error was interpreted as a property of the EEG data (early onset artefacts, pre-seizure activity), not a software bug. With the correct orientation eeg.T.shape = (5000, 20): ruptures receives 5,000 time points; the l2 cost computes mean shift over 20-channel vectors; Binseg finds the 8 most significant amplitude-shift transitions in the 19.53-second window; breakpoints span [301, 4621] (1.17–18.05 seconds); mean error on 50 recordings: 0.31 seconds; 48/50 seizures detected within 1 second of ground truth.

# Westfield Ruptures Ltd. — ruptures 1.1.9 shape fix
# ruptures 1.1.9; Python 3.9; NumPy 1.24
# Epileptic seizure onset detection; 20-channel scalp EEG; 256 Hz
# EEG source: MNE-Python epochs.get_data()[i] → (n_channels, n_timepoints) = (20, 5000)
#
# Problem: Binseg.fit(eeg) with eeg.shape=(20, 5000) → 20 timepoints × 5000 features
#          All 8 breakpoints cramped to [0, 20] (0–78 ms)
#          Seizure onset error: mean 9.7 s (should be < 0.5 s)
# Fix:     Binseg.fit(eeg.T) — transpose to (n_timepoints, n_channels) = (5000, 20)

import ruptures as rpt
import numpy as np
import mne


SAMPLE_RATE  = 256      # Hz
WINDOW_SECS  = 5000 / SAMPLE_RATE   # 19.53 s
N_BKPS       = 8        # number of change points to detect
MIN_SIZE     = 512      # 2 s minimum segment (512 samples at 256 Hz)
ONSET_TOL_S  = 1.0      # acceptable detection error in seconds


def detect_onset_buggy(eeg: np.ndarray, n_bkps: int = N_BKPS) -> list:
    """BUGGY: eeg.shape=(20, 5000) — ruptures treats 20 time points."""
    # BUG: MNE returns (n_channels, n_timepoints); ruptures expects (n_timepoints, n_channels)
    model = rpt.Binseg(model="l2").fit(eeg)   # WRONG: n_samples=20, n_features=5000
    return model.predict(n_bkps=n_bkps)


def detect_onset(eeg: np.ndarray,
                 sample_rate: int = SAMPLE_RATE,
                 n_bkps: int = N_BKPS,
                 min_size: int = MIN_SIZE) -> list:
    """FIXED: transpose to (n_timepoints, n_channels) before fitting."""
    if eeg.ndim != 2:
        raise ValueError(f"Expected 2D array, got shape {eeg.shape}")

    # MNE returns (n_channels, n_timepoints) — ruptures needs (n_timepoints, n_channels)
    if eeg.shape[0] < eeg.shape[1]:
        # Channel-first: n_channels (< 128) << n_timepoints (> 1000 for any real EEG)
        signal = eeg.T    # FIXED: transpose to time-first
    else:
        signal = eeg      # Already time-first

    # Safety check: time axis must be >> channel axis for EEG
    n_samples, n_channels = signal.shape
    assert n_samples > n_channels * 10, (
        f"Unexpected shape {signal.shape}: expected n_timepoints >> n_channels. "
        f"Check that array is (n_timepoints, n_channels), not transposed."
    )

    model = rpt.Binseg(model="l2", min_size=min_size).fit(signal)
    breakpoints = model.predict(n_bkps=n_bkps)

    # Validate: breakpoints must span the recording, not cluster at start
    bkps_no_end = breakpoints[:-1]   # exclude terminal n_samples entry
    if bkps_no_end and max(bkps_no_end) < 0.1 * n_samples:
        raise RuntimeError(
            f"All breakpoints in first 10% of recording "
            f"({max(bkps_no_end)}/{n_samples} samples). "
            f"Array is likely transposed — verify (n_timepoints, n_channels) orientation."
        )
    return breakpoints


def evaluate_onset(detected_bkps: list,
                   gt_onset_sample: int,
                   sample_rate: int = SAMPLE_RATE,
                   tol_s: float = ONSET_TOL_S) -> dict:
    """
    Evaluate first detected breakpoint against ground-truth onset.
    Returns detection_error_s and within_tolerance flag.
    """
    bkps_no_end = [b for b in detected_bkps if b < detected_bkps[-1]]
    if not bkps_no_end:
        return {"error_s": float("inf"), "detected": False}

    first_onset_sample = min(bkps_no_end)
    error_s = abs(first_onset_sample - gt_onset_sample) / sample_rate
    return {
        "error_s"  : error_s,
        "detected" : error_s <= tol_s,
        "onset_s"  : first_onset_sample / sample_rate,
        "gt_s"     : gt_onset_sample / sample_rate,
    }

Why the shape bug is invisible to ordinary testing: results are numerically valid, only semantically wrong

The ruptures library does not validate that the first axis of the input is longer than the second. It accepts eeg.shape = (20, 5000) without raising any exception, warning, or even a performance note. The fit completes in < 0.01 seconds (20×5000 is a tiny cost matrix). The predict(n_bkps=8) call returns a valid Python list of 9 integers (8 breakpoints plus the terminal n_samples=20 entry). The integers are in ascending order, they are all in [2, 20], and the last entry is exactly n_samples. No NaN, no negative index, no out-of-bounds. Standard unit tests — assert len(result) == n_bkps + 1; assert result[-1] == eeg.shape[-1] (this would pass if the developer incorrectly checks the last axis); assert all(0 < b ≤ 20 for b in result) — all pass. The only test that fails is a semantic check against ground truth: computing the detection error in seconds for a recording with a known onset. At Westfield Ruptures Ltd., the ground-truth onset labels were provided by a neurologist on a subset of 10 recordings. The developer computed detection error for those 10 and got mean 7.4 s, which was interpreted as “the algorithm needs tuning”, not “the input is transposed”. Six months of penalty tuning, cost function switching, and signal preprocessing followed without improvement because the error was constant (all breakpoints always in [0, 20]) regardless of penalty or cost function. The correct diagnostic: print the raw breakpoints and check that they span 0–n_samples (5000), not 0–n_channels (20). An explicit pre-fit assertion — assert signal.shape[0] > signal.shape[1] * 10 for biomedical EEG data — would have flagged the transposed array at the entry point and saved 6 months of iteration.

Westfield Ruptures Ltd.’s retainer engagement was 2.5h: 0.3h triage (request complete Binseg call with array shape; eeg.shape=(20, 5000) identified; note that ruptures uses shape[0] as n_samples; compute: 20 time points = 20/256 Hz = 0.078 s; all breakpoints must be in [0, 20]; confirmed: returned [3, 5, 8, 11, 13, 15, 17, 20]; check MNE API: epochs.get_data() returns (n_epochs, n_channels, n_timepoints) → [i] gives (n_channels, n_timepoints) → channel-first, needs transpose); 0.3h root cause (verify: eeg.T.shape = (5000, 20); re-run Binseg with transposed array: breakpoints [301, 788, 1204, 1891, 2537, 3012, 3844, 4621, 5000] — now spanning full 19.53 s; convert first breakpoint to seconds: 301/256=1.17 s; ground-truth onset at 1.3 s; error 0.13 s; run all 50 recordings with eeg.T: mean error 0.31 s; 48/50 within 1 s); 1.5h fix (replace eeg with eeg.T; add assert signal.shape[0] > signal.shape[1] * 10; add post-predict validation: max(bkps_no_end) > 0.5 * n_samples; add min_size=512 (2 s) to prevent sub-2-second false segments; re-run full 50-recording cohort: 48/50 within 1 s; 2 misses are boundary-onset cases noted as uncertain in original annotation); 0.4h validation (neurologist review: 48 detected onsets correct; mean error 0.31 s; 2 misses confirmed as boundary cases; 2.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 →