decent-array 0.2.6__tar.gz → 0.2.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. {decent_array-0.2.6 → decent_array-0.2.8}/PKG-INFO +1 -1
  2. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/_array.py +4 -4
  3. decent_array-0.2.8/decent_array/_utils.py +37 -0
  4. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/__init__.py +14 -2
  5. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_abstracts/backend.py +51 -2
  6. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/creation.py +38 -3
  7. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/linalg.py +14 -0
  8. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/math.py +25 -0
  9. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_jax/jax_backend.py +48 -7
  10. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_numpy/numpy_backend.py +45 -5
  11. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_pytorch/pytorch_backend.py +71 -7
  12. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_tensorflow/tensorflow_backend.py +78 -9
  13. {decent_array-0.2.6 → decent_array-0.2.8}/pyproject.toml +1 -1
  14. {decent_array-0.2.6 → decent_array-0.2.8}/tests/test_array.py +8 -0
  15. {decent_array-0.2.6 → decent_array-0.2.8}/tests/test_iop_functions.py +158 -0
  16. decent_array-0.2.6/decent_array/_utils.py +0 -19
  17. {decent_array-0.2.6 → decent_array-0.2.8}/.github/CODEOWNERS +0 -0
  18. {decent_array-0.2.6 → decent_array-0.2.8}/.github/dependabot.yml +0 -0
  19. {decent_array-0.2.6 → decent_array-0.2.8}/.github/workflows/ci.yaml +0 -0
  20. {decent_array-0.2.6 → decent_array-0.2.8}/.gitignore +0 -0
  21. {decent_array-0.2.6 → decent_array-0.2.8}/LICENSE +0 -0
  22. {decent_array-0.2.6 → decent_array-0.2.8}/README.md +0 -0
  23. {decent_array-0.2.6 → decent_array-0.2.8}/benchmarks/bench_array.py +0 -0
  24. {decent_array-0.2.6 → decent_array-0.2.8}/benchmarks/bench_common.py +0 -0
  25. {decent_array-0.2.6 → decent_array-0.2.8}/benchmarks/bench_iop.py +0 -0
  26. {decent_array-0.2.6 → decent_array-0.2.8}/benchmarks/profile_hotpath.py +0 -0
  27. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/__init__.py +0 -0
  28. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/_constants.py +0 -0
  29. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/_errors.py +0 -0
  30. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_abstracts/__init__.py +0 -0
  31. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_backend_manager.py +0 -0
  32. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/__init__.py +0 -0
  33. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/bit_operators.py +0 -0
  34. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/comparison.py +0 -0
  35. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/manipulations.py +0 -0
  36. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/operators.py +0 -0
  37. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/reductions.py +0 -0
  38. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/rng.py +0 -0
  39. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_iop/utils.py +0 -0
  40. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_jax/__init__.py +0 -0
  41. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_numpy/__init__.py +0 -0
  42. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_pytorch/__init__.py +0 -0
  43. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/interoperability/_tensorflow/__init__.py +0 -0
  44. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/py.typed +0 -0
  45. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/types/__init__.py +0 -0
  46. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/types/_dtypes.py +0 -0
  47. {decent_array-0.2.6 → decent_array-0.2.8}/decent_array/types/_types.py +0 -0
  48. {decent_array-0.2.6 → decent_array-0.2.8}/docs/Makefile +0 -0
  49. {decent_array-0.2.6 → decent_array-0.2.8}/docs/make.bat +0 -0
  50. {decent_array-0.2.6 → decent_array-0.2.8}/docs/requirements.txt +0 -0
  51. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/_static/custom.css +0 -0
  52. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/_static/logo.png +0 -0
  53. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/_templates/module.rst.jinja +0 -0
  54. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/_templates/package.rst.jinja +0 -0
  55. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/api/decent_array.array.rst +0 -0
  56. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/api/decent_array.interoperability.rst +0 -0
  57. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/api/decent_array.rst +0 -0
  58. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/api/decent_array.types.rst +0 -0
  59. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/author.rst +0 -0
  60. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/conf.py +0 -0
  61. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/developer.rst +0 -0
  62. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/index.rst +0 -0
  63. {decent_array-0.2.6 → decent_array-0.2.8}/docs/source/user.rst +0 -0
  64. {decent_array-0.2.6 → decent_array-0.2.8}/readthedocs.yaml +0 -0
  65. {decent_array-0.2.6 → decent_array-0.2.8}/tests/conftest.py +0 -0
  66. {decent_array-0.2.6 → decent_array-0.2.8}/tests/test_backend_manager.py +0 -0
  67. {decent_array-0.2.6 → decent_array-0.2.8}/tests/test_bindings.py +0 -0
  68. {decent_array-0.2.6 → decent_array-0.2.8}/tests/test_dtypes.py +0 -0
  69. {decent_array-0.2.6 → decent_array-0.2.8}/tests/test_iop_rng.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: decent-array
3
- Version: 0.2.6
3
+ Version: 0.2.8
4
4
  Summary: A library of array operations and linear algebra primitives for interoperability across ML frameworks.
5
5
  Project-URL: Documentation, https://decent-array.readthedocs.io/en/latest/
6
6
  Project-URL: Source, https://github.com/team-decent/decent-array
@@ -11,13 +11,13 @@ Operator contract is *strict*: binary arithmetic and indexing accept either anot
11
11
 
12
12
  Hot-path notes:
13
13
 
14
- * ``__add__``/``__sub__``/``__mul__``/``__truediv__``/``__matmul__``, ``__floordiv__``, ``__mod__``,
14
+ * ``__add__``/``__sub__``/``__mul__``/``__truediv__``, ``__floordiv__``, ``__mod__``,
15
15
  the unary ``__neg__``/``__abs__``/``__pow__``, the comparisons ``__eq__``/``__ne__``/``__lt__``/
16
16
  ``__le__``/``__gt__``/``__ge__`` and the bitwise ``__and__``/``__rand__`` are
17
17
  inlined: every supported framework's tensor implements the equivalent operator
18
18
  natively with numpy-equivalent semantics, so routing through the interoperability layer
19
19
  introduces unnecessary overhead.
