Skip to main content

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

Answered

Comments

2 comments

  • Simon Bowly
    Gurobi Staff 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

Please sign in to leave a comment.