8000 BUG: ``array_api.argsort(descending=True)`` respects relative sort order by honno · Pull Request #20788 · numpy/numpy · GitHub
[go: up one dir, main page]

Skip to content

BUG: array_api.argsort(descending=True) respects relative sort order #20788

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

Merged
merged 2 commits into from
Jan 12, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions numpy/array_api/_sorting_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,20 @@ def argsort(
"""
# Note: this keyword argument is different, and the default is different.
kind = "stable" if stable else "quicksort"
res = np.argsort(x._array, axis=axis, kind=kind)
if descending:
res = np.flip(res, axis=axis)
if not descending:
res = np.argsort(x._array, axis=axis, kind=kind)
else:
# As NumPy has no native descending sort, we imitate it here. Note that
# simply flipping the results of np.argsort(x._array, ...) would not
# respect the relative order like it would in native descending sorts.
res = np.flip(
np.argsort(np.flip(x._array, axis=axis), axis=axis, kind=kind),
axis=axis,
)
# Rely on flip()/argsort() to validate axis
normalised_axis = axis if axis >= 0 else x.ndim + axis
max_i = x.shape[normalised_axis] - 1
res = max_i - res
return Array._new(res)


Expand Down
23 changes: 23 additions & 0 deletions numpy/array_api/tests/test_sorting_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import pytest

from numpy import array_api as xp


@pytest.mark.parametrize(
"obj, axis, expected",
[
([0, 0], -1, [0, 1]),
([0, 1, 0], -1, [1, 0, 2]),
([[0, 1], [1, 1]], 0, [[1, 0], [0, 1]]),
([[0, 1], [1, 1]], 1, [[1, 0], [0, 1]]),
],
)
def test_stable_desc_argsort(obj, axis, expected):
"""
Indices respect relative order of a descending stable-sort

See https://github.com/numpy/numpy/issues/20778
"""
x = xp.asarray(obj)
out = xp.argsort(x, axis=axis, stable=True, descending=True)
assert xp.all(out == xp.asarray(expected))
0