Skip to content

Commit db658e5

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 107cd1b commit db658e5

2 files changed

Lines changed: 77 additions & 5 deletions

File tree

‎meegkit/asr.py‎

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

419419

420+
def _rms_window_offsets(ns, N, win_overlap):
421+
"""Window start indices for windowed RMS.
422+
423+
Rounds each window START (not the step), matching ``clean_windows`` and
424+
avoiding phase drift when ``N * (1 - win_overlap)`` is non-integer.
425+
"""
426+
return np.round(np.arange(0, ns - N, N * (1 - win_overlap))).astype(int)
427+
428+
420429
def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
421430
win_overlap=0.66, max_dropout_fraction=0.1,
422431
min_clean_fraction=0.25, method="euclid", estimator="scm"):
@@ -524,7 +533,7 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
524533

525534
# get the threshold matrix T
526535
xsq = np.dot(V.T, X) ** 2
527-
offsets = np.arange(0, ns - N, np.round(N * (1 - win_overlap))).astype(int)
536+
offsets = _rms_window_offsets(ns, N, win_overlap)
528537
if len(offsets) < 2:
529538
raise ValueError(
530539
f"Only {len(offsets)} window(s) available for threshold "
@@ -603,7 +612,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
603612
cov = geometric_median(cov.reshape((-1, nc * nc)))
604613
cov = cov.reshape((nc, nc))
605614

606-
maxdims = int(np.fix(0.66 * nc)) # constant TODO make param
615+
maxdims = int(np.floor(0.66 * nc + 0.5)) # constant TODO make param
607616

608617
# do a PCA to find potential artifacts
609618
if method == "riemann":
@@ -617,7 +626,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
617626
# determine which components to keep (variance below directional threshold
618627
# or not admissible for rejection)
619628
keep = (D < np.sum(np.dot(T, V)**2, axis=0))
620-
keep += (np.arange(nc) < nc - maxdims)
629+
keep += (np.arange(nc) < nc - maxdims - 1)
621630

622631
# update the reconstruction matrix R (reconstruct artifact components using
623632
# the mixing matrix)
@@ -631,7 +640,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
631640
if state["R"] is not None:
632641
# apply the reconstruction to intermediate samples (using raised-cosine
633642
# blending)
634-
blend = (1 - np.cos(np.pi * np.arange(ns) / ns)) / 2
643+
blend = (1 - np.cos(np.pi * np.arange(1, ns + 1) / ns)) / 2
635644
clean = blend * R.dot(X) + (1 - blend) * state["R"].dot(X)
636645
else:
637646
clean = R.dot(X)

‎tests/test_asr.py‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,6 @@ def test_asr_class(method, reref, show=False):
300300
ASR(sfreq=125)
301301
ASR(Sfreq=150)
302302

303-
304303
def test_clean_windows_uses_full_shape_range():
305304
"""clean_windows passes the full 13-point SHAPE_RANGE (incl beta=3.5) down.
306305
@@ -418,6 +417,70 @@ def test_clean_windows_offset_phase_drift():
418417
assert abs(int(offsets_raw[-1]) - int(offsets_truncated[-1])) >= 10
419418

420419

420+
@pytest.mark.parametrize("nc, expected", [(8, 6), (32, 22), (64, 43), (19, 14)])
421+
def test_asr_process_removed_dims(nc, expected):
422+
"""Removed-dim count uses round-half-away maxdims and the fixed keep-mask index.
423+
424+
T is zeroed so the variance test is uniformly False and only the index
425+
term decides how many dimensions are removed.
426+
"""
427+
ns = 20 * nc
428+
X = rng.standard_normal((nc, ns))
429+
cov = X @ X.T / ns + 1e-6 * np.eye(nc) # well-conditioned PSD
430+
M = np.eye(nc)
431+
T = np.zeros((nc, nc))
432+
state = dict(M=M, T=T, R=None)
433+
434+
clean, state = asr_process(X, X, state, cov=cov[None], method="euclid")
435+
436+
removed = nc - np.linalg.matrix_rank(state["R"])
437+
assert removed == expected
438+
439+
440+
def test_asr_process_blend_reaches_one():
441+
"""Raised-cosine blend reaches exactly 1.0 at the block-final sample.
442+
443+
Two calls so the second blends against the first reconstruction; the
444+
final sample must equal the new reconstruction with no residual seam.
445+
"""
446+
nc, ns = 6, 100
447+
X1 = rng.standard_normal((nc, ns))
448+
X2 = rng.standard_normal((nc, ns))
449+
cov1 = X1 @ X1.T / ns + 1e-6 * np.eye(nc)
450+
cov2 = X2 @ X2.T / ns + 1e-6 * np.eye(nc)
451+
M = np.eye(nc)
452+
T = 0.5 * np.eye(nc) # non-trivial threshold so R is non-identity
453+
454+
state = dict(M=M, T=T, R=None)
455+
_, state = asr_process(X1, X1, state, cov=cov1[None], method="euclid")
456+
R_old = state["R"].copy()
457+
458+
clean2, state2 = asr_process(X2, X2, state, cov=cov2[None], method="euclid")
459+
R_new = state2["R"]
460+
461+
# meaningfulness guard: blend is only visible when R changes.
462+
assert not np.allclose(R_old, R_new)
463+
assert np.allclose(clean2[:, -1], R_new.dot(X2)[:, -1], rtol=1e-9)
464+
465+
466+
def test_rms_window_offsets_rounds_each_start():
467+
"""RMS window starts round each start, not the step (matches clean_windows)."""
468+
from meegkit.asr import _rms_window_offsets
469+
470+
ns, N, win_overlap = 1000, 125, 0.66 # step = 42.5 (non-integer)
471+
472+
# rounding the step first gives step 42 -> [0, 42, 84, ...]
473+
old_step = np.round(N * (1 - win_overlap))
474+
old_offsets = np.arange(0, ns - N, old_step).astype(int)
475+
476+
offsets = _rms_window_offsets(ns, N, win_overlap)
477+
478+
assert not np.array_equal(offsets, old_offsets)
479+
# float step is 42.4999..., so 3*step rounds to 127 (not 128)
480+
np.testing.assert_array_equal(
481+
offsets[:7], np.array([0, 42, 85, 127, 170, 212, 255]))
482+
483+
421484
if __name__ == "__main__":
422485
pytest.main([__file__])
423486
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)