Skip to main content

How to use addVars() in GurobiPy using "if" conditional?

Answered

Comments

3 comments

  • Matthias Miltenberger
    Gurobi Staff Gurobi Staff

    Hi Vincent!

    You can do the following to use addVars() and reduce the code to a single line:

    x = m.addVars([(i,j,k) for i in no_nodes for j in no_nodes for k in O if fij[i][j] or mij[i][j]],
    vtype=GRB.INTEGER, name="x")

    The name property will automatically be indexed for every single variable and assuming that fij and mij are binaries, you can also omit the "==1" part.

    You may also use itertools.product:

    from itertools import product
    x = m.addVars([(i,j,k) for (i,j) in product(no_nodes,repeat=2) for k in O if fij[i][j] or mij[i][j]],
    vtype=GRB.INTEGER, name="x")

    Cheers,
    Matthias

    1
  • Vincent
    Curious
    Gurobi-versary
    Conversationalist

    Hi Matthias,

    Thanks for your help. Is the itertools.product method faster than the first one?

    Thanks,
    Vincent

    0
  • Matthias Miltenberger
    Gurobi Staff Gurobi Staff

    Hi Vincent,

    Honestly, I wouldn't worry about the performance of either implementation. Most likely, adding the variables is more expensive than looping over your lists. I would go with the implementation that results in more readable, maintainable, and extendable code.

    Cheers,
    Matthias

    1

Please sign in to leave a comment.