_searching_functions.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from __future__ import annotations
  2. from ._array_object import Array
  3. from ._dtypes import _result_type, _real_numeric_dtypes
  4. from typing import Optional, Tuple
  5. import numpy as np
  6. def argmax(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array:
  7. """
  8. Array API compatible wrapper for :py:func:`np.argmax <numpy.argmax>`.
  9. See its docstring for more information.
  10. """
  11. if x.dtype not in _real_numeric_dtypes:
  12. raise TypeError("Only real numeric dtypes are allowed in argmax")
  13. return Array._new(np.asarray(np.argmax(x._array, axis=axis, keepdims=keepdims)))
  14. def argmin(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array:
  15. """
  16. Array API compatible wrapper for :py:func:`np.argmin <numpy.argmin>`.
  17. See its docstring for more information.
  18. """
  19. if x.dtype not in _real_numeric_dtypes:
  20. raise TypeError("Only real numeric dtypes are allowed in argmin")
  21. return Array._new(np.asarray(np.argmin(x._array, axis=axis, keepdims=keepdims)))
  22. def nonzero(x: Array, /) -> Tuple[Array, ...]:
  23. """
  24. Array API compatible wrapper for :py:func:`np.nonzero <numpy.nonzero>`.
  25. See its docstring for more information.
  26. """
  27. return tuple(Array._new(i) for i in np.nonzero(x._array))
  28. def where(condition: Array, x1: Array, x2: Array, /) -> Array:
  29. """
  30. Array API compatible wrapper for :py:func:`np.where <numpy.where>`.
  31. See its docstring for more information.
  32. """
  33. # Call result type here just to raise on disallowed type combinations
  34. _result_type(x1.dtype, x2.dtype)
  35. x1, x2 = Array._normalize_two_args(x1, x2)
  36. return Array._new(np.where(condition._array, x1._array, x2._array))