Skip to content

Commit 249e8f8

Browse files
committed
[FIX] ASR: correct reconstruction dim count, blend seam, and RMS window rounding
Three independent fixes in the calibration/reconstruction path: - maxdims / keep-mask off-by-one in asr_process: maxdims used np.fix (truncate toward zero) instead of round-half-away, and the keep-mask index term protected one component too many. The spec converts the fractional 0.66 factor with round-half-away-from-zero, and its 1-based (1:C) < (C - maxdims) protects C-maxdims-1 components, so use int(np.floor(0.66 * nc + 0.5)) and np.arange(nc) < nc - maxdims - 1. Together these made meegkit under-remove artifact dimensions. - Raised-cosine blend endpoint in asr_process: np.arange(ns)/ns never reaches 1, so the block's final sample kept a residual fraction of the previous reconstruction. Shift the phase to np.arange(1, ns + 1)/ns so blend[-1] = 1.0 and the last sample equals the new reconstruction. - RMS window starts in asr_calibrate: the step N*(1-win_overlap) was rounded before building the window starts, drifting from the correct positions for a non-integer step (biasing mu/sig/T). Extract a _rms_window_offsets helper that rounds each start (matching clean_windows). Adds a regression test for each.
1 parent 3721224 commit 249e8f8

2 files changed

Lines changed: 77 additions & 4 deletions

File tree

‎meegkit/asr.py‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,15 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
399399
return clean, sample_mask
400400

401401

402+
def _rms_window_offsets(ns, N, win_overlap):
403+
"""Window start indices for windowed RMS.
404+
405+
Rounds each window START (not the step), matching ``clean_windows`` and
406+
avoiding phase drift when ``N * (1 - win_overlap)`` is non-integer.
407+
"""
408+
return np.round(np.arange(0, ns - N, N * (1 - win_overlap))).astype(int)
409+
410+
402411
def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
403412
win_overlap=0.66, max_dropout_fraction=0.1,
404413
min_clean_fraction=0.25, method="euclid", estimator="scm"):
@@ -499,7 +508,7 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
499508

500509
# get the threshold matrix T
501510
xsq = np.dot(V.T, X) ** 2
502-
offsets = np.arange(0, ns - N, np.round(N * (1 - win_overlap))).astype(int)
511+
offsets = _rms_window_offsets(ns, N, win_overlap)
503512

504513
# root mean squared amplitude per channel (windowed sums via cumulative sum)
505514
csum = np.zeros((nc, ns + 1))
@@ -573,7 +582,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
573582
cov = geometric_median(cov.reshape((-1, nc * nc)))
574583
cov = cov.reshape((nc, nc))
575584

576-
maxdims = int(np.fix(0.66 * nc)) # constant TODO make param
585+
maxdims = int(np.floor(0.66 * nc + 0.5)) # constant TODO make param
577586

578587
# do a PCA to find potential artifacts
579588
if method == "riemann":
@@ -587,7 +596,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
587596
# determine which components to keep (variance below directional threshold
588597
# or not admissible for rejection)
589598
keep = (D < np.sum(np.dot(T, V)**2, axis=0))
590-
keep += (np.arange(nc) < nc - maxdims)
599+
keep += (np.arange(nc) < nc - maxdims - 1)
591600

592601
# update the reconstruction matrix R (reconstruct artifact components using
593602
# the mixing matrix)
@@ -601,7 +610,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
601610
if state["R"] is not None:
602611
# apply the reconstruction to intermediate samples (using raised-cosine
603612
# blending)
604-
blend = (1 - np.cos(np.pi * np.arange(ns) / ns)) / 2
613+
blend = (1 - np.cos(np.pi * np.arange(1, ns + 1) / ns)) / 2
605614
clean = blend * R.dot(X) + (1 - blend) * state["R"].dot(X)
606615
else:
607616
clean = R.dot(X)

‎tests/test_asr.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,70 @@ def test_asr_class(method, reref, show=False):
258258
ASR(sfreq=125)
259259
ASR(Sfreq=150)
260260

261+
@pytest.mark.parametrize("nc, expected", [(8, 6), (32, 22), (64, 43), (19, 14)])
262+
def test_asr_process_removed_dims(nc, expected):
263+
"""Removed-dim count uses round-half-away maxdims and the fixed keep-mask index.
264+
265+
T is zeroed so the variance test is uniformly False and only the index
266+
term decides how many dimensions are removed.
267+
"""
268+
ns = 20 * nc
269+
X = rng.standard_normal((nc, ns))
270+
cov = X @ X.T / ns + 1e-6 * np.eye(nc) # well-conditioned PSD
271+
M = np.eye(nc)
272+
T = np.zeros((nc, nc))
273+
state = dict(M=M, T=T, R=None)
274+
275+
clean, state = asr_process(X, X, state, cov=cov[None], method="euclid")
276+
277+
removed = nc - np.linalg.matrix_rank(state["R"])
278+
assert removed == expected
279+
280+
281+
def test_asr_process_blend_reaches_one():
282+
"""Raised-cosine blend reaches exactly 1.0 at the block-final sample.
283+
284+
Two calls so the second blends against the first reconstruction; the
285+
final sample must equal the new reconstruction with no residual seam.
286+
"""
287+
nc, ns = 6, 100
288+
X1 = rng.standard_normal((nc, ns))
289+
X2 = rng.standard_normal((nc, ns))
290+
cov1 = X1 @ X1.T / ns + 1e-6 * np.eye(nc)
291+
cov2 = X2 @ X2.T / ns + 1e-6 * np.eye(nc)
292+
M = np.eye(nc)
293+
T = 0.5 * np.eye(nc) # non-trivial threshold so R is non-identity
294+
295+
state = dict(M=M, T=T, R=None)
296+
_, state = asr_process(X1, X1, state, cov=cov1[None], method="euclid")
297+
R_old = state["R"].copy()
298+
299+
clean2, state2 = asr_process(X2, X2, state, cov=cov2[None], method="euclid")
300+
R_new = state2["R"]
301+
302+
# meaningfulness guard: blend is only visible when R changes.
303+
assert not np.allclose(R_old, R_new)
304+
assert np.allclose(clean2[:, -1], R_new.dot(X2)[:, -1], rtol=1e-9)
305+
306+
307+
def test_rms_window_offsets_rounds_each_start():
308+
"""RMS window starts round each start, not the step (matches clean_windows)."""
309+
from meegkit.asr import _rms_window_offsets
310+
311+
ns, N, win_overlap = 1000, 125, 0.66 # step = 42.5 (non-integer)
312+
313+
# rounding the step first gives step 42 -> [0, 42, 84, ...]
314+
old_step = np.round(N * (1 - win_overlap))
315+
old_offsets = np.arange(0, ns - N, old_step).astype(int)
316+
317+
offsets = _rms_window_offsets(ns, N, win_overlap)
318+
319+
assert not np.array_equal(offsets, old_offsets)
320+
# float step is 42.4999..., so 3*step rounds to 127 (not 128)
321+
np.testing.assert_array_equal(
322+
offsets[:7], np.array([0, 42, 85, 127, 170, 212, 255]))
323+
324+
261325
if __name__ == "__main__":
262326
pytest.main([__file__])
263327
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)