使用PuLP代码的“无法调用int对象”错误

我正在学习PuLP库的工作原理,这是一个线性编程求解器。 我正在使用的代码位于LINK。它解决了以下优化问题(在这种情况下,使用二进制变量x_ {ij}):

使用PuLP代码的“无法调用int对象”错误

这是教程中的代码:

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,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] 

<ipython-input-20-08e33a7305cc> in <dictcomp>(.0)
     28              rhs=b[j],j] 

TypeError: 'int' object is not callable
kirecetycike 回答:使用PuLP代码的“无法调用int对象”错误

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

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

m被定义为一个int,但被称为一个函数。相反,它应该是:

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

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

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


您可能会发现以下代码更具可读性,可用于解决纸浆中的此问题,例如,使用LpVariable.dicts之类的漂亮纸浆功能。我一直很喜欢纸浆的一件事是,模型创建代码实际上非常易读。

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] for i in set_I) <= b[j]

# Objective
opt_mod += pulp.lpSum(c[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])
本文链接:https://www.f2er.com/2793806.html

大家都在问