Repository navigation
fix: support negative offsets, rectangular shapes, and negative axes in sparse.diagonal - #955
Conversation
…in sparse.diagonal
There was a problem hiding this comment.
🟢 Approval recommended
The implementation aligns with NumPy’s diagonal semantics for the reported edge cases and is backed by comprehensive regression tests comparing directly against numpy.diagonal.
Pull request overview
This PR updates sparse.diagonal in the numba COO backend to match numpy.diagonal semantics, fixing crashes and incorrect restrictions around offsets, axis handling, and rectangular/N-D inputs.
Changes:
- Fix diagonal coordinate mapping for negative
offsetvalues and compute diagonal length correctly for rectangular shapes. - Normalize negative axes (
axis1,axis2) and raise a clearer error whenaxis1 == axis2. - Extend regression tests to cover negative offsets, rectangular and N-D shapes, empty diagonals, negative axes, and fill-value preservation (including
NaN).
File summaries
| File | Description |
|---|---|
| sparse/numba_backend/_coo/common.py | Reworks diagonal() to handle negative offsets, rectangular/N-D shapes, negative axes, empty diagonals, and preserve fill_value. |
| sparse/numba_backend/tests/test_coo.py | Expands test_diagonal to validate behavior against numpy.diagonal across the new edge cases and error conditions. |
Review details
- Files reviewed: 2/2 changed files
- Comments generated: 0
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
hameerabbasi
left a comment
There was a problem hiding this comment.
LGTM, thanks for the contribution. Small tweaks to the tests, otherwise should be good to land.
|
Thanks @hameerabbasi, applied all three test suggestions and pushed the changes |
hameerabbasi
left a comment
There was a problem hiding this comment.
LGTM, thanks for the issue and fix, @rautaditya2606!
`_arg_minmax_common` never normalized the axis, and its bounds check only
covered one side (`axis >= x.ndim`), so a negative axis reached the
transpose and reshape logic untouched. The initial `list.pop(axis)`
happens to work for `-1`, but the final un-transpose does
`new_transpose.insert(axis, new_transpose.pop(0))`, which for `-1`
inserts before the last element instead of at the end. The reduced axis
ends up in front.
Measured against numpy on a (2, 3) array:
axis=1 numpy [[1], [0]] (2, 1) sparse [[1], [0]] (2, 1)
axis=-1 numpy [[1], [0]] (2, 1) sparse [[1, 0]] (1, 2)
A 1-D array with `axis=-1` raised `ValueError: shape must be an
non-negative integer...` where numpy returns a value, and `axis=-5` on a
2-D array leaked `IndexError: pop index out of range` instead of a
message naming the bounds.
`normalize_axis` is already imported in this module and every other
axis-taking function in it uses it: `concatenate`, `stack`, `roll`,
`diagonal`, `expand_dims` and `flip`. This was the only one left out,
which also matches the history: the reductions got this treatment in
#118/#119 and `diagonal` in #955, while `argmax`/`argmin` arrived later
in #614 and were never covered. The existing tests parametrize `axis`
over `[None, 0, 1, 2]`, so no negative axis was ever exercised.
The wording of the out-of-bounds `ValueError` is kept so that
`test_argmax_argmin_constraint` still passes, including the 0-D case.
What type of PR is this? (check all applicable)
Related issues
Checklist
Please explain your changes below.
Summary
This PR aligns
sparse.diagonalwithnumpy.diagonalsemantics by fixing several crashes and restrictions:offsetwhenoffset < 0(a.coords[axis1] + offset), ensuring valid diagonal elements map to[0, diag_len)instead of raisingValueError: invalid entry in coordinates array.a.shape[axis1] == a.shape[axis2]. The diagonal length is now derived dynamically from the selected axes:diag_len = max(0, min(M, N - offset)) if offset >= 0 else max(0, min(M + offset, N))axis1andaxis2usingnormalize_axisand verifiedaxis1 != axis2.(*diag_shape[:-1], 0)whendiag_len == 0ora.nnz == 0.test_diagonalcovering square matrices, rectangular shapes, N-D tensors, negative axes, empty diagonals, and fill values (fill_value=1.5,NaN).