I need to optimize a model with different sets of constraints, but a subset of those constraints will be the same for each model. My idea was to build a base model with all the variables and all the constraints that will be needed every time. However, it doesn't look like the Gurobi Model.copy() method copies variables the way I imagined. Here's a very simplified version of what I am hoping to do that shows the error I'm getting.
>>> from gurobipy import Model
>>> m0 = Model("test")
>>> v = m0.addVar(lb=-1, ub=1)
>>> m0.update()
>>> print m0
<gurobi.Model Continuous instance test: 0 constrs, 1 vars, Parameter changes: LogFile=gurobi.log>
>>> print v in m0.getVars()
True
>>> m = m0.copy()
>>> print m
<gurobi.Model Continuous instance test_copy: 0 constrs, 1 vars, Parameter changes: LogFile=gurobi.log>
>>> print v in m.getVars()
True
>>> m0.addConstr(v <= 0)
<gurobi.Constr *Awaiting Model Update*>
>>> m0.update()
>>> print m0
<gurobi.Model Continuous instance test: 1 constrs, 1 vars, Parameter changes: LogFile=gurobi.log>
>>> m.addConstr(v >= 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "model.pxi", line 2196, in gurobipy.Model.addConstr (../../src/python/gurobipy.c:66304)
File "model.pxi", line 2089, in gurobipy.Model.__addConstr (../../src/python/gurobipy.c:64663)
gurobipy.GurobiError: Variable not in model
>>> print m
<gurobi.Model Continuous instance test_copy: 0 constrs, 1 vars, Parameter changes: LogFile=gurobi.log>
Software: Python 2.7.11 and Gurobi 6.5 on OS X El Capitan (also tested on Ubuntu 15.04)
I couldn't find a clear answer to question 1 as to why v in m.getVars() returns True in the original example. I imagine that "in" is only comparing the values within the objects instead of the objects themselves, but I don't have a source for this.
As for question 2, I found a solution:
Simple example:
from gurobipy import Model
m0 = Model("test")
v_name = 'v'
v0 = m0.addVar(lb=-1, ub=1, name=v_name)
m0.update()
m = m0.copy()
# returns True
print v0 in m.getVars()
m0.addConstr(v0 <= 0)
m0.update()
# won't work
#m.addConstr(v0 >= 0)
# will work
v = m.getVarByName(v_name)
m.addConstr(v >= 0)
m.update()
More complicated example:
from gurobipy import Model
v_name = {}
m0 = Model("test")
v0 = {}
for i in range(10):
v_name[i] = "v{0}".format(i)
v0[i] = m0.addVar(lb=-1, ub=1, name=v_name[i])
m0.update()
m = m0.copy()
v = {}
for i in range(10):
m0.addConstr(v0[i] <= 0)
v[i] = m.getVarByName(v_name[i])
m.addConstr(v[i] >= 0)
m0.update()
m.update()
... and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With