From 8da4fba24c193807555dfcbc0e67834cae9185ea Mon Sep 17 00:00:00 2001 From: Sebastian Berg Date: Sat, 30 May 2020 11:36:24 -0500 Subject: BUG: The reduction output must not cause the input to be broadcast This was previously checked for, but during the refactor using NPY_ITER_REDUCTION_AXIS to allocate the result in the iterator instead of manually was lost here. Einsum has a similar issue, but this is not modified here. --- numpy/core/src/umath/reduction.c | 3 ++- numpy/core/tests/test_ufunc.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) (limited to 'numpy') diff --git a/numpy/core/src/umath/reduction.c b/numpy/core/src/umath/reduction.c index bcfbdd954..4037a4757 100644 --- a/numpy/core/src/umath/reduction.c +++ b/numpy/core/src/umath/reduction.c @@ -241,7 +241,8 @@ PyUFunc_ReduceWrapper(PyArrayObject *operand, PyArrayObject *out, NPY_ITER_ALLOCATE | NPY_ITER_NO_SUBTYPE; op_flags[1] = NPY_ITER_READONLY | - NPY_ITER_ALIGNED; + NPY_ITER_ALIGNED | + NPY_ITER_NO_BROADCAST; if (wheremask != NULL) { op[2] = wheremask; diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py index f7126f135..d8f407c97 100644 --- a/numpy/core/tests/test_ufunc.py +++ b/numpy/core/tests/test_ufunc.py @@ -1922,6 +1922,19 @@ class TestUfunc: assert_(check is out) assert_array_equal(check, correct_out) + def test_reduce_output_does_not_broadcast_input(self): + # Test that the output shape cannot broadcast an input dimension + # (it never can add dimensions, but it might expand an existing one) + a = np.ones((1, 10)) + out_correct = (np.empty((1, 1))) + out_incorrect = np.empty((3, 1)) + np.add.reduce(a, axis=-1, out=out_correct, keepdims=True) + np.add.reduce(a, axis=-1, out=out_correct[:, 0], keepdims=False) + with assert_raises(ValueError): + np.add.reduce(a, axis=-1, out=out_incorrect, keepdims=True) + with assert_raises(ValueError): + np.add.reduce(a, axis=-1, out=out_incorrect[:, 0], keepdims=False) + def test_reduce_output_subclass_ok(self): class MyArr(np.ndarray): pass -- cgit v1.2.1