Error in addConstr: KeyError
AnsweredHello, I am new to Gurobi. I am having difficulty modeling a constraint in Python-Gurobi.
My variable X looks like this:
'x[2_OD2,24]', 'x[2_OD2,234]', 'x[10_OD2,24]', 'x[10_OD2,234]'
I want a constraint as attached in the photo.

My attempt:
OD = {'2_OD2': [24, 234, 134], '10_OD2': [24, 234]}
X = mdl.addVars([(item, element) for item in OD for element in OD[item]], vtype = GRB.BINARY)
mdl.addConstrs(quicksum(X[item,j] for item in OD)==1 for j in OD[item])
-
Hi,
To get the constraints you need, you have to interchange the \(\texttt{for}\)-loops
m.addConstrs((gp.quicksum(X[item,j] for j in OD[item])==1) for item in OD)
To get nice names for your variables, you have to add them 1 by 1 and add a name. This is because, you have to loop over a dictionaries and the respective items of each key.
import gurobipy as gp
from gurobipy import GRB
m=gp.Model()
OD = {'2_OD2': [24, 234, 134], '10_OD2': [24, 234]}
X = {}
for item in OD:
for element in OD[item]:
X[item,element] = m.addVar(vtype=GRB.BINARY, name="X[%s,%d]"%(item,element))
m.addConstrs((gp.quicksum(X[item,j] for j in OD[item])==1) for item in OD)
m.write("myLP.lp")The write method will generate a human-readable LP file which you can analyze to check whether your model looks as it should.
Best regards,
Jaromił0 -
Thanks a ton!!
0 -
Hi Jaromił,
Just to clear up my understanding, what is the difference between the block I wrote for the addVars, which is-
X = mdl.addVars(((item, element) for item in OD for element in OD[item]), vtype = GRB.BINARY, name = "X")
and the one you suggested, which is-
for item in OD:
for element in OD[item]:
X[item,element] = m.addVar(vtype=GRB.BINARY, name="X[%s,%d]"%(item,element))In particular, when I check m.write() both produce the same output with the same names for the variables.
Is it just because yours' is more readable?
0 -
Hi Tanvir,
Is it just because yours' is more readable?
There is no particular reason. I did not have the tab open when trying to reproduce the issue and had to write it from memory and it was somehow easier for me to write it this way at this particular moment.
I think your version is well readable as well (maybe even better) and there is no advantage in using any of the versions.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
4 comments