diff --git a/doc/release-notes.md b/doc/release-notes.md index a1c3ff1e..8828503a 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, 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 139683a8..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, @@ -308,10 +318,15 @@ 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 bb4b9fcc..eb4ef37c 100644 --- a/test/test_optimization.py +++ b/test/test_optimization.py @@ -1029,6 +1029,27 @@ 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, 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() if masked else 0 * x) + 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,