我想设置一个二进制的四维变量,比如 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 ...)
让我分享一个小例子:
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
这是 Daniel Junglas 的回答,几乎逐字复制自https://developer.ibm.com/answers/questions/385771/decision-matrices-with-more-than-3-variables-for-d/
您可以使用任何元组作为键来访问字典中的变量:
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]
但是这种方法不支持稀疏维度,需要更多的括号来表示。