我想设置一个二进制的四维变量,例如X [a] [b] [c] [d],所以bur docplex仅具有函数binary_var_cube
来设置三维。如何创建四维?
我发现有人用它来创建三维尺寸,并说可以扩展到更大的尺寸。但这没用。
binary_var_dict((a,b,c) for a in ... for b in ... for c in ...)
答案 0 :(得分:2)
然后让我分享一个小例子:
from docplex.mp.model import Model
# Data
r=range(1,3)
i=[(a,b,c,d) for a in r for b in r for c in r for d in r]
print(i)
mdl = Model(name='model')
#decision variables
mdl.x=mdl.integer_var_dict(i,name="x")
# Constraint
for it in i:
mdl.add_constraint(mdl.x[it] == it[0]+it[1]+it[2]+it[3], 'ct')
mdl.solve()
# Dislay solution
for it in i:
print(" x ",it," --> ",mdl.x[it].solution_value);
给出
[(1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 2, 1), (1, 1, 2, 2), (1, 2, 1, 1), (1, 2, 1, 2), (1, 2, 2, 1), (1, 2, 2, 2), (2, 1, 1, 1), (2, 1, 1, 2), (2, 1, 2, 1), (2, 1, 2, 2), (2, 2, 1, 1), (2, 2, 1, 2), (2, 2, 2, 1), (2, 2, 2, 2)]
x (1, 1, 1, 1) --> 4.0
x (1, 1, 1, 2) --> 5.0
x (1, 1, 2, 1) --> 5.0
x (1, 1, 2, 2) --> 6.0
x (1, 2, 1, 1) --> 5.0
x (1, 2, 1, 2) --> 6.0
x (1, 2, 2, 1) --> 6.0
x (1, 2, 2, 2) --> 7.0
x (2, 1, 1, 1) --> 5.0
x (2, 1, 1, 2) --> 6.0
x (2, 1, 2, 1) --> 6.0
x (2, 1, 2, 2) --> 7.0
x (2, 2, 1, 1) --> 6.0
x (2, 2, 1, 2) --> 7.0
x (2, 2, 2, 1) --> 7.0
x (2, 2, 2, 2) --> 8.0
致谢
答案 1 :(得分:2)
这是丹尼尔·荣格拉斯(Daniel Junglas)的回答,几乎逐字抄录了https://developer.ibm.com/answers/questions/385771/decision-matrices-with-more-than-3-variables-for-d/
您可以使用任何Arue元组作为键来从字典访问变量:
x = m.binary_var_dict((i, l, t, v, r)
for i in types
for l in locations
for t in times
for v in vehicles
for r in routes)
然后您可以使用以下命令访问变量:
for i in types:
for l in locations:
for t in times:
for v in vehicles:
for r in routes:
print x[i, l, t, v, r]
您也可以使用:
x = [[[[[m.binary_var('%d_%d_%d_%d_%d' % (i, l, t, v, r))
for r in routes]
for v in vehicles]
for t in times]
for l in locations]
for i in types]
for i in types:
for l in locations:
for t in times:
for v in vehicles:
for r in routes:
print x[i][l][t][v][r]
但是此方法不支持稀疏维度,并且需要更多的方括号来表示。