Skip to main content

Error in addConstr: KeyError

Answered

Comments

4 comments

  • Jaromił Najman
    • Gurobi Staff

    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
  • Krypt
    • Gurobi-versary
    • Investigator
    • Conversationalist

    Thanks a ton!!

    0
  • Krypt
    • Gurobi-versary
    • Investigator
    • Conversationalist

    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
  • Jaromił Najman
    • Gurobi Staff

    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.