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>
- Why can't m.addConstr(v >= 0) find the variable v when m.getVars() clearly shows v is in the model?
- Is there any other way to reuse the same set of variables and constraints in order to avoid rebuilding each model from scratch?
Software: Python 2.7.11 and Gurobi 6.5 on OS X El Capitan (also tested on Ubuntu 15.04)