Skip to content
Merged
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.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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**

Expand Down
5 changes: 4 additions & 1 deletion linopy/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,8 @@ def add_constraints(

def add_objective(
self,
expr: LinearExpression
expr: Variable
| LinearExpression
| QuadraticExpression
| Sequence[tuple[ConstantLike, VariableLike]],
overwrite: bool = False,
Expand All @@ -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

Expand Down
7 changes: 7 additions & 0 deletions test/test_objective.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
Loading