繁体   English   中英

如何修复 Pulp 约束中的 Traceback(最近一次调用最后一次)错误

[英]How can I fix a Traceback (most recent call last) error in a Pulp constraint

我正在尝试使用 for 循环为这个线性优化问题添加约束。 约束是...... x1A + x1B + x1C + x1D = 1,x2A + x2B + x2C + x2D = 1,等等......

Traceback 错误发生在循环的第一次运行时,我正在努力找出原因。 任何帮助将不胜感激!

problem2 = LpProblem("Problem_2",LpMinimize)
Letter=['A','B','C','D']
Number=['1','2','3','4']
NumArray = [185,225,193,207],[200,190,175,225],[330,320,315,300],[375,389,425,445]
NumArray=makeDict([Number,Letter], NumArray)

[problem2_vars = LpVariable.dicts("x",(Number, Letter),lowBound=0,cat='Binary')
problem2_vars\['1'\]\['A'\]

problem2 += lpSum(\[problem2_vars\[i\]\[j\]*NumArray\[i\]\[j\] for i in Number for j in Letter\])

for j in Number:
    problem2 += lpSum(\[problem2_vars\[j,'A'\]\]) == 1,"%s"%j][1]

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-31-04a89d6c02e1> in <module>
      2 
      3 for j in Number[0:]:
----> 4     problem2 += lpSum([problem2_vars[j,'A']]) == 1,"%s"%j

KeyError: ('1', 'A')

您将很多语法问题打包到一小段代码中::)

几个指针:

  • 你为什么用反斜杠“逃避”一切?
  • 您不需要将变量放在列表中......不清楚您在列表括号中做了什么,等等。
  • 您的错误的主要问题是您没有将要使用的索引列表传递给LpVariable.dicts 您只是传入一个包含两个列表的元组。

将来,尝试像我在下面的示例中那样打印您的 model 以查看正在构建的内容。 如果您在谷歌上搜索pulp示例(或查看此站点上的许多标记),我认为您可以避免一些语法混乱。 祝你好运!

from pulp import *

p2 = LpProblem("p2", LpMinimize)

# data
ltrs = ['A', 'B']
nums = [1, 2]

coefs =  {  ('A', 1): 22,
            ('A', 2): 42,
            ('B', 1): 7,
            ('B', 2): 79}

x = LpVariable.dicts('x', indexs=coefs.keys(), cat='Binary')

# objective
p2 += lpSum(x[ltr, num] * coefs[ltr, num] for (ltr, num) in coefs.keys())

# constraint
for num in nums:
    p2 += lpSum(x[ltr, num] for ltr in ltrs) == 1

sol = p2.solve()

print(p2)

print(sol)

产量:

...
Result - Optimal solution found

Objective value:                49.00000000
Enumerated nodes:               0
Total iterations:               0
Time (CPU seconds):             0.00
Time (Wallclock seconds):       0.00

Option for printingOptions changed from normal to all
Total time (CPU seconds):       0.00   (Wallclock seconds):       0.00

p2:
MINIMIZE
22*x_('A',_1) + 42*x_('A',_2) + 7*x_('B',_1) + 79*x_('B',_2) + 0
SUBJECT TO
_C1: x_('A',_1) + x_('B',_1) = 1

_C2: x_('A',_2) + x_('B',_2) = 1

VARIABLES
0 <= x_('A',_1) <= 1 Integer
0 <= x_('A',_2) <= 1 Integer
0 <= x_('B',_1) <= 1 Integer
0 <= x_('B',_2) <= 1 Integer

1
[Finished in 242ms]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM