Copying Model
AnsweredHello,
I generate a model with several decision variables and constraints. Let's call it Model_1. Next, I want to use Model_1 and add new constraints to it in a while loop. However, after the loop, I want to work with the initial Model_1 without those extra constraints that I have added in the while loop. Can I make a copy of a Model_1 with Model_1.copy() and call it Model_2. Are all decision variables and constraints of Model_1 are in Model_2? How can I call decision variables and constraints of Model_2 in the while loop?
Model_1=Model()
x={}
for i in range(I):
x[i]=Model_1.addVar()
Model_1.addConstr()
Model_2=Model_1.copy()
while iteration<10:
Add constraints to Model_2
Model_2.update()
Model_2.optimize()
Back to Model_1
Thanks.

Yes, you can use Model.copy() for this purpose. However, as you noticed, copying a model doesn't give you local Python variables for the new model's Var/Constr objects. You can construct these data structures yourself using Model.getVarByName() and Model.getConstrByName().
Another (probably easier) approach is to only create one model, then use Model.remove() to remove the extra constraints once your loop completes. E.g.:
import gurobipy as gp
# Model: min{x : x >= 0}
m = gp.Model()
x = m.addVar(obj=1, name='x')
# Optimal objective is 0
m.optimize()
# Add constraints in loop
cons = []
for i in range(10):
# Add each Constr object to cons list
cons.append(m.addConstr(x >= i + 1))
# Optimal objective is i+1
m.optimize()
# Remove constraints added in loop above
for c in cons:
m.remove(c)
# Optimal objective is 0 again
m.optimize()0 
Hello,
when I use the method of Model.getVarByName(), I have the following problems：
subproblem1 = Model('branch1')
model.update() #have defined
subproblem1 = model.copy()
X = subproblem1.getVarByName('x_' + str(i) + '_' + str(j)) #name
print(X)
subproblem1.addConstr(X[index[0],index[1]] <= 0)
TypeError: 'NoneType' object is not subscriptable
(and the X is None)How can I solve this problem? Looking forward to your reply.
0
Please sign in to leave a comment.
Comments
2 comments