coin-or / python-mip

Python-MIP: collection of Python tools for the modeling and solution of Mixed-Integer Linear programs
Eclipse Public License 2.0
514 stars 89 forks source link

Gurobi: Can't access objective #289

Closed Markus28 closed 1 year ago

Markus28 commented 1 year ago

In get_objective in gurobi.py you are trying to set the const property of LinExpr, which doesn't have a setter. To reproduce:

>>> import mip
>>> model = mip.Model(solver_name="gurobi")
Set parameter Username
Academic license - for non-commercial use only - expires 2023-07-07
>>> x = model.add_var("x"I)
>>> model.objective = x
>>> model.objective
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mkrimmel/.local/lib/python3.8/site-packages/mip/model.py", line 821, in objective
    return self.solver.get_objective()
  File "/home/mkrimmel/.local/lib/python3.8/site-packages/mip/gurobi.py", line 543, in get_objective
    obj_expr.const = self.get_objective_const()
AttributeError: can't set attribute

Not sure why const cannot have a setter. Either way, you could just use the constructor of LinExpr directly. I may prepare a PR for this because I probably need to have this fixed.

sebheger commented 1 year ago

@Markus28 Feel free to open a PR, I will review it. Don't forget to write a unit-test.

sebheger commented 1 year ago

I guess that could be easily fixed by adding a constant (add_constant) to the expr instead of setting it.