Skip to content

Commit 8e53091

Browse files
authored
[FIX] ASR: correct reconstruction dim count, blend seam, and RMS window rounding (#111)
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 the code 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`). ### Testing Adds a regression test for each. Full `tests/test_asr.py` passes; `ruff` clean.
1 parent 3b0c530 commit 8e53091

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 "
@@ -604,7 +613,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
604613
cov = geometric_median(cov.reshape((-1, nc * nc)))
605614
cov = cov.reshape((nc, nc))
606615

607-
maxdims = int(np.fix(0.66 * nc)) # constant TODO make param
616+
maxdims = int(np.floor(0.66 * nc + 0.5)) # constant TODO make param
608617

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

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

‎tests/test_asr.py‎

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

304-
305304
def test_clean_windows_uses_full_shape_range():
306305
"""clean_windows passes the full 13-point SHAPE_RANGE (incl beta=3.5) down.
307306
@@ -537,6 +536,70 @@ def test_block_covariance_no_hang_and_float_window():
537536
assert np.isfinite(cov).all()
538537

539538

539+
@pytest.mark.parametrize("nc, expected", [(8, 6), (32, 22), (64, 43), (19, 14)])
540+
def test_asr_process_removed_dims(nc, expected):
541+
"""Removed-dim count uses round-half-away maxdims and the fixed keep-mask index.
542+
543+
T is zeroed so the variance test is uniformly False and only the index
544+
term decides how many dimensions are removed.
545+
"""
546+
ns = 20 * nc
547+
X = rng.standard_normal((nc, ns))
548+
cov = X @ X.T / ns + 1e-6 * np.eye(nc) # well-conditioned PSD
549+
M = np.eye(nc)
550+
T = np.zeros((nc, nc))
551+
state = dict(M=M, T=T, R=None)
552+
553+
clean, state = asr_process(X, X, state, cov=cov[None], method="euclid")
554+
555+
removed = nc - np.linalg.matrix_rank(state["R"])
556+
assert removed == expected
557+
558+
559+
def test_asr_process_blend_reaches_one():
560+
"""Raised-cosine blend reaches exactly 1.0 at the block-final sample.
561+
562+
Two calls so the second blends against the first reconstruction; the
563+
final sample must equal the new reconstruction with no residual seam.
564+
"""
565+
nc, ns = 6, 100
566+
X1 = rng.standard_normal((nc, ns))
567+
X2 = rng.standard_normal((nc, ns))
568+
cov1 = X1 @ X1.T / ns + 1e-6 * np.eye(nc)
569+
cov2 = X2 @ X2.T / ns + 1e-6 * np.eye(nc)
570+
M = np.eye(nc)
571+
T = 0.5 * np.eye(nc) # non-trivial threshold so R is non-identity
572+
573+
state = dict(M=M, T=T, R=None)
574+
_, state = asr_process(X1, X1, state, cov=cov1[None], method="euclid")
575+
R_old = state["R"].copy()
576+
577+
clean2, state2 = asr_process(X2, X2, state, cov=cov2[None], method="euclid")
578+
R_new = state2["R"]
579+
580+
# meaningfulness guard: blend is only visible when R changes.
581+
assert not np.allclose(R_old, R_new)
582+
assert np.allclose(clean2[:, -1], R_new.dot(X2)[:, -1], rtol=1e-9)
583+
584+
585+
def test_rms_window_offsets_rounds_each_start():
586+
"""RMS window starts round each start, not the step (matches clean_windows)."""
587+
from meegkit.asr import _rms_window_offsets
588+
589+
ns, N, win_overlap = 1000, 125, 0.66 # step = 42.5 (non-integer)
590+
591+
# rounding the step first gives step 42 -> [0, 42, 84, ...]
592+
old_step = np.round(N * (1 - win_overlap))
593+
old_offsets = np.arange(0, ns - N, old_step).astype(int)
594+
595+
offsets = _rms_window_offsets(ns, N, win_overlap)
596+
597+
assert not np.array_equal(offsets, old_offsets)
598+
# float step is 42.4999..., so 3*step rounds to 127 (not 128)
599+
np.testing.assert_array_equal(
600+
offsets[:7], np.array([0, 42, 85, 127, 170, 212, 255]))
601+
602+
540603
if __name__ == "__main__":
541604
pytest.main([__file__])
542605
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)