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错误。如何查询本地已安装的优化器,请看这篇文章

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页