KeyError: addConstr
AnsweredHello,
I am encountering keyError at the constraint highlighted in bold. The reproducible code is below. I want to have a set of constraints where my binary variables X are summed up to L[i]. I want to sum over X[i,j] for all i in pot_route and for all j in route_set only, when j meets certain conditions.
My constraints should look like:
L[12] = X[2_OD1,124] + X[2_OD1,1234] +
L[13] = X[2_OD1,134]
L[24] = X[2_OD1,124] + X[10_OD2, 24]
L[23] = X[2_OD1,1234] + X[10_OD2, 234]
L[34] = X[2_OD1,134] + X[2_OD1,1234] + X[10_OD2, 234]
However, I get a keyError when I use this code. Any help is much appreciated!
pot_route = {'2_OD1': [124, 1234, 134], '10_OD2': [24, 234]}
which_links_in_route = {134: [13, 34], 234: [23, 34], 1234: [12, 23, 34], 24: [24], 124: [12, 24]}
road_travel_time = {12: 4.5, 13: 5, 24: 6, 23: 0.8, 34: 5}
mdl = Model('OTR')
X = {}
z1 = {}
z2 = {}
for item in pot_route:
for element in pot_route[item]:
X[item,element] = mdl.addVar(vtype=GRB.BINARY, name="X[{0},{1}]".format(item,element))
mdl.addConstrs((quicksum(X[item,j] for j in pot_route[item])==1) for item in pot_route)
LC = {}
for item in road_travel_time:
route_set = []
for element in which_links_in_route:
if item in which_links_in_route[element]:
route_set.append(element)
mdl.addConstr(LC[item]==quicksum(X[i,j] for i in pot_route for j in route_set), LC)-
Official comment
This post is more than two years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum, or try Gurobot, our chatbot interface offering instant, expert-level support. -
Hi Tanvir,
The error you get occurs because you have to introduce \(\texttt{LC[item]}\) as an optimization variable first.
for item in road_travel_time:
route_set = []
for element in which_links_in_route:
if item in which_links_in_route[element]:
route_set.append(element)
LC[item] = mdl.addVar(lb=-GRB.INFINITY, name="LC[{0}]".format(item))
mdl.addConstr(LC[item]==quicksum(X[i,j] for i in pot_route for j in route_set), name="L[{0}]".format(item))However, this results in another key error which is caused by how you construct your \(\texttt{route_set}\).
KeyError: ('10_OD2', 1234)This means, that you try to access \(\texttt{X['10_OD2', 1234]}\) which is not defined. I don't know what you are trying to achieve with the \(\texttt{route_set}\) so I will leave this fix up to you. Maybe the following is already enough
dl.addConstr(LC[item]==quicksum(X[i,j] for i in pot_route for j in route_set if j in pot_route[i]), name="L[{0}]".format(item))Best regards,
Jaromił0
Post is closed for comments.
Comments
2 comments