Skip to content

Commit

Permalink
Fix Gurobi objective (#290)
Browse files Browse the repository at this point in the history
* Fixed mistake in gurobi objective getter

* Apply black

* Only use add_const
  • Loading branch information
Markus28 authored Aug 5, 2022
1 parent a8b9faf commit c8618b8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
4 changes: 2 additions & 2 deletions mip/gurobi.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,8 +540,8 @@ def get_objective(self) -> LinExpr:
for i in range(self.num_cols())
if abs(obj[i]) > 1e-20
)
obj_expr.const = self.get_objective_const()
obj_expr.sense = self.get_objective_sense
obj_expr.add_const(self.get_objective_const())
obj_expr.sense = self.get_objective_sense()
return obj_expr

def get_objective_const(self) -> float:
Expand Down
1 change: 1 addition & 0 deletions test/dbft_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,3 +495,4 @@ def test_dbft_mip(solver, pdata):
m.check_optimization_results()
if m.status == OptimizationStatus.OPTIMAL:
assert abs(m.objective_value - opt) <= TOL
assert abs(m.objective.x - m.objective_value) <= TOL
38 changes: 37 additions & 1 deletion test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,42 @@ def test_query_attributes_of_lin_expr(solver):

m.optimize()

@pytest.mark.parametrize("solver", SOLVERS)
def test_objective(solver):
m = Model(solver_name=solver, sense=MAXIMIZE)
x = m.add_var(name="x", lb=0, ub=1)
y = m.add_var(name="y", lb=0, ub=1)

m.objective = x - y + 0.5
assert m.objective.x is None
#TODO: assert m.objective.sense == MAXIMIZE

# Make sure that we can access the objective and it's correct
assert len(m.objective.expr) == 2
assert m.objective.expr[x] == 1
assert m.objective.expr[y] == -1
assert m.objective.const == 0.5

status = m.optimize()
assert status == OptimizationStatus.OPTIMAL
assert m.objective_value == 1.5
assert m.objective_value == m.objective.x


# Test changing the objective
m.objective = x + y + 1.5
m.sense = MINIMIZE
# TODO: assert m.objective.sense == MINIMIZE

assert len(m.objective.expr) == 2
assert m.objective.expr[x] == 1
assert m.objective.expr[y] == 1
assert m.objective.const == 1.5

status = m.optimize()
assert status == OptimizationStatus.OPTIMAL
assert m.objective_value == 1.5
assert m.objective_value == m.objective.x

@pytest.mark.parametrize("solver", SOLVERS)
def test_remove(solver):
Expand All @@ -1277,4 +1313,4 @@ def test_remove(solver):
m.remove([None])

m.remove(constr)
# TODO: Test the removal of variables (currently failing, see https://github.com/coin-or/python-mip/pull/288#discussion_r919215654)
# TODO: Test the removal of variables (currently failing, see https://github.com/coin-or/python-mip/pull/288#discussion_r919215654)

0 comments on commit c8618b8

Please sign in to comment.