如何删除 python 中 pulp 中约束的语法错误

how to remove Syntax error for constraints in pulp in python

下面的代码在这一行的 for 循环后显示语法错误

model += x[int((str((i*2)-1)+str(j)))] + x[int((str(i*2)+str(j)))]] <= 1

我希望变量像二维数组 x11、x12、x13 一样声明,因此我收到错误消息。

KeyError   
Traceback (most recent call last)
<ipython-input-95-19b3a6e81910> in <module>()
     19 for i in range (1, (Box//2)+1):
     20      for j in range (1,Pallet+1):
---> 21        model += x[int((str((i*2)-1)+str(j)))] + x[int((str(i*2)+str(j)))] <= 1
     22 
     23 

KeyError: 11

我检查了所有可能的选项,一切似乎都是正确的,有人请帮忙。

'''

from pulp import *
Box=6
Pallet=3
Variable_range=Box*Pallet

from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable
# Define the model
model = LpProblem(name="Container Loading", sense=LpMaximize)

# Define the decision variables
for i in range(1, Box+1):
    for j in range (1,Pallet+1):
      x = {int((str(i)+str(j))):LpVariable(name=f"x{i}_{j}",lowBound=0,upBound=1,cat='Integer')}
      print(x)

# Add constraints
for i in range (1, (Box//2)+1):
     for j in range (1,Pallet+1):
       model += x[int((str((i*2)-1)+str(j)))] + x[int((str(i*2)+str(j)))]] <= 1 # error at this line
        

#Set the objective
model += lpSum(x.values())

# Solve the optimization problem
status = model.solve()

# Get the results
print(f"status: {model.status}, {LpStatus[model.status]}")
print(f"objective: {model.objective.value()}")

for var in x.values():
    print(f"{var.name}: {var.value()}")


for name, constraint in model.constraints.items():
    print(f"{name}: {constraint.value()}")

'''

这是关于误解循环。在:

# Define the decision variables
for i in range(1, Box+1):
    for j in range (1,Pallet+1):
      x = {int((str(i)+str(j))):LpVariable(name=f"x{i}_{j}",lowBound=0,upBound=1,cat='Integer')}

print(x)

你每次都覆盖x。所以你最终 x 只包含一个元素。您可以通过将打印语句移动到循环之后来看到这一点。

更好的是:

# Define the decision variables
x = {int((str(i)+str(j))):LpVariable(name=f"x{i}_{j}",lowBound=0,upBound=1,cat='Integer') 
        for i in range(1, Box+1) for j in range (1,Pallet+1) }

print(x) 

尝试使用下面的代码。我改变了定义决策变量的方式。它没有抛出错误。

from pulp import *
Box=6
Pallet=3
Variable_range=Box*Pallet
x = {}
from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable
# Define the model
model = LpProblem(name="Container Loading", sense=LpMaximize)

# Define the decision variables
for i in range(1, Box+1):
    for j in range (1,Pallet+1):
      x[(i,j)] = pulp.LpVariable('x' + str(i) + '_' + str(j), 0, 1, LpBinary)
      print(x[(i,j)])

# Add constraints
for i in range (1, (Box//2)+1):
     for j in range (1,Pallet+1):
       model += x[(i*2-1,j)] + x[(i*2,j)] <= 1 # error at this line
        

#Set the objective
model += lpSum(x.values())

# Solve the optimization problem
status = model.solve()