Adding new variables to existing model
AnsweredDear all,
I am working on the following model:
m = Model('Test')
first_set = list(range(3))
second_set = list(range(3))
x = m.addVars(first_set, second_set, vtype=GRB.CONTINUOUS) #9
y = m.addVars(second_set, vtype=GRB.BINARY) #3
m.addConstrs(x[i,j] <= y[j] for i in first_set for j in second_set)
m.addConstrs(quicksum(x[i,j] for j in second_set) >= 1 for i in first_set)
m.setObjective(quicksum(y[k] for k in second_set), GRB.MINIMIZE)
m.optimize()
However, if I 'simply' want to add some variables, the model becomes infeasible:
first_set.append(3)
for j in second_set:
x[3,j] = m.addVar(3,j, vtype=GRB.CONTINUOUS)
m.update()
m.optimize()
for v in m.getVars():
print(v.VarName, v.X)
Why can I observe this behaviour and how can I circumvent it? Thanks in advance!
Best wishes,
Jonas

Hi Jonas,
The lines
for j in second_set:
x[3,j] = m.addVar(3,j, vtype=GRB.CONTINUOUS)add variables with lower bound 3 and upper bound j=0/1/2 which is infeasible.
In general, the article How do I determine why my model is infeasible? might help.
Best regards,
Marika0 
You probably wanted to do something like
x[3] = m.addVars(second_set, vtype=GRB.CONTINUOUS)
which adds multiple variables without defining specific bounds?
0 
Hi Marika,
thanks, this helps!
However, the new variables are not forced to fulfill the following constraint:m.addConstrs(quicksum(x[i,j] for j in second_set) >= 1 for i in first_set)
How can I change this? Thanks!
Best wishes,
Jonas0 
In your example, it was not clear that "3" is an index of first_set and that you need a variable for each pair of first_set, second_set.Did you try
x = m.addVars(first_set, second_set, vtype=GRB.CONTINUOUS)
?Then your constraints should work.0 
Yes, I tried, but unfortunately it does not work. Do I have to use the 'column' attribute here? Or is there a more convenient way?
0 
Ok, I see.
Yes, you need to use the column argument like in the feasopt.py example (see also Modify a model) and add the variables individually with addVar().0 
Okay, I see. Thanks a lot!
0
Please sign in to leave a comment.
Comments
7 comments