PuLPの概要とサンプルコードの実行
PuLPの概要
PuLPはPython
で実装された混合整数線形計画問題(MILP; Mixed Integer Linear Programming)などを解くにあたって用いられるライブラリです。
PuLPのインストール
下記のコマンドを実行することでPyPIからPuLPをダウンロードすることができます。
$ pip install PuLP
PuLPのサンプルコードの実行
PuLPのインストール確認にあたって下記のコードを実行します。
from pulp import *
x = LpVariable("x", 0, 3)
y = LpVariable("y", cat="Binary")
prob = LpProblem("myProblem", LpMinimize)
prob += x + y <= 2
prob += -4*x + y
status = prob.solve()
status = prob.solve(GLPK(msg = 0))
print(LpStatus[status])
print(value(x))
・実行結果
Result - Optimal solution found
Objective value: -8.00000000
Enumerated nodes: 0
Total iterations: 0
Time (CPU seconds): 0.00
Time (Wallclock seconds): 0.00
Option for printingOptions changed from normal to all
Total time (CPU seconds): 0.00 (Wallclock seconds): 0.00
Optimal
2.0
上記の問題では下記のような最適化問題について解いています。
\begin{align}
\mathrm{Objective} \quad &: -4x+y \quad \longrightarrow \quad \mathrm{Minimize} \\
\mathrm{Constraint} \quad &: x+y \leq 2, \, 0 \leq x \leq 3
\end{align}
この問題の最適解はx=2
,y=0
のとき-4x+y=-8
であるので、最適な結果の出力が得られていることが確認できます。