Skip to content

Commit 1ae2321

Browse files
authored
[FIX] ASR: round half away from zero for window/bad-chan counts (#116)
numpy's `np.round` (banker's rounding, round-half-to-even) and Python's `int()` truncation diverge from MATLAB's round-half-away-from-zero at exact-half inputs, giving ±1 counts for the bad-channel count and window length `N` in `clean_windows` and `asr_calibrate`. Add a `_round_half_away` helper and apply it at those sites. Reachability is narrow (ties need specific channel counts or odd-integer `sfreq` with `win_len=0.5`; common rates never trigger), so this mainly hardens the edge cases. ### Testing Added a helper unit test covering ties (`2.5→3`, `128.5→129`, `-2.5→-3`), divergence from `np.round`, array input, and `int()` exactness. Full `tests/test_asr.py` passes; `ruff` clean.
1 parent cbc8943 commit 1ae2321

2 files changed

Lines changed: 41 additions & 4 deletions

File tree

‎meegkit/asr.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,15 @@ def _recency_weights(counter, sample_weight):
288288
return weights
289289

290290

291+
def _round_half_away(x):
292+
"""Round half away from zero (MATLAB `round` semantics).
293+
294+
numpy's ``np.round`` rounds half to even (banker's rounding); this
295+
matches MATLAB/Octave which round halves away from zero.
296+
"""
297+
return np.floor(np.abs(x) + 0.5) * np.sign(x)
298+
299+
291300
def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
292301
win_len=.5, win_overlap=0.66, min_clean_fraction=0.25,
293302
max_dropout_fraction=0.1, show=False):
@@ -354,11 +363,11 @@ def clean_windows(X, sfreq, max_bad_chans=0.2, zthresholds=[-3.5, 5],
354363
truncate_quant = [0.0220, 0.6000]
355364
step_sizes = [0.01, 0.01]
356365
shape_range = SHAPE_RANGE
357-
max_bad_chans = np.round(X.shape[0] * max_bad_chans)
366+
max_bad_chans = _round_half_away(X.shape[0] * max_bad_chans)
358367

359368
# set data indices
360369
[nc, ns] = X.shape
361-
N = int(win_len * sfreq)
370+
N = int(_round_half_away(win_len * sfreq))
362371
N_raw = win_len * sfreq # non-truncated N, avoids step-size phase drift
363372
offsets = np.round(np.arange(0, ns - N, N_raw * (1 - win_overlap)))
364373
offsets = offsets.astype(int)
@@ -543,7 +552,7 @@ def asr_calibrate(X, sfreq, cutoff=5, blocksize=100, win_len=0.5,
543552
X, _zf = yulewalk_filter(X, sfreq, ab=None)
544553

545554
# window length for calculating thresholds
546-
N = int(np.round(win_len * sfreq))
555+
N = int(_round_half_away(win_len * sfreq))
547556
if ns < N:
548557
raise ValueError(
549558
f"Calibration data has {ns} samples, shorter than one analysis "

‎tests/test_asr.py‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import pytest
99
from scipy import signal
1010

11-
from meegkit.asr import ASR, asr_calibrate, asr_process, clean_windows
11+
from meegkit.asr import ASR, _round_half_away, asr_calibrate, asr_process, clean_windows
1212
from meegkit.utils.asr import SHAPE_RANGE, fit_eeg_distribution, yulewalk, yulewalk_filter
1313
from meegkit.utils.covariances import block_covariance
1414
from meegkit.utils.matrix import sliding_window
@@ -142,6 +142,34 @@ def test_yulewalk_filter(n_chans, show=False):
142142
plt.show()
143143

144144

145+
def test_round_half_away():
146+
"""_round_half_away rounds ties away from zero, unlike numpy's banker's rounding."""
147+
# exact-half (tie) behavior: rounds away from zero
148+
assert _round_half_away(2.5) == 3
149+
assert _round_half_away(128.5) == 129
150+
assert _round_half_away(-2.5) == -3
151+
assert _round_half_away(0.5) == 1
152+
assert _round_half_away(1.5) == 2 # np.round gives 2 here too (even)
153+
154+
# divergence from banker's rounding on ties
155+
assert _round_half_away(2.5) != np.round(2.5) # 3 != 2
156+
assert _round_half_away(128.5) != np.round(128.5) # 129 != 128
157+
158+
# non-tie values round normally
159+
assert _round_half_away(2.4) == 2
160+
assert _round_half_away(2.6) == 3
161+
assert _round_half_away(-2.6) == -3
162+
163+
# int() of the result is exact for scalars
164+
assert int(_round_half_away(2.5)) == 3
165+
assert int(_round_half_away(-2.5)) == -3
166+
167+
# array input
168+
ties = np.array([2.5, 128.5, -2.5, 0.5, 1.5])
169+
expected = np.array([3, 129, -3, 1, 2])
170+
np.testing.assert_array_equal(_round_half_away(ties), expected)
171+
172+
145173
def test_asr_functions(show=False, method="riemann"):
146174
"""Test ASR functions (offline use).
147175

0 commit comments

Comments
 (0)