|
14 | 14 | import xarray as xr |
15 | 15 | from xarray.testing import assert_equal |
16 | 16 |
|
17 | | -from linopy import LinearExpression, Model, QuadraticExpression, Variable, merge |
| 17 | +from linopy import LinearExpression, Model, QuadraticExpression, Variable |
18 | 18 | from linopy.constants import HELPER_DIMS, TERM_DIM |
19 | | -from linopy.expressions import ScalarLinearExpression |
20 | | -from linopy.testing import assert_linequal, assert_quadequal |
| 19 | +from linopy.expressions import ScalarLinearExpression, merge |
| 20 | +from linopy.testing import assert_linequal, assert_lists_equal, assert_quadequal |
21 | 21 | from linopy.variables import ScalarVariable |
22 | 22 |
|
23 | 23 |
|
@@ -238,6 +238,44 @@ def test_linear_expression_with_multiplication(x: Variable) -> None: |
238 | 238 | assert expr.__rmul__(object()) is NotImplemented |
239 | 239 |
|
240 | 240 |
|
| 241 | +def test_linear_expression_multiplication_with_missing_coords() -> None: |
| 242 | + m = Model() |
| 243 | + full_index = pd.Index(range(5), name="i") |
| 244 | + x = m.add_variables(coords=[full_index]) |
| 245 | + nan = float("nan") |
| 246 | + scale = xr.DataArray([10.0, 30.0], dims=["i"], coords={"i": [1, 3]}) |
| 247 | + |
| 248 | + # These two expressions should produce the same result |
| 249 | + r1 = x * scale |
| 250 | + r2 = (1 * x) * scale |
| 251 | + |
| 252 | + for result in [r1, r2]: |
| 253 | + assert result.coords.equals(x.coords) |
| 254 | + assert result.vars.equals(r1.vars) |
| 255 | + |
| 256 | + # Use pandas to make sure nans are considered equal |
| 257 | + expected_coeffs = [nan, 10.0, nan, 30.0, nan] |
| 258 | + assert_lists_equal(result.coeffs.values.squeeze(), expected_coeffs) |
| 259 | + |
| 260 | + |
| 261 | +def test_linear_expression_with_missing_coords_in_coeff_and_const() -> None: |
| 262 | + m = Model() |
| 263 | + full_index = pd.Index(range(5), name="i") |
| 264 | + x = m.add_variables(coords=[full_index]) |
| 265 | + nan = float("nan") |
| 266 | + scale = xr.DataArray([10.0, 30.0], dims=["i"], coords={"i": [1, 3]}) |
| 267 | + const = xr.DataArray([1.0, 2.0], dims=["i"], coords={"i": [0, 1]}) |
| 268 | + |
| 269 | + # These two expressions should produce the same result |
| 270 | + result = (x + const) * scale |
| 271 | + assert result.coords.equals(x.coords) |
| 272 | + |
| 273 | + expected_coeffs = [nan, 10.0, nan, 30.0, nan] |
| 274 | + expected_const = [nan, 20.0, nan, 0.0, nan] # Constants are filled with zeros |
| 275 | + assert_lists_equal(result.coeffs.values.squeeze(), expected_coeffs) |
| 276 | + assert_lists_equal(result.const.values.squeeze(), expected_const) |
| 277 | + |
| 278 | + |
241 | 279 | def test_linear_expression_with_addition(m: Model, x: Variable, y: Variable) -> None: |
242 | 280 | expr = 10 * x + y |
243 | 281 | assert isinstance(expr, LinearExpression) |
|
0 commit comments