Skip to content

Commit be557df

Browse files
sappelhoffnbara
authored andcommitted
[MAINT] ASR: fit_eeg_distribution docstring fixes + asr_calibrate input guards
- fit_eeg_distribution: correct the transposed min_clean_fraction / max_dropout_fraction default values in the docstring, and describe X as the 1-D amplitude vector it actually is (not a 2-D array). - asr_calibrate: zero non-finite samples before filtering so a NaN/Inf in the calibration data no longer propagates into a silent all-NaN threshold; and raise clear errors when the calibration data is too short to form at least two analysis windows, instead of an obscure downstream IndexError.
1 parent 1fcfbfd commit be557df

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
@@ -479,11 +479,18 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
479479
# set number of channels and number of samples
480480
[nc, ns] = X.shape
481481

482+
# avoid propagating non-finite samples into the filter and thresholds
483+
X = np.where(np.isfinite(X), X, 0.0)
484+
482485
# filter the data
483486
X, _zf = yulewalk_filter(X, sfreq, ab=None)
484487

485488
# window length for calculating thresholds
486489
N = int(np.round(win_len * sfreq))
490+
if ns < N:
491+
raise ValueError(
492+
f"Calibration data has {ns} samples, shorter than one analysis "
493+
f"window of {N} samples (win_len={win_len} at sfreq={sfreq}).")
487494

488495
U = block_covariance(X, window=blocksize, overlap=win_overlap,
489496
estimator=estimator)
@@ -502,6 +509,11 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
502509
# get the threshold matrix T
503510
xsq = np.dot(V.T, X) ** 2
504511
offsets = np.arange(0, ns - N, np.round(N * (1 - win_overlap))).astype(int)
512+
if len(offsets) < 2:
513+
raise ValueError(
514+
f"Only {len(offsets)} window(s) available for threshold "
515+
"estimation; at least 2 are required. Provide more calibration "
516+
"data.")
505517

506518
# root mean squared amplitude per channel (windowed sums via cumulative sum)
507519
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
if __name__ == "__main__":
280303
pytest.main([__file__])
281304
# test_yulewalk(250, True)

0 commit comments

Comments
 (0)