How to use addVars() in GurobiPy using "if" conditional?
AnsweredI have defined a variable using addVar() method as follows:
for i in range(no_nodes):
for j in range(no_nodes):
for k in O:
if fij[i][j]==1 or mij[i][j]==1:
x[i,j,k] = m.addVar(vtype=GRB.INTEGER, name="x[%s,%s,%s]" %(i,j,k))
where fij and mij are model's parameters and O is an unordered set containing more than 1000 elements.
It works properly, and there is no issue in solving the model. I just wonder how this variable definition can be revised by applying the addVars() method instead of addVar()?
Thanks.

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,
Matthias1 
Hi Matthias,
Thanks for your help. Is the itertools.product method faster than the first one?
Thanks,
Vincent0 
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,
Matthias1
Please sign in to leave a comment.
Comments
3 comments