How can I use addVars for indexes that are dependant? (in Python)
回答済みHello. I have a code with a binary variable that has 3 indexes: 'x[i,j,k]'
I understand that for instance, if
I = [1,2,3]
J=[1,2]
K=[1,2,3,4]
x = m.addVars(I,J,K,vtype = GRB.BINARY,name = 'X') would create 4*3*2 = 24 variables no problem.
What if I had not J bui J(i), such as:
I = [1,2,3]
Ji=[[1,2],[1],[2]]
K = [1,2,3,4]
How can I create the 1*2*4 + 1*1*4 + 1*1*4 = 16 variables?
This code doesn't seem to respond properly, why so?
for i in I:
J = J[i-1]
x = m.addVars(I,J,K,vtype = GRB.BINARY,name = 'X')
Thank you in advance.
-
正式なコメント
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. -
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 -
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
投稿コメントは受け付けていません。
コメント
3件のコメント