Skip to content

Commit d2f4494

Browse files
authored
[MAINT] ASR: defensive hardening and docstring fixes (#117)
A group of small defensive and documentation fixes in the ASR module (no behavior change on the common paths): - **`asr_process`:** read `state` by key (`state["M"]`, `state["T"]`, `state["R"]`) instead of `state.values()`, removing the reliance on dict insertion order. - **`fit_eeg_distribution`:** nudge the descending gridsearch `arange` stop endpoint so `min_width` is not dropped by floating-point error (mirrors the existing `cols` grid nudge). - **`ASR`:** expose `max_bad_chans` as a constructor parameter (default `0.3`, preserving current behavior) and document it. - **`clean_windows`:** build the window-start offsets from the non-truncated `win_len * sfreq` to avoid ~1-sample phase drift for non-integer products (byte-identical when the product is integer, including all existing tests); fix the `win_len` docstring default (0.5, not 1); document the meegkit-specific flat-window removal criterion. ### Testing Adds tests for the `max_bad_chans` parameter, `state` key-order independence, and the offset spacing. Full `tests/test_asr.py` passes; `ruff` clean.
1 parent 1fcfbfd commit d2f4494

3 files changed

Lines changed: 74 additions & 6 deletions

File tree

‎meegkit/asr.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ class ASR:
4444
Window overlap fraction. The fraction of two successive windows that
4545
overlaps. Higher overlap ensures that fewer artifact portions are going
4646
to be missed, but is slower (default=0.66).
47+
max_bad_chans : float
48+
The maximum number or fraction of bad channels that a retained window
49+
may still contain (more than this and it is removed) during
50+
calibration window selection (default=0.3).
4751
max_dropout_fraction : float
4852
Maximum fraction of windows that can be subject to signal dropouts
4953
(e.g., sensor unplugged), used for threshold estimation (default=0.1).
@@ -94,7 +98,8 @@ class ASR:
9498
"""
9599

96100
def __init__(self, *, sfreq=250, cutoff=5, blocksize=100, win_len=0.5,
97-
win_overlap=0.66, max_dropout_fraction=0.1,
101+
win_overlap=0.66, max_bad_chans=0.3,
102+
max_dropout_fraction=0.1,
98103
min_clean_fraction=0.25, method="euclid", memory=None,
99104
estimator="scm", **kwargs):
100105

@@ -104,7 +109,7 @@ def __init__(self, *, sfreq=250, cutoff=5, blocksize=100, win_len=0.5,
104109
self.win_overlap = win_overlap
105110
self.max_dropout_fraction = max_dropout_fraction
106111
self.min_clean_fraction = min_clean_fraction
107-
self.max_bad_chans = 0.3
112+
self.max_bad_chans = max_bad_chans
108113
self.method = method
109114
if memory is None:
110115
self.memory = int(2 * sfreq) # smoothing window for covariances
@@ -290,7 +295,7 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
290295
Window length that is used to check the data for artifact content.
291296
This is ideally as long as the expected time scale of the artifacts
292297
but not shorter than half a cycle of the high-pass filter that was
293-
used. Default: 1.
298+
used. Default: 0.5.
294299
win_overlap : float
295300
Window overlap fraction. The fraction of two successive windows that
296301
overlaps. Higher overlap ensures that fewer artifact portions are
@@ -330,7 +335,8 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
330335
# set data indices
331336
[nc, ns] = X.shape
332337
N = int(win_len * sfreq)
333-
offsets = np.round(np.arange(0, ns - N, (N * (1 - win_overlap))))
338+
N_raw = win_len * sfreq # non-truncated N, avoids step-size phase drift
339+
offsets = np.round(np.arange(0, ns - N, N_raw * (1 - win_overlap)))
334340
offsets = offsets.astype(int)
335341
logging.debug("[ASR] Determining channel-wise rejection thresholds")
336342

@@ -360,6 +366,8 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
360366
if np.min(zthresholds) < 0:
361367
mask2 = (swz[1 + int(max_bad_chans - 1), :] < np.min(zthresholds))
362368

369+
# extra meegkit-specific criterion: drop windows whose across-channel
370+
# z-scores are nearly flat (very low MAD or std)
363371
bad_by_mad = mad(wz, c=1, axis=0) < .1
364372
bad_by_std = np.std(wz, axis=0) < .1
365373
mask3 = np.logical_or(bad_by_mad, bad_by_std)
@@ -558,7 +566,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
558566
Output ASR parameters.
559567
560568
"""
561-
M, T, R = state.values()
569+
M, T, R = state["M"], state["T"], state["R"]
562570
[nc, ns] = X.shape
563571

564572
if cov is None:

‎meegkit/utils/asr.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,9 @@ def fit_eeg_distribution(X, min_clean_fraction=0.25, max_dropout_fraction=0.1,
114114
opt_lu = np.inf
115115
opt_bounds = np.inf
116116
opt_beta = np.inf
117-
gridsearch = np.round(n * np.arange(max_width, min_width, -step_sizes[1]))
117+
# nudge the stop so min_width isn't dropped by float error (as for cols)
118+
gridsearch = np.round(
119+
n * np.arange(max_width, min_width - step_sizes[1] * 1e-9, -step_sizes[1]))
118120
for m in gridsearch.astype(int):
119121
mcurr = m - 1
120122
nbins = int(np.round(3 * np.log2(1 + m / 2)))

‎tests/test_asr.py‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,64 @@ def test_asr_class(method, reref, show=False):
276276
ASR(sfreq=125)
277277
ASR(Sfreq=150)
278278

279+
def test_asr_max_bad_chans_param():
280+
"""max_bad_chans is exposed on ASR and defaults to 0.3."""
281+
assert ASR().max_bad_chans == 0.3
282+
assert ASR(max_bad_chans=0.2).max_bad_chans == 0.2
283+
284+
285+
def test_asr_process_state_key_order():
286+
"""asr_process reads state by key, not by dict insertion order.
287+
288+
M and T are distinct and the keep mask is non-trivial, so a positional
289+
unpack of a reordered dict would change the output.
290+
"""
291+
nc, ns = 4, 8
292+
X = np.arange(nc * ns, dtype=float).reshape(nc, ns) + 1.0
293+
X_filt = X.copy()
294+
# T's large column-2 norm keeps component 2 while M=eye rejects it, so the
295+
# two dict orderings give different keep masks (hence different R) under a
296+
# positional unpack.
297+
cov = np.diag([1.0, 1.0, 1000.0, 1000.0])
298+
T = np.eye(nc)
299+
T[2, 2] = 40.0 # column-2 sum of squares = 1600 > 1000
300+
M = np.eye(nc)
301+
302+
state_ordered = dict(M=M, T=T, R=None)
303+
out_ordered, _ = asr_process(
304+
X, X_filt, state_ordered, cov=cov.copy(), method="euclid")
305+
306+
# Same content, different insertion order
307+
state_reordered = dict(T=T, M=M, R=None)
308+
out_reordered, _ = asr_process(
309+
X, X_filt, state_reordered, cov=cov.copy(), method="euclid")
310+
311+
np.testing.assert_allclose(out_ordered, out_reordered)
312+
313+
314+
def test_clean_windows_offset_phase_drift():
315+
"""Offsets use the non-truncated win_len*sfreq to avoid phase drift.
316+
317+
Diverges from truncated-N spacing only when win_len*sfreq is non-integer.
318+
"""
319+
sfreq = 251
320+
win_len = 0.5 # win_len * sfreq = 125.5, non-integer
321+
win_overlap = 0.66
322+
ns = 5000
323+
324+
N = int(win_len * sfreq)
325+
N_raw = win_len * sfreq
326+
offsets_raw = np.round(
327+
np.arange(0, ns - N, N_raw * (1 - win_overlap))).astype(int)
328+
offsets_truncated = np.round(
329+
np.arange(0, ns - N, N * (1 - win_overlap))).astype(int)
330+
331+
assert len(offsets_raw) == len(offsets_truncated)
332+
# The two stepping schemes diverge (truncated-N accumulates drift)
333+
assert not np.array_equal(offsets_raw, offsets_truncated)
334+
assert abs(int(offsets_raw[-1]) - int(offsets_truncated[-1])) >= 10
335+
336+
279337
if __name__ == "__main__":
280338
pytest.main([__file__])
281339
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)