Skip to content

Commit 538e551

Browse files
committed
Make create_diagonal support broadcasting
1 parent 27b0bf2 commit 538e551

File tree

3 files changed

+48
-16
lines changed

3 files changed

+48
-16
lines changed

src/array_api_extra/_lib/_funcs.py

+18-14
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from ._at import at
1313
from ._utils import _compat, _helpers
1414
from ._utils._compat import array_namespace, is_jax_array
15-
from ._utils._helpers import asarrays
15+
from ._utils._helpers import asarrays, ndindex
1616
from ._utils._typing import Array
1717

1818
__all__ = [
@@ -172,7 +172,7 @@ def create_diagonal(
172172
Parameters
173173
----------
174174
x : array
175-
A 1-D array.
175+
An array having shape (*broadcast_dims, k).
176176
offset : int, optional
177177
Offset from the leading diagonal (default is ``0``).
178178
Use positive ints for diagonals above the leading diagonal,
@@ -183,7 +183,8 @@ def create_diagonal(
183183
Returns
184184
-------
185185
array
186-
A 2-D array with `x` on the diagonal (offset by `offset`).
186+
An array having shape (*broadcast_dims, k+abs(offset), k+abs(offset)) with `x`
187+
on the diagonal (offset by `offset`).
187188
188189
Examples
189190
--------
@@ -206,18 +207,21 @@ def create_diagonal(
206207
if xp is None:
207208
xp = array_namespace(x)
208209

209-
if x.ndim != 1:
210-
err_msg = "`x` must be 1-dimensional."
210+
if x.ndim == 0:
211+
err_msg = "`x` must be at least 1-dimensional."
211212
raise ValueError(err_msg)
212-
n = x.shape[0] + abs(offset)
213-
diag = xp.zeros(n**2, dtype=x.dtype, device=_compat.device(x))
214-
215-
start = offset if offset >= 0 else abs(offset) * n
216-
stop = min(n * (n - offset), diag.shape[0])
217-
step = n + 1
218-
diag = at(diag)[start:stop:step].set(x)
219-
220-
return xp.reshape(diag, (n, n))
213+
pre = x.shape[:-1]
214+
n = x.shape[-1] + abs(offset)
215+
diag = xp.zeros((*pre, n**2), dtype=x.dtype, device=_compat.device(x))
216+
217+
target_slice = slice(
218+
offset if offset >= 0 else abs(offset) * n,
219+
min(n * (n - offset), diag.shape[-1]),
220+
n + 1,
221+
)
222+
for index in ndindex(*pre):
223+
diag = at(diag)[(*index, target_slice)].set(x[*index, :])
224+
return xp.reshape(diag, (*pre, n, n))
221225

222226

223227
def expand_dims(

src/array_api_extra/_lib/_utils/_helpers.py

+19
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# https://github.com/scikit-learn/scikit-learn/pull/27910#issuecomment-2568023972
44
from __future__ import annotations
55

6+
from collections.abc import Generator
67
from types import ModuleType
78
from typing import cast
89

@@ -175,3 +176,21 @@ def asarrays(
175176
xa, xb = xp.asarray(a), xp.asarray(b)
176177

177178
return (xb, xa) if swap else (xa, xb)
179+
180+
181+
def ndindex(*x: int) -> Generator[tuple[int, ...]]:
182+
"""Generate all N-dimensional indices for a given array shape.
183+
184+
Given the shape of an array, an ndindex instance iterates over the N-dimensional
185+
index of the array. At each iteration a tuple of indices is returned, the last
186+
dimension is iterated over first.
187+
188+
This has an identical API to numpy.ndindex.
189+
"""
190+
if not x:
191+
yield ()
192+
return
193+
indices = list(ndindex(*x[1:]))
194+
for i in range(x[0]):
195+
for j in indices:
196+
yield i, *j

tests/test_funcs.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from array_api_extra._lib import Backend
2222
from array_api_extra._lib._testing import xp_assert_close, xp_assert_equal
2323
from array_api_extra._lib._utils._compat import device as get_device
24+
from array_api_extra._lib._utils._helpers import ndindex
2425
from array_api_extra._lib._utils._typing import Array, Device
2526
from array_api_extra.testing import lazy_xp_function
2627

@@ -193,9 +194,17 @@ def test_0d(self, xp: ModuleType):
193194
with pytest.raises(ValueError, match="1-dimensional"):
194195
create_diagonal(xp.asarray(1))
195196

197+
@pytest.mark.xfail_xp_backend(Backend.SPARSE, reason="no device kwarg in zeros()")
196198
def test_2d(self, xp: ModuleType):
197-
with pytest.raises(ValueError, match="1-dimensional"):
198-
create_diagonal(xp.asarray([[1]]))
199+
result = create_diagonal(xp.asarray([[1]]))
200+
xp_assert_equal(result, xp.asarray([[[1]]]))
201+
b = xp.zeros((3, 2, 4, 5), dtype=xp.int64)
202+
for i in ndindex(*b.shape):
203+
b = at(b)[*i].set(hash(i))
204+
c = create_diagonal(b)
205+
zero = xp.zeros((), dtype=xp.int64)
206+
for i in ndindex(*c.shape):
207+
xp_assert_equal(c[*i], b[*(i[:-1])] if i[-2] == i[-1] else zero)
199208

200209
@pytest.mark.xfail_xp_backend(Backend.SPARSE, reason="no device kwarg in zeros()")
201210
def test_device(self, xp: ModuleType, device: Device):

0 commit comments

Comments
 (0)