使用Python进行纸浆线性求解器/线性优化

时间:2015-04-25 16:59:09

标签: python mathematical-optimization linear solver pulp

过去几个小时我一直在为Python安装不同的线性求解器和模块,存在各种安装和运行时错误。以下是我到目前为止所做的总结:

  • 我安装了Pulp w / pip install pulp

虽然据说包括COIN优化器,但事实并非如此。我跑了一个例子:

import pulp
# Create problem instance
giapetto = pulp.LpProblem("Giapetto's Workshop", pulp.LpMaximize)

# Define Variables with lower bounds of zero
x1 = pulp.LpVariable("Soldiers",0)
x2 = pulp.LpVariable("Trains",0)

# Add Objective
giapetto += 3*x1 + 2*x2, "Profit"

# Add Constraints
giapetto += 2*x1 + x2 <= 100,"Finishing Labor"
giapetto += x1 + x2 <= 80, "Carpentry Labor"
giapetto += x1 <= 40, "Soldier Demand"
giapetto += x1 + x2 == 20, "Minimum Production"

giapetto.solve()
#giapetto.solve(GLPK())

print pulp.LpStatus[giapetto.status]
print pulp.LpSenses[giapetto.sense], giapetto.objective.name, "=", pulp.value(giapetto.objective)

..包含在Pulp的文档中,并收到此错误:

AttributeError:'NoneType'对象没有属性'actualSolve'

我在导入GLPK后尝试了它(brew install glpk;它花费了大约30分钟bc的缺失gcc依赖关系),并得到了错误:

NameError:名称'GLPK'未定义

但是,当我在iPython中模拟命令行时,我能够运行GLPK:

%%script glpsol -m /dev/stdin -o /dev/stdout --out output

# declare problem variables
var x;
var y;
var z;

# list all equations
eqn1 : 3*x + 2*y + z = 12;
eqn2 : 2.1*x + y = -3;
eqn3 : y - z = 4;

# solve
solve;

# display results
display x, y, z;

end;

print output

[Out:]
GLPSOL: GLPK LP/MIP Solver, v4.52
Parameter(s) specified in the command line:
 -m /dev/stdin -o /dev/stdout
Reading model section from /dev/stdin...
18 lines were read
Generating eqn1...
Generating eqn2...
Generating eqn3...
Model has been successfully generated

所以,我的问题有两个:

  1. 如何使用第一个代码示例(不使用命令行)运行GLPK(或任何解算器)?
  2. 是否有一个与Python更兼容或更易于使用的解算器,我可以从下面的列表中使用内联?
  3. * Solver pulp.solvers.GLPK_CMD passed.
    Solver pulp.solvers.PULP_CBC_CMD unavailable
    Solver pulp.solvers.CPLEX_DLL unavailable
    Solver pulp.solvers.CPLEX_CMD unavailable
    Solver pulp.solvers.CPLEX_PY unavailable
    Solver pulp.solvers.COIN_CMD unavailable
    Solver pulp.solvers.COINMP_DLL unavailable
    Solver pulp.solvers.GLPK_CMD unavailable
    Solver pulp.solvers.XPRESS unavailable
    Solver pulp.solvers.GUROBI unavailable
    Solver pulp.solvers.GUROBI_CMD unavailable
    Solver pulp.solvers.PYGLPK unavailable
    Solver pulp.solvers.YAPOSIB unavailable

2 个答案:

答案 0 :(得分:0)

对于我使用ubuntu而言,只需从存储库中安装硬币或库就可以完美地完成:

sudo apt-get install coinor-cbc coinor-clp

请记住,商业解决方案是如此昂贵,有充分理由;但在很多情况下,硬币求解器对我很有帮助。

答案 1 :(得分:0)

您可以在此处下载(免费软件)COIN-OR解算器: http://www.coin-or.org/download/binary/SYMPHONY/

安装完成后你可以使用giapetto.solve(),它应该自动检测并使用COIN-OR解算器。