Skip to content

Keep CSR backing for elementwise ops with non-scalar constants #965

Description

@FabianHofmann

Note

The following content was generated by AI.

Describe the feature you'd like to see

Keep the CSR backing for elementwise arithmetic with non-scalar constants. Child of #756.

Today the sparse fast path accepts only a plain scalar. LinearExpression.__mul__ gates on int | float | np.number (linopy/expressions.py:2500) and calls CSRLinearExpression.scaled. A DataArray, Series or ndarray factor falls through to _multiply_by_constant and densifies the whole rectangle, even though only the coefficients change.

Adding or subtracting a constant is worse: _add_constant (expressions.py:1153-1178) expands everything although only const changes and the CSR matrix is untouched.

Coefficient vectors over a grid dimension are the normal case in real models, for example efficiencies per generator or weights per snapshot, so this gate excludes most realistic arithmetic.

Implementation ideas

Two new methods on CSRLinearExpression, both cheap on the stored arrays:

  • scaled_by(vector, dim) — broadcast the factor along the grid and scale each row's data slice. Reuse Grid.indexer/strides to map cells to row ranges.
  • shifted(const) — add to the stored const only, leaving indptr/indices/data alone.

Then wire __mul__, __rmul__, __truediv__, div, _add_constant and _sub_constant to them. Alignment of the operand against the grid should reuse _matmul_operand_to_matrix in linopy/alignment.py (#961), which already enforces the v1 NaN, label-mismatch and aux-coord rules identically to *.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestperformanceThis improves performance while not (meaningfully) altering behaviour for userssparseSparse / CSR-backed expressions and constraints

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions