Skip to content

Commit 14c15a4

Browse files
committed
[MAINT] ASR: defensive hardening and docstring fixes
- asr_process: read state by key instead of relying on dict order - fit_eeg_distribution: nudge gridsearch arange endpoint (mirror cols grid) - clean_windows: build window offsets from non-truncated N (phase drift) - ASR: expose max_bad_chans as a constructor parameter (default 0.3) - docs: fix clean_windows win_len default (0.5); document the mask3 term
1 parent 3721224 commit 14c15a4

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
@@ -295,7 +300,7 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
295300
Window length that is used to check the data for artifact content.
296301
This is ideally as long as the expected time scale of the artifacts
297302
but not shorter than half a cycle of the high-pass filter that was
298-
used. Default: 1.
303+
used. Default: 0.5.
299304
win_overlap : float
300305
Window overlap fraction. The fraction of two successive windows that
301306
overlaps. Higher overlap ensures that fewer artifact portions are
@@ -328,7 +333,8 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
328333
# set data indices
329334
[nc, ns] = X.shape
330335
N = int(win_len * sfreq)
331-
offsets = np.round(np.arange(0, ns - N, (N * (1 - win_overlap))))
336+
N_raw = win_len * sfreq # non-truncated N, avoids step-size phase drift
337+
offsets = np.round(np.arange(0, ns - N, N_raw * (1 - win_overlap)))
332338
offsets = offsets.astype(int)
333339
logging.debug("[ASR] Determining channel-wise rejection thresholds")
334340

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

367+
# extra meegkit-specific criterion: drop windows whose across-channel
368+
# z-scores are nearly flat (very low MAD or std)
361369
bad_by_mad = mad(wz, c=1, axis=0) < .1
362370
bad_by_std = np.std(wz, axis=0) < .1
363371
mask3 = np.logical_or(bad_by_mad, bad_by_std)
@@ -556,7 +564,7 @@ def asr_process(X, X_filt, state, cov=None, detrend=False, method="riemann",
556564
Output ASR parameters.
557565
558566
"""
559-
M, T, R = state.values()
567+
M, T, R = state["M"], state["T"], state["R"]
560568
[nc, ns] = X.shape
561569

562570
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
@@ -258,6 +258,64 @@ def test_asr_class(method, reref, show=False):
258258
ASR(sfreq=125)
259259
ASR(Sfreq=150)
260260

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

0 commit comments

Comments
 (0)