Skip to content

Commit

Permalink
BUG: array_api.argsort(descending=True) respects relative sort order (
Browse files Browse the repository at this point in the history
#20788)

* BUG: `array_api.argsort(descending=True)` respects relative order

* Regression test for stable descending `array_api.argsort()`
  • Loading branch information
honno authored and charris committed Jan 12, 2022
1 parent 4877d60 commit f6f28d0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
17 changes: 14 additions & 3 deletions numpy/array_api/_sorting_functions.py
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
@@ -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 comments on commit f6f28d0

Please sign in to comment.