Skip to content

Commit 6b107c9

Browse files
sappelhoffnbara
andauthored
[MAINT] ASR: fit_eeg_distribution docstring fixes + asr_calibrate input guards (#121)
A small bundle of documentation and defensive-hardening fixes: - **`fit_eeg_distribution` docstring:** the `min_clean_fraction` / `max_dropout_fraction` default values were transposed relative to the signature (`0.25` / `0.1`); corrected. Also `X` was described as a 2-D `(n_channels, n_samples)` array, but the function operates on a **1-D** vector of amplitude values (it does `np.sort(X); n=len(X)`) — description fixed. - **`asr_calibrate` non-finite guard:** a `NaN`/`Inf` in the calibration data previously propagated silently through the filter into `M`/`T` (an all-`NaN` threshold, no error). Non-finite samples are now zeroed before filtering so calibration degrades gracefully. - **`asr_calibrate` insufficient-data guards:** raise a clear `ValueError` when the calibration data is too short to form one analysis window, or yields fewer than two threshold-estimation windows — instead of an obscure downstream error. ### Testing Adds tests that non-finite calibration input yields finite `M`/`T`, and that too-short calibration raises a clear `ValueError`. Full `tests/test_asr.py` + `tests/test_cov.py` pass; `ruff` clean. --- **Note:** includes the `nonlinear_eigenspace` reproducibility fix from #118 so the riemann CI test is stable regardless of what this PR changes. Once #118 merges first, that commit drops out on rebase. Co-authored-by: Nicolas Barascud <10333715+nbara@users.noreply.github.com>
1 parent d2f4494 commit 6b107c9

3 files changed

Lines changed: 40 additions & 4 deletions

File tree

‎meegkit/asr.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,11 +487,18 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
487487
# set number of channels and number of samples
488488
[nc, ns] = X.shape
489489

490+
# avoid propagating non-finite samples into the filter and thresholds
491+
X = np.where(np.isfinite(X), X, 0.0)
492+
490493
# filter the data
491494
X, _zf = yulewalk_filter(X, sfreq, ab=None)
492495

493496
# window length for calculating thresholds
494497
N = int(np.round(win_len * sfreq))
498+
if ns < N:
499+
raise ValueError(
500+
f"Calibration data has {ns} samples, shorter than one analysis "
501+
f"window of {N} samples (win_len={win_len} at sfreq={sfreq}).")
495502

496503
U = block_covariance(X, window=blocksize, overlap=win_overlap,
497504
estimator=estimator)
@@ -510,6 +517,11 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
510517
# get the threshold matrix T
511518
xsq = np.dot(V.T, X) ** 2
512519
offsets = np.arange(0, ns - N, np.round(N * (1 - win_overlap))).astype(int)
520+
if len(offsets) < 2:
521+
raise ValueError(
522+
f"Only {len(offsets)} window(s) available for threshold "
523+
"estimation; at least 2 are required. Provide more calibration "
524+
"data.")
513525

514526
# root mean squared amplitude per channel (windowed sums via cumulative sum)
515527
csum = np.zeros((nc, ns + 1))

‎meegkit/utils/asr.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,17 @@ def fit_eeg_distribution(X, min_clean_fraction=0.25, max_dropout_fraction=0.1,
3838
3939
Parameters
4040
----------
41-
X : array, shape=(n_channels, n_samples)
42-
EEG data, possibly containing artifacts.
41+
X : array, shape=(n_samples,)
42+
1-D vector of amplitude values (e.g., per-window RMS), possibly
43+
containing artifacts.
4344
min_clean_fraction : float
4445
Minimum fraction that needs to be clean. This is the minimum fraction
4546
of time windows that need to contain essentially uncontaminated EEG
46-
(default=0.1).
47+
(default=0.25).
4748
max_dropout_fraction : float
4849
Maximum fraction that can have dropouts. This is the maximum fraction
4950
of time windows that may have arbitrarily low amplitude (e.g., due to
50-
the sensors being unplugged) (default=0.25).
51+
the sensors being unplugged) (default=0.1).
5152
fit_quantiles : 2-tuple
5253
Quantile range [lower,upper] of the truncated generalized Gaussian
5354
distribution that shall be fit to the EEG contents (default=[0.022

‎tests/test_asr.py‎

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

279+
280+
def test_asr_calibrate_nonfinite_input():
281+
"""Non-finite calibration samples must not silently yield NaN M/T."""
282+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
283+
sfreq = 250
284+
train_idx = np.arange(5 * sfreq, 45 * sfreq, dtype=int)
285+
X = raw[:, train_idx].copy()
286+
X[0, 100] = np.nan
287+
X[0, 200] = np.inf
288+
289+
M, T = asr_calibrate(X, sfreq)
290+
291+
assert np.all(np.isfinite(M))
292+
assert np.all(np.isfinite(T))
293+
294+
295+
def test_asr_calibrate_too_short():
296+
"""Calibration data shorter than one analysis window should raise."""
297+
X_short = rng.standard_normal((8, 50)) # N = round(0.5 * 250) = 125
298+
with pytest.raises(ValueError, match="shorter than one analysis window"):
299+
asr_calibrate(X_short, 250)
300+
301+
279302
def test_asr_max_bad_chans_param():
280303
"""max_bad_chans is exposed on ASR and defaults to 0.3."""
281304
assert ASR().max_bad_chans == 0.3

0 commit comments

Comments
 (0)