Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/release-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
15 changes: 15 additions & 0 deletions linopy/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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:
Expand Down
21 changes: 21 additions & 0 deletions test/test_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading