Skip to content

sum() over a dimension crashes when a sibling dimension is empty #906

Description

@FBumann

I found this edge case while working on lpspec. I think its better handled here than in lpspecs linopy lane

Note

The following content was generated by AI, on behalf of a user of linopy.

Summing an expression over one dimension raises inside the term reshape when another dimension of the expression has size 0 — even though summing over the empty dimension itself works, and the result (an expression with no terms) is well-defined.

import linopy, pandas as pd

m = linopy.Model()
x = m.add_variables(
    coords=[pd.RangeIndex(4, name='t'), pd.Index([], name='cycle'), pd.Index(['a', 'b'], name='line')],
    name='x',
)
x.sum('cycle').sizes   # Frozen({'t': 4, 'line': 2}) — fine
x.sum('line')          # ValueError: cannot reshape array of size 0 into shape (4,0,newaxis)

Traceback ends in expressions.py, BaseExpression._sum (variables.py:1243 → expressions.py:1633 → expressions.py:2141). Reproduced on 0.9.1.post1.dev3+g09c34dd9d (master).

Where it bites: a PyPSA-style model whose cycle basis is empty (no meshed network) — sum(..., 'line') of a term still carrying the empty cycle dimension. Expected: the same result as LinearExpression.from_constant(m, xr.zeros_like(...)) over the kept coordinates, i.e. {'t': 4, 'cycle': 0} with zero terms — which is what x.sum('cycle') already returns for the mirror case. Presumably the stacking reshape needs the term count taken from the summed dimension rather than inferred with -1, which fails once the array has zero elements.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions