PuLP—整数规划例子

一个简单的整数规划问题
m a x x + y + 2 z s . t . x + 2 y + 3 z ≤ 4 x + y ≥ 1 x , y , z b i n a r y \begin{aligned} & max & \quad x+y+2z \\ & \\ & s.t. \quad & x+2y+3z \le 4 \\ & \quad & x+y \ge 1 \\ & \quad & x,y,z \quad binary \end{aligned} maxs.t.x+y+2zx+2y+3z4x+y1x,y,zbinary

实现

Python代码:

# coding=utf-8

from pulp import LpProblem, LpVariable, LpConstraint, LpConstraintLE, LpConstraintGE, LpMaximize, LpBinary, LpStatus

# Create a new model
m = LpProblem(name="MIP Model", sense=LpMaximize)

# Create variables
x = LpVariable(cat=LpBinary, name="x")
y = LpVariable(cat=LpBinary, name="y")
z = LpVariable(cat=LpBinary, name="z")

# Add constraint: x + 2 y + 3 z <= 4
m += LpConstraint(e=(x + 2 * y + 3 * z), sense=LpConstraintLE, rhs=4, name='c0')

# Add constraint: x + y >= 1
m += LpConstraint(e=(x + y), sense=LpConstraintGE, rhs=1, name='c1')

# Set objective
m.setObjective(x + y + 2 * z)

# Calculate with the default CBC optimizer
status = m.solve()

if LpStatus[status] == 'Optimal':

    for v in m.variables():
        print('%s %g' % (v.name, v.varValue))

    print('Obj: %g' % m.objective.value())

输出:

x 1
y 0
z 1
Obj: 3

Bonus

其中约束条件和目标函数的写法可简写为:

# Add constraint: x + 2 y + 3 z <= 4
m += x + 2 * y + 3 * z <= 4, 'c0'

# Add constraint: x + y >= 1
m += x + y >= 1, 'c1'

# Set objective
m += x + y + 2 * z, 'Obj'

PuLP默认使用CBC优化器,如果想用其它的优化器:

from pulp.solvers import CPLEX, GUROBI

# Calculate with CPLEX or GUROBI
m.solve(solver=CPLEX())

如果优化器未安装,则会报pulp.solvers.PulpSolverError: PuLP: cannot execute cplex.exe错误。如何查询本地已安装的优化器,请看这篇文章

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

手撕机

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值