在开始一个更大的问题之前,我试图做以下简单的优化问题示例。代码:
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:UsersmahabubalamDesktopWorksGUIwhiskas.py", line 85, in <module>
status = prob.solve(GLPK(msg = 0))
File "C:Python34libsite-packagespulp-1.5.6-py3.4.eggpulppulp.py", line 1619, in solve
status = solver.actualSolve(self, **kwargs)
File "C:Python34libsite-packagespulp-1.5.6-py3.4.eggpulpsolvers.py", line 335, in actualSolve
raise PulpSolverError("PuLP: cannot execute "+self.path)
pulp.solvers.PulpSolverError: PuLP: cannot execute glpsol.exe
谁能告诉我为什么会这样? 执行以下两步后,我已经成功运行了您的代码:
-
从
下载GLPKhttp://sourceforge.net/projects/winglpk/files/latest/download(如yyvind所述)
- 解压缩到(例如):
C:glpk_is_here
-
在运行python之前将GLPK二进制文件添加到系统路径中
C:>set PATH=%PATH%;C:glpk_is_hereglpk-4.55w64
-
使用与(3)相同的cmd窗口,使用python/ipython来运行您的代码:
C:>ipython your_code.py
-
查看结果
Out[4]: 2.0
好运。
当我在变量名中使用非法字符时,我得到了这个错误。从我在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
这在unbuntu中适合我:
sudo apt-get install python-glpk
sudo apt-get install glpk-utils
我想在windows中也有类似的解决方案
安装GLPK,例如从sourceforge.net/projects/winglpk
Mac - brew install glpk
终端
Homebrew是最好的。