Skip to content

Commit a333d9e

Browse files
sappelhoffnbara
authored andcommitted
[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 1ae2321 commit a333d9e

2 files changed

Lines changed: 51 additions & 2 deletions

File tree

‎meegkit/utils/asr.py‎

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

127127
# per-column histogram over integer bins [0, 1, ..., nbins]
128+
# a tied/flat run (e.g. a dead channel) can make a column's baseline
129+
# value 0, so H may contain inf/nan; such entries are counted in no
130+
# bin instead of crashing the cast to int
128131
ncol = H.shape[1]
129-
binidx = np.minimum(H.astype(int), nbins - 1)
132+
finite = np.isfinite(H)
133+
binidx = np.minimum(np.where(finite, H, 0).astype(int), nbins - 1)
130134
flat = binidx + np.arange(ncol) * nbins
131135
hist_all = np.bincount(
132-
flat.ravel(), minlength=nbins * ncol).reshape(ncol, nbins).T
136+
flat.ravel(), weights=finite.ravel(),
137+
minlength=nbins * ncol).reshape(ncol, nbins).T
133138
hist_all = np.vstack((hist_all, np.zeros(ncol, dtype=int)))
134139
logq = np.log(hist_all + 0.01)
135140

‎tests/test_asr.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,50 @@ def test_round_half_away():
170170
np.testing.assert_array_equal(_round_half_away(ties), expected)
171171

172172

173+
def test_fit_eeg_distribution_flat_run():
174+
"""fit_eeg_distribution must not crash on a run of tied values."""
175+
vec = np.r_[np.zeros(700), np.linspace(0, 1, 300)]
176+
mu, sig, alpha, beta = fit_eeg_distribution(vec)
177+
assert np.isfinite(mu)
178+
assert np.isfinite(sig)
179+
assert np.isfinite(alpha)
180+
assert np.isfinite(beta)
181+
182+
183+
def test_fit_eeg_distribution_clean_data():
184+
"""fit_eeg_distribution result on clean data is unchanged."""
185+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
186+
sfreq = 250
187+
train_idx = np.arange(5 * sfreq, 45 * sfreq, dtype=int)
188+
X = raw[:, train_idx]
189+
190+
win_len, win_overlap = 0.5, 0.66
191+
N = int(win_len * sfreq)
192+
ns = X.shape[1]
193+
offsets = np.round(
194+
np.arange(0, ns - N, (N * (1 - win_overlap)))).astype(int)
195+
csum = np.zeros((1, ns + 1))
196+
np.cumsum(X[0:1] ** 2, axis=1, out=csum[:, 1:])
197+
rms = np.sqrt((csum[:, offsets + N] - csum[:, offsets]) / N)[0]
198+
199+
mu, sig, alpha, beta = fit_eeg_distribution(rms)
200+
assert np.isfinite(mu) and np.isfinite(sig)
201+
expected = (8.001450519084575, 0.5339755761243605, 0.8942468424981882, 3.35)
202+
np.testing.assert_allclose((mu, sig, alpha, beta), expected)
203+
204+
205+
def test_asr_fit_dead_channel():
206+
"""ASR.fit must not crash when a channel is flatlined."""
207+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
208+
sfreq = 250
209+
train_idx = np.arange(5 * sfreq, 45 * sfreq, dtype=int)
210+
X = raw[:, train_idx].copy()
211+
X[0] = 0.0 # dead channel
212+
213+
asr = ASR(sfreq=sfreq)
214+
asr.fit(X)
215+
216+
173217
def test_asr_functions(show=False, method="riemann"):
174218
"""Test ASR functions (offline use).
175219

0 commit comments

Comments
 (0)