Skip to main content

How can I use addVars for indexes that are dependant? (in Python)

Answered

Comments

3 comments

  • Official comment
    Simranjit Kaur
    • Gurobi Staff
    This post is more than three 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.
  • Simon Bowly
    • Gurobi Staff

    Hi Eduardo,

    You can build sparse indexes like this, but you'll need to create a list of index tuples explicitly first and pass it to addVars. One way to do this is the following:

    I = [1, 2, 3]
    Ji = [[1, 2], [1], [2]]
    K = [1, 2, 3, 4]

    indices = [(i, j, k) for i, J in zip(I, Ji) for j in J for k in K]
    x = m.addVars(indices, name='X')

    (Your original code was close to what you needed, but you wind up creating separate subsets of variables and overwriting 'x' on each pass in the loop)

    0
  • Eduardo Praça
    • Gurobi-versary
    • First Question
    • First Comment

    Thank you! It works properly now!

    Another way would be to create with a dictionary, but I've no idea if it would work when putting constrains. Anyway, the one above is faster.

     

    Best Regards,

    Eduardo.

     

    x={}
    for i in I:
      J = Ji[i-1]
      for j in J:
          for k in K:
              x[i,j,k] = m.addVar(vtype = GRB.BINARY, name=f'X[{i},{j},{k}]')
    0

Post is closed for comments.