Pulp中的线性整数优化
我在开始一个更复杂的问题之前,想先做一个简单的优化问题。代码如下:
from pulp import *
x = LpVariable("x", 0, 3)
y = LpVariable("y", 0, 1)
prob = LpProblem("myProblem", LpMinimize)
prob += x + y <= 2
#objective function
prob += -4*x + y
status = prob.solve(GLPK(msg = 0))
#results
value(x)
但是我遇到了以下错误:
Traceback (most recent call last):
File "C:\Users\mahabubalam\Desktop\Works\GUI\whiskas.py", line 85, in <module>
status = prob.solve(GLPK(msg = 0))
File "C:\Python34\lib\site-packages\pulp-1.5.6-py3.4.egg\pulp\pulp.py", line 1619, in solve
status = solver.actualSolve(self, **kwargs)
File "C:\Python34\lib\site-packages\pulp-1.5.6-py3.4.egg\pulp\solvers.py", line 335, in actualSolve
raise PulpSolverError("PuLP: cannot execute "+self.path)
pulp.solvers.PulpSolverError: PuLP: cannot execute glpsol.exe
有没有人能帮我理解一下这是为什么呢?
5 个回答
1
在Mac上,你可以在终端输入 brew install glpk
来安装。
Homebrew 是最好的工具。
1
安装GLPK,比如可以从sourceforge.net/projects/winglpk这个网站下载。
2
在Ubuntu系统上,这个方法对我有效:
sudo apt-get install python-glpk
sudo apt-get install glpk-utils
我觉得在Windows系统上也有类似的解决办法。
2
我在给变量起名字的时候用了不合法的字符,所以出现了这个错误。根据我在pulp的代码(具体来说是LpElement)中了解到的,像-+[] ->/
这些字符是不能用的,系统会把它们都替换成下划线。
发现这个错误后,我用下面这个函数来处理我的变量名,这样就解决了问题:
def variableName(s):
# illegalChars = "-+[] ->/"
s = s.replace("-","(hyphen)")
s = s.replace("+","(plus)")
s = s.replace("[","(leftBracket)")
s = s.replace("]","(rightBracket)")
s = s.replace(" ","(space)")
s = s.replace(">","(greaterThan)")
s = s.replace("/","(slash)")
return s
4
我成功运行了你的代码,做了以下两个步骤:
从这个链接下载GLPK:
http://sourceforge.net/projects/winglpk/files/latest/download(这是oyvind提到的)
- 把下载的文件解压到(比如说):
C:\glpk_is_here\
在运行python之前,把GLPK的程序添加到你的系统路径中:
C:\>set PATH=%PATH%;C:\glpk_is_here\glpk-4.55\w64
在(3)中使用的同一个命令窗口,用python或ipython来运行你的代码:
C:\>ipython your_code.py
查看结果:
Out[4]: 2.0
祝你好运。