from pulp import *
#最大最適化問題
problem = LpProblem("LP", LpMaximize)
x = LpVariable("x", cat="Continues")
y = LpVariable("y", cat="Continues")
#条件式
problem += x >= 0
problem += y >= 0
problem += x+3*y <= 30
problem += 2*x+y <= 40
problem += x+2*y
#数理モデルを解く。
status = problem.solve()
print(LpStatus[status])
print("x = ", x.value(),"y = ", y.value(),"obj", problem.objective.value())
import pandas as pd
import pulp
# データの取得
require_df = pd.read_csv("./requires.csv")
gain_df = pd.read_csv("./gains.csv")
stock_df = pd.read_csv("./stocks.csv")
# リストの定義
P = gain_df["p"].to_list()
M = stock_df["m"].to_list()
# 定数の定義
stock = {row.m:row.stock for row in stock_df.itertuples()}
gain = {row.p:row.gain for row in gain_df.itertuples()}
require = {(row.p,row.m):row.require for row in require_df.itertuples()}
# 数理最適化モデルを定義
problem = pulp.LpProblem("LP2",pulp.LpMaximize)
# 変数の定義。
x = pulp.LpVariable.dicts("x", P, cat = "Continuous")
# 制約式の定義
for p in P:
problem += x[p] >= 0
for m in M:
problem += pulp.lpSum([require[p,m] *x[p] for p in P]) <= stock[m]
# 目的関数の定義
problem += pulp.lpSum([gain[p] * x[p] for p in P])
# 求解
status = problem.solve()
print("status", pulp.LpStatus[status])
# 計算結果の表示
for p in P:
print(p, x[p].value())
# リストの定義
P = gain_df["p"].to_list()
M = stock_df["m"].to_list()
製品名と材料名のリストを定義しています。
stock = {row.m:row.stock for row in stock_df.itertuples()}
gain = {row.p:row.gain for row in gain_df.itertuples()}
require = {(row.p,row.m):row.require for row in require_df.itertuples()}
定数を定義しています。
CSV からタプル型でデータを抽出して辞書型で格納しています。
# 数理最適化モデルを定義
problem = pulp.LpProblem("LP2",pulp.LpMaximize)
数理モデルを定義しています。
# 変数の定義。
x = pulp.LpVariable.dicts("x", P, cat="Continuous")
# 制約式の定義
for p in P:
problem += x[p] >= 0
for m in M:
problem += pulp.lpSum([require[p,m] *x[p] for p in P]) <= stock[m]
# 目的関数の定義
problem += pulp.lpSum([gain[p] * x[p] for p in P])
制約式、目的関数を定義しています。lpSum()は引数に指定したリストの総和を生成します。
# 求解
status = problem.solve()
print("status", pulp.LpStatus[status])
# 計算結果の表示
for p in P:
print(p, x[p].value())