Skip to content

Commit 85c2a6d

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 107cd1b commit 85c2a6d

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
@@ -141,6 +141,50 @@ def test_yulewalk_filter(n_chans, show=False):
141141
plt.show()
142142

143143

144+
def test_fit_eeg_distribution_flat_run():
145+
"""fit_eeg_distribution must not crash on a run of tied values."""
146+
vec = np.r_[np.zeros(700), np.linspace(0, 1, 300)]
147+
mu, sig, alpha, beta = fit_eeg_distribution(vec)
148+
assert np.isfinite(mu)
149+
assert np.isfinite(sig)
150+
assert np.isfinite(alpha)
151+
assert np.isfinite(beta)
152+
153+
154+
def test_fit_eeg_distribution_clean_data():
155+
"""fit_eeg_distribution result on clean data is unchanged."""
156+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
157+
sfreq = 250
158+
train_idx = np.arange(5 * sfreq, 45 * sfreq, dtype=int)
159+
X = raw[:, train_idx]
160+
161+
win_len, win_overlap = 0.5, 0.66
162+
N = int(win_len * sfreq)
163+
ns = X.shape[1]
164+
offsets = np.round(
165+
np.arange(0, ns - N, (N * (1 - win_overlap)))).astype(int)
166+
csum = np.zeros((1, ns + 1))
167+
np.cumsum(X[0:1] ** 2, axis=1, out=csum[:, 1:])
168+
rms = np.sqrt((csum[:, offsets + N] - csum[:, offsets]) / N)[0]
169+
170+
mu, sig, alpha, beta = fit_eeg_distribution(rms)
171+
assert np.isfinite(mu) and np.isfinite(sig)
172+
expected = (8.557660078140897, 0.8349677153567411, 1.4090685615364371, 3.5)
173+
np.testing.assert_allclose((mu, sig, alpha, beta), expected)
174+
175+
176+
def test_asr_fit_dead_channel():
177+
"""ASR.fit must not crash when a channel is flatlined."""
178+
raw = np.load(os.path.join(THIS_FOLDER, "data", "eeg_raw.npy"))
179+
sfreq = 250
180+
train_idx = np.arange(5 * sfreq, 45 * sfreq, dtype=int)
181+
X = raw[:, train_idx].copy()
182+
X[0] = 0.0 # dead channel
183+
184+
asr = ASR(sfreq=sfreq)
185+
asr.fit(X)
186+
187+
144188
def test_asr_functions(show=False, method="riemann"):
145189
"""Test ASR functions (offline use).
146190

0 commit comments

Comments
 (0)