利用Pulp解决线性规划问题

一、常用的线性规划求解器

  • Excel
  • Lingo
  • Matlab

二、Python interface for optimization

  • Pulp
    • LP Modules
  • OpenOpt
    • LP Modules
    • non-LP Modules

三、Pulp

3.1 安装pulp
1
pip install pulp
3.2 导入库函数
1
from pulp import *
3.3 定义线性规划问题
1
PB = LpProblen(Problem name, sense)

构造函数,用来构造一个LP问题实例,其中name指定问题名(输出信息用),sense值是 LpMinimize 或 LpMaximize 中的一个,用来指定目标函数是求最大值还是最小值。

3.4 定义决策变量
1
X1 = LpVariable(variable name, lowbound, upbound, category)

variable name 指定变量名, lowbound 和 upbound 是下界和上界,默认分别是 -inf 到 inf,category 用来指定变量是离散(LpInteger,LpBinary)还是连续(LpContinuous)。

3.5 添加目标函数
1
PB += linear objective in equantion for objective name
3.6 添加约束条件
1
PB += linear objective in equantion for constraint name
3.7 写入LP文件
1
PB.writeLP(filename)
3.8 模型求解
1
PB.slove()
3.9 结果显示
1
pulp.LpStatus[PB.status]

四、Python实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from pulp import * 

prob = LpProblem('Problem1', LpMaximize)

x1 = LpVariable('x1', 0, None, LpContinuous)
x2 = LpVariable('x2', 0, None, LpContinuous)
x3 = LpVariable('x2', 0, None, LpContinuous)

prob += 1000 * x1 + 2000 * x2 + 3000 * x3

prob += x1 + 2 * x2 + 3 * x3 <= 10
prob += 0 * x1 + x2 + 2 * x3 <= 5

prob.writeLP('Problem1.lp')
prob.solve()

print("status: ", LpStatus[prob.status])
for v in prob.variables():
print(v.name,'=',v.variable)
print("Maximun Profit = ", value(prob.objective))