Skip to content

Commit db7ae31

Browse files
committed
[FIX] ASR: uncentered scm block covariance + overlap/bound/jump fixes
Fixes a cluster of issues in block_covariance: - Overlap convention: jump now uses round(window * (1 - overlap)) so `overlap` is the fraction of overlap (higher = more overlap), matching clean_windows and asr_calibrate. Previously a larger overlap produced a larger jump (less actual overlap), colliding with asr_calibrate's win_overlap convention. - Loop bound: it is now computed against the padded length. Previously n_samples was captured before padding, so padding added zero iterations and trailing samples were dropped. A window too large to form any complete block now raises a clear ValueError. - jump is clamped to >= 1 so zero-overlap no longer loops forever, and window is cast to int so fractional windows don't break slicing. - For estimator="scm", compute the uncentered per-block second moment E[x x.T] = B @ B.T / window directly, matching ASR.transform (cov = 1/N * X @ X.T) and the ASR spec (covariance is not mean-subtracted). pyriemann's scm mean-centers each block, which diverges the calibration matrix M from the correct value on real data and makes calibrate inconsistent with transform. Other estimators still route through pyriemann covariances. Adds regression tests for each fix.
1 parent 3721224 commit db7ae31

2 files changed

Lines changed: 95 additions & 7 deletions

File tree

‎meegkit/utils/covariances.py‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def block_covariance(data, window=128, overlap=0.5, padding=True, estimator="cov
2626
window : int
2727
Window size.
2828
overlap : float
29-
Overlap between successive windows.
29+
Fraction of overlap between successive windows (higher = more overlap).
3030
3131
Returns
3232
-------
@@ -35,19 +35,30 @@ def block_covariance(data, window=128, overlap=0.5, padding=True, estimator="cov
3535
3636
"""
3737
assert 0 <= overlap < 1, "overlap must be < 1"
38+
window = int(window) # window may be fractional
3839
blocks = []
3940
n_chans, n_samples = data.shape
4041
if padding: # pad data with zeros
41-
pad = np.zeros((n_chans, int(window / 2)))
42+
pad = np.zeros((n_chans, window // 2))
4243
data = np.concatenate((pad, data, pad), axis=1)
44+
n_samples = data.shape[1] # bound against the padded length
4345

44-
jump = int(window * overlap)
46+
jump = max(int(round(window * (1 - overlap))), 1) # >= 1 so overlap=0 advances
4547
ix = 0
46-
while (ix + window < n_samples):
48+
while ix + window < n_samples:
4749
blocks.append(data[:, ix:ix + window])
48-
ix = ix + jump
49-
50-
return covariances(np.array(blocks), estimator=estimator)
50+
ix += jump
51+
52+
if len(blocks) == 0:
53+
raise ValueError(
54+
"block_covariance: window is too large for the given data "
55+
"(no complete blocks).")
56+
57+
blocks = np.array(blocks)
58+
if estimator == "scm":
59+
# uncentered second moment E[x x.T] per block (not mean-subtracted)
60+
return blocks @ blocks.transpose(0, 2, 1) / window
61+
return covariances(blocks, estimator=estimator)
5162

5263

5364
def cov_lags(X, Y, shifts=None):

‎tests/test_asr.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from meegkit.asr import ASR, asr_calibrate, asr_process, clean_windows
1010
from meegkit.utils.asr import yulewalk, yulewalk_filter
11+
from meegkit.utils.covariances import block_covariance
1112
from meegkit.utils.matrix import sliding_window
1213

1314
# Data files
@@ -258,6 +259,82 @@ def test_asr_class(method, reref, show=False):
258259
ASR(sfreq=125)
259260
ASR(Sfreq=150)
260261

262+
def test_block_covariance_uncentered_scm():
263+
"""scm blocks use the uncentered second moment, not the mean-subtracted cov.
264+
265+
A large per-channel DC offset makes the two estimates diverge strongly.
266+
"""
267+
W = 50
268+
data = rng.standard_normal((4, 250)) + np.arange(1, 5)[:, None] * 100.0
269+
270+
cov = block_covariance(data, window=W, overlap=0.5, padding=False,
271+
estimator="scm")
272+
273+
# Reference: same block start indices the function uses.
274+
jump = max(int(round(W * (1 - 0.5))), 1)
275+
n_samples = data.shape[1]
276+
ref, centered = [], []
277+
ix = 0
278+
while ix + W < n_samples:
279+
B = data[:, ix:ix + W]
280+
ref.append(B @ B.T / W) # uncentered second moment
281+
centered.append(np.cov(B, bias=True)) # mean-subtracted
282+
ix += jump
283+
ref = np.array(ref)
284+
centered = np.array(centered)
285+
286+
assert cov.shape == ref.shape
287+
assert np.allclose(cov, ref, rtol=1e-10)
288+
# Must NOT be the centered (mean-subtracted) version.
289+
assert not np.allclose(cov, centered)
290+
291+
292+
def test_block_covariance_overlap_semantics():
293+
"""Higher overlap yields more blocks."""
294+
W = 50
295+
data = rng.standard_normal((4, 500))
296+
n_hi = block_covariance(data, window=W, overlap=0.8).shape[0]
297+
n_lo = block_covariance(data, window=W, overlap=0.2).shape[0]
298+
assert n_hi > n_lo
299+
300+
301+
def test_block_covariance_padding_bound():
302+
"""Padding adds blocks (loop bound uses the padded length)."""
303+
W = 100
304+
data = rng.standard_normal((8, 300))
305+
n_pad = block_covariance(data, window=W, overlap=0.5, padding=True).shape[0]
306+
n_nopad = block_covariance(data, window=W, overlap=0.5,
307+
padding=False).shape[0]
308+
assert n_pad > n_nopad
309+
310+
311+
def test_block_covariance_empty_guard():
312+
"""A window too large for the data raises a clear error."""
313+
data = rng.standard_normal((4, 30))
314+
with pytest.raises(ValueError, match="too large"):
315+
block_covariance(data, window=100, padding=False)
316+
317+
318+
def test_block_covariance_no_hang_and_float_window():
319+
"""Zero-overlap does not hang and float windows are accepted."""
320+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
321+
sfreq = 250
322+
X_small = raw[:, 5 * sfreq:15 * sfreq] # 8 chans x 10 s
323+
324+
# win_overlap=0.0 previously looped forever (jump=0)
325+
asr = ASR(sfreq=sfreq, win_overlap=0.0)
326+
asr.fit(X_small)
327+
M = asr.state_["M"]
328+
T = asr.state_["T"]
329+
assert np.isfinite(M).all()
330+
assert np.isfinite(T).all()
331+
332+
# Float window must not break slicing (int-cast).
333+
cov = block_covariance(X_small, window=100.0, overlap=0.5,
334+
estimator="scm")
335+
assert np.isfinite(cov).all()
336+
337+
261338
if __name__ == "__main__":
262339
pytest.main([__file__])
263340
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)