Skip to content

Commit ef2cefa

Browse files
committed
WIP: start adding top_k
1 parent a6433ac commit ef2cefa

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

array_api_strict/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -297,9 +297,9 @@
297297

298298
__all__ += ["concat", "expand_dims", "flip", "moveaxis", "permute_dims", "repeat", "reshape", "roll", "squeeze", "stack", "tile", "unstack"]
299299

300-
from ._searching_functions import argmax, argmin, nonzero, count_nonzero, searchsorted, where
300+
from ._searching_functions import argmax, argmin, nonzero, count_nonzero, searchsorted, where, top_k
301301

302-
__all__ += ["argmax", "argmin", "nonzero", "count_nonzero", "searchsorted", "where"]
302+
__all__ += ["argmax", "argmin", "nonzero", "count_nonzero", "searchsorted", "where", "top_k"]
303303

304304
from ._set_functions import unique_all, unique_counts, unique_inverse, unique_values, isin
305305

array_api_strict/_searching_functions.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,14 +122,25 @@ def where(condition: Array, x1: Array | complex, x2: Array | complex, /) -> Arra
122122
return Array._new(np.where(condition._array, x1._array, x2._array), device=x1.device)
123123

124124

125+
125126
def top_k(a, k, /, axis=-1, *, mode="largest"):
127+
"""
128+
Array API compatible wrapper for :py:func:`np.top_k <numpy.top_k>`.
129+
130+
See its docstring for more information.
131+
"""
126132
if k <= 0:
127133
raise ValueError(f'k(={k}) provided must be positive.')
128134

129-
positive_axis = axis if axis > 0 else axis % arr.ndim
135+
if mode not in ["largest", "smallest"]:
136+
raise ValueError(f'{mode = } not in ["largest", "smallest"]')
137+
138+
positive_axis = axis if axis > 0 else axis % a.ndim
139+
140+
arr = a._array
130141

131142
slice_start = (np.s_[:],) * positive_axis
132-
if largest:
143+
if mode == "largest":
133144
indices_array = np.argpartition(arr, -k, axis=axis)
134145
slice = slice_start + (np.s_[-k:],)
135146
topk_indices = indices_array[slice]
@@ -140,5 +151,5 @@ def top_k(a, k, /, axis=-1, *, mode="largest"):
140151

141152
topk_values = np.take_along_axis(arr, topk_indices, axis=axis)
142153

143-
return topk_values, topk_indices
154+
return Array._new(topk_values, device=a.device), Array._new(topk_indices, device=a.device)
144155

0 commit comments

Comments
 (0)