20
- * Operators that *do* go through the backend (in-place math, indexing, properties
20
+ * Operators that *do* go through the backend (``__matmul__``, shifts, in-place math, indexing, properties
21
21
  like ``shape``/``transpose``) read the cached ``_backend`` slot.
22
22
  * Overriding ``__eq__`` makes :class:`Array` unhashable (Python clears ``__hash__``
23
23
  automatically). This matches numpy/torch/jax/tf, where element-wise equality is
@@ -144,11 +144,11 @@ class Array:
144
144
 
145
145
  def __matmul__(self, other: Array, /) -> Array:
146
146
  """Return the matrix multiplication of the array with ``other``."""
147
- return Array(self.value @ other.value)
147
+ return self._backend.matmul(self, other)
148
148
 
149
149
  def __rmatmul__(self, other: Array, /) -> Array:
150
150
  """Return the matrix multiplication of ``other`` with the array."""
151
- return Array(other.value @ self.value)
151
+ return self._backend.matmul(other, self)
152
152
 
153
153
  def __pow__(self, other: int | float | complex | Array, /) -> Array:
154
154
  """Exponentiate the array element-wise."""
@@ -0,0 +1,37 @@
1
+ import operator
2
+ from typing import Any
3
+
4
+ from decent_array._array import Array
5
+
6
+
7
+ def unwrap(x: Any) -> Any: # noqa: ANN401
8
+ """
9
+ Return the underlying value of an :class:`Array`, or pass ``x`` through.
10
+
11
+ Typed as ``Any`` because operator dunders may pass either an :class:`Array` or a
12
+ Python scalar; the strict abstract signature would force a ``cast`` at every call
13
+ site without runtime benefit.
14
+ """
15
+ return x.value if type(x) is Array else x
16
+
17
+
18
+ def unwrap_key(key: Any) -> Any: # noqa: ANN401
19
+ """
20
+ Normalize an indexing key for the native framework.
21
+
22
+ Unwraps :class:`Array` items and converts custom ``SupportsIndex`` objects (e.g. ``W[agent_i, agent_j]``)
23
+ to ``int``, since TensorFlow and JAX reject them. Native arrays/scalars (which expose ``shape``) and
24
+ ``bool`` (which numpy treats as a new axis) are passed through unchanged.
25
+ """
26
+ if type(key) is Array:
27
+ return key.value
28
+ if type(key) is tuple:
29
+ return tuple(unwrap_key(k) for k in key)
30
+ if not isinstance(key, int) and hasattr(key, "__index__") and not hasattr(key, "shape"):
31
+ return operator.index(key)
32
+ return key
33
+
34
+
35
+ def is_scalar(x: Array) -> bool:
36
+ """Return True if ``x`` is a 0-dim Array."""
37
+ return x.ndim == 0
@@ -22,8 +22,8 @@ from ._iop.bit_operators import (
22
22
  bitwise_xor,
23
23
  )
24
24
  from ._iop.comparison import equal, greater, greater_equal, less, less_equal, not_equal
25
- from ._iop.creation import eye, ones, ones_like, zeros, zeros_like
26
- from ._iop.linalg import dot, matmul, norm, vecdot, vector_norm
25
+ from ._iop.creation import arange, empty, empty_like, eye, linspace, ones, ones_like, zeros, zeros_like
26
+ from ._iop.linalg import dot, eigvalsh, matmul, norm, solve, vecdot, vector_norm
27
27
  from ._iop.manipulations import (
28
28
  asarray,
29
29
  astype,
@@ -49,10 +49,12 @@ from ._iop.math import (
49
49
  absolute,
50
50
  add,
51
51
  divide,
52
+ exp,
52
53
  floor_divide,
53
54
  isfinite,
54
55
  isinf,
55
56
  isnan,
57
+ logaddexp,
56
58
  multiply,
57
59
  negative,
58
60
  positive,
@@ -60,6 +62,7 @@ from ._iop.math import (
60
62
  remainder,
61
63
  sqrt,
62
64
  subtract,
65
+ where,
63
66
  )
64
67
  from ._iop.operators import argmax, argmin, maximum, sign
65
68
  from ._iop.reductions import all, any, max, mean, min, sum # noqa: A004
@@ -84,6 +87,7 @@ __all__ = [
84
87
  "add",
85
88
  "all",
86
89
  "any",
90
+ "arange",
87
91
  "argmax",
88
92
  "argmin",
89
93
  "asarray",
@@ -103,7 +107,11 @@ __all__ = [
103
107
  "diagonal",
104
108
  "divide",
105
109
  "dot",
110
+ "eigvalsh",
111
+ "empty",
112
+ "empty_like",
106
113
  "equal",
114
+ "exp",
107
115
  "expand_dims",
108
116
  "eye",
109
117
  "floor_divide",
@@ -119,6 +127,8 @@ __all__ = [
119
127
  "isnan",
120
128
  "less",
121
129
  "less_equal",
130
+ "linspace",
131
+ "logaddexp",
122
132
  "matmul",
123
133
  "matrix_transpose",
124
134
  "max",
@@ -144,6 +154,7 @@ __all__ = [
144
154
  "shape",
145
155
  "sign",
146
156
  "size",
157
+ "solve",
147
158
  "sqrt",
148
159
  "squeeze",
149
160
  "stack",
@@ -156,6 +167,7 @@ __all__ = [
156
167
  "unsqueeze",
157
168
  "vecdot",
158
169
  "vector_norm",
170
+ "where",
159
171
  "zeros",
160
172
  "zeros_like",
161
173
  ]
@@ -42,6 +42,14 @@ class Backend(ABC):
42
42
 
43
43
  # Array creation ------------------------------------------------------
44
44
 
45
+ @abstractmethod
46
+ def empty(self, shape: int | tuple[int, ...]) -> Array:
47
+ """Create an uninitialized array with the given shape."""
48
+
49
+ @abstractmethod
50
+ def empty_like(self, x: Array, /) -> Array:
51
+ """Create an uninitialized array with the same shape as ``x``."""
52
+
45
53
  @abstractmethod
46
54
  def zeros(self, shape: int | tuple[int, ...]) -> Array:
47
55
  """Create an array of zeros with the given shape."""
@@ -59,8 +67,24 @@ class Backend(ABC):
59
67
  """Create an array of ones matching the shape and type of ``x``."""
60
68
 
61
69
  @abstractmethod
62
- def eye(self, n: int) -> Array:
63
- """Create an ``n x n`` identity matrix."""
70
+ def eye(self, n_rows: int, n_cols: int | None = None, /, *, k: int = 0) -> Array:
71
+ """Create a two-dimensional array with ones on the diagonal at offset ``k``."""
72
+
73
+ @abstractmethod
74
+ def arange(self, start: int | float, /, stop: int | float | None = None, step: int | float = 1) -> Array:
75
+ """Return evenly spaced values within a half-open interval."""
76
+
77
+ @abstractmethod
78
+ def linspace(
79
+ self,
80
+ start: int | float | complex,
81
+ stop: int | float | complex,
82
+ /,
83
+ num: int,
84
+ *,
85
+ endpoint: bool = True,
86
+ ) -> Array:
87
+ """Return evenly spaced numbers over a specified interval."""
64
88
 
65
89
  @abstractmethod
66
90
  def device_to_native(self, device: Devices) -> Any: # noqa: ANN401
@@ -186,6 +210,14 @@ class Backend(ABC):
186
210
  ) -> Array:
187
211
  """Compute the norm of ``x``."""
188
212
 
213
+ @abstractmethod
214
+ def solve(self, x1: Array, x2: Array) -> Array:
215
+ """Solve the linear system ``x1 @ solution = x2``."""
216
+
217
+ @abstractmethod
218
+ def eigvalsh(self, x: Array) -> Array:
219
+ """Return eigenvalues of a symmetric/Hermitian matrix."""
220
+
189
221
  # Math reductions -----------------------------------------------------
190
222
 
191
223
  @abstractmethod
@@ -284,6 +316,23 @@ class Backend(ABC):
284
316
  def sqrt(self, x: Array) -> Array:
285
317
  """Element-wise square root."""
286
318
 
319
+ @abstractmethod
320
+ def exp(self, x: Array) -> Array:
321
+ """Element-wise exponential."""
322
+
323
+ @abstractmethod
324
+ def logaddexp(self, x1: int | float | Array, x2: int | float | Array) -> Array:
325
+ """Element-wise log(exp(x1) + exp(x2)) computed stably."""
326
+
327
+ @abstractmethod
328
+ def where(
329
+ self,
330
+ condition: Array,
331
+ x1: bool | int | float | complex | Array,
332
+ x2: bool | int | float | complex | Array,
333
+ ) -> Array:
334
+ """Select elements from ``x1`` or ``x2`` according to ``condition``."""
335
+
287
336
  @abstractmethod
288
337
  def isfinite(self, x: Array) -> Array:
289
338
  """Element-wise test for finite values."""
@@ -61,8 +61,43 @@ def ones_like(x: Array) -> Array:
61
61
  return _BACKEND_INSTANCE.ones_like(x)
62
62
 
63
63
 
64
- def eye(n: int) -> Array:
65
- """Create an ``n x n`` identity matrix."""
64
+ def empty(shape: int | tuple[int, ...]) -> Array:
65
+ """Create an uninitialized array with the given shape."""
66
66
  if _BACKEND_INSTANCE is None:
67
67
  raise no_backend_error
68
- return _BACKEND_INSTANCE.eye(n)
68
+ return _BACKEND_INSTANCE.empty(shape)
69
+
70
+
71
+ def empty_like(x: Array, /) -> Array:
72
+ """Create an uninitialized array with the same shape as ``x``."""
73
+ if _BACKEND_INSTANCE is None:
74
+ raise no_backend_error
75
+ return _BACKEND_INSTANCE.empty_like(x)
76
+
77
+
78
+ def eye(n_rows: int, n_cols: int | None = None, /, *, k: int = 0) -> Array:
79
+ """Create a two-dimensional array with ones on the diagonal at offset ``k``."""
80
+ if _BACKEND_INSTANCE is None:
81
+ raise no_backend_error
82
+ return _BACKEND_INSTANCE.eye(n_rows, n_cols, k=k)
83
+
84
+
85
+ def arange(start: int | float, /, stop: int | float | None = None, step: int | float = 1) -> Array:
86
+ """Return evenly spaced values within a half-open interval."""
87
+ if _BACKEND_INSTANCE is None:
88
+ raise no_backend_error
89
+ return _BACKEND_INSTANCE.arange(start, stop, step)
90
+
91
+
92
+ def linspace(
93
+ start: int | float | complex,
94
+ stop: int | float | complex,
95
+ /,
96
+ num: int,
97
+ *,
98
+ endpoint: bool = True,
99
+ ) -> Array:
100
+ """Return evenly spaced numbers over a specified interval."""
101
+ if _BACKEND_INSTANCE is None:
102
+ raise no_backend_error
103
+ return _BACKEND_INSTANCE.linspace(start, stop, num, endpoint=endpoint)
@@ -84,3 +84,17 @@ def norm(
84
84
  if _BACKEND_INSTANCE is None:
85
85
  raise no_backend_error
86
86
  return _BACKEND_INSTANCE.vector_norm(x, axis, keepdims, ord)
87
+
88
+
89
+ def solve(x1: Array, x2: Array) -> Array:
90
+ """Solve the linear system ``x1 @ solution = x2``."""
91
+ if _BACKEND_INSTANCE is None:
92
+ raise no_backend_error
93
+ return _BACKEND_INSTANCE.solve(x1, x2)
94
+
95
+
96
+ def eigvalsh(x: Array) -> Array:
97
+ """Return eigenvalues of a symmetric/Hermitian matrix."""
98
+ if _BACKEND_INSTANCE is None:
99
+ raise no_backend_error
100
+ return _BACKEND_INSTANCE.eigvalsh(x)
@@ -149,6 +149,31 @@ def sqrt(x: Array) -> Array:
149
149
  return _BACKEND_INSTANCE.sqrt(x)
150
150
 
151
151
 
152
+ def exp(x: Array) -> Array:
153
+ """Element-wise exponential."""
154
+ if _BACKEND_INSTANCE is None:
155
+ raise no_backend_error
156
+ return _BACKEND_INSTANCE.exp(x)
157
+
158
+
159
+ def logaddexp(x1: int | float | Array, x2: int | float | Array) -> Array:
160
+ """Element-wise log(exp(x1) + exp(x2)) computed stably."""
161
+ if _BACKEND_INSTANCE is None:
162
+ raise no_backend_error
163
+ return _BACKEND_INSTANCE.logaddexp(x1, x2)
164
+
165
+
166
+ def where(
167
+ condition: Array,
168
+ x1: bool | int | float | complex | Array,
169
+ x2: bool | int | float | complex | Array,
170
+ ) -> Array:
171
+ """Select elements from ``x1`` or ``x2`` according to ``condition``."""
172
+ if _BACKEND_INSTANCE is None:
173
+ raise no_backend_error
174
+ return _BACKEND_INSTANCE.where(condition, x1, x2)
175
+
176
+
152
177
  def isfinite(x: Array) -> Array:
153
178
  """Element-wise test for finite values."""
154
179
  if _BACKEND_INSTANCE is None:
@@ -27,7 +27,7 @@ from decent_array._errors import (
27
27
  UnsupportedDTypeCreationError,
28
28
  stack_empty_error,
29
29
  )
30
- from decent_array._utils import is_scalar, unwrap
30
+ from decent_array._utils import is_scalar, unwrap, unwrap_key
31
31
  from decent_array.interoperability._abstracts import Backend
32
32
  from decent_array.interoperability._backend_manager import register_backend
33
33
  from decent_array.types import ArrayKey, ArrayLike, ArrayTypes, Devices, Frameworks
@@ -46,6 +46,12 @@ class JaxBackend(Backend):
46
46
 
47
47
  # Array creation
48
48
 
49
+ def empty(self, shape: int | tuple[int, ...]) -> Array:
50
+ return Array(jnp.empty(shape, device=self._native_device))
51
+
52
+ def empty_like(self, x: Array, /) -> Array:
53
+ return Array(jnp.empty_like(x.value, device=self._native_device))
54
+
49
55
  def zeros(self, shape: int | tuple[int, ...]) -> Array:
50
56
  return Array(jnp.zeros(shape, device=self._native_device))
51
57
 
@@ -58,8 +64,22 @@ class JaxBackend(Backend):
58
64
  def ones_like(self, x: Array) -> Array:
59
65
  return Array(jnp.ones_like(x.value))
60
66
 
61
- def eye(self, n: int) -> Array:
62
- return Array(jnp.eye(n, device=self._native_device))
67
+ def eye(self, n_rows: int, n_cols: int | None = None, /, *, k: int = 0) -> Array:
68
+ return Array(jnp.eye(n_rows, n_cols, k=k, device=self._native_device))
69
+
70
+ def arange(self, start: int | float, /, stop: int | float | None = None, step: int | float = 1) -> Array:
71
+ return Array(jnp.arange(start, stop, step, device=self._native_device))
72
+
73
+ def linspace(
74
+ self,
75
+ start: int | float | complex,
76
+ stop: int | float | complex,
77
+ /,
78
+ num: int,
79
+ *,
80
+ endpoint: bool = True,
81
+ ) -> Array:
82
+ return Array(jnp.linspace(start, stop, num, endpoint=endpoint, device=self._native_device))
63
83
 
64
84
  def device_to_native(self, device: Devices) -> jax.Device:
65
85
  if device == Devices.CPU:
@@ -174,6 +194,12 @@ class JaxBackend(Backend):
174
194
  ) -> Array:
175
195
  return Array(jnp.linalg.norm(x.value, ord=ord, axis=axis, keepdims=keepdims))
176
196
 
197
+ def solve(self, x1: Array, x2: Array) -> Array:
198
+ return Array(jnp.linalg.solve(x1.value, x2.value))
199
+
200
+ def eigvalsh(self, x: Array) -> Array:
201
+ return Array(jnp.linalg.eigvalsh(x.value))
202
+
177
203
  # Math reductions
178
204
 
179
205
  def sum(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
@@ -256,6 +282,20 @@ class JaxBackend(Backend):
256
282
  def sqrt(self, x: Array) -> Array:
257
283
  return Array(jnp.sqrt(x.value))
258
284
 
285
+ def exp(self, x: Array) -> Array:
286
+ return Array(jnp.exp(x.value))
287
+
288
+ def logaddexp(self, x1: int | float | Array, x2: int | float | Array) -> Array:
289
+ return Array(jnp.logaddexp(unwrap(x1), unwrap(x2)))
290
+
291
+ def where(
292
+ self,
293
+ condition: Array,
294
+ x1: bool | int | float | complex | Array,
295
+ x2: bool | int | float | complex | Array,
296
+ ) -> Array:
297
+ return Array(jnp.where(condition.value, unwrap(x1), unwrap(x2)))
298
+
259
299
  def isfinite(self, x: Array) -> Array:
260
300
  """Element-wise test for finite values."""
261
301
  return Array(jnp.isfinite(x.value))
@@ -344,10 +384,10 @@ class JaxBackend(Backend):
344
384
 
345
385
  def set_item(self, x: Array, key: ArrayKey, value: bool | int | float | complex | Array) -> None:
346
386
  # JAX arrays are immutable; rebind the wrapper to a new array with `key` updated.
347
- x.value = x.value.at[key].set(unwrap(value))
387
+ x.value = x.value.at[unwrap_key(key)].set(unwrap(value))
348
388
 
349
389
  def get_item(self, x: Array, key: ArrayKey) -> Array:
350
- return Array(x.value[key])
390
+ return Array(x.value[unwrap_key(key)])
351
391
 
352
392
  # RNG
353
393
 
@@ -391,8 +431,9 @@ class JaxBackend(Backend):
391
431
 
392
432
  def _next_key(self) -> jax.Array:
393
433
  """Split the stored key, advance state, return a sub-key for one draw."""
394
- self._key, sub = jax.random.split(self._key)
395
- return cast("jax.Array", sub)
434
+ self._key, raw_sub = jax.random.split(self._key)
435
+ sub: jax.Array = raw_sub
436
+ return sub
396
437
 
397
438
  # Dtypes
398
439
 
@@ -22,7 +22,7 @@ from decent_array._errors import (
22
22
  UnsupportedDTypeCreationError,
23
23
  stack_empty_error,
24
24
  )
25
- from decent_array._utils import is_scalar, unwrap
25
+ from decent_array._utils import is_scalar, unwrap, unwrap_key
26
26
  from decent_array.interoperability._abstracts import Backend
27
27
  from decent_array.interoperability._backend_manager import register_backend
28
28
  from decent_array.types import ArrayKey, ArrayLike, ArrayTypes, Devices, Frameworks
@@ -40,6 +40,12 @@ class NumpyBackend(Backend):
40
40
 
41
41
  # Array creation
42
42
 
43
+ def empty(self, shape: int | tuple[int, ...]) -> Array:
44
+ return Array(np.empty(shape))
45
+
46
+ def empty_like(self, x: Array, /) -> Array:
47
+ return Array(np.empty_like(x.value))
48
+
43
49
  def zeros(self, shape: int | tuple[int, ...]) -> Array:
44
50
  return Array(np.zeros(shape))
45
51
 
@@ -52,8 +58,22 @@ class NumpyBackend(Backend):
52
58
  def ones_like(self, x: Array) -> Array:
53
59
  return Array(np.ones_like(x.value))
54
60
 
55
- def eye(self, n: int) -> Array:
56
- return Array(np.eye(n))
61
+ def eye(self, n_rows: int, n_cols: int | None = None, /, *, k: int = 0) -> Array:
62
+ return Array(np.eye(n_rows, n_cols, k=k))
63
+
64
+ def arange(self, start: int | float, /, stop: int | float | None = None, step: int | float = 1) -> Array:
65
+ return Array(np.arange(start, stop, step))
66
+
67
+ def linspace(
68
+ self,
69
+ start: int | float | complex,
70
+ stop: int | float | complex,
71
+ /,
72
+ num: int,
73
+ *,
74
+ endpoint: bool = True,
75
+ ) -> Array:
76
+ return Array(np.linspace(start, stop, num, endpoint=endpoint))
57
77
 
58
78
  def device_to_native(self, device: Devices) -> Any: # noqa: ANN401
59
79
  # NumPy has no explicit device management; surface the request unchanged.
@@ -169,6 +189,12 @@ class NumpyBackend(Backend):
169
189
  # but is still typed as int | tuple[int, int] | None, hence the ignore
170
190
  return Array(np.linalg.vector_norm(x.value, ord=ord, axis=axis, keepdims=keepdims)) # type: ignore[arg-type]
171
191
 
192
+ def solve(self, x1: Array, x2: Array) -> Array:
193
+ return Array(np.linalg.solve(x1.value, x2.value))
194
+
195
+ def eigvalsh(self, x: Array) -> Array:
196
+ return Array(np.linalg.eigvalsh(x.value))
197
+
172
198
  # Math reductions
173
199
 
174
200
  def sum(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
@@ -268,6 +294,20 @@ class NumpyBackend(Backend):
268
294
  def sqrt(self, x: Array) -> Array:
269
295
  return Array(np.sqrt(x.value))
270
296
 
297
+ def exp(self, x: Array) -> Array:
298
+ return Array(np.exp(x.value))
299
+
300
+ def logaddexp(self, x1: int | float | Array, x2: int | float | Array) -> Array:
301
+ return Array(np.logaddexp(unwrap(x1), unwrap(x2)))
302
+
303
+ def where(
304
+ self,
305
+ condition: Array,
306
+ x1: bool | int | float | complex | Array,
307
+ x2: bool | int | float | complex | Array,
308
+ ) -> Array:
309
+ return Array(np.where(condition.value, unwrap(x1), unwrap(x2)))
310
+
271
311
  def isfinite(self, x: Array) -> Array:
272
312
  """Element-wise test for finite values."""
273
313
  return Array(np.isfinite(x.value))
@@ -361,10 +401,10 @@ class NumpyBackend(Backend):
361
401
  return Array(np.argmin(v, axis=axis))
362
402
 
363
403
  def set_item(self, x: Array, key: ArrayKey, value: bool | int | float | complex | Array) -> None:
364
- x.value[key] = unwrap(value)
404
+ x.value[unwrap_key(key)] = unwrap(value)
365
405
 
366
406
  def get_item(self, x: Array, key: ArrayKey) -> Array:
367
- return Array(x.value[key])
407
+ return Array(x.value[unwrap_key(key)])
368
408
 
369
409
  # RNG
370
410
 
@@ -16,7 +16,7 @@ from numpy.typing import NDArray
16
16
 
17
17
  from decent_array import Array
18
18
  from decent_array._errors import MatrixTransposeError, NDimError, UnsupportedDTypeCreationError, stack_empty_error
19
- from decent_array._utils import is_scalar, unwrap
19
+ from decent_array._utils import is_scalar, unwrap, unwrap_key
20
20
  from decent_array.interoperability._abstracts import Backend
21
21
  from decent_array.interoperability._backend_manager import register_backend
22
22
  from decent_array.types import ArrayKey, ArrayLike, ArrayTypes, Devices, Frameworks
@@ -33,6 +33,12 @@ class PyTorchBackend(Backend):
33
33
 
34
34
  # Array creation
35
35
 
36
+ def empty(self, shape: int | tuple[int, ...]) -> Array:
37
+ return Array(torch.empty(shape, device=self._native_device))
38
+
39
+ def empty_like(self, x: Array, /) -> Array:
40
+ return Array(torch.empty_like(x.value))
41
+
36
42
  def zeros(self, shape: int | tuple[int, ...]) -> Array:
37
43
  return Array(torch.zeros(shape, device=self._native_device))
38
44
 
@@ -45,8 +51,40 @@ class PyTorchBackend(Backend):
45
51
  def ones_like(self, x: Array) -> Array:
46
52
  return Array(torch.ones_like(x.value))
47
53
 
48
- def eye(self, n: int) -> Array:
49
- return Array(torch.eye(n, device=self._native_device))
54
+ def eye(self, n_rows: int, n_cols: int | None = None, /, *, k: int = 0) -> Array:
55
+ columns = n_rows if n_cols is None else n_cols
56
+ result = torch.zeros((n_rows, columns), device=self._native_device)
57
+ if k >= 0:
58
+ length = min(n_rows, columns - k)
59
+ if length > 0:
60
+ indices = torch.arange(length, device=self._native_device)
61
+ result[indices, indices + k] = 1
62
+ else:
63
+ length = min(n_rows + k, columns)
64
+ if length > 0:
65
+ indices = torch.arange(length, device=self._native_device)
66
+ result[indices - k, indices] = 1
67
+ return Array(result)
68
+
69
+ def arange(self, start: int | float, /, stop: int | float | None = None, step: int | float = 1) -> Array:
70
+ if stop is None:
71
+ return Array(torch.arange(start, device=self._native_device))
72
+ return Array(torch.arange(start, stop, step, device=self._native_device))
73
+
74
+ def linspace(
75
+ self,
76
+ start: int | float | complex,
77
+ stop: int | float | complex,
78
+ /,
79
+ num: int,
80
+ *,
81
+ endpoint: bool = True,
82
+ ) -> Array:
83
+ if endpoint:
84
+ return Array(torch.linspace(start, stop, num, device=self._native_device))
85
+ if num == 0:
86
+ return Array(torch.empty(0, device=self._native_device))
87
+ return Array(torch.linspace(start, stop, num + 1, device=self._native_device)[:-1])
50
88
 
51
89
  def device_to_native(self, device: Devices) -> str:
52
90
  if device == Devices.CPU:
@@ -176,6 +214,16 @@ class PyTorchBackend(Backend):
176
214
  ) -> Array:
177
215
  return Array(torch.linalg.norm(x.value, ord=ord, axis=axis, keepdim=keepdims))
178
216
 
217
+ def solve(self, x1: Array, x2: Array) -> Array:
218
+ if x1.value.device.type == "mps":
219
+ return Array(torch.linalg.solve(x1.value.cpu(), x2.value.cpu()).to(x1.value.device))
220
+ return Array(torch.linalg.solve(x1.value, x2.value))
221
+
222
+ def eigvalsh(self, x: Array) -> Array:
223
+ if x.value.device.type == "mps":
224
+ return Array(torch.linalg.eigvalsh(x.value.cpu()).to(x.value.device))
225
+ return Array(torch.linalg.eigvalsh(x.value))
226
+
179
227
  # Math reductions
180
228
 
181
229
  def sum(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
@@ -186,9 +234,11 @@ class PyTorchBackend(Backend):
186
234
 
187
235
  def mean(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
188
236
  v = x.value
237
+ # torch.mean refuses bool/int inputs ("could not infer output dtype"); promote to float like numpy.
238
+ out_dtype = None if v.is_floating_point() or v.is_complex() else torch.get_default_dtype()
189
239
  if axis is None:
190
- return Array(torch.mean(v))
191
- return Array(torch.mean(v, dim=axis, keepdim=keepdims))
240
+ return Array(torch.mean(v, dtype=out_dtype))
241
+ return Array(torch.mean(v, dim=axis, keepdim=keepdims, dtype=out_dtype))
192
242
 
193
243
  def min(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
194
244
  v = x.value
@@ -269,6 +319,20 @@ class PyTorchBackend(Backend):
269
319
  def sqrt(self, x: Array) -> Array:
270
320
  return Array(torch.sqrt(x.value))
271
321
 
322
+ def exp(self, x: Array) -> Array:
323
+ return Array(torch.exp(x.value))
324
+
325
+ def logaddexp(self, x1: int | float | Array, x2: int | float | Array) -> Array:
326
+ return Array(torch.logaddexp(unwrap(x1), unwrap(x2)))
327
+
328
+ def where(
329
+ self,
330
+ condition: Array,
331
+ x1: bool | int | float | complex | Array,
332
+ x2: bool | int | float | complex | Array,
333
+ ) -> Array:
334
+ return Array(torch.where(condition.value, unwrap(x1), unwrap(x2)))
335
+
272
336
  def isfinite(self, x: Array) -> Array:
273
337
  """Element-wise test for finite values."""
274
338
  return Array(torch.isfinite(x.value))
@@ -364,10 +428,10 @@ class PyTorchBackend(Backend):
364
428
  return Array(torch.argmin(x.value, dim=axis, keepdim=keepdims))
365
429
 
366
430
  def set_item(self, x: Array, key: ArrayKey, value: bool | int | float | complex | Array) -> None:
367
- x.value[key] = unwrap(value)
431
+ x.value[unwrap_key(key)] = unwrap(value)
368
432
 
369
433
  def get_item(self, x: Array, key: ArrayKey) -> Array:
370
- return Array(x.value[key])
434
+ return Array(x.value[unwrap_key(key)])
371
435
 
372
436
  # RNG
373
437
 
@@ -25,7 +25,7 @@ from decent_array._errors import (
25
25
  UnsupportedDTypeCreationError,
26
26
  stack_empty_error,
27
27
  )
28
- from decent_array._utils import is_scalar, unwrap
28
+ from decent_array._utils import is_scalar, unwrap, unwrap_key
29
29
  from decent_array.interoperability._abstracts import Backend
30
30
  from decent_array.interoperability._backend_manager import register_backend
31
31
  from decent_array.types import ArrayKey, ArrayLike, ArrayTypes, Devices, Frameworks
@@ -44,6 +44,14 @@ class TensorflowBackend(Backend):
44
44
 
45
45
  # Array creation
46
46
 
47
+ def empty(self, shape: int | tuple[int, ...]) -> Array:
48
+ with tf.device(self._native_device):
49
+ return Array(tf.experimental.numpy.empty(shape, dtype=tf.float32))
50
+
51
+ def empty_like(self, x: Array, /) -> Array:
52
+ with tf.device(self._native_device):
53
+ return Array(tf.experimental.numpy.empty_like(x.value))
54
+
47
55
  def zeros(self, shape: int | tuple[int, ...]) -> Array:
48
56
  with tf.device(self._native_device):
49
57
  return Array(tf.zeros(shape))
@@ -58,9 +66,25 @@ class TensorflowBackend(Backend):
58
66
  def ones_like(self, x: Array) -> Array:
59
67
  return Array(tf.ones_like(x.value))
60
68
 
61
- def eye(self, n: int) -> Array:
69
+ def eye(self, n_rows: int, n_cols: int | None = None, /, *, k: int = 0) -> Array:
70
+ with tf.device(self._native_device):
71
+ return Array(tf.experimental.numpy.eye(n_rows, n_cols, k=k, dtype=tf.float32))
72
+
73
+ def arange(self, start: int | float, /, stop: int | float | None = None, step: int | float = 1) -> Array:
62
74
  with tf.device(self._native_device):
63
- return Array(tf.eye(n))
75
+ return Array(tf.experimental.numpy.arange(start, stop, step))
76
+
77
+ def linspace(
78
+ self,
79
+ start: int | float | complex,
80
+ stop: int | float | complex,
81
+ /,
82
+ num: int,
83
+ *,
84
+ endpoint: bool = True,
85
+ ) -> Array:
86
+ with tf.device(self._native_device):
87
+ return Array(tf.experimental.numpy.linspace(start, stop, num=num, endpoint=endpoint))
64
88
 
65
89
  def device_to_native(self, device: Devices) -> str:
66
90
  if device in {Devices.CPU, Devices.GPU}:
@@ -197,13 +221,26 @@ class TensorflowBackend(Backend):
197
221
  axis = axis if axis is not None else (-2, -1) if v.ndim == 2 else None
198
222
  return Array(tf.norm(v, ord=ord, axis=axis, keepdims=keepdims))
199
223
 
224
+ def solve(self, x1: Array, x2: Array) -> Array:
225
+ rhs = x2.value
226
+ if rhs.shape.rank == x1.value.shape.rank - 1:
227
+ return Array(tf.squeeze(tf.linalg.solve(x1.value, tf.expand_dims(rhs, axis=-1)), axis=-1))
228
+ return Array(tf.linalg.solve(x1.value, rhs))
229
+
230
+ def eigvalsh(self, x: Array) -> Array:
231
+ return Array(tf.linalg.eigvalsh(x.value))
232
+
200
233
  # Math reductions
201
234
 
202
235
  def sum(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
203
236
  return Array(tf.reduce_sum(x.value, axis=axis, keepdims=keepdims))
204
237
 
205
238
  def mean(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
206
- return Array(tf.reduce_mean(x.value, axis=axis, keepdims=keepdims))
239
+ # tf.reduce_mean rejects bool and truncates integer means; promote to float like numpy.
240
+ v = x.value
241
+ if not v.dtype.is_floating and not v.dtype.is_complex:
242
+ v = tf.cast(v, tf.float32)
243
+ return Array(tf.reduce_mean(v, axis=axis, keepdims=keepdims))
207
244
 
208
245
  def min(self, x: Array, axis: int | tuple[int, ...] | None = None, keepdims: bool = False) -> Array:
209
246
  return Array(tf.reduce_min(x.value, axis=axis, keepdims=keepdims))
@@ -279,17 +316,49 @@ class TensorflowBackend(Backend):
279
316
  def sqrt(self, x: Array) -> Array:
280
317
  return Array(tf.sqrt(x.value))
281
318
 
319
+ def exp(self, x: Array) -> Array:
320
+ return Array(tf.exp(x.value))
321
+
322
+ def logaddexp(self, x1: int | float | Array, x2: int | float | Array) -> Array:
323
+ return Array(tf.keras.ops.logaddexp(unwrap(x1), unwrap(x2)))
324
+
325
+ def where(
326
+ self,
327
+ condition: Array,
328
+ x1: bool | int | float | complex | Array,
329
+ x2: bool | int | float | complex | Array,
330
+ ) -> Array:
331
+ return Array(tf.where(condition.value, unwrap(x1), unwrap(x2)))
332
+
333
+ # tf.math.is_* only accept real floats: complex values are checked component-wise (numpy semantics), and
334
+ # integer/bool values are always finite and never inf/nan.
335
+
282
336
  def isfinite(self, x: Array) -> Array:
283
337
  """Element-wise test for finite values."""
284
- return Array(tf.math.is_finite(x.value))
338
+ v = x.value
339
+ if v.dtype.is_complex:
340
+ return Array(tf.math.is_finite(tf.math.real(v)) & tf.math.is_finite(tf.math.imag(v)))
341
+ if not v.dtype.is_floating:
342
+ return Array(tf.ones_like(v, dtype=tf.bool))
343
+ return Array(tf.math.is_finite(v))
285
344
 
286
345
  def isinf(self, x: Array) -> Array:
287
346
  """Element-wise test for infinite values."""
288
- return Array(tf.math.is_inf(x.value))
347
+ v = x.value
348
+ if v.dtype.is_complex:
349
+ return Array(tf.math.is_inf(tf.math.real(v)) | tf.math.is_inf(tf.math.imag(v)))
350
+ if not v.dtype.is_floating:
351
+ return Array(tf.zeros_like(v, dtype=tf.bool))
352
+ return Array(tf.math.is_inf(v))
289
353
 
290
354
  def isnan(self, x: Array) -> Array:
291
355
  """Element-wise test for NaN values."""
292
- return Array(tf.math.is_nan(x.value))
356
+ v = x.value
357
+ if v.dtype.is_complex:
358
+ return Array(tf.math.is_nan(tf.math.real(v)) | tf.math.is_nan(tf.math.imag(v)))
359
+ if not v.dtype.is_floating:
360
+ return Array(tf.zeros_like(v, dtype=tf.bool))
361
+ return Array(tf.math.is_nan(v))
293
362
 
294
363
  # Comparisons
295
364
 
@@ -395,12 +464,12 @@ class TensorflowBackend(Backend):
395
464
  # that hammer set_item in tight loops should consider numpy or pytorch.
396
465
  original = x.value
397
466
  np_array = original.numpy().copy()
398
- np_array[key] = np.asarray(unwrap(value))
467
+ np_array[unwrap_key(key)] = np.asarray(unwrap(value))
399
468
  with tf.device(self._native_device):
400
469
  x.value = tf.convert_to_tensor(np_array, dtype=original.dtype)
401
470
 
402
471
  def get_item(self, x: Array, key: ArrayKey) -> Array:
403
- return Array(x.value[key])
472
+ return Array(x.value[unwrap_key(key)])
404
473
 
405
474
  # RNG
406
475
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "decent-array"
3
- version = "0.2.6"
3
+ version = "0.2.8"
4
4
  authors = [{name = "Simon Granström"}, {name = "Nicola Bastianello"}]
5
5
  maintainers = [{name = "Team Decent"}]
6
6
  description = "A library of array operations and linear algebra primitives for interoperability across ML frameworks."
@@ -170,6 +170,14 @@ def test_matmul_array(backend: tuple) -> None:
170
170
  np.testing.assert_allclose(_np(a @ b), expected)
171
171
 
172
172
 
173
+ def test_matmul_vector(backend: tuple) -> None:
174
+ mat = _create_array([[1.0, 2.0], [3.0, 4.0]])
175
+ vec = _create_array([5.0, 6.0])
176
+ np.testing.assert_allclose(_np(mat @ vec), [17.0, 39.0])
177
+ np.testing.assert_allclose(_np(vec @ mat), [23.0, 34.0])
178
+ np.testing.assert_allclose(_np(vec @ vec), 61.0)
179
+
180
+
173
181
  def test_rmatmul_explicit_call(backend: tuple) -> None:
174
182
  # Python dispatch never picks Array.__rmatmul__ when both operands are Array,
175
183
  # so call it directly to exercise the code path.
@@ -42,11 +42,110 @@ def test_ones_like(backend: tuple) -> None:
42
42
  np.testing.assert_allclose(_np(arr), np.ones((2, 3)))
43
43
 
44
44
 
45
+ def test_empty(backend: tuple) -> None:
46
+ arr = iop.empty((2, 3))
47
+ assert iop.shape(arr) == (2, 3)
48
+
49
+
50
+ def test_empty_scalar_shape(backend: tuple) -> None:
51
+ arr = iop.empty(4)
52
+ assert iop.shape(arr) == (4,)
53
+
54
+
55
+ def test_empty_like(backend: tuple) -> None:
56
+ src = iop.from_numpy(np.ones((2, 3), dtype=np.float32))
57
+ arr = iop.empty_like(src)
58
+ assert iop.shape(arr) == iop.shape(src)
59
+ assert arr.dtype == src.dtype
60
+
61
+
45
62
  def test_eye(backend: tuple) -> None:
46
63
  arr = iop.eye(3)
47
64
  np.testing.assert_allclose(_np(arr), np.eye(3))
48
65
 
49
66
 
67
+ def test_eye_rectangular(backend: tuple) -> None:
68
+ np.testing.assert_allclose(_np(iop.eye(2, 4)), np.eye(2, 4))
69
+
70
+
71
+ def test_eye_positive_offset(backend: tuple) -> None:
72
+ np.testing.assert_allclose(_np(iop.eye(3, 4, k=1)), np.eye(3, 4, k=1))
73
+
74
+
75
+ def test_eye_negative_offset(backend: tuple) -> None:
76
+ np.testing.assert_allclose(_np(iop.eye(4, 3, k=-1)), np.eye(4, 3, k=-1))
77
+
78
+
79
+ def test_arange(backend: tuple) -> None:
80
+ np.testing.assert_array_equal(_np(iop.arange(5)), np.arange(5))
81
+
82
+
83
+ def test_arange_start_stop_step(backend: tuple) -> None:
84
+ np.testing.assert_array_equal(_np(iop.arange(1, 8, 2)), np.arange(1, 8, 2))
85
+
86
+
87
+ def test_arange_negative_step(backend: tuple) -> None:
88
+ np.testing.assert_array_equal(_np(iop.arange(5, 0, -2)), np.arange(5, 0, -2))
89
+
90
+
91
+ def test_arange_float(backend: tuple) -> None:
92
+ np.testing.assert_allclose(_np(iop.arange(0.0, 1.0, 0.25)), np.arange(0.0, 1.0, 0.25))
93
+
94
+
95
+ def test_linspace(backend: tuple) -> None:
96
+ np.testing.assert_allclose(_np(iop.linspace(0.0, 1.0, 5)), np.linspace(0.0, 1.0, 5))
97
+
98
+
99
+ def test_linspace_without_endpoint(backend: tuple) -> None:
100
+ np.testing.assert_allclose(_np(iop.linspace(0.0, 1.0, 5, endpoint=False)), np.linspace(0.0, 1.0, 5, endpoint=False))
101
+
102
+
103
+ def test_linspace_zero_samples(backend: tuple) -> None:
104
+ assert iop.shape(iop.linspace(0.0, 1.0, 0)) == (0,)
105
+
106
+
107
+ def test_exp(backend: tuple) -> None:
108
+ arr = iop.exp(iop.from_numpy(np.array([-2.0, 0.0, 2.0], dtype=np.float32)))
109
+ np.testing.assert_allclose(_np(arr), np.exp([-2.0, 0.0, 2.0]))
110
+
111
+
112
+ def test_where_arrays_and_broadcasting(backend: tuple) -> None:
113
+ condition = iop.from_numpy(np.array([[True], [False]], dtype=np.bool_))
114
+ x1 = iop.from_numpy(np.array([1.0, 2.0, 3.0], dtype=np.float32))
115
+ x2 = iop.from_numpy(np.array([4.0, 5.0, 6.0], dtype=np.float32))
116
+ np.testing.assert_array_equal(_np(iop.where(condition, x1, x2)), [[1, 2, 3], [4, 5, 6]])
117
+
118
+
119
+ def test_where_scalar_and_array_operands(backend: tuple) -> None:
120
+ condition = iop.from_numpy(np.array([True, False], dtype=np.bool_))
121
+ x = iop.from_numpy(np.array([1.0, 2.0], dtype=np.float32))
122
+ np.testing.assert_array_equal(_np(iop.where(condition, x, 0.0)), [1.0, 0.0])
123
+ np.testing.assert_array_equal(_np(iop.where(condition, -1.0, x)), [-1.0, 2.0])
124
+
125
+
126
+ def test_logaddexp_is_stable(backend: tuple) -> None:
127
+ values = iop.from_numpy(np.array([1000.0, -1000.0], dtype=np.float32))
128
+ result = iop.logaddexp(values, values)
129
+ np.testing.assert_allclose(_np(result), [1000.0 + np.log(2.0), -1000.0 + np.log(2.0)])
130
+
131
+
132
+ def test_logaddexp_infinities(backend: tuple) -> None:
133
+ values = iop.from_numpy(np.array([np.inf, -np.inf], dtype=np.float32))
134
+ np.testing.assert_array_equal(_np(iop.logaddexp(values, values)), [np.inf, -np.inf])
135
+
136
+
137
+ def test_solve_known_system(backend: tuple) -> None:
138
+ matrix = iop.from_numpy(np.array([[3.0, 1.0], [1.0, 2.0]], dtype=np.float32))
139
+ rhs = iop.from_numpy(np.array([9.0, 8.0], dtype=np.float32))
140
+ solution = iop.solve(matrix, rhs)
141
+ np.testing.assert_allclose(_np(iop.matmul(matrix, solution)), _np(rhs), rtol=1e-5, atol=1e-5)
142
+
143
+
144
+ def test_eigvalsh_known_symmetric_matrix(backend: tuple) -> None:
145
+ matrix = iop.from_numpy(np.array([[2.0, 1.0], [1.0, 2.0]], dtype=np.float32))
146
+ np.testing.assert_allclose(_np(iop.eigvalsh(matrix)), [1.0, 3.0], rtol=1e-5, atol=1e-5)
147
+
148
+
50
149
  def test_device_to_native(backend: tuple) -> None:
51
150
  framework, device = backend
52
151
  native = device_to_native(device)
@@ -62,6 +161,7 @@ def test_device_of(backend: tuple) -> None:
62
161
 
63
162
  # Array manipulation -----------------------------------------------------
64
163
 
164
+
65
165
  def test_asarray_existing_array_is_identity(backend: tuple) -> None:
66
166
  arr = Array(4)
67
167
 
@@ -422,6 +522,15 @@ def test_all_dim_keepdims(backend: tuple) -> None:
422
522
  np.testing.assert_array_equal(_np(iop.all(arr, axis=0, keepdims=True)), [[True, False]])
423
523
 
424
524
 
525
+ def test_mean_bool_and_int(backend: tuple) -> None:
526
+ bool_arr = iop.from_numpy(np.array([[True, False], [True, True]], dtype=np.bool_))
527
+ np.testing.assert_allclose(_np(iop.mean(bool_arr)), 0.75)
528
+ np.testing.assert_allclose(_np(iop.mean(bool_arr, axis=1)), [0.5, 1.0])
529
+
530
+ int_arr = iop.from_numpy(np.array([1, 2, 3, 4], dtype=np.int32))
531
+ np.testing.assert_allclose(_np(iop.mean(int_arr)), 2.5)
532
+
533
+
425
534
  # Math elementwise -------------------------------------------------------
426
535
 
427
536
 
@@ -566,6 +675,27 @@ def test_isnan(backend: tuple) -> None:
566
675
  np.testing.assert_array_equal(_np(iop.isnan(arr)), [False, False, False, True])
567
676
 
568
677
 
678
+ @pytest.mark.parametrize("dtype", [np.bool_, np.int32, np.uint8])
679
+ def test_finiteness_checks_non_float(backend: tuple, dtype: type[np.generic]) -> None:
680
+ arr = iop.from_numpy(np.array([0, 1, 1], dtype=dtype))
681
+ for fn, expected in ((iop.isfinite, True), (iop.isinf, False), (iop.isnan, False)):
682
+ out = fn(arr)
683
+ assert out.dtype == da.bool_
684
+ np.testing.assert_array_equal(_np(out), [expected, expected, expected])
685
+
686
+
687
+ def test_finiteness_checks_complex(backend: tuple) -> None:
688
+ # Built with complex(re, im): ``np.nan * 1j`` would give nan+nanj and hide component-wise bugs.
689
+ vals = np.array(
690
+ [complex(1, 2), complex(np.inf, 0), complex(0, -np.inf), complex(np.nan, 0), complex(0, np.nan)],
691
+ dtype=np.complex64,
692
+ )
693
+ arr = iop.from_numpy(vals)
694
+ np.testing.assert_array_equal(_np(iop.isfinite(arr)), np.isfinite(vals)) # [T, F, F, F, F]
695
+ np.testing.assert_array_equal(_np(iop.isinf(arr)), np.isinf(vals)) # [F, T, T, F, F]
696
+ np.testing.assert_array_equal(_np(iop.isnan(arr)), np.isnan(vals)) # [F, F, F, T, T]
697
+
698
+
569
699
  # Operators --------------------------------------------------------------
570
700
 
571
701
 
@@ -774,6 +904,34 @@ def test_get_item_function(backend: tuple) -> None:
774
904
  np.testing.assert_allclose(_np(get_item(arr, 1)), 2.0)
775
905
 
776
906
 
907
+ def test_supports_index_and_array_keys(backend: tuple) -> None:
908
+ # Mirrors decent-bench agents, which implement __index__ so that ``W[agent_i, agent_j]`` works.
909
+ class CustomIndex:
910
+ def __init__(self, idx: int) -> None:
911
+ self._idx = idx
912
+
913
+ def __index__(self) -> int:
914
+ return self._idx
915
+
916
+ mat = iop.from_numpy(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
917
+ i0, i1 = CustomIndex(0), CustomIndex(1)
918
+ np.testing.assert_allclose(_np(mat[i0, i1]), 2.0)
919
+ mat[i1, i0] = 9.0
920
+ np.testing.assert_allclose(_np(mat[i1, i0]), 9.0)
921
+
922
+ mask = mat > 2.5
923
+ np.testing.assert_allclose(_np(mat[mask]), [9.0, 4.0])
924
+ mat[mask] = 0.0
925
+ np.testing.assert_allclose(_np(mat), [[1.0, 2.0], [0.0, 0.0]])
926
+
927
+
928
+ def test_creation_default_float_dtype_consistent(backend: tuple) -> None:
929
+ expected = iop.zeros((2, 2)).dtype
930
+ assert iop.ones((2, 2)).dtype == expected
931
+ assert iop.empty((2, 2)).dtype == expected
932
+ assert iop.eye(2).dtype == expected
933
+
934
+
777
935
  # No-backend errors ------------------------------------------------------
778
936
 
779
937
 
@@ -1,19 +0,0 @@
1
- from typing import Any
2
-
3
- from decent_array._array import Array
4
-
5
-
6
- def unwrap(x: Any) -> Any: # noqa: ANN401
7
- """
8
- Return the underlying value of an :class:`Array`, or pass ``x`` through.
9
-
10
- Typed as ``Any`` because operator dunders may pass either an :class:`Array` or a
11
- Python scalar; the strict abstract signature would force a ``cast`` at every call
12
- site without runtime benefit.
13
- """
14
- return x.value if type(x) is Array else x
15
-
16
-
17
- def is_scalar(x: Array) -> bool:
18
- """Return True if ``x`` is a 0-dim Array."""
19
- return x.ndim == 0
File without changes
File without changes
File without changes
File without changes
File without changes