From 2e1923fae48e055de987b78ae8aece431b38af18 Mon Sep 17 00:00:00 2001 From: Fabian Date: Thu, 4 Sep 2025 13:23:29 +0200 Subject: [PATCH] feat: add objective from variable --- doc/release_notes.rst | 1 + linopy/model.py | 5 ++++- test/test_objective.py | 7 +++++++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/doc/release_notes.rst b/doc/release_notes.rst index daa65f52..d3721743 100644 --- a/doc/release_notes.rst +++ b/doc/release_notes.rst @@ -11,6 +11,7 @@ Version 0.5.6 * Improved variable/expression arithmetic methods so that they correctly handle types * Gurobi: Pass dictionary as env argument `env={...}` through to gurobi env creation * Mosek: Remove explicit use of Env, use global env instead +* Objectives can now be created from variables via `linopy.Model.add_objective`. **Breaking Changes** diff --git a/linopy/model.py b/linopy/model.py index c8024843..0255d00e 100644 --- a/linopy/model.py +++ b/linopy/model.py @@ -684,7 +684,8 @@ def add_constraints( def add_objective( self, - expr: LinearExpression + expr: Variable + | LinearExpression | QuadraticExpression | Sequence[tuple[ConstantLike, VariableLike]], overwrite: bool = False, @@ -710,6 +711,8 @@ def add_objective( "Objective already defined." " Set `overwrite` to True to force overwriting." ) + if isinstance(expr, Variable): + expr = 1 * expr self.objective.expression = expr self.objective.sense = sense diff --git a/test/test_objective.py b/test/test_objective.py index d0831d25..d869175a 100644 --- a/test/test_objective.py +++ b/test/test_objective.py @@ -31,6 +31,13 @@ def test_model(linear_objective: Objective, quadratic_objective: Objective) -> N assert isinstance(quadratic_objective.model, Model) +def test_add_objective_from_variable() -> None: + m = Model() + v = m.add_variables(coords=[[1, 2, 3]]) + m.add_objective(v) + assert isinstance(m.objective, Objective) + + def test_sense(linear_objective: Objective, quadratic_objective: Objective) -> None: assert linear_objective.sense == "min" assert quadratic_objective.sense == "max"