Skip to content

Commit c566605

Browse files
authored
Merge pull request #104 from antonsoo/fix/integer-grouped-squares
Widen integer values before grouped sum of squares
2 parents 026e3a9 + 31e0c6c commit c566605

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

‎numpy_groupies/aggregate_numpy.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,8 @@ def _sum_of_squres(
363363
fill_value: Any,
364364
dtype: np.dtype | None = np.dtype(np.float64),
365365
) -> np.ndarray:
366+
if np.issubdtype(a.dtype, np.integer):
367+
a = a.astype(dtype, copy=False)
366368
if iscomplexobj(a):
367369
# the squared magnitude |a|^2 - the power of complex values, giving
368370
# a real result like np.var, instead of the complex a*a

‎numpy_groupies/tests/test_generic.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,26 @@ def test_preserve_missing(aggregate_all):
3131
assert "int" in res.dtype.name
3232

3333

34+
@pytest.mark.parametrize("func", ["sumofsquares", "nansumofsquares"])
35+
@pytest.mark.parametrize("dtype", [np.int8, np.uint8, np.int16, np.uint16, np.int32, np.uint32])
36+
def test_numpy_integer_sumofsquares(func, dtype):
37+
maximum = min(int(np.iinfo(dtype).max), 50000)
38+
a = np.array([maximum, maximum - 1, maximum // 2, 1], dtype=dtype)
39+
group_idx = np.array([0, 0, 1, 1])
40+
expected = [sum(int(value) ** 2 for value in a[:2]), sum(int(value) ** 2 for value in a[2:]), -1]
41+
result = aggregate_np(group_idx, a, func=func, size=3, fill_value=-1)
42+
assert result.dtype == np.int64
43+
np.testing.assert_array_equal(result, expected)
44+
45+
46+
@pytest.mark.parametrize("func", ["sumofsquares", "nansumofsquares"])
47+
def test_numpy_integer_sumofsquares_float_output(func):
48+
a = np.array([[20000, -20000], [10000, -10000]], dtype=np.int16)
49+
result = aggregate_np(np.array([0, 0]), a, func=func, axis=1, dtype=np.float64)
50+
assert result.dtype == np.float64
51+
np.testing.assert_array_equal(result, [[800000000], [200000000]])
52+
53+
3454
@pytest.mark.parametrize("group_idx_type", [int, "uint32", "uint64"])
3555
def test_uint_group_idx(aggregate_all, group_idx_type):
3656
group_idx = np.array([1, 1, 2, 2, 2, 2, 4, 4], dtype=group_idx_type)

0 commit comments

Comments
 (0)