Skip to content

Commit c7d7acc

Browse files
authored
Avoid integer overflow in normalize_bound (#681)
`normalize_bound()` subtracts NumPy integer extrema in their original dtype. A signed signal whose range exceeds that dtype can wrap before the scaling coefficient is computed. ```python sig = np.array([-30000, 0, 30000], dtype=np.int16) processing.normalize_bound(sig, -1, 1) # before: [22.67630058, 11.83815029, 1.0] # after: [-1.0, 0.0, 1.0] ``` Widen integer extrema to Python integers before computing their difference. Use `np.multiply` for scaling so integer list inputs remain supported after the coefficient becomes a Python float. The floating-input formula is unchanged. The 19 added regression cases cover signed int8/int16/int32/int64 ranges and three bound pairs, unsigned endpoints, float behavior, list input, unchanged input arrays, and an int16 digital signal written and read through the WFDB API. On unchanged code, 14 fail and 5 controls pass. Validation on current main 05db3a2 plus this patch: - `tests/test_processing.py tests/test_normalize_bound.py`: 153 passed on Python 3.12.16. - Ruff 0.17.3 check and format passed for changed Python files. - Strict Sphinx HTML build with `-W --keep-going` passed. Earlier validation of the same change: 28 normalization-related tests passed on Python 3.10.12 and 1,000 seeded float-input comparisons were byte-identical to the original formula. The full repository suite and remote CI have not been verified. This fixes arithmetic overflow; it does not promise exact integer resolution beyond floating-point precision or change constant-signal/nonfinite behavior. No clinical validation is claimed. AI assistance was used to develop and test this change. Independent review has not been completed.
2 parents 51fd0fc + f871684 commit c7d7acc

3 files changed

Lines changed: 69 additions & 1 deletion

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
**Avoid integer overflow when normalizing signal bounds**
2+
``normalize_bound`` now computes the range of integer signals without
3+
wrapping, so large signed ranges map to the requested bounds.

‎src/wfdb/processing/basic.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,9 +186,12 @@ def normalize_bound(sig, lb=0, ub=1):
186186
mid = ub - (ub - lb) / 2
187187
min_v = np.min(sig)
188188
max_v = np.max(sig)
189+
if isinstance(min_v, np.integer) and isinstance(max_v, np.integer):
190+
# Widen integer extrema before computing their difference.
191+
min_v, max_v = int(min_v), int(max_v)
189192
mid_v = max_v - (max_v - min_v) / 2
190193
coef = (ub - lb) / (max_v - min_v)
191-
return sig * coef - (mid_v * coef) + mid
194+
return np.multiply(sig, coef) - (mid_v * coef) + mid
192195

193196

194197
def smooth(sig, window_size):

‎tests/test_normalize_bound.py‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""Integer dynamic-range regressions for signal normalization."""
2+
3+
import numpy as np
4+
import pytest
5+
6+
import wfdb
7+
from wfdb import processing
8+
9+
10+
@pytest.mark.parametrize("dtype", [np.int8, np.int16, np.int32, np.int64])
11+
@pytest.mark.parametrize("bounds", [(-1, 1), (0, 1), (-3, 7)])
12+
def test_signed_integer_full_range(dtype, bounds):
13+
info = np.iinfo(dtype)
14+
sig = np.array([info.min + 1, 0, info.max], dtype=dtype)
15+
original = sig.copy()
16+
with np.errstate(over="raise", divide="raise", invalid="raise"):
17+
result = processing.normalize_bound(sig, *bounds)
18+
np.testing.assert_allclose(result, [bounds[0], sum(bounds) / 2, bounds[1]])
19+
np.testing.assert_array_equal(sig, original)
20+
21+
22+
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64])
23+
def test_unsigned_integer_full_range(dtype):
24+
info = np.iinfo(dtype)
25+
sig = np.array([0, info.max], dtype=dtype)
26+
np.testing.assert_allclose(processing.normalize_bound(sig, -1, 1), [-1, 1])
27+
28+
29+
def test_normalize_digital_record(tmp_path):
30+
digital = np.array([[-30000], [0], [30000]], dtype=np.int16)
31+
wfdb.wrsamp(
32+
"normalize",
33+
fs=250,
34+
units=["mV"],
35+
sig_name=["ECG"],
36+
d_signal=digital,
37+
fmt=["16"],
38+
adc_gain=[200],
39+
baseline=[0],
40+
write_dir=str(tmp_path),
41+
)
42+
record = wfdb.rdrecord(str(tmp_path / "normalize"), physical=False, return_res=16)
43+
with np.errstate(over="raise"):
44+
result = processing.normalize_bound(record.d_signal[:, 0], -1, 1)
45+
np.testing.assert_allclose(result, [-1, 0, 1])
46+
47+
48+
def test_float_signal_retains_formula():
49+
sig = np.array([-3.5, -0.25, 1.75, 4.5])
50+
lb, ub = -3, 7
51+
mid = ub - (ub - lb) / 2
52+
lo, hi = np.min(sig), np.max(sig)
53+
center = hi - (hi - lo) / 2
54+
coef = (ub - lb) / (hi - lo)
55+
expected = sig * coef - center * coef + mid
56+
np.testing.assert_array_equal(processing.normalize_bound(sig, lb, ub), expected)
57+
58+
59+
def test_integer_list_input():
60+
np.testing.assert_allclose(
61+
processing.normalize_bound([-30000, 0, 30000], -1, 1), [-1, 0, 1]
62+
)

0 commit comments

Comments
 (0)