From ae1e193d9e0160e0f669e6f1f2136efc7778dd9b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:41:14 +0000 Subject: [PATCH 1/2] fix: write no objective term to an LP file when the objective has no live variable An objective whose variables are all masked is constant, so its polars frame holds one row with null vars. The LP writer formatted that row as a bare `x`, which the solver read as a new column and the solution parser could not map back to a label. Closes #1176 --- doc/release-notes.md | 1 + linopy/io.py | 2 ++ test/test_optimization.py | 19 +++++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/doc/release-notes.md b/doc/release-notes.md index a1c3ff1e..450e90ae 100644 --- a/doc/release-notes.md +++ b/doc/release-notes.md @@ -144,6 +144,7 @@ linopy 1.0 makes the strict arithmetic convention the only behaviour and puts de *I/O* +- A solve through an LP file no longer fails when the objective has no live variable, e.g. when all its variables are masked. ([\#1176](https://github.com/PyPSA/linopy/issues/1176)) - `to_netcdf` handles timezone-aware datetimes in indexes, coordinates and `Model.parameters`. ([\#1021](https://github.com/PyPSA/linopy/pull/1021)) - Object-dtype parameters, e.g. strings with `NaN` holes, round-trip through netcdf with their holes. Mixed-type object arrays raise a `TypeError` on write. diff --git a/linopy/io.py b/linopy/io.py index 139683a8..ec3d8af1 100644 --- a/linopy/io.py +++ b/linopy/io.py @@ -308,6 +308,8 @@ def objective_to_file( sense = m.objective.sense f.write(f"{sense}\n\nobj:\n\n".encode()) + if m.objective.expression.is_constant: + return df = m.objective.to_polars() if m.is_linear: diff --git a/test/test_optimization.py b/test/test_optimization.py index bb4b9fcc..ca335e88 100644 --- a/test/test_optimization.py +++ b/test/test_optimization.py @@ -1029,6 +1029,25 @@ def test_masked_variable_model_fillna_binds( assert (np.isclose(m.variables.x.solution[-2:], 10, rtol=tol)).all() +@pytest.mark.parametrize("solver,io_api,explicit_coordinate_names", params) +def test_objective_without_live_terms( + solver: str, + io_api: str, + explicit_coordinate_names: bool, +) -> None: + m = Model() + x = m.add_variables(lower=0, name="x") + z = m.add_variables(lower=0, coords=[range(2)], mask=pd.Series([False, False])) + m.add_constraints(x >= 1) + m.add_objective(z.sum()) + status, _ = m.solve( + solver, io_api=io_api, explicit_coordinate_names=explicit_coordinate_names + ) + assert status == "ok" + assert np.isclose(m.objective.value or 0, 0) + assert np.isclose(x.solution.item(), 1) + + @pytest.mark.parametrize("solver,io_api,explicit_coordinate_names", params) def test_masked_constraint_model( masked_constraint_model: Model, From 38b3a9807b402634ac9ea063749d3aed03edb286 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 10:59:22 +0000 Subject: [PATCH 2/2] fix: write a zero term when the LP objective has no live term GLPK rejects an LP file whose objective section holds no term, which an all-masked objective or 0 * x produces. Write a zero-coefficient term on the first live variable instead. The test now also pins x to a unique optimum, as a zero objective left SCIP free to return any x >= 1. --- doc/release-notes.md | 2 +- linopy/io.py | 13 +++++++++++++ test/test_optimization.py | 6 ++++-- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/doc/release-notes.md b/doc/release-notes.md index 450e90ae..8828503a 100644 --- a/doc/release-notes.md +++ b/doc/release-notes.md @@ -144,7 +144,7 @@ linopy 1.0 makes the strict arithmetic convention the only behaviour and puts de *I/O* -- A solve through an LP file no longer fails when the objective has no live variable, e.g. when all its variables are masked. ([\#1176](https://github.com/PyPSA/linopy/issues/1176)) +- A solve through an LP file no longer fails when the objective has no live variable, e.g. when all its variables are masked, or, with GLPK, when it is `0 * x`. ([\#1176](https://github.com/PyPSA/linopy/issues/1176)) - `to_netcdf` handles timezone-aware datetimes in indexes, coordinates and `Model.parameters`. ([\#1021](https://github.com/PyPSA/linopy/pull/1021)) - Object-dtype parameters, e.g. strings with `NaN` holes, round-trip through netcdf with their holes. Mixed-type object arrays raise a `TypeError` on write. diff --git a/linopy/io.py b/linopy/io.py index ec3d8af1..c4b237ca 100644 --- a/linopy/io.py +++ b/linopy/io.py @@ -289,6 +289,16 @@ def objective_write_quadratic_terms( f.write(b"] / 2\n") +def _zero_objective_term(m: Model) -> pl.DataFrame: + """ + A zero-coefficient term on the first live variable. + + LP readers such as GLPK reject an objective section without terms. + """ + vars = m.variables.label_index.vlabels[:1] + return pl.DataFrame({"coeffs": np.zeros(len(vars)), "vars": vars}) + + def objective_to_file( m: Model, f: BufferedWriter, @@ -309,11 +319,14 @@ def objective_to_file( sense = m.objective.sense f.write(f"{sense}\n\nobj:\n\n".encode()) if m.objective.expression.is_constant: + objective_write_linear_terms(f, _zero_objective_term(m), print_variable) return df = m.objective.to_polars() if m.is_linear: df = _scale_objective_dataframe(df, variable_scaling, m.objective.scaling) + if df.is_empty(): + df = _zero_objective_term(m) objective_write_linear_terms(f, df, print_variable) elif m.is_quadratic: diff --git a/test/test_optimization.py b/test/test_optimization.py index ca335e88..eb4ef37c 100644 --- a/test/test_optimization.py +++ b/test/test_optimization.py @@ -1029,17 +1029,19 @@ def test_masked_variable_model_fillna_binds( assert (np.isclose(m.variables.x.solution[-2:], 10, rtol=tol)).all() +@pytest.mark.parametrize("masked", [True, False]) @pytest.mark.parametrize("solver,io_api,explicit_coordinate_names", params) def test_objective_without_live_terms( solver: str, io_api: str, explicit_coordinate_names: bool, + masked: bool, ) -> None: m = Model() - x = m.add_variables(lower=0, name="x") + x = m.add_variables(lower=0, upper=1, name="x") z = m.add_variables(lower=0, coords=[range(2)], mask=pd.Series([False, False])) m.add_constraints(x >= 1) - m.add_objective(z.sum()) + m.add_objective(z.sum() if masked else 0 * x) status, _ = m.solve( solver, io_api=io_api, explicit_coordinate_names=explicit_coordinate_names )