Skip to main content

Keyerror in objective function

Answered

Comments

4 comments

  • Jaromił Najman
    • Gurobi Staff

    You define variable \(X\) over the tuples in \(\texttt{proc_combo}\)\(\times\)\(\texttt{hours}\). Thus, you can access the tupledict returned by the addVars method via, e.g.,

    print(X[0.0, 0.0, 0.0 ,0])
    print(X[0.0, 1.0, 1.0 ,0])
    print(X[1.0, 1.0, 1.0 ,0])
    # etc

    However, what you are trying is to access the \(X\) variables via a tuple from the \(\texttt{proc_combo}\) dictionary and an entry from \(\texttt{hours}\). In other words, what you are trying to do is

    print(X[(0.0, 0.0, 0.0) ,0])
    print(X[(0.0, 1.0, 1.0) ,0])
    print(X[(1.0, 1.0, 1.0) ,0])

    which does not work. To make it work, you have to unpack the tuple via the \(\texttt{*}\) operator

    m.setObjective(quicksum(costs[combo]*X[(*combo),t]
                    for combo in proc_combo
                    for t in time_points), GRB.MINIMIZE)

    Best regards, 
    Jaromił

    0
  • Sander Mertens
    • Gurobi-versary
    • Curious
    • Conversationalist

    Thank you for your quick explanation, it solved the problem!

    0
  • Sander Mertens
    • Gurobi-versary
    • Curious
    • Conversationalist

    If you don't mind, I have a additional question.

    As can be seen before, the X variables have four subsets. In my objective function I want to sum all the X variables together, with an exclusion of the X variables in where the first subset is 3, so:

    Until now, I've only managed to sum all X variables with:

    m.addConstr((quicksum(X) <= n ), 'name')

    Is there a way to exclude these specific variables from the summation?

     

    0
  • Jaromił Najman
    • Gurobi Staff

    Yes, it is possible. You can use \(\texttt{for}\)-loops and \(\texttt{if}\)-clauses within the \(\texttt{quicksum}\) when constructing the list of variables. In your case, something like the following should work

    m.addConstr((quicksum(X[p,j,k,t] for p in P if p != 3 
    for j in J[p]
    for k in K[p]
    for t in T) <= n ), 'name')
    0

Please sign in to leave a comment.