Skip to content

Commit 98b2477

Browse files
committed
Collapse into a numpy scalar in 0-d and 1-d reduction results
1 parent 0e43e92 commit 98b2477

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

src/blosc2/lazyexpr.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2366,7 +2366,13 @@ def reduce_slices( # noqa: C901
23662366
dtype = np.float64
23672367
out = convert_none_out(dtype, reduce_op, reduced_shape)
23682368

2369-
out = out[()] if reduced_shape == () else out # undo dummy dim from inside convert_none_out
2369+
if reduced_shape == ():
2370+
# convert_none_out() may allocate shape (1,) as an internal buffer for scalar reductions.
2371+
# Collapse it to a numpy scalar while handling both 0-d and 1-d singleton arrays.
2372+
if isinstance(out, np.ndarray):
2373+
out = out[()] if out.ndim == 0 else out[0]
2374+
else:
2375+
out = out[()]
23702376
final_mask = tuple(np.where(mask_slice)[0])
23712377
if np.any(mask_slice): # remove dummy dims
23722378
out = np.squeeze(out, axis=final_mask)

tests/ndarray/test_dsl_kernels.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,16 @@ def test_dsl_kernel_with_no_inputs_works_with_explicit_shape():
214214
np.testing.assert_equal(res, expected)
215215

216216

217+
def test_dsl_kernel_with_no_inputs_sum_returns_scalar():
218+
shape = (10, 5)
219+
expr = blosc2.lazyudf(kernel_index_ramp_no_inputs, (), dtype=np.float32, shape=shape)
220+
result = expr.sum()
221+
222+
expected = np.arange(np.prod(shape), dtype=np.float32).reshape(shape).sum()
223+
assert np.isscalar(result)
224+
np.testing.assert_allclose(result, expected, rtol=0.0, atol=0.0)
225+
226+
217227
def test_dsl_kernel_with_no_inputs_requires_shape_or_out():
218228
with pytest.raises(ValueError, match="shape"):
219229
_ = blosc2.lazyudf(kernel_index_ramp_no_inputs, (), dtype=np.float32)

0 commit comments

Comments
 (0)