我想设置一个二进制的四维变量,比如Xac,但是docplex只有binary_var_cube函数来设置三维变量。如何创建一个四维模型?我发现有人用它来创建三维,并说它可以扩展到更多的dimensions.But,这是没有用的。
binary_var_dict((a,b,c) for a in ... for b in ... for c in ...)发布于 2019-04-24 16:13:03
让我来分享一个小例子:
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发布于 2019-04-24 16:38:54
以下是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]但是这个方法不支持稀疏维度,并且需要更多的括号来表示。
https://stackoverflow.com/questions/55821484
复制相似问题