Skip to content

Commit a97b8f4

Browse files
Merge branch 'master' into oetc-support
2 parents 87fc221 + e2c51d5 commit a97b8f4

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
@@ -12,6 +12,7 @@ Version 0.5.6
1212
* Gurobi: Pass dictionary as env argument `env={...}` through to gurobi env creation
1313
* Added integration with OETC platform
1414
* Mosek: Remove explicit use of Env, use global env instead
15+
* Objectives can now be created from variables via `linopy.Model.add_objective`.
1516

1617
**Breaking Changes**
1718

linopy/model.py

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

686686
def add_objective(
687687
self,
688-
expr: LinearExpression
688+
expr: Variable
689+
| LinearExpression
689690
| QuadraticExpression
690691
| Sequence[tuple[ConstantLike, VariableLike]],
691692
overwrite: bool = False,
@@ -711,6 +712,8 @@ def add_objective(
711712
"Objective already defined."
712713
" Set `overwrite` to True to force overwriting."
713714
)
715+
if isinstance(expr, Variable):
716+
expr = 1 * expr
714717
self.objective.expression = expr
715718
self.objective.sense = sense
716719

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)