Skip to main content

Keyerror in objective function

Answered

Comments

5 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    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.
  • 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

Post is closed for comments.