首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用python在docplex中设置一个四维变量?

如何用python在docplex中设置一个四维变量?
EN

Stack Overflow用户
提问于 2019-04-24 10:20:33
回答 2查看 699关注 0票数 0

我想设置一个二进制的四维变量,比如Xac,但是docplex只有binary_var_cube函数来设置三维变量。如何创建一个四维模型?我发现有人用它来创建三维,并说它可以扩展到更多的dimensions.But,这是没有用的。

代码语言:javascript
复制
binary_var_dict((a,b,c) for a in ... for b in ... for c in ...)
EN

回答 2

Stack Overflow用户

发布于 2019-04-24 16:13:03

让我来分享一个小例子:

代码语言:javascript
复制
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); 

这给了我们

代码语言:javascript
复制
[(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
票数 2
EN

Stack Overflow用户

发布于 2019-04-24 16:38:54

以下是Daniel Junglas的回答,几乎是逐字抄袭自https://developer.ibm.com/answers/questions/385771/decision-matrices-with-more-than-3-variables-for-d/

您可以使用任意数量的元组作为键来访问字典中的变量:

代码语言:javascript
复制
 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)

然后,您可以使用以下命令访问变量:

代码语言:javascript
复制
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]

你也可以使用:

代码语言:javascript
复制
 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]

但是这个方法不支持稀疏维度,并且需要更多的括号来表示。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55821484

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档