Repository navigation
feat: accept sparse (pydata/sparse-backed) operands in @ without densifying - #1119
Merged
Merged
Conversation
…ifying A labelled xarray.DataArray whose data is a pydata/sparse array (e.g. sparse.COO, fill value 0) now goes through the existing sparse contraction of LinearExpression.__matmul__ / Variable.__matmul__ / dot without being densified: it is transposed and reshaped as a sparse array and handed to scipy via to_scipy_sparse(). Label checks (§8), aux coords (§11) and NaN handling (§5, stored or as fill value) match the dense operand; a non-zero fill value raises. Where the sparse product does not apply (and for QuadraticExpression), the operand is densified with a PerformanceWarning, silenced by options["warn_on_densify"] = False. sparse stays optional: it is never imported unless the operand is a sparse array, it is added to the dev extra, and the tests skip without it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F4nx8GJ8mSNvkTagja9dMj
Merging this PR will not alter performance
Comparing Footnotes
|
…pact helpers and tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F4nx8KhK8QzSzHhpYKvcSx
…heck Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F4nx8GJ8mSNvkTagja9dMj
A pydata/sparse operand is always passed on purpose, so its densify fallback warns under the default warn_on_densify=None in a dense model too, unlike the CSR densify notice; only warn_on_densify=False silences it. Tests cover the default, True and False settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F4nx8JJokf4NAtRpcKAuov
FabianHofmann
marked this pull request as ready for review
November 4, 2026 07:38
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes # (if applicable).
Changes proposed in this Pull Request
Note
The following content was generated by AI.
Variable @ C,LinearExpression @ Cand.dot(C)already contract a constant as one sparse product, but_matmul_operand_to_matrixdensified the constant first (.valuesthencsr_array(...)). A link-by-bus incidence of a PyPSA sector network (6830 x 2164) is about 118 MB dense per port, so PyPSA could not use@.This PR lets
Cbe a labelledxarray.DataArraywhose data is a pydata/sparse array (sparse.COO, also GCXS/DOK viasparse.as_coo) with fill value 0:linopy/alignment.py:is_sparse_backed(checkssys.modules, never importssparse);_matmul_operand_to_matrixtransposes and reshapes the sparse array and builds the CSR matrix withcoo.to_scipy_sparse(). The NaN check readscoo.fill_valueandcoo.data, runs before the label checks like the dense path, and raises the same §5 error. The §8 shared-dim label checks and the §11 aux-coord checks are unchanged, since they only look at coordinates. A non-zero fill value raises aValueError, because every implicit entry would become a coefficient._sparse_matmulreturns aReason(no shared dim, zero-dim expression, non-unique labels, coordinates the grid cannot hold), and also forQuadraticExpression.__matmul__, the operand is densified throughdensify_sparse_operand. This emitsPerformanceWarning("Sparse (pydata/sparse) operand densified: <reason>."). Without it, pydata/sparse would raise its ownRuntimeErrordeep inside xarray.LinearExpression.__matmul__,BaseExpression.dot,Variable.__matmul__andVariable.dot. A release note under 1.0.0 Features.sparseadded to thedevextra only. It stays an optional dependency, and the new tests usepytest.importorskip("sparse").Open design questions
scipy.sparsematrices are not accepted (they still raiseTypeErroras before). They are unlabelled, so they would have to pair axes by size like numpy (v1 convention: pair unlabeled operands with dimensions by size, raise on ambiguity #736). That works only in 2-D, and it is ambiguous when the contracted and new dims have the same size. The new dim would also get no labels, which takes the "unlabelled output dim" fallback and densifies anyway. Wrapping inxr.DataArray(sparse.COO.from_scipy_sparse(m), coords=...)is explicit and cheap. Should we accept scipy matrices anyway?warn_on_densify=Falseturns it off. This differs from the CSR densify notice, which defaults tomodel.sparse. The reasoning is that a user who passes a sparse array wants it kept sparse. Should it follow the samemodel.sparsedefault instead, or should it raise?@/dotare covered.expr * C_sparseand other arithmetic with a sparse-backed DataArray still fail with pydata/sparse'sRuntimeError("Cannot convert a sparse array to dense automatically"). Should that be a follow-up?Tests and checks
New
test/test_sparse_operand.py(43 tests, skipped withoutsparse):assert_equivalent) for Variable and LinearExpression receivers, in dense and sparse models. Cases: one contracted dim, two contracted dims, two contracted dims plus a new dim, one contracted dim plus two new dims. Same for.dot. NoPerformanceWarningis emitted, and the CSR backing followsmodel.sparse.PerformanceWarningand match dense. The warning can be silenced.sparse.COO.todensepatched to raise. Peak traced memory is under a tenth of the 120 MB dense array, runtime is under 10 s, and the coefficient sum is correct.Results:
pytest test -q: 5300 passed, 117 skippedruff check --fix .: all checks passedruff format .: unchangedmypy linopy: no issues in 46 source filesChecklist
AGENTS.md).doc.doc/release_notes.rstof the upcoming release is included.Generated by Claude Code