Skip to content

Commit b375a26

Browse files
committed
[FIX] ASR: tolerate flat/degenerate segments in fit_eeg_distribution
The vectorized grid-search histogram divided by a per-column baseline- relative value that is zero for a run of tied samples (e.g. a flatlined channel), producing inf/nan bin values; casting nan to int gave INT64_MIN and np.bincount raised ValueError. A flat segment is exactly the dropout case max_dropout_fraction is meant to tolerate. Make the binning ignore non-finite entries (count them in no bin) so the grid search degrades gracefully instead of crashing; results on finite input are unchanged. Fixes a crash reachable via ASR.fit() on data with a dead channel.
1 parent 3721224 commit b375a26

2 files changed

Lines changed: 52 additions & 3 deletions

File tree

‎meegkit/utils/asr.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,11 +122,16 @@ def fit_eeg_distribution(X, min_clean_fraction=0.25, max_dropout_fraction=0.1,
122122
H = newX[:m] * cols
123123

124124
# per-column histogram over integer bins [0, 1, ..., nbins]
125+
# a tied/flat run (e.g. a dead channel) can make a column's baseline
126+
# value 0, so H may contain inf/nan; such entries are counted in no
127+
# bin instead of crashing the cast to int
125128
ncol = H.shape[1]
126-
binidx = np.minimum(H.astype(int), nbins - 1)
129+
finite = np.isfinite(H)
130+
binidx = np.minimum(np.where(finite, H, 0).astype(int), nbins - 1)
127131
flat = binidx + np.arange(ncol) * nbins
128132
hist_all = np.bincount(
129-
flat.ravel(), minlength=nbins * ncol).reshape(ncol, nbins).T
133+
flat.ravel(), weights=finite.ravel(),
134+
minlength=nbins * ncol).reshape(ncol, nbins).T
130135
hist_all = np.vstack((hist_all, np.zeros(ncol, dtype=int)))
131136
logq = np.log(hist_all + 0.01)
132137

‎tests/test_asr.py‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from scipy import signal
88

99
from meegkit.asr import ASR, asr_calibrate, asr_process, clean_windows
10-
from meegkit.utils.asr import yulewalk, yulewalk_filter
10+
from meegkit.utils.asr import fit_eeg_distribution, yulewalk, yulewalk_filter
1111
from meegkit.utils.matrix import sliding_window
1212

1313
# Data files
@@ -122,6 +122,50 @@ def test_yulewalk_filter(n_chans, show=False):
122122
plt.show()
123123

124124

125+
def test_fit_eeg_distribution_flat_run():
126+
"""fit_eeg_distribution must not crash on a run of tied values."""
127+
vec = np.r_[np.zeros(700), np.linspace(0, 1, 300)]
128+
mu, sig, alpha, beta = fit_eeg_distribution(vec)
129+
assert np.isfinite(mu)
130+
assert np.isfinite(sig)
131+
assert np.isfinite(alpha)
132+
assert np.isfinite(beta)
133+
134+
135+
def test_fit_eeg_distribution_clean_data():
136+
"""fit_eeg_distribution result on clean data is unchanged."""
137+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
138+
sfreq = 250
139+
train_idx = np.arange(5 * sfreq, 45 * sfreq, dtype=int)
140+
X = raw[:, train_idx]
141+
142+
win_len, win_overlap = 0.5, 0.66
143+
N = int(win_len * sfreq)
144+
ns = X.shape[1]
145+
offsets = np.round(
146+
np.arange(0, ns - N, (N * (1 - win_overlap)))).astype(int)
147+
csum = np.zeros((1, ns + 1))
148+
np.cumsum(X[0:1] ** 2, axis=1, out=csum[:, 1:])
149+
rms = np.sqrt((csum[:, offsets + N] - csum[:, offsets]) / N)[0]
150+
151+
mu, sig, alpha, beta = fit_eeg_distribution(rms)
152+
assert np.isfinite(mu) and np.isfinite(sig)
153+
expected = (8.557660078140897, 0.8349677153567411, 1.4090685615364371, 3.5)
154+
np.testing.assert_allclose((mu, sig, alpha, beta), expected)
155+
156+
157+
def test_asr_fit_dead_channel():
158+
"""ASR.fit must not crash when a channel is flatlined."""
159+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
160+
sfreq = 250
161+
train_idx = np.arange(5 * sfreq, 45 * sfreq, dtype=int)
162+
X = raw[:, train_idx].copy()
163+
X[0] = 0.0 # dead channel
164+
165+
asr = ASR(sfreq=sfreq)
166+
asr.fit(X)
167+
168+
125169
def test_asr_functions(show=False, method="riemann"):
126170
"""Test ASR functions (offline use).
127171

0 commit comments

Comments
 (0)