Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: properly handle negative indexes in ufunc_at fast path #24150

Merged
merged 1 commit into from
Jul 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 8 additions & 3 deletions numpy/core/src/umath/ufunc_object.c
Original file line number Diff line number Diff line change
Expand Up @@ -5812,14 +5812,19 @@ trivial_at_loop(PyArrayMethodObject *ufuncimpl, NPY_ARRAYMETHOD_FLAGS flags,
}
}

npy_intp *inner_size = NpyIter_GetInnerLoopSizePtr(iter->outer);

if (!(flags & NPY_METH_NO_FLOATINGPOINT_ERRORS)) {
npy_clear_floatstatus_barrier((char *)context);
}

do {
args[1] = (char *) iter->outer_ptrs[0];
npy_intp *inner_size = NpyIter_GetInnerLoopSizePtr(iter->outer);
npy_intp * indxP = (npy_intp *)iter->outer_ptrs[0];
for (npy_intp i=0; i < *inner_size; i++) {
if (indxP[i] < 0) {
indxP[i] += iter->fancy_dims[0];
}
}
args[1] = (char *)indxP;
steps[1] = iter->outer_strides[0];

res = ufuncimpl->contiguous_indexed_loop(
Expand Down
8 changes: 8 additions & 0 deletions numpy/core/tests/test_ufunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2224,6 +2224,14 @@ def test_ufunc_at_advanced(self):
np.maximum.at(a, [0], 0)
assert_equal(a, np.array([1, 2, 3]))

def test_at_negative_indexes(self):
a = np.arange(10)
indxs = np.array([-1, 1, -1, 2])
np.add.at(a, indxs, 1)
assert a[-1] == 11 # issue 24147
assert a[1] == 2
assert a[2] == 3

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An bad merge (locally) brought me here, but then I noticed that this can modify the original index array:

assert indxs[0] == -1

would fail. I think it shows that passing pointers or full offsets rather than indices makes more sense here (we need a temporary array anyway), but I have to think about how a hot-fix should look like.
Probably either need a local buffer here, or push the fixing into the indexed loop.

(Maybe local buffer is good, since that is what I would want to do with that hot-fix anyway in some form, even if it may make sense to push the buffer for that case slightly further up.)

def test_at_not_none_signature(self):
# Test ufuncs with non-trivial signature raise a TypeError
a = np.ones((2, 2, 2))
Expand Down