Skip to content

fix: support negative offsets, rectangular shapes, and negative axes in sparse.diagonal - #955

Merged
hameerabbasi merged 2 commits into
pydata:mainfrom
rautaditya2606:fix-sparse-diagonal
Sep 1, 2026
Merged

hameerabbasi merged 2 commits into
pydata:mainfrom
rautaditya2606:fix-sparse-diagonal

Conversation

@rautaditya2606

Copy link
Copy Markdown
Contributor

What type of PR is this? (check all applicable)

  • 💾 Refactor
  • 🪄 Feature
  • 🐞 Bug Fix
  • 🔧 Optimization
  • 📚 Documentation
  • 🧪 Test
  • 🛠️ Other

Related issues

Checklist

  • Code follows style guide
  • Tests added
  • Documented the changes

Please explain your changes below.

Summary

This PR aligns sparse.diagonal with numpy.diagonal semantics by fixing several crashes and restrictions:

  1. Negative Offsets: Shifted coordinate mapping by offset when offset < 0 (a.coords[axis1] + offset), ensuring valid diagonal elements map to [0, diag_len) instead of raising ValueError: invalid entry in coordinates array.
  2. Arbitrary Rectangular & N-D Shapes: Removed the restriction 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))
  3. Negative Axes: Normalized axis1 and axis2 using normalize_axis and verified axis1 != axis2.
  4. Out-of-Bounds Offsets: Return an empty COO array of shape (*diag_shape[:-1], 0) when diag_len == 0 or a.nnz == 0.
  5. Tests: Added comprehensive regression tests in test_diagonal covering square matrices, rectangular shapes, N-D tensors, negative axes, empty diagonals, and fill values (fill_value=1.5, NaN).

Copilot AI lite review requested due to automatic review settings September 1, 2026 03:30
@github-actions github-actions Bot added the fix label Sep 1, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 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 offset values and compute diagonal length correctly for rectangular shapes.
  • Normalize negative axes (axis1, axis2) and raise a clearer error when axis1 == 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 hameerabbasi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for the contribution. Small tweaks to the tests, otherwise should be good to land.

Comment thread sparse/numba_backend/tests/test_coo.py Resolved
Comment thread sparse/numba_backend/tests/test_coo.py Resolved
Comment thread sparse/numba_backend/tests/test_coo.py Resolved
@rautaditya2606

Copy link
Copy Markdown
Contributor Author

Thanks @hameerabbasi, applied all three test suggestions and pushed the changes

@hameerabbasi hameerabbasi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks for the issue and fix, @rautaditya2606!

@hameerabbasi
hameerabbasi enabled auto-merge (squash) September 1, 2026 08:07
@hameerabbasi
hameerabbasi merged commit 5a7bdfa into pydata:main Sep 1, 2026
12 of 14 checks passed
hameerabbasi pushed a commit that referenced this pull request Oct 7, 2026
`_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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: sparse.diagonal crashes on negative offsets and rectangular arrays

3 participants