Skip to content

Inconsistent behavior when multiplying with subset coordinates #570

@FabianHofmann

Description

@FabianHofmann

Version Checks

  • I have confirmed this bug exists on the current master branch of Linopy.

Issue Description

Multiplying variables/expressions with constants that have a subset of coordinates produces inconsistent behavior:

  1. Variable * subset_const: Creates NaN coefficients with valid variable labels
  2. LinearExpression * subset_const: Fails with AssertionError in _multiply_by_constant
  3. Variable + subset_const: Works correctly (fills missing with 0)

The root cause is that addition uses merge() with controlled join='outer' and fill_value=0, while multiplication uses uncontrolled xarray operations.

Reproducible Example

import xarray as xr
import pandas as pd
import linopy

m = linopy.Model()
x = m.add_variables(coords=[pd.Index(range(5), name='i')])
subset = xr.DataArray([10.0, 30.0], dims=['i'], coords={'i': [1, 3]})

# Works but produces NaN coefficients with valid var labels
result1 = x * subset
print(result1.coeffs.squeeze().values)  # [nan, 10., nan, 30., nan]
print(result1.data.vars.squeeze().values)  # [0, 1, 2, 3, 4] - all valid!

# Fails with AssertionError
expr = 1 * x
result2 = expr * subset  # AssertionError in _multiply_by_constant

# Addition works correctly
result3 = x + subset
print(result3.const.values)  # [0., 10., 0., 30., 0.]

Expected Behavior

Multiplication should behave consistently:

  • Either fill missing coordinates with 0 (like addition)
  • Or raise an error for misaligned coordinates
  • Both x * c and (1*x) * c should behave the same

Installed Versions

Details

linopy @ master (commit 59f92ae)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions