Skip to content

Commit e2c51d5

Browse files
feat: add objective from variable (#489)
1 parent b14208f commit e2c51d5

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

doc/release_notes.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Version 0.5.6
1111
* Improved variable/expression arithmetic methods so that they correctly handle types
1212
* Gurobi: Pass dictionary as env argument `env={...}` through to gurobi env creation
1313
* Mosek: Remove explicit use of Env, use global env instead
14+
* Objectives can now be created from variables via `linopy.Model.add_objective`.
1415

1516
**Breaking Changes**
1617

linopy/model.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,8 @@ def add_constraints(
684684

685685
def add_objective(
686686
self,
687-
expr: LinearExpression
687+
expr: Variable
688+
| LinearExpression
688689
| QuadraticExpression
689690
| Sequence[tuple[ConstantLike, VariableLike]],
690691
overwrite: bool = False,
@@ -710,6 +711,8 @@ def add_objective(
710711
"Objective already defined."
711712
" Set `overwrite` to True to force overwriting."
712713
)
714+
if isinstance(expr, Variable):
715+
expr = 1 * expr
713716
self.objective.expression = expr
714717
self.objective.sense = sense
715718

test/test_objective.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ def test_model(linear_objective: Objective, quadratic_objective: Objective) -> N
3131
assert isinstance(quadratic_objective.model, Model)
3232

3333

34+
def test_add_objective_from_variable() -> None:
35+
m = Model()
36+
v = m.add_variables(coords=[[1, 2, 3]])
37+
m.add_objective(v)
38+
assert isinstance(m.objective, Objective)
39+
40+
3441
def test_sense(linear_objective: Objective, quadratic_objective: Objective) -> None:
3542
assert linear_objective.sense == "min"
3643
assert quadratic_objective.sense == "max"

0 commit comments

Comments
 (0)