"int object is not callable" 使用 PuLP 代码时出错

"int object is not callable" error using PuLP code

我正在学习 PuLP 库的工作原理,它是一个线性规划求解器。 我正在使用的代码是在此处找到的:LINK。它解决了以下优化问题(在本例中,使用二进制变量 x_{ij}):

这是教程中的代码:

import random
import pulp as plp

#Creating random constants for the model's input
n = 10
m = 5
set_I = range(1, n+1)
set_J = range(1, m+1)
c = {(i,j): random.normalvariate(0,1) for i in set_I for j in set_J}
a = {(i,j): random.normalvariate(0,5) for i in set_I for j in set_J}
l = {(i,j): random.randint(0,10) for i in set_I for j in set_J}
u = {(i,j): random.randint(10,20) for i in set_I for j in set_J}
b = {j: random.randint(0,30) for j in set_J}

opt_model = plp.LpProblem(name="Binary Model")


# if x is Binary
x_vars  = {(i,j):
plp.LpVariable(cat=plp.LpBinary, name="x_{0}_{1}".format(i,j)) 
for i in set_I for j in set_J}


# Less than equal constraints
constraints = {j : opt_model.addConstraint(
plp.LpConstraint(
             e=m(a[i,j] * x_vars[i,j] for i in set_I),
             sense=plp.plp.LpConstraintLE,
             rhs=b[j],
             name="constraint_{0}".format(j)))
       for j in set_J}

objective = plp.lpSum(x_vars[i,j] * c[i,j] 
                    for i in set_I 
                    for j in set_J)

# for minimization
opt_model.sense = plp.LpMinimize
opt_model.setObjective(objective)

我收到以下我不理解的错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-08e33a7305cc> in <module>
     28              rhs=b[j],
     29              name="constraint_{0}"))
---> 30        for j in set_J}
     31 
     32 objective = plp.lpSum(x_vars[i,j] * c[i,j] 

<ipython-input-20-08e33a7305cc> in <dictcomp>(.0)
     28              rhs=b[j],
     29              name="constraint_{0}"))
---> 30        for j in set_J}
     31 
     32 objective = plp.lpSum(x_vars[i,j] * c[i,j] 

TypeError: 'int' object is not callable

您的代码包含以下内容作为 plp.LpConstraint 的参数:

e=m(a[i,j] * x_vars[i,j] for i in set_I)

m 被定义为 int,但被作为函数调用。它应该是:

e=plp.lpSum(a[i,j] * x_vars[i,j] for i in set_I)

这就是错误的原因,似乎只是您指南中的错字。同一表达式中的另一个错字是 plp.plp.LpConstraintLE 应该只是 plp.LpConstraintLE.

一旦你清除了这两个错误,你应该就可以解锁了,继续 opt_model.solve() 将解决模型。


您可能会发现以下代码更具可读性,可用于解决 pulp 中的此问题,例如使用 LpVariable.dicts 等出色的 pulp 功能。我一直喜欢 pulp 的一点是模型创建代码实际上非常易读。

import pulp

### Create n, m, set_I, set_J, c, a, l, u, and b as before

# Model
opt_mod = pulp.LpProblem(name="Binary_model", sense=pulp.LpMinimize)

# Variables from a dictionary
x_vars = pulp.LpVariable.dicts("x", c.keys(), cat=pulp.LpBinary)

# Constraints
for j in set_J:
    opt_mod += pulp.lpSum(a[i,j] * x_vars[i,j] for i in set_I) <= b[j]

# Objective
opt_mod += pulp.lpSum(c[i,j] * x_vars[i,j] for i,j in c)

# Solve
opt_mod.solve()

# Which variables are set?
print([x for x in x_vars if x_vars[x].varValue > 0.999])