Pulp,用python来做线性规划

Pulp是一款python实现的非常强大的线性规划模型,两个字好用!
官网链接:https://code.google.com/p/pulp-or/
文档链接:http://www.coin-or.org/PuLP/index.html
需要安装pulp(easy_install)和glpk(apt-get)

入门程序:

max: 2 * x1 + 5 * x2
约束:
1.  2 * x1 - x2 <= 4
2.  x1 + 2 * x2 <= 9
3.  -x1 + x2 <= 3

代码:

from pulp import *
prob = LpProblem('lptest', LpMaximize)

x1 = LpVariable('x1', lowBound = 0)
x2 = LpVariable('x2', lowBound = 0)

prob += 2 * x1 + 5 * x2

prob += 2 * x1 - x2 <= 4
prob += x1 + 2 * x2 <= 9
prob += -x1 + x2 <= 3

GLPK().solve(prob)

for v in prob.variables():
    print v.name, '=', v.varValue

print 'objective =', value(prob.objective)

计算结果:

GLPSOL: GLPK LP/MIP Solver, v4.45
Parameter(s) specified in the command line:
 --cpxlp /tmp/3624-pulp.lp -o /tmp/3624-pulp.sol
Reading problem data from `/tmp/3624-pulp.lp'...
3 rows, 2 columns, 6 non-zeros
8 lines were read
GLPK Simplex Optimizer, v4.45
3 rows, 2 columns, 6 non-zeros
Preprocessing...
3 rows, 2 columns, 6 non-zeros
Scaling...
 A: min|aij| =  1.000e+00  max|aij| =  2.000e+00  ratio =  2.000e+00
Problem data seem to be well scaled
Constructing initial basis...
Size of triangular part = 3
*     0: obj =   0.000000000e+00  infeas =  0.000e+00 (0)
*     2: obj =   2.200000000e+01  infeas =  0.000e+00 (0)
OPTIMAL SOLUTION FOUND
Time used:   0.0 secs
Memory used: 0.0 Mb (40571 bytes)
Writing basic solution to `/tmp/3624-pulp.sol'...
x1 = 1.0
x2 = 4.0
objective = 22.0

来一发算法书上的单纯形法执行过程,备忘。
simplex

Tags : ,

0 thoughts on “Pulp,用python来做线性规划”

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Click the right image To submit your comment: