YOUTUBE PLAYLIST
講義動画
本書の各章を解説する講義動画(全 11 本)を YouTube で公開しています。各章の動画は、下のサンプルコードの章見出しからも開けます。
本書について
本書は、Postek, Zocca, Gromicho, Kantor によるオンライン書籍 Hands-On Mathematical Optimization with AMPL in Python(2024)を、AMPL 社の承諾を得て翻訳したものです。代数モデリング言語 AMPL と、それを Python から操作するライブラリ amplpy を道具に、約 50 の実問題を通して数理最適化を学びます。
第 1 章で数理最適化と AMPL・amplpy の使い方を学び、第 2〜6 章で線形・混合整数線形・ネットワーク・凸・錐最適化へと問題のクラスを広げます。第 7〜10 章では感度分析、ロバスト最適化、確率的最適化、2 段階問題といった、データが不確実な状況を扱います。
このページでは、本書の各節に対応する Python コード(50 ファイル)と、それが読み込む AMPL モデル(84 ファイル)・データ(18 ファイル)を章ごとに配布しています。
実行環境の準備
Python 3.9 以降で動作します。Google Colab でもそのまま実行できます(その場合はセッションごとにインストールが必要です)。
-
amplpy と補助ライブラリをインストールします。
python -m pip install amplpy matplotlib pandas -
各コードの冒頭にある
ampl_notebook()が、modules引数で指定したソルバー(HiGHS、CBC、Ipopt、MOSEK など)を自動的に導入します。from amplpy import AMPL, ampl_notebook ampl = ampl_notebook( modules=["highs"], # 使うソルバー license_uuid="default", # 使うライセンス ) -
サンプルコード一式を展開し、章のディレクトリ(例:
code/02)を作業ディレクトリにして Jupyter や VS Code で開き、# %%で区切られたセルを上から順に実行します。モデル(.mod)とデータは同じディレクトリから読み込まれます。
コードについての注意
- 各
.pyファイルは、本書のもとになったノートブックのコードセルを取り出したものです。# %%の区切りが 1 つのセルに対応します。 - ノートブックで
%%writefileによって書き出していた AMPL モデルは、同じ名前の.modファイルとして同梱しています。各節の「この節のモデル」から内容を確認できます。 %%ampl_evalのセルは、同じ働きをするampl.eval(r"""…""")に置き換えています。インストール用の%pip行は除き、%timeと%timeitはマジックを外して文だけを残しています。- 第 9 章の
seafood.pyでは同じ名前のモデルseafood.modを 2 度書き出しているため、2 つ目をseafood_2.modとして同梱し、コードもそれに合わせています。 - データの多くは、コード中で GitHub 上の URL から読み込んでいます。同梱のデータファイルは、オフラインで実行するときなどに URL の代わりに使ってください(第 4 章の暗号資産の裁定取引は、手元の CSV を読み込みます)。
- 原著のノートブック(英語)は ampl.com/mo-book で公開されています。
サンプルコード
第1章数理最適化2 ファイル▶ 講義動画(18:20)
基本的なAMPLモデル production-planning-basic.py 11 セル ・ 120 行 ・ モデル 1
この節のモデル(1)
AMPLproduction_planning_basic.mod
# decision variables
var x_M >= 0;
var x_A >= 0, <= 80;
var x_B >= 0, <= 100;
var y_U >= 0, <= 40;
var y_V >= 0;
# auxiliary variables
var revenue = 270 * y_U + 210 * y_V;
var cost = 10 * x_M + 50 * x_A + 40 * x_B;
# objective
maximize profit: revenue - cost;
# constraints
s.t. raw_materials: 10 * y_U + 9 * y_V <= x_M;
s.t. labor_A: 2 * y_U + 1 * y_V <= x_A;
s.t. labor_B: 1 * y_U + 1 * y_V <= x_B;
# %%
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc", "highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
ampl.eval(r"""
# define decision variables
reset;
var xM >= 0;
var xA >= 0, <= 80;
var xB >= 0, <= 100;
var yU >= 0, <= 40;
var yV >= 0;
""")
# %%
ampl.eval(r"""
# define objective function
maximize Profit:
270*yU + 210*yV - 10*xM - 50*xA - 40*xB;
""")
# %%
ampl.eval(r"""
# define constraints
subj to raw_materials: 10*yU + 9*yV <= xM;
subj to labor_A: 2*yU + 1*yV <= xA;
subj to labor_B: 1*yU + 1*yV <= xB;
""")
# %%
# exhibit the model that has been built
ampl.eval("show;")
ampl.eval("expand;")
# solve using two different solvers
ampl.solve(solver="cbc")
assert ampl.solve_result == "solved", ampl.solve_result
ampl.solve(solver="highs")
assert ampl.solve_result == "solved", ampl.solve_result
# %%
solution = ampl.get_solution(zeros=True)
print(solution)
print("xM", solution["xM"])
print("xA", solution["xA"])
print("xB", solution["xB"])
print("yU", solution["yU"])
print("yV", solution["yV"])
# %%
# display a component of the model
ampl.display("Profit")
ampl.display("270*yU + 210*yV", "10*xM + 50*xA + 40*xB")
ampl.display("_varname", "_var")
# %%
print(f" Profit = {ampl.get_value('Profit'): 9.2f}")
print(f"Revenue = {ampl.get_value('270*yU + 210*yV'): 9.2f}")
print(f" Cost = {ampl.get_value('10*xM + 50*xA + 40*xB'): 9.2f}")
# %%
import pandas as pd
# create pandas series for production and raw materials
production = pd.Series(
{
"U": ampl.get_value("yU"),
"V": ampl.get_value("yV"),
}
)
raw_materials = pd.Series(
{
"A": ampl.get_value("xA"),
"B": ampl.get_value("xB"),
"M": ampl.get_value("xM"),
}
)
# display pandas series
display(production)
display(raw_materials)
# %%
import matplotlib.pyplot as plt
# create grid of subplots
fig, ax = plt.subplots(1, 2, figsize=(8, 2))
# show pandas series as horizontal bar plots
production.plot(ax=ax[0], kind="barh", title="Production")
raw_materials.plot(ax=ax[1], kind="barh", title="Raw Materials")
# show vertical axis in descending order
ax[0].invert_yaxis()
ax[1].invert_yaxis()
# %%
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("production_planning_basic.mod")
# Select a solver and solve the problem
ampl.solve(solver="highs")
assert ampl.solve_result == "solved", ampl.solve_result
データ駆動型AMPLモデル production-planning-advanced.py 11 セル ・ 204 行 ・ モデル 1
この節のモデル(1)
AMPLproduction_planning.mod
# define sets
set PRODUCTS;
set RESOURCES;
# define parameters
param demand {PRODUCTS} >= 0;
param price {PRODUCTS} > 0;
param available {RESOURCES} >= 0;
param cost {RESOURCES} > 0;
param need {RESOURCES,PRODUCTS} >= 0;
# define variables
var Use {r in RESOURCES} >= 0, <= available[r];
var Sell {p in PRODUCTS} >= 0, <= demand[p];
# define objective function
maximize Profit:
sum {p in PRODUCTS} price[p] * Sell[p] -
sum {r in RESOURCES} cost[r] * Use[r];
# create indexed constraint
subject to ResourceLimit {r in RESOURCES}:
sum {p in PRODUCTS} need[r,p] * Sell[p] <= Use[r];
# %%
Inf = float("inf")
products = {
"U": {"demand": 40, "price": 270},
"V": {"demand": Inf, "price": 210},
}
resources = {
"M": {"available": Inf, "cost": 10},
"A": {"available": 80, "cost": 50},
"B": {"available": 100, "cost": 40},
}
processes = {
"U": {"M": 10, "A": 2, "B": 1},
"V": {"M": 9, "A": 1, "B": 1},
}
# %%
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
ampl.eval(r"""
# define sets
set PRODUCTS;
set RESOURCES;
""")
# %%
ampl.eval(r"""
# define parameters
param demand {PRODUCTS} >= 0;
param price {PRODUCTS} > 0;
param available {RESOURCES} >= 0;
param cost {RESOURCES} > 0;
param need {RESOURCES,PRODUCTS} >= 0;
""")
# %%
ampl.eval(r"""
# define variables
var Use {r in RESOURCES} >= 0, <= available[r];
var Sell {p in PRODUCTS} >= 0, <= demand[p];
""")
# %%
ampl.eval(r"""
# define objective function
maximize Profit:
sum {p in PRODUCTS} price[p] * Sell[p] -
sum {r in RESOURCES} cost[r] * Use[r];
""")
# %%
ampl.eval(r"""
# create indexed constraint
subject to ResourceLimit {r in RESOURCES}:
sum {p in PRODUCTS} need[r,p] * Sell[p] <= Use[r];
""")
# %%
# set data
PRODUCTS = products.keys()
RESOURCES = resources.keys()
# product data
demand = {k: v["demand"] for k, v in products.items()}
price = {k: v["price"] for k, v in products.items()}
# resource data
available = {k: v["available"] for k, v in resources.items()}
cost = {k: v["cost"] for k, v in resources.items()}
need = {(r, p): value for p in processes.keys() for r, value in processes[p].items()}
print(PRODUCTS, RESOURCES)
print(demand, price)
print(available, cost)
print(need)
# %%
# load set data
ampl.set["PRODUCTS"] = PRODUCTS
ampl.set["RESOURCES"] = RESOURCES
# load parameter data
ampl.param["price"] = price
ampl.param["demand"] = demand
ampl.param["cost"] = cost
ampl.param["available"] = available
ampl.param["need"] = need
# set solver and solve
ampl.solve(solver="highs")
assert ampl.solve_result == "solved", ampl.solve_result
# %%
# create a solution report
print(f"Profit = {ampl.obj['Profit'].value()}")
print("\nProduction Report")
for product, Sell in ampl.var["Sell"].to_dict().items():
print(f" {product} produced = {Sell}")
print("\nResource Report")
for resource, Use in ampl.var["Use"].to_dict().items():
print(f" {resource} consumed = {Use}")
# %%
import pandas as pd
from IPython.display import display # 追加
class ProductionModel(AMPL):
"""
A class representing a production model using AMPL.
"""
def __init__(self, products, resources, processes):
"""
Initialize ProductionModel as an AMPL instance.
:param products: A dictionary containing product information.
:param resources: A dictionary containing resource information.
:param processes: A dictionary containing process information.
"""
super(ProductionModel, self).__init__()
# save data in the model instance
self.products = products
self.resources = resources
self.processes = processes
# flag to monitor solution status
self.solved = False
def load_data(self):
"""
Prepare the data and pass the information to AMPL.
"""
# convert the data dictionaries into pandas data frames
products = pd.DataFrame(self.products).T
resources = pd.DataFrame(self.resources).T
processes = pd.DataFrame(self.processes).T
products.index.name = "PRODUCTS"
resources.index.name = "RESOURCES"
# display the generated data frames
display(products)
display(resources)
display(processes)
# pass data to AMPL
self.set_data(products,"PRODUCTS")
self.set_data(resources, "RESOURCES")
self.param["need"] = processes.T
def solve(self, solver="highs"):
"""
Read the model, load the data, set the solver and solve the optimization problem.
"""
self.read("production_planning.mod")
self.load_data()
self.option["solver"] = solver
super(ProductionModel, self).solve()
self.solved = True
def report(self):
"""
Solve, if necessary, then report the model solution.
"""
if not self.solved:
self.solve()
print(f"Profit = {self.obj['Profit'].value()}")
print("\nProduction Report")
Sell = self.var["Sell"].to_pandas()
Sell.rename(columns={Sell.columns[0]: "produced"}, inplace=True)
Sell.index.rename("PRODUCTS", inplace=True)
display(Sell)
print("\nResource Report")
Use = self.var["Use"].to_pandas()
Use.rename(columns={Use.columns[0]: "consumed"}, inplace=True)
Use.index.rename("RESOURCES", inplace=True)
display(Use)
m = ProductionModel(products, resources, processes)
m.report()
第2章線形最適化8 ファイル▶ 講義動画(21:11)
BIM生産計画 bim.py 4 セル ・ 42 行 ・ モデル 1
この節のモデル(1)
AMPLbim_dual.mod
var y1 >= 0;
var y2 >= 0;
var y3 >= 0;
var y4 >= 0;
minimize obj: 1000 * y1 + 1500 * y2 + 1750 * y3 + 4800 * y4;
s.t. x1: y1 + y3 + 4 * y4 >= 12;
s.t. x2: y2 + y3 + 2 * y4 >= 9;
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
ampl.eval(r"""
var x1 >= 0;
var x2 >= 0;
maximize profit: 12 * x1 + 9 * x2;
s.t. silicon: x1 <= 1000;
s.t. germanium: x2 <= 1500;
s.t. plastic: x1 + x2 <= 1750;
s.t. copper: 4 * x1 + 2 * x2 <= 4800;
""")
# %%
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
print(f'x = ({ampl.var["x1"].value():.1f}, {ampl.var["x2"].value():.1f})')
print(f'optimal value = {ampl.obj["profit"].value():.2f}')
# %%
ampl = AMPL()
ampl.read("bim_dual.mod")
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
print(
f'y = ({ampl.var["y1"].value():.1f}, {ampl.var["y2"].value():.1f}, {ampl.var["y3"].value():.1f}, {ampl.var["y4"].value():.1f})'
)
print(f'optimal value = {ampl.obj["obj"].value():.2f}')
最小絶対偏差回帰 lad-regression.py 5 セル ・ 83 行 ・ モデル 1
この節のモデル(1)
AMPLlad_regression.mod
# indexing sets
set I;
set J;
# parameters
param y{I};
param X{I, J};
# variables
var ep{I} >= 0;
var em{I} >= 0;
var m{J} >= 0;
var b;
# constraints
s.t. residuals {i in I}:
ep[i] - em[i] == y[i] - sum{j in J}(X[i, j] * m[j]) - b;
# objective
minimize sum_of_abs_errors: sum{i in I}(ep[i] + em[i]);
# %%
# install dependencies and select solver
#%pip install -q amplpy numpy matplotlib scikit-learn ipywidgets
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
from sklearn.datasets import make_regression
import numpy as np
n_features = 1
n_samples = 1000
noise = 30
# generate regression dataset
np.random.seed(2020)
X, y = make_regression(n_samples=n_samples, n_features=n_features, noise=noise)
# %%
import matplotlib.pyplot as plt
if n_features == 1:
plt.scatter(X, y, alpha=0.3)
plt.xlabel("X")
plt.ylabel("y")
plt.grid(True)
plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))))
plt.title("histogram y - mean(y)")
plt.ylabel("counts")
# %%
def lad_regression(X, y):
ampl = AMPL()
ampl.read("lad_regression.mod")
n, k = X.shape
# note use of Python style zero based indexing
ampl.set["I"] = range(n)
ampl.set["J"] = range(k)
ampl.param["y"] = y
ampl.param["X"] = X
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl
m = lad_regression(X, y)
m.display("m")
m.display("b")
# %%
m_m = list(m.var["m"].to_dict().values())
m_b = m.var["b"].value()
y_fit = np.array([sum(x[j] * v for j, v in enumerate(m_m)) + m_b for x in X])
if n_features == 1:
plt.scatter(X, y, alpha=0.3, label="data")
plt.plot(X, y_fit, "r", label="y_fit")
plt.xlabel("X")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))), alpha=0.5, label="y - mean(y)")
plt.hist(y - y_fit, bins=int(np.sqrt(len(y))), color="r", alpha=0.8, label="y - y_fit")
plt.title("histogram of residuals")
plt.ylabel("counts")
plt.legend()
平均絶対偏差ポートフォリオ最適化 mad-portfolio-optimization.py 12 セル ・ 295 行 ・ モデル 2
この節のモデル(2)
AMPLmad_portfolio.mod
param R default 0;
param w_lb default 0;
param w_ub default 1;
set ASSETS;
set TIME;
param daily_returns{TIME, ASSETS};
param mean_return{ASSETS};
var w{ASSETS};
var u{TIME} >= 0;
var v{TIME} >= 0;
minimize MAD: sum{t in TIME}(u[t] + v[t]) / card(TIME);
s.t. portfolio_returns {t in TIME}:
u[t] - v[t] == sum{j in ASSETS}(w[j] * (daily_returns[t, j] - mean_return[j]));
s.t. sum_of_weights: sum{j in ASSETS} w[j] == 1;
s.t. mean_portfolio_return: sum{j in ASSETS}(w[j] * mean_return[j]) >= R;
s.t. no_short {j in ASSETS}: w[j] >= w_lb;
s.t. diversify {j in ASSETS}: w[j] <= w_ub;
AMPLmad_portfolio_cash.mod
param R default 0;
param rf default 0;
param w_lb default 0;
param w_ub default 1;
set ASSETS;
set TIME;
param daily_returns{TIME, ASSETS};
param mean_return{ASSETS};
var w{ASSETS};
var u{TIME} >= 0;
var v{TIME} >= 0;
minimize MAD: sum{t in TIME}(u[t] + v[t]) / card(TIME);
s.t. portfolio_returns {t in TIME}:
u[t] - v[t] == sum{j in ASSETS}(w[j] * (daily_returns[t, j] - mean_return[j]));
s.t. sum_of_weights: sum{j in ASSETS} w[j] <= 1;
s.t. mean_portfolio_return: sum{j in ASSETS}(w[j] * (mean_return[j] - rf)) >= R - rf;
s.t. no_short {j in ASSETS}: w[j] >= w_lb;
s.t. diversify {j in ASSETS}: w[j] <= w_ub;
# %%
# install dependencies and select solver
# %pip install -q amplpy pandas numpy matplotlib scipy scikit-learn yfinance
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.stats as stats
import datetime as datetime
import yfinance as yf
# %%
# list of stock symbols
tickers = [
"AXP",
"AAPL",
"AMGN",
"BA",
"CAT",
"CRM",
"CSCO",
"CVX",
"DIS",
"DOW",
"GS",
"HD",
"IBM",
"INTC",
"JNJ",
"JPM",
"KO",
"MCD",
"MMM",
"MRK",
"MSFT",
"NKE",
"PG",
"TRV",
"UNH",
"V",
"VZ",
"WBA",
"WMT",
"XOM",
]
# number of years
n_years = 3.0
# historical period
end_date = datetime.datetime(2025, 1, 31).date() # datetime.datetime.today().date()
start_date = end_date - datetime.timedelta(round(n_years * 365))
assets = yf.download(tickers, start=start_date, end=end_date, auto_adjust=True)["Close"]
assets.fillna(method="bfill", inplace=True)
assets.fillna(method="ffill", inplace=True)
assets.plot(logy=True, figsize=(12, 8), grid=True, lw=1, title="Adjusted Close")
plt.legend(bbox_to_anchor=(1.0, 1.0))
# %%
# scaled asset prices
assets_scaled = assets.div(assets.iloc[0])
assets_scaled.plot(figsize=(12, 8), grid=True, lw=1, title="Adjusted Close: Scaled")
plt.legend(bbox_to_anchor=(1.0, 1.0))
# %%
# daily returns
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
fig, ax = plt.subplots(6, 5, figsize=(12, 10), sharex=True, sharey=True)
for a, s in zip(ax.flatten(), sorted(daily_returns.columns)):
daily_returns[s].plot(ax=a, lw=1, title=s, grid=True, fontsize=6)
plt.tight_layout()
# %%
# distributions of returns
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
fig, ax = plt.subplots(6, 5, figsize=(12, 10), sharex=True, sharey=True)
ax = ax.flatten()
for a, s in zip(ax.flatten(), daily_returns.columns):
daily_returns[s].hist(ax=a, lw=1, grid=True, bins=50)
mean_return = daily_returns[s].mean()
mean_absolute_deviation = abs((daily_returns[s] - mean_return)).mean()
a.set_title(f"{s} = {mean_return:0.5f}")
a.set_xlim(-0.08, 0.08)
a.axvline(mean_return, color="r", linestyle="--")
a.axvline(mean_return + mean_absolute_deviation, color="g", linestyle="--")
a.axvline(mean_return - mean_absolute_deviation, color="g", linestyle="--")
plt.tight_layout()
# %%
# bar charts of mean return and mean absolute deviation in returns
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
mean_return = daily_returns.mean()
mean_absolute_deviation = abs(daily_returns - mean_return).mean()
fig, ax = plt.subplots(1, 2, figsize=(12, 0.35 * len(daily_returns.columns)))
mean_return.plot(kind="barh", ax=ax[0], title="Mean Return")
ax[0].invert_yaxis()
mean_absolute_deviation.plot(kind="barh", ax=ax[1], title="Mean Absolute Deviation")
ax[1].invert_yaxis()
# %%
# plot return vs risk
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
mean_return = daily_returns.mean()
mean_absolute_deviation = abs(daily_returns - mean_return).mean()
fig, ax = plt.subplots(1, 1, figsize=(10, 6))
for s in assets.keys():
ax.plot(mean_absolute_deviation[s], mean_return[s], "s", ms=8)
ax.text(mean_absolute_deviation[s] * 1.03, mean_return[s], s)
ax.set_xlim(0, 1.1 * mean_absolute_deviation.max())
ax.axhline(0, color="r", linestyle="--")
ax.set_title("Daily return versus mean absolute deviaion")
ax.set_xlabel("Mean Absolute Deviation in Daily Returns")
ax.set_ylabel("Mean Daily Return")
ax.grid(True)
# %%
def mad_portfolio(assets):
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
mean_return = daily_returns.mean()
daily_returns["Date"] = daily_returns.index.format()
daily_returns.set_index("Date", inplace=True)
ampl = AMPL()
ampl.read("mad_portfolio.mod")
ampl.set["ASSETS"] = list(assets.columns)
ampl.set["TIME"] = daily_returns.index.values
ampl.param["daily_returns"] = daily_returns
ampl.param["mean_return"] = mean_return
return ampl
def mad_visualization(assets, m):
mean_portfolio_return = m.get_value("sum{j in ASSETS}(w[j] * mean_return[j])")
print(f"Weight lower bound {m.param['w_lb'].value():0.3f}")
print(f"Weight upper bound {m.param['w_ub'].value():0.3f}")
print(
f"Fraction of portfolio invested {m.get_value('sum{j in ASSETS} w[j]'):0.3f}"
)
print(f"Required portfolio daily return {m.param['R'].value():0.5f}")
print(f"Portfolio mean daily return {mean_portfolio_return:0.5f}")
print(f"Portfolio mean absolute deviation {m.obj['MAD'].value():0.5f}")
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
mean_return = daily_returns.mean()
mean_absolute_deviation = abs(daily_returns - mean_return).mean()
mad_portfolio_weights = m.var["w"].to_pandas()
fig, ax = plt.subplots(1, 3, figsize=(15, 0.35 * len(daily_returns.columns)))
mad_portfolio_weights.plot(kind="barh", ax=ax[0], title="MAD Portfolio Weights")
ax[0].invert_yaxis()
ax[0].axvline(m.param["w_lb"].value(), ls="--", color="g")
ax[0].axvline(m.param["w_ub"].value(), ls="--", color="r")
ax[0].legend(["lower bound", "upper bound"])
mean_return.plot(kind="barh", ax=ax[1], title="asset mean daily return")
ax[1].axvline(m.param["R"].value(), ls="--", color="g")
ax[1].axvline(mean_portfolio_return, ls="--", color="r")
ax[1].invert_yaxis()
ax[1].legend(["required return", "portfolio return"])
mean_absolute_deviation.plot(
kind="barh", ax=ax[2], title="asset mean absolute deviation"
)
ax[2].axvline(m.obj["MAD"].value(), ls="--", color="r")
ax[2].legend(["portfolio MAD"])
ax[2].invert_yaxis()
m = mad_portfolio(assets)
m.param["w_lb"] = 0
m.param["w_ub"] = 0.2
m.param["R"] = 0.001
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
mad_visualization(assets, m)
# %%
# plot return vs risk
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
mean_return = daily_returns.mean()
mean_absolute_deviation = abs(daily_returns - mean_return).mean()
fig, ax = plt.subplots(1, 1, figsize=(10, 6))
for s in assets.keys():
ax.plot(mean_absolute_deviation[s], mean_return[s], "s", ms=8)
ax.text(mean_absolute_deviation[s] * 1.03, mean_return[s], s)
ax.set_xlim(0, 1.1 * max(mean_absolute_deviation))
ax.axhline(0, color="r", linestyle="--")
ax.set_title("Return vs Risk")
ax.set_xlabel("Mean Absolute Deviation in Daily Returns")
ax.set_ylabel("Mean Daily Return")
ax.grid(True)
m = mad_portfolio(assets)
for R in np.linspace(0, mean_return.max(), 20):
m.param["R"] = R
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
mad_portfolio_weights = m.var["w"].to_pandas()
portfolio_returns = daily_returns.dot(mad_portfolio_weights)
portfolio_mean_return = portfolio_returns.mean()
portfolio_mean_absolute_deviation = abs(
portfolio_returns - portfolio_mean_return
).mean()
ax.plot(portfolio_mean_absolute_deviation, portfolio_mean_return, "ro", ms=10)
# %%
def mad_portfolio_cash(assets):
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
mean_return = daily_returns.mean()
daily_returns["Date"] = daily_returns.index.format()
daily_returns.set_index("Date", inplace=True)
ampl = AMPL()
ampl.read("mad_portfolio_cash.mod")
ampl.set["ASSETS"] = list(assets.columns)
ampl.set["TIME"] = daily_returns.index.values
ampl.param["daily_returns"] = daily_returns
ampl.param["mean_return"] = mean_return
return ampl
m = mad_portfolio_cash(assets)
m.param["w_lb"] = 0
m.param["w_ub"] = 0.2
m.param["R"] = 0.001
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
mad_visualization(assets, m)
# %%
# plot return vs risk
daily_returns = assets.diff()[1:] / assets.shift(1)[1:]
mean_return = daily_returns.mean()
mean_absolute_deviation = abs(daily_returns - mean_return).mean()
fig, ax = plt.subplots(1, 1, figsize=(10, 6))
for s in assets.keys():
ax.plot(mean_absolute_deviation[s], mean_return[s], "s", ms=8)
ax.text(mean_absolute_deviation[s] * 1.03, mean_return[s], s)
ax.set_xlim(0, 1.1 * max(mean_absolute_deviation))
ax.axhline(0, color="r", linestyle="--")
ax.set_title("Return vs Risk")
ax.set_xlabel("Mean Absolute Deviation in Daily Returns")
ax.set_ylabel("Mean Daily Return")
ax.grid(True)
for color, m in zip(["ro", "go"], [mad_portfolio(assets), mad_portfolio_cash(assets)]):
for R in np.linspace(0, mean_return.max(), 20):
m.param["R"] = R
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
mad_portfolio_weights = m.var["w"].to_pandas()
portfolio_returns = daily_returns.dot(mad_portfolio_weights)
portfolio_mean_return = portfolio_returns.mean()
portfolio_mean_absolute_deviation = abs(
portfolio_returns - portfolio_mean_return
).mean()
ax.plot(portfolio_mean_absolute_deviation, portfolio_mean_return, color, ms=10)
L1 回帰によるワインの品質予測 L1-regression-wine-quality.py 11 セル ・ 148 行 ・ モデル 2
この節のモデル(2)
AMPLlad_fit_1.mod
set I;
param y{I};
param X{I};
var a;
var b;
var e_pos{I} >= 0;
var e_neg{I} >= 0;
var prediction{i in I} = a * X[i] + b;
s.t. prediction_error{i in I}: e_pos[i] - e_neg[i] == prediction[i] - y[i];
minimize mean_absolute_deviation: sum{i in I}(e_pos[i] + e_neg[i]) / card(I);
AMPLl1_fit.mod
set I;
set J;
param y{I};
param X{I, J};
var a{J};
var b;
var e_pos{I} >= 0;
var e_neg{I} >= 0;
var prediction{i in I} = sum{j in J}(a[j] * X[i, j]) + b;
s.t. prediction_error{i in I}: e_pos[i] - e_neg[i] == prediction[i] - y[i];
minimize mean_absolute_deviation: sum{i in I}(e_pos[i] + e_neg[i]) / card(I);
# %%
# 依存関係をインストールし、ソルバーを選択します
#%pip install -q amplpy pandas matplotlib
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="81d4bb7d-1b52-4088-b0c7-75ce4aa6234a", # license to use
) # instantiate AMPL object and register magics
# %%
import pandas as pd
import matplotlib.pyplot as plt
base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/dev/notebooks/02/"
wines = pd.read_csv(
base_url + "data/winequality-red.csv",
sep=";",
)
display(wines)
# %%
def MAD(df):
return (df - df.mean()).abs().mean()
print("MAD = ", MAD(wines["quality"]))
fig, ax = plt.subplots(figsize=(12, 4))
ax = wines["quality"].plot(alpha=0.6, title="wine quality")
ax.axhline(wines["quality"].mean(), color="r", ls="--", lw=3)
mad = MAD(wines["quality"])
ax.axhline(wines["quality"].mean() + mad, color="g", lw=3)
ax.axhline(wines["quality"].mean() - mad, color="g", lw=3)
ax.legend(["y", "mean", "mad"])
ax.set_xlabel("observation")
plt.show()
# %%
fig, axes = plt.subplots(3, 4, figsize=(12, 8), sharey=True)
for ax, column in zip(axes.flatten(), wines.columns):
wines[column].hist(ax=ax, bins=30)
ax.axvline(wines[column].mean(), color="r", label="mean")
ax.set_title(column)
ax.legend()
plt.tight_layout()
# %%
_ = wines.corr()["quality"].plot(kind="bar", grid=True)
# %%
wines[["volatile acidity", "density", "alcohol", "quality"]].corr()
# %%
def lad_fit_1(df, y_col, x_col):
m = AMPL()
m.read("lad_fit_1.mod")
m.set["I"] = df.index.values
m.param["y"] = df[y_col]
m.param["X"] = df[x_col]
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
m = lad_fit_1(wines, "quality", "alcohol")
print(
f'The mean absolute deviation for a single-feature regression is {m.obj["mean_absolute_deviation"].value():0.5f}'
)
# %%
wines.columns
# %%
mad = (wines["alcohol"] - wines["alcohol"].mean()).abs().mean()
vars = {}
for i in wines.columns:
m = lad_fit_1(wines, "quality", i)
vars[i] = m.obj["mean_absolute_deviation"].value()
fig, ax = plt.subplots()
pd.Series(vars).plot(kind="bar", ax=ax, grid=True)
ax.axhline(mad, color="r", lw=3)
ax.set_title("MADs for single-feature regressions")
plt.show()
# %%
wines["prediction"] = [i[1] for i in m.var["prediction"].get_values()]
wines["quality"].hist(label="data")#
wines.plot(x="quality", y="prediction", kind="scatter")
plt.show()
# %%
def l1_fit(df, y_col, x_cols):
m = AMPL()
m.read("l1_fit.mod")
m.set["I"] = df.index.values
m.set["J"] = x_cols
m.param["y"] = df[y_col]
m.param["X"] = df[x_cols]
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
m = l1_fit(
wines,
"quality",
[
"alcohol",
"volatile acidity",
"citric acid",
"sulphates",
"total sulfur dioxide",
"density",
"fixed acidity",
],
)
print(f"MAD = {m.obj['mean_absolute_deviation'].value():0.5f}\n")
for k, v in m.var["a"].get_values():
print(f"{k} {v}")
print("\n")
wines["prediction"] = [i[1] for i in m.var["prediction"].get_values()]
wines["quality"].hist(label="data")
wines.plot(x="quality", y="prediction", kind="scatter")
plt.show()
BIM生産計画の変形:最悪ケースの利益の最大化 bim-maxmin.py 2 セル ・ 30 行 ・ モデル 1
この節のモデル(1)
AMPLbim_maxmin.mod
var x1 >= 0;
var x2 >= 0;
var z;
set costs dimen 2;
maximize profit: z;
s.t. maxmin {(c1,c2) in costs}:
z <= c1 * x1 + c2 * x2;
s.t. silicon: x1 <= 1000;
s.t. germanium: x2 <= 1500;
s.t. plastic: x1 + x2 <= 1750;
s.t. copper: 4 * x1 + 2 * x2 <= 4800;
# %%
# 依存関係をインストールし、ソルバーを選択します
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
def BIM_maxmin(costs):
ampl = AMPL()
ampl.read("bim_maxmin.mod")
ampl.set["costs"] = costs
return ampl
m = BIM_maxmin([[12, 9], [11, 10], [8, 11]])
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print(
"x=({:.1f},{:.1f}) revenue={:.3f}".format(
m.var["x1"].value(), m.var["x2"].value(), m.obj["profit"].value()
)
)
BIM問題の変形:分数目的関数と固定費 bim-fractional.py 3 セル ・ 64 行 ・ モデル 2
この節のモデル(2)
AMPLBIM_with_revenues_minus_costs.mod
var x1 >= 0;
var x2 >= 0;
var revenue = 12 * x1 + 9 * x2;
var variable_cost = 7/6 * x1 + 5/6 * x2;
param fixed_cost default 100;
maximize profit: revenue - variable_cost - fixed_cost;
s.t. silicon: x1 <= 1000;
s.t. germanium: x2 <= 1500;
s.t. plastic: x1 + x2 <= 1750;
s.t. copper: 4 * x1 + 2 * x2 <= 4800;
AMPLBIM_with_revenues_over_costs.mod
var y1 >= 0;
var y2 >= 0;
var t >= 0;
var revenue = 12 * y1 + 9 * y2;
var variable_cost = 7/6 * y1 + 5/6 * y2;
param fixed_cost default 100;
maximize profit: revenue;
s.t. silicon: y1 <= 1000 * t;
s.t. germanium: y2 <= 1500 * t;
s.t. plastic: y1 + y2 <= 1750 * t;
s.t. copper: 4 * y1 + 2 * y2 <= 4800 * t;
s.t. frac: variable_cost + fixed_cost * t == 1;
# %%
# 依存関係をインストールし、ソルバーを選択します
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
def BIM_with_revenues_minus_costs():
m = AMPL()
m.read("BIM_with_revenues_minus_costs.mod")
return m
BIM_linear = BIM_with_revenues_minus_costs()
BIM_linear.solve(solver=SOLVER)
assert BIM_linear.solve_result == "solved", BIM_linear.solve_result
print(
"x=({:.1f},{:.1f}) value={:.3f} revenue={:.2f} cost={:.2f}".format(
BIM_linear.var["x1"].value(),
BIM_linear.var["x2"].value(),
BIM_linear.obj["profit"].value(),
BIM_linear.var["revenue"].value(),
BIM_linear.var["variable_cost"].value()
+ BIM_linear.param["fixed_cost"].value(),
)
)
# %%
def BIM_with_revenues_over_costs():
m = AMPL()
m.read("BIM_with_revenues_over_costs.mod")
return m
BIM_fractional = BIM_with_revenues_over_costs()
BIM_fractional.solve(solver=SOLVER)
assert BIM_fractional.solve_result == "solved", BIM_fractional.solve_result
t = BIM_fractional.var["t"].value()
y1 = BIM_fractional.var["y1"].value()
y2 = BIM_fractional.var["y2"].value()
profit = BIM_fractional.obj["profit"].value()
variable_cost = BIM_fractional.var["variable_cost"].value()
fixed_cost = BIM_fractional.param["fixed_cost"].value()
revenue = BIM_fractional.var["revenue"].value()
print(
"x=({:.1f},{:.1f}) value={:.3f} revenue={:.2f} cost={:.2f}".format(
y1 / t,
y2 / t,
profit / (variable_cost + fixed_cost * t),
revenue / t,
variable_cost / t + fixed_cost,
)
)
需要予測を用いたBIM生産計画 bim-rawmaterialplanning.py 8 セル ・ 163 行 ・ モデル 2
この節のモデル(2)
AMPLBIMProductAcquisitionAndInventory.mod
set T ordered;
set P;
var x{P, T} >= 0;
var s{P, T} >= 0;
param pi{P, T};
param h{P, T} default 0.05;
param delta{P, T};
param existing{P};
param desired{P};
param month_budget;
param stock_limit;
var acquisition_cost = sum{p in P, t in T} pi[p,t] * x[p,t];
var inventory_cost = sum{p in P, t in T} h[p,t] * s[p,t];
minimize total_cost: acquisition_cost + inventory_cost;
s.t. balance {p in P, t in T}:
(if t == first(T) then
existing[p] + x[p,t]
else
x[p,t] + s[p,prev(t)])
== delta[p,t] + s[p,t];
s.t. finish {p in P}: s[p, last(T)] >= desired[p];
s.t. inventory {t in T}: sum{p in P} s[p,t] <= stock_limit;
s.t. budget {t in T}: sum{p in P} pi[p,t] * x[p,t] <= month_budget;
AMPLBIMProductAcquisitionAndInventory_v2.mod
set T ordered;
set P;
param pi{P, T};
param h{P, T} default 0.05;
param delta{P, T};
param existing{P};
param desired{P};
param month_budget;
param stock_limit;
var x{P,T} >= 0;
param acquisition_price{P,T};
var s{p in P, t in T} = if t == first(T) then
existing[p] + x[p,t] - delta[p,t]
else
x[p,t] + s[p,prev(t)] - delta[p,t];
s.t. non_negative_stock {p in P, t in T}: s[p,t] >= 0;
var acquisition_cost = sum{p in P, t in T} pi[p,t] * x[p,t];
var inventory_cost = sum{p in P, t in T} h[p,t] * s[p,t];
minimize total_cost: acquisition_cost + inventory_cost;
s.t. finish {p in P}: s[p,last(T)] >= desired[p];
s.t. inventory {t in T}: sum{p in P} s[p,t] <= stock_limit;
s.t. budget {t in T}: sum{p in P} pi[p,t] * x[p,t] <= month_budget;
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import matplotlib.pyplot as plt
from io import StringIO
import pandas as pd
demand_data = """chip,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
logic,88,125,260,217,238,286,248,238,265,293,259,244
memory,47,62,81,65,95,118,86,89,82,82,84,66"""
price_data = """product,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
copper,1,1,1,2,2,3,3,2,2,1,1,2
silicon,4,3,3,3,5,5,6,5,4,3,3,5
germanium,5,5,5,3,3,3,3,2,3,4,5,6
plastic,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1"""
demand_chips = pd.read_csv(StringIO(demand_data), index_col="chip")
display(demand_chips)
price = pd.read_csv(StringIO(price_data), index_col="product")
price
# %%
use = dict()
use["logic"] = {"silicon": 1, "plastic": 1, "copper": 4}
use["memory"] = {"germanium": 1, "plastic": 1, "copper": 2}
use = pd.DataFrame.from_dict(use).fillna(0).astype(int)
display(use)
demand = use.dot(demand_chips)
demand
# %%
def ShowTableOfAmplVariables(m, X):
P = m.set["P"].to_list()
T = m.set["T"].to_list()
df = pd.DataFrame(m.var[X].to_list(), columns=["P", "T", "values"]).round(
decimals=2
)
df = df.pivot(index="P", columns="T", values="values")
df = df.reindex(P)
df = df[T]
return df
def BIMProductAcquisitionAndInventory(
demand, acquisition_price, existing, desired, stock_limit, month_budget
):
m = AMPL()
m.read("BIMProductAcquisitionAndInventory.mod")
m.set["T"] = list(demand.columns)
m.set["P"] = demand.index.values
m.param["pi"] = acquisition_price
m.param["delta"] = demand
m.param["existing"] = existing
m.param["desired"] = desired
m.param["month_budget"] = month_budget
m.param["stock_limit"] = stock_limit
return m
# %%
budget = 5000
m = BIMProductAcquisitionAndInventory(
demand,
price,
{"silicon": 1000, "germanium": 1500, "plastic": 1750, "copper": 4800},
{"silicon": 500, "germanium": 500, "plastic": 1000, "copper": 2000},
9000,
budget,
)
m.option["solver"] = SOLVER
m.solve()
print("\nThe optimal amount of raw materials to acquire in each month is:")
display(ShowTableOfAmplVariables(m, "x"))
print("\nThe corresponding optimal stock levels in each months are:")
stock = ShowTableOfAmplVariables(m, "s")
display(stock)
print("\nThe stock levels can be visualized as follows")
stock.T.plot(drawstyle="steps-mid", grid=True, figsize=(13, 4))
plt.xticks(np.arange(len(stock.columns)), stock.columns)
plt.show()
# %%
budget = 2000
m = BIMProductAcquisitionAndInventory(
demand,
price,
{"silicon": 1000, "germanium": 1500, "plastic": 1750, "copper": 4800},
{"silicon": 500, "germanium": 500, "plastic": 1000, "copper": 2000},
9000,
budget,
)
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print("\nThe optimal amount of raw materials to acquire in each month is:")
display(ShowTableOfAmplVariables(m, "x"))
print("\nThe corresponding optimal stock levels in each months are:")
stock = ShowTableOfAmplVariables(m, "s")
display(stock)
print("\nThe stock levels can be visualized as follows")
stock.T.plot(drawstyle="steps-mid", grid=True, figsize=(13, 4))
plt.xticks(np.arange(len(stock.columns)), stock.columns)
plt.show()
# %%
def BIMProductAcquisitionAndInventory_v2(
demand, acquisition_price, existing, desired, stock_limit, month_budget
):
m = AMPL()
m.read("BIMProductAcquisitionAndInventory_v2.mod")
m.set["T"] = list(demand.columns)
m.set["P"] = demand.index.values
m.param["pi"] = acquisition_price
m.param["delta"] = demand
m.param["existing"] = existing
m.param["desired"] = desired
m.param["month_budget"] = month_budget
m.param["stock_limit"] = stock_limit
return m
# %%
m = BIMProductAcquisitionAndInventory_v2(
demand,
price,
{"silicon": 1000, "germanium": 1500, "plastic": 1750, "copper": 4800},
{"silicon": 500, "germanium": 500, "plastic": 1000, "copper": 2000},
9000,
2000,
)
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print("\nThe optimal amount of raw materials to acquire in each month is:")
display(ShowTableOfAmplVariables(m, "x"))
print("\nThe corresponding optimal stock levels in each months are:")
stock = ShowTableOfAmplVariables(m, "s")
display(stock)
print("\nThe stock levels can be visualized as follows")
stock.T.plot(drawstyle="steps-mid", grid=True, figsize=(13, 4))
plt.xticks(np.arange(len(stock.columns)), stock.columns)
plt.show()
補足:多製品の生産計画 multiproductionfaciliity_worstcase.py 7 セル ・ 119 行 ・ モデル 2
この節のモデル(2)
AMPLmaxmin.mod
set I;
set J;
set S;
param a{I,J};
param b{I};
param c{S,J};
var x{J} >= 0;
var z;
maximize profit: z;
s.t. scenario_profit {s in S}: z <= sum{j in J} c[s, j] * x[j];
s.t. resource_limits {i in I}: sum{j in J} a[i, j] * x[j] <= b[i];
AMPLmax_profit.mod
set I;
set J;
param a{I,J};
param b{I};
param c{J};
var x{J} >= 0;
maximize profit: sum{j in J} c[j] * x[j];
s.t. resource_limits {i in I}: sum{j in J} a[i, j] * x[j] <= b[i];
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import pandas as pd
BIM_scenarios = pd.DataFrame(
[[12, 9], [11, 10], [8, 11]], columns=["product 1", "product 2"]
)
BIM_scenarios.index.name = "scenarios"
print("\nProfit scenarios")
display(BIM_scenarios)
BIM_resources = pd.DataFrame(
[
["silicon", 1000, 1, 0],
["germanium", 1500, 0, 1],
["plastic", 1750, 1, 1],
["copper", 4000, 1, 2],
],
columns=["resource", "available", "product 1", "product 2"],
)
BIM_resources = BIM_resources.set_index("resource")
print("\nAvailable resources and resource requirements")
display(BIM_resources)
# %%
def maxmin(scenarios, resources):
products = resources.columns.tolist()
products.remove("available")
model = AMPL()
model.read("maxmin.mod")
model.set["I"] = resources.index.values
model.set["J"] = products
model.set["S"] = scenarios.index.values
model.param["a"] = resources.drop("available", axis=1)
model.param["b"] = resources["available"]
model.param["c"] = scenarios
return model
BIM = maxmin(BIM_scenarios, BIM_resources)
BIM.solve(solver=SOLVER)
assert BIM.solve_result == "solved", BIM.solve_result
worst_case_plan = pd.Series(BIM.var["x"].to_dict(), name="worst case")
worst_case_profit = BIM.obj["profit"].value()
print("\nWorst case profit =", worst_case_profit)
print(f"\nWorst case production plan:")
display(worst_case_plan)
# %%
def max_profit(scenario, resources):
products = resources.columns.tolist()
products.remove("available")
model = AMPL()
model.read("max_profit.mod")
model.set["I"] = resources.index.values
model.set["J"] = products
model.param["a"] = resources.drop("available", axis=1)
model.param["b"] = resources["available"]
model.param["c"] = scenario
return model
# %%
# create mean scenario
mean_case = max_profit(BIM_scenarios.mean(), BIM_resources)
mean_case.solve(solver=SOLVER)
assert mean_case.solve_result == "solved", mean_case.solve_result
mean_case_profit = mean_case.obj["profit"].value()
mean_case_plan = pd.Series(mean_case.var["x"].to_dict(), name="mean case")
print(f"\nMean case profit = {mean_case_profit:0.1f}")
print("\nMean case production plan:")
print(mean_case_plan)
# %%
mean_case_outcomes = BIM_scenarios.dot(mean_case_plan)
mean_case_outcomes.name = "mean outcomes"
worst_case_outcomes = BIM_scenarios.dot(worst_case_plan)
worst_case_outcomes.name = "worst case outcomes"
ax = pd.concat([worst_case_outcomes, mean_case_outcomes], axis=1).plot(
kind="bar", ylim=(15000, 20000)
)
ax.axhline(worst_case_profit)
ax.axhline(worst_case_outcomes.mean(), linestyle="--", label="worst case plan, mean")
ax.axhline(
mean_case_outcomes.mean(),
linestyle="--",
color="orange",
label="mean case plan, mean",
)
_ = ax.legend()
# %%
ax = pd.concat([worst_case_plan, mean_case_plan], axis=1).plot(kind="bar")
この章のデータファイル(1)
第3章混合整数線形最適化10 ファイル▶ 講義動画(18:03)
データを摂動したBIM生産問題 bim-perturbed.py 3 セル ・ 37 行 ・ モデル 2
この節のモデル(2)
AMPLBIM_perturbed_LO.mod
var x1 >= 0;
var x2 >= 0;
maximize profit: 12 * x1 + 9 * x2;
s.t. silicon: x1 <= 1000;
s.t. germanium: x2 <= 1500;
s.t. plastic: x1 + x2 <= 1750;
s.t. copper: 4.04 * x1 + 2.02 * x2 <= 4800;
AMPLBIM_perturbed_MILO.mod
var x1 integer >= 0;
var x2 integer >= 0;
maximize profit: 12 * x1 + 9 * x2;
s.t. silicon: x1 <= 1000;
s.t. germanium: x2 <= 1500;
s.t. plastic: x1 + x2 <= 1750;
s.t. copper: 4.04 * x1 + 2.02 * x2 <= 4800;
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
m = AMPL()
m.read("BIM_perturbed_LO.mod")
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print(
"x = ({:.3f}, {:.3f}), optimal value = {:.3f}".format(
m.var["x1"].value(), m.var["x2"].value(), m.obj["profit"].value()
)
)
# %%
m = AMPL()
m.read("BIM_perturbed_MILO.mod")
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print(
"x = ({:.3f}, {:.3f}), optimal value = {:.3f}".format(
m.var["x1"].value(), m.var["x2"].value(), m.obj["profit"].value()
)
)
従業員のシフトスケジューリング shift-scheduling.py 6 セル ・ 158 行 ・ モデル 1
この節のモデル(1)
AMPLshift_schedule.mod
# sets
# ordered set of avaiable workers
set WORKERS ordered;
# ordered sets of days and shifts
set DAYS ordered;
set SHIFTS ordered;
# set of day, shift time slots
set SLOTS within {DAYS, SHIFTS};
# set of 24 hour time blocks
set BLOCKS within {SLOTS, SLOTS, SLOTS};
# set of weekend shifts
set WEEKENDS within SLOTS;
# parameters
# number of workers required for each slot
param WorkersRequired{SLOTS};
# max hours per week per worker
param Hours;
# weight of the weekend component in the objective function
param gamma default 0.1;
# variables
# assign[worker, day, shift] = 1 assigns worker to a time slot
var assign{WORKERS, SLOTS} binary;
# weekend[worker] = 1 worker is assigned weekend shift
var weekend{WORKERS} binary;
# needed[worker] = 1
var needed{WORKERS} binary;
# constraints
# assign a sufficient number of workers for each time slot
s.t. required_workers {(day, shift) in SLOTS}:
WorkersRequired[day, shift] == sum{worker in WORKERS} assign[worker, day, shift];
# workers limited to forty hours per week assuming 8 hours per shift
s.t. forty_hour_limit {worker in WORKERS}:
8 * sum{(day, shift) in SLOTS} assign[worker, day, shift] <= Hours;
# workers are assigned no more than one time slot per 24 time block
s.t. required_rest {worker in WORKERS, (d1, s1, d2, s2, d3, s3) in BLOCKS}:
assign[worker, d1, s1] + assign[worker, d2, s2] + assign[worker, d3, s3] <= 1;
# determine if a worker is assigned to any shift
s.t. is_needed {worker in WORKERS}:
sum{(day, shift) in SLOTS} assign[worker, day, shift] <= card(SLOTS) * needed[worker];
# determine if a worker is assigned to a weekend shift
s.t. is_weekend {worker in WORKERS}:
6 * weekend[worker] >= sum{(day, shift) in WEEKENDS} assign[worker, day, shift];
# choose(uncomment) one of the following objective functions
# minimize a blended objective of needed workers and needed weekend workers
#minimize minimize_workers:
#sum{worker in WORKERS} needed[worker] + gamma * sum{worker in WORKERS} weekend[worker];
# weighted version: since we are minimizing the objective function a smaller weight will give higher
# priority to a given worker
# weight is obtained with the ord function, that returns the index of a given worker in the weights SET
minimize minimize_workers:
sum{worker in WORKERS} ord(worker) * needed[worker] +
gamma * sum{worker in WORKERS} ord(worker) * weekend[worker];
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
def shift_schedule(N=10, hours=40):
"""return a solved model assigning N workers to shifts"""
workers = [f"W{i:02d}" for i in range(1, N + 1)]
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
shifts = ["morning", "evening", "night"]
slots = [(d, s) for d in days for s in shifts]
blocks = [(slots[i] + slots[i + 1] + slots[i + 2]) for i in range(len(slots) - 2)]
weekends = [(d, s) for (d, s) in slots if d in ["Sat", "Sun"]]
workers_required = {
(d, s): (1 if s in ["night"] or d in ["Sun"] else 2)
for d in days
for s in shifts
}
m = AMPL()
m.read("shift_schedule.mod")
m.set["WORKERS"] = workers
m.set["DAYS"] = days
m.set["SHIFTS"] = shifts
m.set["SLOTS"] = slots
m.set["BLOCKS"] = blocks
m.set["WEEKENDS"] = weekends
m.param["WorkersRequired"] = workers_required
m.param["Hours"] = hours
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
m = shift_schedule(10, 40)
# %%
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
def visualize(m):
workers = m.set["WORKERS"].to_list()
slots = m.set["SLOTS"].to_list()
days = m.set["DAYS"].to_list()
assign = m.var["assign"].to_dict()
needed = m.var["needed"].to_dict()
weekend = m.var["weekend"].to_dict()
bw = 1.0
fig, ax = plt.subplots(1, 1, figsize=(12, 1 + 0.3 * len(workers)))
ax.set_title("Shift Schedule")
# x axis styling
ax.set_xlim(0, len(slots))
colors = ["teal", "gold", "magenta"]
for i in range(len(slots) + 1):
ax.axvline(i, lw=0.3)
ax.fill_between(
[i, i + 1], [0] * 2, [len(workers)] * 2, alpha=0.1, color=colors[i % 3]
)
for i in range(len(days) + 1):
ax.axvline(3 * i, lw=1)
ax.set_xticks([3 * i + 1.5 for i in range(len(days))])
ax.set_xticklabels(days)
ax.set_xlabel("Shift")
# y axis styling
ax.set_ylim(0, len(workers))
for j in range(len(workers) + 1):
ax.axhline(j, lw=0.3)
ax.set_yticks([j + 0.5 for j in range(len(workers))])
ax.set_yticklabels(workers)
ax.set_ylabel("Worker")
# show shift assignments
for i, slot in enumerate(slots):
day, shift = slot
for j, worker in enumerate(workers):
if round(assign[worker, day, shift]):
ax.add_patch(Rectangle((i, j + (1 - bw) / 2), 1, bw, edgecolor="b"))
ax.text(
i + 1 / 2, j + 1 / 2, worker, ha="center", va="center", color="w"
)
# display needed and weekend data
for j, worker in enumerate(workers):
if not needed[worker]:
ax.fill_between(
[0, len(slots)], [j, j], [j + 1, j + 1], color="k", alpha=0.3
)
if needed[worker] and not weekend[worker]:
ax.fill_between(
[15, len(slots)], [j, j], [j + 1, j + 1], color="k", alpha=0.3
)
visualize(m)
# %%
import pandas as pd
# get the schedule from AMPL and convert to pandas DataFrame with defined columns
schedule = m.var["assign"].to_list()
schedule = pd.DataFrame(
[[s[0], s[1], s[2]] for s in schedule if s[3]], columns=["worker", "day", "shift"]
)
# create and assign a worker category type
worker_type = pd.CategoricalDtype(categories=m.set["WORKERS"].to_list(), ordered=True)
schedule["worker"] = schedule["worker"].astype(worker_type)
# create and assign a day category type
day_type = pd.CategoricalDtype(categories=m.set["DAYS"].to_list(), ordered=True)
schedule["day"] = schedule["day"].astype(day_type)
# create and assign a shift category type
shift_type = pd.CategoricalDtype(categories=m.set["SHIFTS"].to_list(), ordered=True)
schedule["shift"] = schedule["shift"].astype(shift_type)
# demonstrate sorting and display of the master schedule
schedule.sort_values(by=["day", "shift", "worker"])
# %%
# sort schedule by worker
schedule = schedule.sort_values(by=["worker", "day", "shift"])
# print worker schedules
for worker, worker_schedule in schedule.groupby("worker"):
print(f"\n Work schedule for {worker}")
if len(worker_schedule) > 0:
for s in worker_schedule.to_string(index=False).split("\n"):
print(s)
else:
print(" no assigned shifts")
# %%
# sort by day, shift, worker
schedule = schedule.sort_values(by=["day", "shift", "worker"])
for day, day_schedule in schedule.groupby("day"):
print(f"\nShift schedule for {day}")
for shift, shift_schedule in day_schedule.groupby("shift"):
print(f" {shift} shift: ", end="")
print(", ".join([worker for worker in shift_schedule["worker"].values]))
選言を用いた生産モデル simple-production-model-gdp.py 4 セル ・ 41 行 ・ モデル 3
この節のモデル(3)
AMPLmulti_product_factory.mod
# decision variables
var profit;
var production_x >= 0;
var production_y >= 0;
# profit objective
maximize maximize_profit: profit;
# constraints
s.t. profit_expr: profit == 40 * production_x + 30 * production_y;
s.t. demand: production_x <= 40;
s.t. laborA: production_x + production_y <= 80;
s.t. laborB: 2 * production_x + production_y <= 100;
AMPLmulti_product_factory_milo.mod
# decision variables
var profit;
var production_x >= 0;
var production_y >= 0;
var z binary;
param M = 10000;
# profit objective
maximize maximize_profit: profit;
# constraints
s.t. profit_constr_1: profit <= 40 * production_x + 30 * production_y + M * z;
s.t. profit_constr_2: profit <= 60 * production_x + 30 * production_y + M * (1 - z);
s.t. demand: production_x <= 40;
s.t. laborA: production_x + production_y <= 80;
s.t. laborB_1: 2 * production_x + production_y <= 100 + M * z;
s.t. laborB_2: 1.5 * production_x + production_y <= 100 + M * (1 - z);
AMPLmulti_product_factory_milo_disjunctive.mod
var profit >= -1000, <= 10000;
var x >= 0, <= 1000;
var y >= 0, <= 1000;
maximize maximize_profit: profit;
s.t. demand: x <= 40;
s.t. laborA: x + y <= 80;
s.t. technologies:
((profit == 40 * x + 30 * y and 2 * x + y <= 100)
or
(profit == 60 * x + 30 * y and 1.5 * x + y <= 100))
and not
((profit == 40 * x + 30 * y and 2 * x + y <= 100)
and
(profit == 60 * x + 30 * y and 1.5 * x + y <= 100))
;
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
m = AMPL()
m.read("multi_product_factory.mod")
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print(f"Profit = {m.var['profit'].value():.2f} €")
print(f"Production X = {m.var['production_x'].value()}")
print(f"Production Y = {m.var['production_y'].value()}")
# %%
m = AMPL()
m.read("multi_product_factory_milo.mod")
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print(f"Profit = {m.var['profit'].value():.2f} €")
print(f"Production X = {m.var['production_x'].value()}")
print(f"Production Y = {m.var['production_y'].value()}")
# %%
m = AMPL()
m.read("multi_product_factory_milo_disjunctive.mod")
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
print(f"Profit = {m.var['profit'].value():.2f} €")
print(f"x = {m.var['x'].value()}")
print(f"y = {m.var['y'].value()}")
機械スケジューリング machine-scheduling.py 8 セル ・ 178 行 ・ モデル 1
この節のモデル(1)
AMPLjob_machine_scheduling.mod
set JOBS;
set PAIRS within{JOBS, JOBS};
param release{JOBS};
param duration{JOBS};
param due{JOBS};
var start{JOBS} >= 0, <= 300;
var finish{JOBS} >= 0, <= 300;
var past{JOBS} >= 0, <= 300;
s.t. job_release {job in JOBS}: start[job] >= release[job];
s.t. job_duration {job in JOBS}: finish[job] == start[job] + duration[job];
s.t. past_due_constraint {job in JOBS}: past[job] >= finish[job] - due[job];
s.t. machine_deconflict {(job_a, job_b) in PAIRS}:
(finish[job_a] <= start[job_b] or finish[job_b] <= start[job_a])
and not
(finish[job_a] <= start[job_b] and finish[job_b] <= start[job_a])
;
minimize minimize_past: sum{job in JOBS} past[job];
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import pandas as pd
jobs = pd.DataFrame(
{
"A": {"release": 2, "duration": 5, "due": 10},
"B": {"release": 5, "duration": 6, "due": 21},
"C": {"release": 4, "duration": 8, "due": 15},
"D": {"release": 0, "duration": 4, "due": 10},
"E": {"release": 0, "duration": 2, "due": 5},
"F": {"release": 8, "duration": 3, "due": 15},
"G": {"release": 9, "duration": 2, "due": 22},
}
).T
jobs
# %%
def schedule_jobs(jobs, seq):
"""
Schedule a sequence of jobs based on their release times, durations, and due times.
Args:
jobs (DataFrame): Job information with columns "release", "duration", and "due".
seq (DataFrame): A list of job indices representing the sequence in which the jobs will be scheduled.
Return:
A DataFrame containing schedule information, including "start", "finish", and "past" due times.
"""
schedule = pd.DataFrame(index=jobs.index)
t = 0
for job in seq:
t = max(t, jobs.loc[job]["release"])
schedule.loc[job, "start"] = t
t += jobs.loc[job, "duration"]
schedule.loc[job, "finish"] = t
schedule.loc[job, "past"] = max(0, t - jobs.loc[job, "due"])
return schedule
schedule = schedule_jobs(jobs, jobs.index)
schedule
# %%
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
def gantt(jobs, schedule, title="Job Schedule"):
"""
Plot a Gantt chart for a given job schedule.
Args:
jobs (DataFrame): Contains job release times and due times.
schedule (DataFrame): Contains job start times, finish times, and past due times.
title (str, optional): Title of the Gantt chart. Defaults to "Job Schedule".
"""
w = 0.25 # bar width
fig, ax = plt.subplots(1, 1, figsize=(10, 0.7 * len(jobs.index)))
for k, job in enumerate(jobs.index):
r = jobs.loc[job, "release"]
d = jobs.loc[job, "due"]
s = schedule.loc[job, "start"]
f = schedule.loc[job, "finish"]
# Show job release-due window
ax.fill_between(
[r, d], [-k - w, -k - w], [-k + w, -k + w], lw=1, color="k", alpha=0.2
)
ax.plot(
[r, r, d, d, r], [-k - w, -k + w, -k + w, -k - w, -k - w], lw=0.5, color="k"
)
# Show job start-finish window
color = "g" if f <= d else "r"
ax.fill_between(
[s, f], [-k - w, -k - w], [-k + w, -k + w], color=color, alpha=0.6
)
ax.text(
(s + f) / 2.0,
-k,
"Job " + job,
color="white",
weight="bold",
ha="center",
va="center",
)
# If past due
if f > d:
ax.plot([d] * 2, [-k + w, -k + 2 * w], lw=0.5, color="k")
ax.plot([f] * 2, [-k + w, -k + 2 * w], lw=0.5, color="k")
ax.plot([d, f], [-k + 1.5 * w] * 2, solid_capstyle="butt", lw=1, color="k")
ax.text(
f + 0.5,
-k + 1.5 * w,
f"{schedule.loc[job, 'past']} past due",
va="center",
)
total_past_due = schedule["past"].sum()
ax.set_ylim(-len(jobs.index), 1)
ax.set_title(f"{title}: Total past due = {total_past_due}")
ax.set_xlabel("Time")
ax.set_ylabel("Jobs")
ax.set_yticks([]) # range(len(jobs.index)), jobs.index)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["top"].set_visible(False)
custom_lines = [
Line2D([0], [0], c="k", lw=10, alpha=0.2),
Line2D([0], [0], c="g", lw=10, alpha=0.6),
Line2D([0], [0], c="r", lw=10, alpha=0.6),
]
ax.legend(
custom_lines,
["Job release/due window", "Completed on time", "Completed past due"],
)
gantt(jobs, schedule, "Execute Jobs in Order")
# %%
fifo = schedule_jobs(jobs, jobs.sort_values(by="release").index)
gantt(jobs, fifo, "First in, First out")
# %%
edd = schedule_jobs(jobs, jobs.sort_values(by="due").index)
gantt(jobs, edd, "First in, First out")
# %%
def build_model(jobs):
m = AMPL()
m.read("job_machine_scheduling.mod")
m.set_data(jobs, "JOBS")
pairs = [(i, j) for i in jobs.index for j in jobs.index if i < j]
m.set["PAIRS"] = pairs
return m
def solve_model(m, solver_name=SOLVER):
m.solve(solver=solver_name)
assert m.solve_result == "solved", m.solve_result
schedule = pd.DataFrame(
{
"start": m.var["start"].to_dict(),
"finish": m.var["finish"].to_dict(),
"past": m.var["past"].to_dict(),
}
)
schedule["past"] = schedule["past"].round()
return schedule
model = build_model(jobs)
schedule = solve_model(model)
display(schedule)
# %%
gantt(jobs, schedule, "Minimize total past due")
電気自動車の充電スケジューリング recharging-electric-vehicle.py 6 セル ・ 228 行 ・ モデル 1
この節のモデル(1)
AMPLev_plan.mod
param n;
# locations and road segments between location x and x + D
set STATIONS; # 1..n
set LOCATIONS; # 0, 1..n, D
set SEGMENTS; # 1..n + 1
param C{STATIONS};
param D;
param c_min;
param c_max;
param v;
param R;
param r_max;
param location{LOCATIONS};
param dist{SEGMENTS};
param t_lost;
# distance traveled
var x{LOCATIONS} >= 0, <= 10000;
# arrival and departure charge at each charging station
var c_arr{LOCATIONS} >= c_min, <= c_max;
var c_dep{LOCATIONS} >= c_min, <= c_max;
# arrival and departure times from each charging station
var t_arr{LOCATIONS} >= 0, <= 100;
var t_dep{LOCATIONS} >= 0, <= 100;
# arrival and departure rest from each charging station
var r_arr{LOCATIONS} >= 0, <= r_max;
var r_dep{LOCATIONS} >= 0, <= r_max;
minimize min_time: t_arr[n + 1];
s.t. drive_time {i in SEGMENTS}: t_arr[i] == t_dep[i-1] + dist[i]/v;
s.t. rest_time {i in SEGMENTS}: r_arr[i] == r_dep[i-1] + dist[i]/v;
s.t. drive_distance {i in SEGMENTS}: x[i] == x[i-1] + dist[i];
s.t. discharge {i in SEGMENTS}: c_arr[i] == c_dep[i-1] - R * dist[i];
s.t. recharge {i in STATIONS}:
# list of constraints that apply if there is no stop at station i
((c_dep[i] == c_arr[i] and t_dep[i] == t_arr[i] and r_dep[i] == r_arr[i])
or
# list of constraints that apply if there is a stop at station i
(t_dep[i] == t_lost + t_arr[i] + (c_dep[i] - c_arr[i])/C[i] and
c_dep[i] >= c_arr[i] and r_dep[i] == 0))
and not
((c_dep[i] == c_arr[i] and t_dep[i] == t_arr[i] and r_dep[i] == r_arr[i])
and
(t_dep[i] == t_lost + t_arr[i] + (c_dep[i] - c_arr[i])/C[i] and
c_dep[i] >= c_arr[i] and r_dep[i] == 0));
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# specify number of charging stations
n_charging_stations = 20
# randomly distribute charging stations along a fixed route
np.random.seed(1842)
d = np.round(np.cumsum(np.random.triangular(20, 150, 223, n_charging_stations)), 1)
# randomly assign changing capacities
c = np.random.choice([50, 100, 150, 250], n_charging_stations, p=[0.2, 0.4, 0.3, 0.1])
# assign names to the charging stations
s = [f"S_{i:02d}" for i in range(n_charging_stations)]
stations = pd.DataFrame([s, d, c]).T
stations.columns = ["name", "location", "kw"]
display(stations)
# %%
# current location (km) and charge (kw)
x = 0
# planning horizon
D = 2000
# visualize
fig, ax = plt.subplots(1, 1, figsize=(15, 3))
def plot_stations(stations, x, D, ax=ax):
for station in stations.index:
xs = stations.loc[station, "location"]
ys = stations.loc[station, "kw"]
ax.plot([xs, xs], [0, ys], "b", lw=10, solid_capstyle="butt")
ax.text(xs, 0 - 30, stations.loc[station, "name"], ha="center")
ax.plot([x, x + D], [0, 0], "r", lw=5, solid_capstyle="butt", label="plan horizon")
ax.plot([x, x + D], [0, 0], "r.", ms=20)
ax.axhline(0)
ax.set_ylim(-50, 300)
ax.set_xlabel("Distance")
ax.set_ylabel("kw")
ax.set_title("charging stations")
ax.legend()
plot_stations(stations, x, D)
# %%
# charge limits (kw)
c_max = 150
c_min = 0.2 * c_max
c = c_max
# velocity km/hr and discharge rate kwh/km
v = 100.0
R = 0.24
# lost time
t_lost = 10 / 60
t_rest = 10 / 60
# rest time
r_max = 3
# %%
def ev_plan(stations, x, D):
# data preprocessing
# find stations between x and x + D
on_route = stations[(stations["location"] >= x) & (stations["location"] <= x + D)]
# adjust the index to match the model directly
on_route.index += 1
n = len(on_route)
# get the values of the location parameter
location = on_route["location"].to_dict()
location[0] = x
location[n + 1] = x + D
# get the values for the dist parameter
dist = {}
for s in range(1, n + 2):
dist[s] = location[s] - location[s - 1]
# define the indexing sets
# note the +1 at the end because Python ranges are not inclusive at the endpoint
STATIONS = list(range(1, n + 1)) # 1 to n
LOCATIONS = list(range(n + 2)) # 0 to n + 1
SEGMENTS = list(range(1, n + 2)) # 1 to n + 1
# instantiate AMPL and load model
m = AMPL()
m.read("ev_plan.mod")
m.set["STATIONS"] = STATIONS
m.set["LOCATIONS"] = LOCATIONS
m.set["SEGMENTS"] = SEGMENTS
# load data
m.param["C"] = on_route["kw"]
m.param["location"] = location
m.param["D"] = D
m.param["n"] = n
m.param["c_min"] = c_min
m.param["c_max"] = c_max
m.param["r_max"] = r_max
m.param["t_lost"] = t_lost
m.param["v"] = v
m.param["R"] = R
m.param["dist"] = dist
# initial conditions
m.var["x"][0].fix(x)
m.var["t_dep"][0].fix(0.0)
m.var["r_dep"][0].fix(0.0)
m.var["c_dep"][0].fix(c)
# set solver and solve
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
def get_results(model):
x = [(int(k), v) for k, v in model.var["x"].to_list()]
t_arr = [v for k, v in model.var["t_arr"].to_list()]
t_dep = [v for k, v in model.var["t_dep"].to_list()]
c_arr = [v for k, v in model.var["c_arr"].to_list()]
c_dep = [v for k, v in model.var["c_dep"].to_list()]
results = pd.DataFrame(x, columns=["index", "location"]).set_index("index")
results["t_arr"] = t_arr
results["t_dep"] = t_dep
results["c_arr"] = c_arr
results["c_dep"] = c_dep
results["t_stop"] = results["t_dep"] - results["t_arr"]
results["t_stop"] = results["t_stop"].round(6)
return results
m = ev_plan(stations, 0, 2000)
results = get_results(m)
display(results)
# %%
# visualize
def visualize(m):
D = m.param["D"].value()
results = get_results(m)
results["t_stop"] = results["t_dep"] - results["t_arr"]
fig, ax = plt.subplots(2, 1, figsize=(15, 8), sharex=True)
# plot stations
for station in stations.index:
xs = stations.loc[station, "location"]
ys = stations.loc[station, "kw"]
ax[0].plot([xs, xs], [0, ys], "b", lw=10, solid_capstyle="butt")
ax[0].text(xs, 0 - 30, stations.loc[station, "name"], ha="center")
# plot planning horizon
ax[0].plot(
[x, x + D], [0, 0], "r", lw=5, solid_capstyle="butt", label="plan horizon"
)
ax[0].plot([x, x + D], [0, 0], "r.", ms=20)
# annotations
ax[0].axhline(0)
ax[0].set_ylim(-50, 300)
ax[0].set_ylabel("kw")
ax[0].set_title("charging stations")
ax[0].legend()
SEGMENTS = m.set["SEGMENTS"].to_list()
# plot battery charge
for i in SEGMENTS:
xv = [results.loc[i - 1, "location"], results.loc[i, "location"]]
cv = [results.loc[i - 1, "c_dep"], results.loc[i, "c_arr"]]
ax[1].plot(xv, cv, "g")
STATIONS = m.set["STATIONS"].to_list()
# plot charge at stations
for i in STATIONS:
xv = [results.loc[i, "location"]] * 2
cv = [results.loc[i, "c_arr"], results.loc[i, "c_dep"]]
ax[1].plot(xv, cv, "g")
# mark stop locations
for i in STATIONS:
if results.loc[i, "t_stop"] > 0:
ax[1].axvline(results.loc[i, "location"], color="r", ls="--")
# show constraints on battery charge
ax[1].axhline(c_max, c="g")
ax[1].axhline(c_min, c="g")
ax[1].set_ylim(0, 1.1 * c_max)
ax[1].set_ylabel("Charge (kw)")
visualize(ev_plan(stations, 0, 2000))
BIM生産問題:再訪 bim-production-revisited.py 13 セル ・ 144 行 ・ モデル 1
この節のモデル(1)
AMPLBIMproduction_v1.mod
set periods ordered;
set products;
set supplying_batches;
set supplying_copper;
set unitary_products;
param delta{products, periods}; # demand
param pi{supplying_batches}; # aquisition price
param kappa{supplying_copper}; # price of copper sheet
param beta;
param gamma{products}; # unitary holding costs
param Alpha{products}; # initial stock
param Omega{products}; # desired stock
param copper_bucket_size;
param stock_limit;
param batch_size;
param copper_sheet_mass;
var y{periods, supplying_copper} integer >= 0;
var x{unitary_products, periods, supplying_batches} >= 0;
var ss{products, periods} >= 0;
var uu{products, periods} >= 0;
var bb{periods, supplying_batches} integer >= 0;
var pp{periods} integer >= 0;
var rr{periods} integer >= 0;
s.t. units_in_batches {t in periods, s in supplying_batches}:
sum{p in unitary_products} x[p,t,s] <= batch_size * bb[t,s];
s.t. copper_in_buckets {t in periods}:
ss['copper', t] <= copper_bucket_size * rr[t];
s.t. inventory_capacity {t in periods}:
ss['copper', t] <= stock_limit;
s.t. pairs_in_batches {t in periods}:
pp[t] <= bb[t,'C'];
s.t. pairs_in_sheets {t in periods}:
pp[t] <= y[t,'C'];
s.t. bought {t in periods, p in products}:
(if p == 'copper' then
copper_sheet_mass * sum{s in supplying_copper} y[t,s]
else
sum{s in supplying_batches} x[p,t,s])
== uu[p,t];
var acquisition_cost =
sum{t in periods}(
sum{s in supplying_batches} pi[s] * bb[t,s] +
sum{s in supplying_copper} kappa[s] * y[t,s] -
beta * pp[t]
);
var inventory_cost =
sum{t in periods}(
gamma['copper'] * rr[t] +
sum{p in unitary_products} gamma[p] * ss[p,t]
);
minimize total_cost: acquisition_cost + inventory_cost;
s.t. balance {p in products, t in periods}:
(if t == first(periods) then
Alpha[p]
else
ss[p,prev(t)]) +
uu[p,t] == delta[p,t] + ss[p,t];
s.t. finish {p in products}:
ss[p, last(periods)] >= Omega[p];
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
from io import StringIO
import pandas as pd
demand_data = """
chip, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
logic, 88, 125, 260, 217, 238, 286, 248, 238, 265, 293, 259, 244
memory, 47, 62, 81, 65, 95, 118, 86, 89, 82, 82, 84, 66
"""
demand_chips = pd.read_csv(StringIO(demand_data), index_col="chip")
display(demand_chips)
# %%
use = dict()
use["logic"] = {"silicon": 1, "plastic": 1, "copper": 4}
use["memory"] = {"germanium": 1, "plastic": 1, "copper": 2}
use = pd.DataFrame.from_dict(use).fillna(0).astype(int)
display(use)
# %%
demand = use.dot(demand_chips)
display(demand)
# %%
def BIMproduction_v1(
demand,
existing,
desired,
stock_limit,
supplying_copper,
supplying_batches,
price_copper_sheet,
price_batch,
discounted_price,
batch_size,
copper_sheet_mass,
copper_bucket_size,
unitary_products,
unitary_holding_costs,
):
m = AMPL()
m.read("BIMproduction_v1.mod")
m.set["periods"] = demand.columns
m.set["products"] = demand.index
m.param["delta"] = demand
m.set["supplying_batches"] = supplying_batches
m.param["pi"] = price_batch
m.set["supplying_copper"] = supplying_copper
m.param["kappa"] = price_copper_sheet
m.param["beta"] = price_batch["C"] + price_copper_sheet["C"] - discounted_price
m.set["unitary_products"] = unitary_products
m.param["gamma"] = unitary_holding_costs
m.param["Alpha"] = existing
m.param["Omega"] = desired
m.param["batch_size"] = batch_size
m.param["copper_bucket_size"] = copper_bucket_size
m.param["stock_limit"] = stock_limit
m.param["copper_sheet_mass"] = copper_sheet_mass
return m
# %%
m1 = BIMproduction_v1(
demand=demand,
existing={"silicon": 1000, "germanium": 1500, "plastic": 1750, "copper": 4800},
desired={"silicon": 500, "germanium": 500, "plastic": 1000, "copper": 2000},
stock_limit=10000,
supplying_copper=["B", "C"],
supplying_batches=["A", "C"],
price_copper_sheet={"B": 300, "C": 400},
price_batch={"A": 500, "C": 600},
discounted_price=700,
batch_size=100,
copper_sheet_mass=100,
copper_bucket_size=10,
unitary_products=["silicon", "germanium", "plastic"],
unitary_holding_costs={"copper": 10, "silicon": 2, "germanium": 2, "plastic": 2},
)
m1.solve(solver=SOLVER, highs_options="outlev=1")
assert m1.solve_result == "solved", m1.solve_result
# %%
stock = m1.var["ss"].to_pandas().unstack()
stock.columns = stock.columns.get_level_values(1)
stock = stock.reindex(index=demand.index, columns=demand.columns)
display(stock)
# %%
import matplotlib.pyplot as plt, numpy as np
stock.T.plot(drawstyle="steps-mid", grid=True, figsize=(13, 4))
plt.xticks(np.arange(len(stock.columns)), stock.columns)
plt.show()
# %%
m1.var["pp"].to_pandas().T
# %%
df = m1.var["uu"].to_pandas().unstack()
df.columns = df.columns.get_level_values(1)
df = df.reindex(index=demand.index, columns=demand.columns)
display(df)
# %%
b = m1.var["bb"].to_pandas().unstack().T
b.index = b.index.get_level_values(1)
b = b.reindex(columns=demand.columns)
b.index.names = [None]
display(b)
# %%
y = m1.var["y"].to_pandas().unstack().T
y.index = y.index.get_level_values(1)
y = y.reindex(columns=demand.columns)
y.index.names = [None]
display(y)
# %%
x = m1.var["x"].to_pandas().unstack(1)
x.columns = x.columns.get_level_values(1)
x = x.reindex(columns=demand.columns)
x.index.names = ["materials", "supplier"]
display(x)
補足:覆面算 cryptarithms.py 2 セル ・ 36 行 ・ モデル 1
この節のモデル(1)
AMPLcryptarithms.mod
set LETTERS;
set PAIRS within {LETTERS, LETTERS};
var n{LETTERS} integer >= 0, <= 9;
s.t. message:
1000*n['S'] + 100*n['E'] + 10*n['N'] + n['D']
+ 1000*n['M'] + 100*n['O'] + 10*n['R'] + n['E']
== 10000*n['M'] + 1000*n['O'] + 100*n['N'] + 10*n['E'] + n['Y'];
# leading digit must be non-zero
s.t. leading_digit_nonzero: n['M'] >= 1;
# assign a different number to each letter
s.t. unique_assignment{(a, b) in PAIRS}:
(n[a] >= n[b] + 1
or
n[b] >= n[a] + 1)
and not
(n[a] >= n[b] + 1
and
n[b] >= n[a] + 1);
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
m = AMPL()
m.read("cryptarithms.mod")
LETTERS = ["S", "E", "N", "D", "M", "O", "R", "Y"]
PAIRS = [(a, b) for a in LETTERS for b in LETTERS if a < b]
m.set["LETTERS"] = LETTERS
m.set["PAIRS"] = PAIRS
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
n = m.var["n"].to_dict()
def letters2num(s):
return " ".join(map(lambda s: f"{int(round(n[s], 0))}", list(s)))
print(" ", letters2num("SEND"))
print(" + ", letters2num("MORE"))
print(" ----------")
print("= ", letters2num("MONEY"))
補足:ストリップパッキング strip-packing.py 7 セル ・ 225 行 ・ モデル 4
この節のモデル(4)
AMPLpack_boxes_V1.mod
set BOXES;
set PAIRS within {BOXES,BOXES};
param w{BOXES};
param W_ub;
var W >= 0, <= W_ub;
var x1{BOXES} >= 0, <= W_ub;
var x2{BOXES} >= 0, <= W_ub;
minimize minimize_width: W;
s.t. bounding_box {i in BOXES}:
x2[i] == x1[i] + w[i];
s.t. width {i in BOXES}:
x2[i] <= W;
s.t. no_overlap {(i, j) in PAIRS}:
(x2[i] <= x1[j] or x2[j] <= x1[i])
and not
(x2[i] <= x1[j] and x2[j] <= x1[i]);
AMPLpack_boxes_V2.mod
set BOXES;
set PAIRS within {BOXES,BOXES};
param w{BOXES};
param d{BOXES};
param W_ub;
var W >= 0, <= W_ub;
var x1{BOXES} >= 0, <= W_ub;
var x2{BOXES} >= 0, <= W_ub;
var y1{BOXES} >= 0, <= W_ub;
var y2{BOXES} >= 0, <= W_ub;
var r{BOXES} binary;
minimize minimize_width: W;
s.t. width {i in BOXES}:
x2[i] <= W;
s.t. yloc {i in BOXES}:
y1[i] == 0;
s.t. rotate {i in BOXES}:
r[i] == 0 ==>
(x2[i] == x1[i] + w[i] and y2[i] == y1[i] + d[i])
else
(x2[i] == x1[i] + d[i] and y2[i] == y1[i] + w[i]);
s.t. no_overlap {(i, j) in PAIRS}:
(x2[i] <= x1[j] or x2[j] <= x1[i])
and not
(x2[i] <= x1[j] and x2[j] <= x1[i])
;
AMPLpack_boxes_V3.mod
set BOXES;
set PAIRS within {BOXES,BOXES};
param w{BOXES};
param d{BOXES};
param D;
param W_ub;
var W >= 0, <= W_ub;
var x1{BOXES} >= 0, <= W_ub;
var x2{BOXES} >= 0, <= W_ub;
var y1{BOXES} >= 0, <= W_ub;
var y2{BOXES} >= 0, <= W_ub;
var r{BOXES} binary;
minimize minimize_width: W;
s.t. width {i in BOXES}:
x2[i] <= W;
s.t. height {i in BOXES}:
y2[i] <= D;
s.t. rotate {i in BOXES}:
r[i] == 0 ==> (x2[i] == x1[i] + w[i] and y2[i] == y1[i] + d[i])
else
(x2[i] == x1[i] + d[i] and y2[i] == y1[i] + w[i]);
s.t. no_overlap {(i, j) in PAIRS}:
(x2[i] <= x1[j] or x2[j] <= x1[i] or y2[i] <= y1[j] or y2[j] <= y1[i])
and not
(x2[i] <= x1[j] and x2[j] <= x1[i] and y2[i] <= y1[j] and y2[j] <= y1[i])
;
AMPLpack_boxes_V4.mod
set BOXES;
set PAIRS within {BOXES,BOXES};
param w{BOXES};
param d{BOXES};
param D;
param W_ub;
var W >= 0, <= W_ub;
var x1{BOXES} >= 0, <= W_ub;
var x2{BOXES} >= 0, <= W_ub;
var y1{BOXES} >= 0, <= W_ub;
var y2{BOXES} >= 0, <= W_ub;
var r{BOXES} binary;
minimize minimize_width: W;
s.t. width {i in BOXES}:
x2[i] <= W;
s.t. height {i in BOXES}:
y2[i] <= D;
s.t. rotate {i in BOXES}:
r[i] == 0 ==> (x2[i] == x1[i] + w[i] and y2[i] == y1[i] + d[i])
else
(x2[i] == x1[i] + d[i] and y2[i] == y1[i] + w[i])
;
s.t. no_overlap {(i, j) in PAIRS}:
x2[i] <= x1[j] or
x2[j] <= x1[i] or
(y2[i] <= y1[j] and x2[i] >= x1[j] + 1 and x2[j] >= x1[i] + 1) or
(y2[j] <= y1[i] and x2[i] >= x1[j] + 1 and x2[j] >= x1[i] + 1);
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import random
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
# random seed
random.seed(1842)
# generate boxes
def generate_boxes(N, max_width=200, max_depth=200):
boxes = pd.DataFrame()
boxes["w"] = [random.randint(0.2 * max_width, max_width) for i in range(N)]
boxes["d"] = [random.randint(0.2 * max_depth, max_depth) for i in range(N)]
return boxes
N = 8
boxes = generate_boxes(8)
display(boxes)
# set shelf width as a multiple of the deepest box
D = 2 * boxes["d"].max()
print("Shelf Depth = ", D)
# %%
def pack_boxes_V0(boxes):
soln = boxes.copy()
soln["x1"] = soln["w"].cumsum() - soln["w"]
soln["x2"] = soln["w"].cumsum()
soln["y1"] = 0
soln["y2"] = soln["d"]
soln["r"] = 0
return soln
def show_boxes(soln, D):
"""Show bounding boxes on a diagram of the shelf."""
fig, ax = plt.subplots(1, 1, figsize=(14, 4))
for i, x, y, w, h, r in zip(
soln.index, soln["x1"], soln["y1"], soln["w"], soln["d"], soln["r"]
):
c = "g"
if r:
h, w = w, h
c = "r"
ax.add_patch(Rectangle((x, y), w, h, edgecolor="k", facecolor=c, alpha=0.6))
xc = x + w / 2
yc = y + h / 2
ax.annotate(
i, (xc, yc), color="w", weight="bold", fontsize=12, ha="center", va="center"
)
W_lb = (soln["w"] * soln["d"]).sum() / D
ax.set_xlim(0, 1.1 * soln["w"].sum())
ax.set_ylim(0, D * 1.1)
ax.axhline(D, label="shelf depth $D$", lw=0.8)
ax.axvline(W_lb, label="lower bound $W_{lb}$", color="g", lw=0.8)
ax.axvline(soln["x2"].max(), label="shelf width $W$", color="r", lw=0.8)
ax.fill_between([0, ax.get_xlim()[1]], [D, D], color="b", alpha=0.1)
ax.set_title(f"shelf width $W$ = {soln['x2'].max():.0f}")
ax.set_xlabel("width")
ax.set_ylabel("depth")
ax.set_aspect("equal")
ax.legend(loc="upper right")
soln = pack_boxes_V0(boxes)
display(soln)
show_boxes(soln, D)
# %%
def pack_boxes_V1(boxes):
# a simple upper bound on shelf width
W_ub = boxes["w"].sum()
BOXES = list(boxes.index)
PAIRS = [(i, j) for i in BOXES for j in BOXES if i < j]
m = AMPL()
m.read("pack_boxes_V1.mod")
m.set["BOXES"] = BOXES
m.set["PAIRS"] = PAIRS
m.param["w"] = boxes["w"]
m.param["W_ub"] = int(W_ub)
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
soln = boxes.copy()
soln["x1"] = m.var["x1"].to_dict()
soln["x2"] = m.var["x2"].to_dict()
soln["y1"] = 0
soln["y2"] = soln["y1"] + soln["d"]
soln["r"] = 0
return soln
soln = pack_boxes_V1(boxes)
display(soln)
show_boxes(soln, D)
# %%
def pack_boxes_V2(boxes):
W_ub = boxes["w"].sum()
BOXES = list(boxes.index)
PAIRS = [(i, j) for i in BOXES for j in BOXES if i < j]
m = AMPL()
m.read("pack_boxes_V2.mod")
m.set["BOXES"] = BOXES
m.set["PAIRS"] = PAIRS
m.param["w"] = boxes["w"]
m.param["d"] = boxes["d"]
m.param["W_ub"] = int(W_ub)
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
soln = boxes.copy()
soln["x1"] = m.var["x1"].to_dict()
soln["x2"] = m.var["x2"].to_dict()
soln["y1"] = m.var["y1"].to_dict()
soln["y2"] = m.var["y2"].to_dict()
soln["r"] = m.var["r"].to_dict()
return soln
soln = pack_boxes_V2(boxes)
display(soln)
show_boxes(soln, D)
# %%
def pack_boxes_V3(boxes, D):
W_ub = boxes["w"].sum()
BOXES = list(boxes.index)
PAIRS = [(i, j) for i in BOXES for j in BOXES if i < j]
m = AMPL()
m.read("pack_boxes_V3.mod")
m.set["BOXES"] = BOXES
m.set["PAIRS"] = PAIRS
m.param["w"] = boxes["w"]
m.param["d"] = boxes["d"]
m.param["W_ub"] = int(W_ub)
m.param["D"] = int(D)
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
r = m.var["r"].to_dict()
r = {i: int(round(r[i])) for i in r}
soln = boxes.copy()
soln["x1"] = m.var["x1"].to_dict()
soln["x2"] = m.var["x2"].to_dict()
soln["y1"] = m.var["y1"].to_dict()
soln["y2"] = m.var["y2"].to_dict()
soln["r"] = r
return soln
soln = pack_boxes_V3(boxes, D)
display(soln)
show_boxes(soln, D)
# %%
def pack_boxes_V4(boxes, D):
W_ub = boxes["w"].sum()
BOXES = list(boxes.index)
PAIRS = [(i, j) for i in BOXES for j in BOXES if i < j]
m = AMPL()
m.read("pack_boxes_V4.mod")
m.set["BOXES"] = BOXES
m.set["PAIRS"] = PAIRS
m.param["w"] = boxes["w"]
m.param["d"] = boxes["d"]
m.param["W_ub"] = int(W_ub)
m.param["D"] = int(D)
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
r = m.var["r"].to_dict()
r = {i: int(round(r[i])) for i in r}
soln = boxes.copy()
soln["x1"] = m.var["x1"].to_dict()
soln["x2"] = m.var["x2"].to_dict()
soln["y1"] = m.var["y1"].to_dict()
soln["y2"] = m.var["y2"].to_dict()
soln["r"] = r
return soln
soln = pack_boxes_V4(boxes, D)
display(soln)
show_boxes(soln, D)
補足:ジョブショップ・スケジューリング問題 job-shop-scheduling.py 14 セル ・ 294 行 ・ モデル 3
この節のモデル(3)
AMPLjobshop_model.mod
set JOBS;
set MACHINES;
set TASKS within {JOBS, MACHINES};
set TASKORDER within {TASKS, TASKS};
set DISJUNCTIONS within {JOBS, JOBS, MACHINES};
param dur{TASKS};
param ub;
var makespan >= 0, <= ub;
var start{TASKS} >= 0, <= ub;
minimize minimize_makespan: makespan;
s.t. finish_tasks {(j,m) in TASKS}:
start[j, m] + dur[j, m] <= makespan;
s.t. preceding {(j, m, k, n) in TASKORDER}:
start[k, n] + dur[k, n] <= start[j, m];
s.t. no_overlap {(j, k, m) in DISJUNCTIONS}:
(start[j, m] + dur[j, m] <= start[k, m]
or
start[k, m] + dur[k, m] <= start[j, m])
and not
(start[j, m] + dur[j, m] <= start[k, m]
and
start[k, m] + dur[k, m] <= start[j, m]);
AMPLjobshop_model_clean.mod
set JOBS;
set MACHINES;
set TASKS within {JOBS, MACHINES};
set TASKORDER within {TASKS, TASKS};
set DISJUNCTIONS within {JOBS, JOBS, MACHINES};
param dur{TASKS};
param ub;
var makespan >= 0, <= ub;
var start{TASKS} >= 0, <= ub;
minimize minimize_makespan: makespan;
s.t. finish_tasks {(j,m) in TASKS}:
start[j, m] + dur[j, m] <= makespan;
s.t. preceding {(j, m, k, n) in TASKORDER}:
start[k, n] + dur[k, n] <= start[j, m];
s.t. no_overlap {(j, k, m) in DISJUNCTIONS}:
(start[j, m] + dur[j, m] + tclean <= start[k, m]
or
start[k, m] + dur[k, m] + tclean <= start[j, m]);
AMPLjobshop_model_clean_zw.mod
set JOBS;
set MACHINES;
set TASKS within {JOBS, MACHINES};
set TASKORDER within {TASKS, TASKS};
set DISJUNCTIONS within {JOBS, JOBS, MACHINES};
param dur{TASKS};
param ub;
param tclean;
param ZW default 1;
var makespan >= 0, <= ub;
var start{TASKS} >= 0, <= ub;
minimize minimize_makespan: makespan;
s.t. finish_tasks {(j,m) in TASKS}:
start[j, m] + dur[j, m] <= makespan;
s.t. preceding {(j, m, k, n) in TASKORDER}:
ZW == 1 ==> start[k, n] + dur[k, n] == start[j, m]
else
start[k, n] + dur[k, n] <= start[j, m];
s.t. disjunctions {(j, k, m) in DISJUNCTIONS}:
(start[j, m] + dur[j, m] + tclean <= start[k, m]
or
start[k, m] + dur[k, m] + tclean <= start[j, m]);
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
TASKS = {
("Paper_1", "Blue"): {"dur": 45, "prec": None},
("Paper_1", "Yellow"): {"dur": 10, "prec": ("Paper_1", "Blue")},
("Paper_2", "Blue"): {"dur": 20, "prec": ("Paper_2", "Green")},
("Paper_2", "Green"): {"dur": 10, "prec": None},
("Paper_2", "Yellow"): {"dur": 34, "prec": ("Paper_2", "Blue")},
("Paper_3", "Blue"): {"dur": 12, "prec": ("Paper_3", "Yellow")},
("Paper_3", "Green"): {"dur": 17, "prec": ("Paper_3", "Blue")},
("Paper_3", "Yellow"): {"dur": 28, "prec": None},
}
# %%
def jobshop_model(TASKS):
m = AMPL()
m.read("jobshop_model.mod")
jobs = list(set([j for (j, m) in TASKS]))
machines = list(set([m for (j, m) in TASKS]))
tasks = list(TASKS.keys())
taskorder = [
(j, m, k, n)
for (j, m) in tasks
for (k, n) in tasks
if (k, n) == TASKS[(j, m)]["prec"]
]
disjunctions = [
(j, k, m) for (j, m) in tasks for (k, n) in tasks if m == n and j < k
]
dur = {(j, m): TASKS[(j, m)]["dur"] for (j, m) in TASKS}
ub = sum(dur[i] for i in dur)
m.set["JOBS"] = jobs
m.set["MACHINES"] = machines
m.set["TASKS"] = tasks
m.set["TASKORDER"] = taskorder
m.set["DISJUNCTIONS"] = disjunctions
m.param["dur"] = dur
m.param["ub"] = ub
return m
jobshop_model(TASKS)
# %%
def jobshop_solve(model):
model.solve(solver=SOLVER)
assert model.solve_result == "solved", model.solve_result
start = model.var["start"].to_dict()
dur = model.param["dur"].to_dict()
tasks = model.set["TASKS"].to_dict()
results = [
{
"Job": j,
"Machine": m,
"Start": start[j, m],
"Duration": dur[j, m],
"Finish": start[j, m] + dur[j, m],
}
for j, m in tasks
]
return results
def jobshop(TASKS):
return jobshop_solve(jobshop_model(TASKS))
results = jobshop(TASKS)
results
# %%
import pandas as pd
schedule = pd.DataFrame(results)
print("\nSchedule by Job")
print(schedule.sort_values(by=["Job", "Start"]).set_index(["Job", "Machine"]))
print("\nSchedule by Machine")
print(schedule.sort_values(by=["Machine", "Start"]).set_index(["Machine", "Job"]))
# %%
import matplotlib.pyplot as plt
import matplotlib as mpl
def visualize(results):
schedule = pd.DataFrame(results)
JOBS = sorted(list(schedule["Job"].unique()))
MACHINES = sorted(list(schedule["Machine"].unique()))
makespan = schedule["Finish"].max()
bar_style = {"alpha": 1.0, "lw": 25, "solid_capstyle": "butt"}
text_style = {"color": "white", "weight": "bold", "ha": "center", "va": "center"}
colors = mpl.cm.Dark2.colors
schedule.sort_values(by=["Job", "Start"])
schedule.set_index(["Job", "Machine"], inplace=True)
fig, ax = plt.subplots(2, 1, figsize=(12, 5 + (len(JOBS) + len(MACHINES)) / 4))
for jdx, j in enumerate(JOBS, 1):
for mdx, m in enumerate(MACHINES, 1):
if (j, m) in schedule.index:
xs = schedule.loc[(j, m), "Start"]
xf = schedule.loc[(j, m), "Finish"]
ax[0].plot([xs, xf], [jdx] * 2, c=colors[mdx % 7], **bar_style)
ax[0].text((xs + xf) / 2, jdx, m, **text_style)
ax[1].plot([xs, xf], [mdx] * 2, c=colors[jdx % 7], **bar_style)
ax[1].text((xs + xf) / 2, mdx, j, **text_style)
ax[0].set_title("Job Schedule")
ax[0].set_ylabel("Job")
ax[1].set_title("Machine Schedule")
ax[1].set_ylabel("Machine")
for idx, s in enumerate([JOBS, MACHINES]):
ax[idx].set_ylim(0.5, len(s) + 0.5)
ax[idx].set_yticks(range(1, 1 + len(s)))
ax[idx].set_yticklabels(s)
ax[idx].text(
makespan,
ax[idx].get_ylim()[0] - 0.2,
"{0:0.1f}".format(makespan),
ha="center",
va="top",
)
ax[idx].plot([makespan] * 2, ax[idx].get_ylim(), "r--")
ax[idx].set_xlabel("Time")
ax[idx].grid(True)
fig.tight_layout()
visualize(results)
# %%
def recipe_to_tasks(jobs, machines, durations):
TASKS = {}
for j in jobs:
prec = (None, None)
for m, d in zip(machines, durations):
task = (j, m)
if prec == (None, None):
TASKS.update({(j, m): {"dur": d, "prec": None}})
else:
TASKS.update({(j, m): {"dur": d, "prec": prec}})
prec = task
return TASKS
recipeA = recipe_to_tasks(
"A", ["Mixer", "Reactor", "Separator", "Packaging"], [1, 5, 4, 1.5]
)
visualize(jobshop(recipeA))
# %%
recipeB = recipe_to_tasks("B", ["Separator", "Packaging"], [4.5, 1])
visualize(jobshop(recipeB))
# %%
recipeC = recipe_to_tasks("C", ["Separator", "Reactor", "Packaging"], [5, 3, 1.5])
visualize(jobshop(recipeC))
# %%
TASKS = recipe_to_tasks(
["A1", "A2", "A3", "A4"],
["Mixer", "Reactor", "Separator", "Packaging"],
[1, 5, 4, 1.5],
)
results = jobshop(TASKS)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))
# %%
# update is used to append dictionaries
TASKS = recipeA
TASKS.update(recipeB)
TASKS.update(recipeC)
for k, v in TASKS.items():
print(k, v)
results = jobshop(TASKS)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))
# %%
TASKS = recipe_to_tasks(
["A1", "A2"], ["Mixer", "Reactor", "Separator", "Packaging"], [1, 5, 4, 1.5]
)
TASKS.update(recipe_to_tasks(["B1", "B2"], ["Separator", "Packaging"], [4.5, 1]))
TASKS.update(
recipe_to_tasks(["C1", "C2"], ["Separator", "Reactor", "Packaging"], [5, 3, 1.5])
)
results = jobshop(TASKS)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))
# %%
def jobshop_model_clean(TASKS, tclean=0):
m = AMPL()
m.read("jobshop_model.mod")
jobs = list(set([j for (j, m) in TASKS]))
machines = list(set([m for (j, m) in TASKS]))
tasks = list(TASKS.keys())
taskorder = [
(j, m, k, n)
for (j, m) in tasks
for (k, n) in tasks
if (k, n) == TASKS[(j, m)]["prec"]
]
disjunctions = [
(j, k, m) for (j, m) in tasks for (k, n) in tasks if m == n and j < k
]
dur = {(j, m): TASKS[(j, m)]["dur"] for (j, m) in TASKS}
ub = sum(dur[i] for i in dur)
m.set["JOBS"] = jobs
m.set["MACHINES"] = machines
m.set["TASKS"] = tasks
m.set["TASKORDER"] = taskorder
m.set["DISJUNCTIONS"] = disjunctions
m.param["dur"] = dur
m.param["ub"] = ub
return m
model = jobshop_model_clean(TASKS, tclean=0.5)
results = jobshop_solve(model)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))
# %%
def jobshop_model_clean_zw(TASKS, tclean=0, ZW=False):
m = AMPL()
m.read("jobshop_model_clean_zw.mod")
jobs = list(set([j for (j, m) in TASKS]))
machines = list(set([m for (j, m) in TASKS]))
tasks = list(TASKS.keys())
taskorder = [
(j, m, k, n)
for (j, m) in tasks
for (k, n) in tasks
if (k, n) == TASKS[(j, m)]["prec"]
]
disjunctions = [
(j, k, m) for (j, m) in tasks for (k, n) in tasks if m == n and j < k
]
dur = {(j, m): TASKS[(j, m)]["dur"] for (j, m) in TASKS}
ub = sum(dur[i] for i in dur)
m.set["JOBS"] = jobs
m.set["MACHINES"] = machines
m.set["TASKS"] = tasks
m.set["TASKORDER"] = taskorder
m.set["DISJUNCTIONS"] = disjunctions
m.param["dur"] = dur
m.param["ub"] = ub
m.param["tclean"] = tclean
m.param["ZW"] = 1 if ZW else 0
m.option["solver"] = SOLVER
return m
model = jobshop_model_clean_zw(TASKS, tclean=0.5, ZW=True)
results = jobshop_solve(model)
visualize(results)
print("Makespan =", max([task["Finish"] for task in results]))
補足:保全計画 maintenance-planning.py 6 セル ・ 130 行 ・ モデル 3
この節のモデル(3)
AMPLmaintenance_planning.mod
param T; # number of planning periods
param P; # number of maintenance periods
param M; # number of days for each maintenance period
set PH := 1..T; # set of planning horizon time periods
set Y := 1..(T - M + 1);
set S := 0..(M - 1);
param c{PH}; # profit
var x{PH} binary;
var y{PH} binary;
maximize profit: sum{t in PH} c[t] * x[t];
s.t. required_maintenance: P == sum{t in Y} y[t];
s.t. no_overlap {t in Y}: sum{s in S} y[t + s] <= 1;
s.t. required_shutdown {t in Y}:
(y[t] == 0 or sum{s in S} x[t + s] == 0)
and not
(y[t] == 0 and sum{s in S} x[t + s] == 0);
AMPLmaintenance_planning_ramp.mod
param T; # number of planning periods
param P; # number of maintenance periods
param M; # number of days for each maintenance period
param upos_max;
param uneg_max;
set PH := 1..T; # set of planning horizon time periods
set Y := 1..(T - M + 1);
set S := 0..(M - 1);
param c{PH}; # profit
var x{PH} >= 0, <= 1;
var y{PH} binary;
var upos{PH} >= 0, <= upos_max;
var uneg{PH} >= 0, <= uneg_max;
maximize profit: sum{t in PH} c[t] * x[t];
s.t. required_maintenance: P == sum{t in Y} y[t];
s.t. no_overlap {t in Y}: sum{s in S} y[t + s] <= 1;
s.t. required_shutdown {t in Y}:
y[t] == 1 ==> sum{s in S} x[t + s] == 0;
s.t. ramp {t in PH: t != 1}:
x[t] == x[t-1] + upos[t] - uneg[t];
AMPLmaintenance_planning_ramp_operational.mod
param T; # number of planning periods
param P; # number of maintenance periods
param M; # number of days for each maintenance period
param N;
param upos_max;
param uneg_max;
set PH := 1..T; # set of planning horizon time periods
set Y := 1..(T - M + 1);
set S := 0..(M - 1);
set W := 0..(M + N - 1);
param c{PH}; # profit
var x{PH} >= 0, <= 1;
var y{PH} binary;
var upos{PH} >= 0, <= upos_max;
var uneg{PH} >= 0, <= uneg_max;
maximize profit: sum{t in PH} c[t] * x[t];
# ramp constraint
s.t. ramp {t in PH: t > 1}:
x[t] == x[t-1] + upos[t] - uneg[t];
# required number P of maintenance starts
s.t. sumy: P == sum{t in Y} y[t];
# no more than one maintenance start in the period of length M
s.t. sprd {t in Y}:
sum{s in W: t + s <= T} y[t+s] <= 1;
# Choose one of the following constraints (disj or bigm).
# Comment out the constraint not used.
#s.t. disj {t in Y}:
# y[t] == 1 ==> sum{s in W: t + s <= T} x[t+s] == 0;
s.t. bigm {t in Y}:
sum{s in W: t + s <= T} x[t+s] <= (M+N)*(1 - y[t]);
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import matplotlib.pyplot as plt
import numpy as np
# %%
# problem parameters
T = 90 # planning period from 1..T
M = 3 # length of maintenance period
P = 4 # number of maintenance periods
# daily profits
np.random.seed(0)
c = {k: np.random.uniform() for k in range(1, T + 1)}
# %%
class MP(object):
def __init__(self, c, M, P):
self.T = len(c)
self.M = M
self.P = P
self.c = c
self.modfile = "maintenance_planning.mod"
self.ampl = AMPL()
self.ampl.option["solver"] = SOLVER
self.solved = False
def load_data(self):
self.ampl.param["T"] = self.T
self.ampl.param["P"] = self.P
self.ampl.param["M"] = self.M
self.ampl.param["c"] = self.c
def set_solver(self, solver):
self.ampl.option["solver"] = solver
def set_modfile(self, modfile):
self.modfile = modfile
def solve(self):
self.ampl.read(self.modfile)
self.load_data()
self.ampl.solve()
assert self.ampl.solve_result == "solved", self.ampl.solve_result
self.solved = True
def plot_schedule(self):
if not self.solved:
self.solve()
T = self.T
M = self.M
P = self.P
PH = list(range(1, T + 1))
Y = list(range(1, T - M + 2))
S = list(range(M))
fig, ax = plt.subplots(3, 1, figsize=(9, 4))
ax[0].bar(PH, [self.c[t] for t in PH])
ax[0].set_title("daily profit $c_t$")
x = self.ampl.var["x"].to_dict()
ax[1].bar(PH, [x[t] for t in PH], label="normal operation")
ax[1].set_title("unit operating schedule $x_t$")
y = self.ampl.var["y"].to_dict()
ax[2].bar(Y, [y[t] for t in Y])
ax[2].set_title(str(P) + " maintenance starts $y_t$")
for a in ax:
a.set_xlim(0.1, T + 0.9)
plt.tight_layout()
model = MP(c, M, P)
model.plot_schedule()
# %%
class MPRamp(MP):
def __init__(self, c, M, P, upos_max, uneg_max):
super(MPRamp, self).__init__(c, M, P)
super(MPRamp, self).set_modfile("maintenance_planning_ramp.mod")
self.upos_max = upos_max
self.uneg_max = uneg_max
def load_data(self):
super(MPRamp, self).load_data()
self.ampl.param["upos_max"] = self.upos_max
self.ampl.param["uneg_max"] = self.uneg_max
upos_max = 0.3334
uneg_max = 0.5000
model = MPRamp(c, M, P, upos_max, uneg_max)
model.plot_schedule()
# %%
class MPRampOperational(MPRamp):
def __init__(self, c, M, P, upos_max, uneg_max, N):
super(MPRampOperational, self).__init__(c, M, P, upos_max, uneg_max)
super(MPRampOperational, self).set_modfile(
"maintenance_planning_ramp_operational.mod"
)
self.N = N
def load_data(self):
super(MPRampOperational, self).load_data()
self.ampl.param["N"] = self.N
N = 10 # minimum number of operational days between maintenance periods
model = MPRampOperational(c, M, P, upos_max, uneg_max, N)
model.plot_schedule()
第4章ネットワーク最適化5 ファイル▶ 講義動画(14:12)
晩餐会の座席配置 dinner-seat-allocation.py 13 セル ・ 181 行 ・ モデル 4
この節のモデル(4)
AMPLtable_seat.mod
set F;
set T;
param M{F};
param C{T};
param k;
var x{F, T} >= 0, <= k;
var dummy >= 0, <= 1, default 0;
minimize goal: dummy;
s.t. capacity {t in T}: sum{f in F} x[f, t] <= C[t];
s.t. seat {f in F}: sum{t in T} x[f, t] == M[f];
AMPLtable_seat_minimize_max_group_at_table.mod
set F;
set T;
param M{F};
param C{T};
var x{F,T} >= 0;
var k >= 0;
minimize goal: k;
s.t. capacity {t in T}: sum{f in F} x[f,t] <= C[t];
s.t. seat {f in F}: sum{t in T} x[f,t] == M[f];
s.t. bound {f in F, t in T}: x[f,t] <= k;
AMPLtable_seat_minimize_number_of_tables.mod
set F;
set T;
param M{F};
param C{T};
param k;
var x{F,T} integer >= 0, <= k;
var y{T} binary;
minimize goal: sum{t in T} y[t];
s.t. capacity{t in T}: sum{f in F} x[f,t] <= C[t] * y[t];
s.t. seat{f in F}: sum{t in T} x[f,t] == M[f];
AMPLtable_seat_maximize_members_flow_to_tables.mod
set F;
set T;
param M{F};
param C{T};
param k;
var x{F,T} integer >= 0, <= k;
maximize goal: sum{f in F, t in T} x[f, t];
s.t. capacity {t in T}: sum{f in F} x[f,t] <= C[t];
s.t. seat {f in F}: sum{t in T} x[f,t] == M[f];
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
from IPython.display import display
import networkx as nx
import pandas as pd
# %%
def table_seat(members, capacity, k):
m = AMPL()
m.read("table_seat.mod")
m.set["F"] = range(len(members))
m.set["T"] = range(len(capacity))
m.param["M"] = members
m.param["C"] = capacity
m.param["k"] = k
m.option["solver"] = SOLVER
return m
def get_solution(model):
df = model.var["x"].to_pandas()
df.index.names = ["family", "table"]
df = df.unstack()
df.columns = df.columns.get_level_values(1)
return df.round(5)
def report(model, results, type=int):
print(f"Solve result: {model.solve_result}")
if model.solve_result == "solved":
soln = get_solution(model).astype(type)
display(soln)
print(f'objective: {model.obj["goal"].value()}')
print(f"places at table: {list(soln.sum(axis=0))}")
print(f"members seated: {list(soln.sum(axis=1))}")
# %%
seatplan = table_seat(members=[6, 8, 2, 9, 13, 1], capacity=[8, 8, 10, 4, 9], k=3)
results = seatplan.solve()
assert seatplan.solve_result == "solved", seatplan.solve_result
report(seatplan, results, type=float)
# %%
def table_seat_minimize_max_group_at_table(members, capacity):
m = AMPL()
m.read("table_seat_minimize_max_group_at_table.mod")
m.set["F"] = range(len(members))
m.set["T"] = range(len(capacity))
m.param["M"] = members
m.param["C"] = capacity
m.option["solver"] = SOLVER
return m
# %%
seatplan = table_seat_minimize_max_group_at_table(
members=[6, 8, 2, 9, 13, 1], capacity=[8, 8, 10, 4, 9]
)
results = seatplan.solve()
report(seatplan, results, type=float)
# %%
def table_seat_minimize_number_of_tables(members, capacity, k, relax=False):
m = AMPL()
m.read("table_seat_minimize_number_of_tables.mod")
m.set["F"] = range(len(members))
m.set["T"] = range(len(capacity))
m.param["M"] = members
m.param["C"] = capacity
m.param["k"] = k
m.option["solver"] = SOLVER
if relax:
m.option["relax_integrality"] = 1
return m
# %%
members = [6, 8, 2, 9, 13, 1]
capacity = [8, 8, 10, 4, 9]
k = 3
print("\nMILO problem\n")
seatplan = table_seat_minimize_number_of_tables(members, capacity, k)
results = seatplan.solve()
report(seatplan, results, type=int)
print("\nRelaxed problem\n")
seatplan = table_seat_minimize_number_of_tables(members, capacity, k, relax=True)
results = seatplan.solve()
report(seatplan, results, type=float)
# %%
def table_seat_maximize_members_flow_to_tables(members, capacity, k, relax=False):
m = AMPL()
m.read("table_seat_maximize_members_flow_to_tables.mod")
m.set["F"] = range(len(members))
m.set["T"] = range(len(capacity))
m.param["M"] = members
m.param["C"] = capacity
m.param["k"] = k
m.option["solver"] = SOLVER
if relax:
m.option["relax_integrality"] = 1
return m
members = [6, 8, 2, 9, 13, 1]
capacity = [8, 8, 10, 4, 9]
k = 3
print("\nMILO problem\n")
seatplan = table_seat_maximize_members_flow_to_tables(members, capacity, k)
results = seatplan.solve()
report(seatplan, results, type=int)
print("\nRelaxed problem\n")
seatplan = table_seat_maximize_members_flow_to_tables(members, capacity, k, relax=True)
results = seatplan.solve()
report(seatplan, results, type=float)
# %%
def model_as_network(members, capacity, k):
# create lists of families and tables
families = [f"f{i}" for i in range(len(members))]
tables = [f"t{j}" for j in range(len(capacity))]
# create digraphy object
G = nx.DiGraph()
# add edges
G.add_edges_from(["door", f, {"capacity": n}] for f, n in zip(families, members))
G.add_edges_from([(f, t) for f in families for t in tables], capacity=k)
G.add_edges_from([t, "seat", {"capacity": n}] for t, n in zip(tables, capacity))
return G
# %%
members = [6, 8, 2, 9, 13, 1]
capacity = [8, 8, 10, 4, 9]
G = model_as_network(members, capacity=[8, 8, 10, 4, 9], k=3)
labels = {(e[0], e[1]): e[2] for e in G.edges(data="capacity")}
# %%
flow_value, flow_dict = nx.maximum_flow(G, 'door', 'seat')
# %%
families = [f"f{i:.0f}" for i in range(len(members))]
tables = [f"t{j:.0f}" for j in range(len(capacity))]
pd.DataFrame(flow_dict).loc[tables, families].astype("int")
ガソリン配送問題 gasoline-distribution.py 18 セル ・ 315 行 ・ モデル 3
この節のモデル(3)
AMPLtransport.mod
set SOURCES;
set DESTINATIONS;
param Rates{DESTINATIONS, SOURCES};
param supply{SOURCES};
param demand{DESTINATIONS};
var x{DESTINATIONS, SOURCES} >= 0;
minimize total_cost:
sum{dst in DESTINATIONS, src in SOURCES} Rates[dst, src] * x[dst, src];
var cost_to_destination {dst in DESTINATIONS} =
sum{src in SOURCES} Rates[dst, src] * x[dst, src];
var shipped_to_destination {dst in DESTINATIONS} =
sum{src in SOURCES} x[dst, src];
var shipped_from_source {src in SOURCES} =
sum{dst in DESTINATIONS} x[dst, src];
s.t. supply_constraint {src in SOURCES}:
shipped_from_source[src] <= supply[src];
s.t. demand_constraint {dst in DESTINATIONS}:
shipped_to_destination[dst] == demand[dst];
AMPLtransport2.mod
set SOURCES;
set DESTINATIONS;
param Rates{DESTINATIONS, SOURCES};
param supply{SOURCES};
param demand{DESTINATIONS};
var x{DESTINATIONS, SOURCES} >= 0;
var rate;
minimize delivery_rate: rate;
var cost_to_destination {dst in DESTINATIONS} =
sum{src in SOURCES} Rates[dst, src] * x[dst, src];
var total_cost = sum{dst in DESTINATIONS} cost_to_destination[dst];
s.t. rate_to_destination {dst in DESTINATIONS}:
cost_to_destination[dst] == rate * demand[dst];
var shipped_to_destination {dst in DESTINATIONS} =
sum{src in SOURCES} x[dst, src];
var shipped_from_source {src in SOURCES} =
sum{dst in DESTINATIONS} x[dst, src];
s.t. supply_constraint {src in SOURCES}:
shipped_from_source[src] <= supply[src];
s.t. demand_constraint {dst in DESTINATIONS}:
shipped_to_destination[dst] == demand[dst];
AMPLtransport3.mod
set SOURCES;
set DESTINATIONS;
param Rates{DESTINATIONS, SOURCES};
param supply{SOURCES};
param demand{DESTINATIONS};
var x{DESTINATIONS, SOURCES} >= 0;
var rate;
minimize total_cost:
sum{dst in DESTINATIONS, src in SOURCES} Rates[dst, src] * x[dst, src];
var cost_to_destination {dst in DESTINATIONS} =
rate * demand[dst];
s.t. allocate_costs:
sum{dst in DESTINATIONS} cost_to_destination[dst] ==
sum{dst in DESTINATIONS, src in SOURCES} Rates[dst, src] * x[dst, src];
var shipped_to_destination {dst in DESTINATIONS} =
sum{src in SOURCES} x[dst, src];
var shipped_from_source {src in SOURCES} =
sum{dst in DESTINATIONS} x[dst, src];
s.t. supply_constraint {src in SOURCES}:
shipped_from_source[src] <= supply[src];
s.t. demand_constraint {dst in DESTINATIONS}:
shipped_to_destination[dst] == demand[dst];
# %%
# install dependencies and select solver
#%pip install -q amplpy pandas matplotlib graphviz
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import pandas as pd
from IPython.display import HTML, display
import matplotlib.pyplot as plt
# %%
rates = pd.DataFrame(
[
["Alice", 8.3, 10.2, 8.75],
["Badri", 8.1, 12.0, 8.75],
["Cara", 8.3, 100.0, 8.75],
["Dan", 9.3, 8.0, 8.75],
["Emma", 10.1, 10.0, 8.75],
["Fujita", 9.8, 10.0, 8.75],
["Grace", 100, 8.0, 8.75],
["Helen", 7.5, 10.0, 8.75],
],
columns=["Destination", "Terminal A", "Terminal B", "Current Supplier"],
).set_index("Destination")
demand = pd.Series(
{
"Alice": 30000,
"Badri": 40000,
"Cara": 50000,
"Dan": 20000,
"Emma": 30000,
"Fujita": 45000,
"Grace": 80000,
"Helen": 18000,
},
name="demand",
)
supply = pd.Series(
{"Terminal A": 100000, "Terminal B": 80000, "Current Supplier": 500000},
name="supply",
)
display(HTML("<br><b>Gasoline Supply (Gallons)</b>"))
display(supply.to_frame())
display(HTML("<br><b>Gasoline Demand (Gallons)</b>"))
display(demand.to_frame())
display(HTML("<br><b>Transportation Rates (€ cents per Gallon)</b>"))
display(rates)
# %%
def transport(supply, demand, rates):
m = AMPL()
m.read("transport.mod")
m.set["SOURCES"] = rates.columns
m.set["DESTINATIONS"] = rates.index
m.param["Rates"] = rates
m.param["supply"] = supply
m.param["demand"] = demand
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
def get_results(m):
results = m.var["x"].to_pandas().unstack()
results.columns = results.columns.get_level_values(1)
results = results.reindex(index=rates.index, columns=rates.columns)
results["current costs"] = 700 * demand / 8000
results["contract costs"] = m.var["cost_to_destination"].to_pandas()
results["savings"] = results["current costs"].round(1) - results[
"contract costs"
].round(1)
results["contract rate"] = round(results["contract costs"] / demand, 4)
results["marginal cost"] = m.con["demand_constraint"].to_pandas()
return results
m = transport(supply, demand, rates / 100)
model1_results = get_results(m)
print(f"Old Delivery Costs = {sum(demand)*700/8000:.2f}€")
print(f"New Delivery Costs = {m.obj['total_cost'].value():.2f}€\n")
display(model1_results)
model1_results.plot(y="savings", kind="bar")
# %%
def transport2(supply, demand, rates):
m = AMPL()
m.read("transport2.mod")
m.set["SOURCES"] = rates.columns
m.set["DESTINATIONS"] = rates.index
m.param["Rates"] = rates
m.param["supply"] = supply
m.param["demand"] = demand
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
m = transport2(supply, demand, rates / 100)
print(f"Old Delivery Costs = $ {sum(demand)*700/8000}")
print(f"New Delivery Costs = $ {m.var['total_cost'].value()}")
print(f"rate = {m.var['rate'].value()}")
results = get_results(m)
display(results.round(1))
results.plot(y="savings", kind="bar")
plt.show()
# %%
def transport3(supply, demand, rates):
m = AMPL()
m.read("transport3.mod")
m.set["SOURCES"] = rates.columns
m.set["DESTINATIONS"] = rates.index
m.param["Rates"] = rates
m.param["supply"] = supply
m.param["demand"] = demand
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
m = transport3(supply, demand, rates / 100)
print(f"Old Delivery Costs = {sum(demand)*700/8000:.2f}€")
print(f"New Delivery Costs = {m.obj['total_cost'].value():.2f}€\n")
model3_results = get_results(m)
display(model3_results)
model3_results.plot(y="savings", kind="bar")
# %%
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(12, 3))
alpha = 0.45
model1_results.plot(y=["savings"], kind="bar", ax=ax[0], color="g", alpha=alpha)
model1_results.plot(y="savings", marker="o", ax=ax[0], color="g", alpha=alpha)
model3_results.plot(y="savings", kind="bar", ax=ax[0], color="r", alpha=alpha)
model3_results.plot(y="savings", marker="o", ax=ax[0], color="r", alpha=alpha)
ax[0].legend(["Model 1", "Model 3"])
ax[0].set_title("Delivery costs by franchise")
model1_results.plot(y=["contract rate"], kind="bar", ax=ax[1], color="g", alpha=alpha)
model1_results.plot(y="contract rate", marker="o", ax=ax[1], color="g", alpha=alpha)
model3_results.plot(y="contract rate", kind="bar", ax=ax[1], color="r", alpha=alpha)
model3_results.plot(y="contract rate", marker="o", ax=ax[1], color="r", alpha=alpha)
ax[1].set_ylim(0.07, 0.09)
ax[1].legend(["Model 1", "Model 3"])
ax[1].set_title("Contract rates by franchise")
plt.show()
# %%
# display elements of sets
m.display("SOURCES")
m.display("DESTINATIONS")
# %%
# display elements of an indexed parameter
m.display("Rates")
# %%
# display elements of an auxiliary variable
m.display("shipped_to_destination")
# %%
m.display("shipped_from_source")
# %%
# display Objective
m.display("total_cost")
# %%
# display indexed Constraints
m.display("supply_constraint") # dual is displayed by default
m.display(
"supply_constraint.lb, supply_constraint.body, supply_constraint.ub, supply_constraint.dual"
)
m.display("demand_constraint")
# %%
# display decision variables
m.display("x")
# %%
# display decision variables with bounds and reduced cost
m.display("x.lb", "x", "x.ub", "x.rc")
# %%
# Objective report
print("\nObjective: cost")
print(f"cost = {m.obj['total_cost'].value()}")
SOURCES = m.set["SOURCES"].to_list()
DESTINATIONS = m.set["DESTINATIONS"].to_list()
# Constraint reports
supply_constraint_body = m.get_data("supply_constraint.body").to_dict()
supply_constraint_rc = m.con["supply_constraint"].to_dict()
print("\nConstraint: supply_constraint")
for src in SOURCES:
print(
f"{src:12s} {supply_constraint_body[src]:8.2f} {supply_constraint_rc[src]:8.2f}"
)
demand_constraint_body = m.get_data("demand_constraint.body").to_dict()
demand_constraint_rc = m.con["demand_constraint"].to_dict()
print("\nConstraint: demand_constraint")
for dst in DESTINATIONS:
print(
f"{dst:12s} {demand_constraint_body[dst]:8.2f} {demand_constraint_rc[dst]:8.2f}"
)
# Decision variable reports
print("\nDecision variables: x")
x = m.var["x"].to_dict()
for src in SOURCES:
for dst in DESTINATIONS:
print(f"{src:12s} -> {dst:12s} {x[dst, src]:8.2f}")
print()
# %%
suppliers = pd.DataFrame(supply)
suppliers["shipped"] = m.get_data("supply_constraint.body").to_pandas()
suppliers["sensitivity"] = m.con["supply_constraint"].to_pandas()
display(suppliers)
customers = pd.DataFrame(demand)
customers["shipped"] = m.get_data("demand_constraint.body").to_pandas()
customers["sensitivity"] = m.con["demand_constraint"].to_pandas()
display(customers)
shipments = m.var["x"].to_pandas()
shipments.index.names = ["destinations", "sources"]
shipments = shipments.unstack()
shipments.columns = shipments.columns.get_level_values(1)
display(shipments)
shipments.plot(kind="bar")
plt.show()
# %%
import sys
if "google.colab" in sys.modules:
import graphviz
from graphviz import Digraph
dot = Digraph(
node_attr={"fontsize": "10", "shape": "rectangle", "style": "filled"},
edge_attr={"fontsize": "10"},
)
for index, row in suppliers.iterrows():
label = (
f"{index}"
+ f"\nsupply = {row['supply']}"
+ f"\nshipped = {row['shipped']}"
+ f"\nsens = {row['sensitivity']}"
)
dot.node(src, label=label, fillcolor="lightblue")
for index, row in customers.iterrows():
label = (
f"{dst}"
+ f"\ndemand = {row['demand']}"
+ f"\nshipped = {row['shipped']}"
+ f"\nsens = {row['sensitivity']:.6g}"
)
dot.node(dst, label=label, fillcolor="gold")
for src in SOURCES:
for dst in DESTINATIONS:
if shipments.loc[dst, src] > 0:
dot.edge(
src,
dst,
f"rate = {rates.loc[dst, src]}\nshipped = {shipments.loc[dst, src]}",
)
display(dot)
暗号資産の裁定取引 cryptocurrency-arbitrage.py 22 セル ・ 530 行 ・ モデル 1
この節のモデル(1)
AMPLcrypto_model.mod
param T;
# length of the trading chain
set T0 := 0..T;
set T1 := 1..T;
# currency nodes and trading edges
set NODES;
set EDGES within NODES cross NODES;
# currency on hand at each node
var v{NODES, T0} >= 0;
# amount traded on each edge at each trade
var x{EDGES, T1} >= 0;
# total amount traded on each edge over all trades
var z{EDGES} >= 0;
# "multiplier" on each trading edge
param a{EDGES};
param c{EDGES};
param v0;
maximize wealth: v["USD", T];
s.t. total_traded {(src, dst) in EDGES}:
z[src, dst] == sum{t in T1} x[src, dst, t];
s.t. edge_capacity {(src, dst) in EDGES}:
z[src, dst] <= c[src, dst];
# initial assignment of V0 units on a selected currency
s.t. initial {node in NODES}:
v[node, 0] == (if node == "USD" then v0 else 0);
s.t. no_shorting {node in NODES, t in T1}:
v[node, t - 1] >= sum{(src, dst) in EDGES: src == node} x[node, dst, t];
s.t. balances {node in NODES, t in T1}:
v[node, t] == v[node, t - 1] +
sum{(src, dst) in EDGES: dst == node} a[src, node] * x[src, node, t] -
sum{(src, dst) in EDGES: src == node} x[node, dst, t]
;
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import os
import sys
from time import time
from timeit import default_timer as timer
import ccxt
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
# %%
print("Available exchanges:\n")
for i, exchange in enumerate(ccxt.exchanges):
print(f"{i+1:3d}) {exchange.ljust(20)}", end="" if (i + 1) % 4 else "\n")
# %%
# global variables used in subsequent cells
# create an exchange object
exchange = ccxt.binanceus()
def get_exchange_dg(exchange, minimum_in_degree=1):
"""
Return a directed graph constructed from the market symbols on a specified exchange.
"""
markets = exchange.load_markets()
symbols = markets.keys()
# create an edge for all market symbols
dg = nx.DiGraph()
for base, quote in [symbol.split("/") for symbol in symbols]:
dg.add_edge(quote, base, color="k", width=1)
# remove base currencies with in_degree less than minimum_in_degree
remove_nodes = [
node
for node in dg.nodes
if dg.out_degree(node) == 0 and dg.in_degree(node) < minimum_in_degree
]
for node in reversed(list(nx.topological_sort(dg))):
if node in remove_nodes:
dg.remove_node(node)
else:
break
# color quote currencies in gold
for node in dg.nodes():
dg.nodes[node]["color"] = "gold" if dg.out_degree(node) > 0 else "lightblue"
return dg
def draw_dg(dg, rad=0.0):
"""
Draw directed graph of markets symbols.
"""
n_nodes = len(dg.nodes)
size = int(2.5 * np.sqrt(n_nodes))
fig = plt.figure(figsize=(size, size))
pos = nx.circular_layout(dg)
nx.draw(
dg,
pos,
with_labels=True,
node_color=[dg.nodes[node]["color"] for node in dg.nodes()],
edge_color=[dg.edges[u, v]["color"] for u, v in dg.edges],
width=[dg.edges[u, v]["width"] for u, v in dg.edges],
node_size=1000,
font_size=8,
arrowsize=15,
connectionstyle=f"arc3, rad={rad}",
)
nx.draw_networkx_edge_labels(
dg, pos, edge_labels={(src, dst): f"{src}/{dst}" for src, dst in dg.edges()}
)
return plt.gca()
minimum_in_degree = 5
exchange_dg = get_exchange_dg(exchange, minimum_in_degree)
ax = draw_dg(exchange_dg, 0.01)
ax.set_title(
exchange.name + "\n" + f"Minimum in Degree (Base Currencies) = {minimum_in_degree}"
)
print(f"Number of nodes = {len(exchange_dg.nodes()):3d}")
print(f"Number of edges = {len(exchange_dg.edges()):3d}")
# %%
if "google.colab" in sys.modules:
csv = "Binance_US_orderbook_20230313_152616.csv"
order_book = pd.read_csv(
"https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/notebooks/04/"
+ csv,
index_col=0,
)
else:
import glob
# find all previously saved order books
fnames = sorted(glob.glob(f"*orderbook*".replace(" ", "_")))
fname = fnames[-1]
# read the last order book from the list of order books
print(f"\nReading: {fname}\n")
order_book = pd.read_csv(fname, index_col=0)
display(order_book)
# %%
def order_book_to_dg(order_book):
"""
Convert an order book dataframe into a directed graph using the NetworkX library.
Parameters:
-----------
order_book : pandas.DataFrame
A dataframe containing the order book information.
Returns:
--------
dg_order_book : networkx.DiGraph
A directed graph representing the order book.
"""
# create a dictionary of edges index by (src, dst)
dg_order_book = nx.DiGraph()
# loop over each order in the order book dataframe
for order in order_book.index:
# if the order is a 'bid', i.e., an order to purchase the base currency
if not np.isnan(order_book.at[order, "bid_volume"]):
src = order_book.at[order, "base"]
dst = order_book.at[order, "quote"]
# add an edge to the graph with the relevant attributes
dg_order_book.add_edge(
src,
dst,
kind="bid",
a=order_book.at[order, "bid_price"],
capacity=order_book.at[order, "bid_volume"],
weight=-np.log(order_book.at[order, "bid_price"]),
color="g",
width=0.5,
)
# if the order is an 'ask', i.e., an order to sell the base currency
if not np.isnan(order_book.at[order, "ask_volume"]):
src = order_book.at[order, "quote"]
dst = order_book.at[order, "base"]
# add an edge to the graph with the relevant attributes
dg_order_book.add_edge(
src,
dst,
kind="ask",
a=1.0 / order_book.at[order, "ask_price"],
capacity=order_book.at[order, "ask_volume"]
* order_book.at[order, "ask_price"],
weight=-np.log(1.0 / order_book.at[order, "ask_price"]),
color="r",
width=0.5,
)
# loop over each node in the graph and set the color attribute to "lightblue"
for node in dg_order_book.nodes():
dg_order_book.nodes[node]["color"] = "lightblue"
return dg_order_book
order_book_dg = order_book_to_dg(order_book)
# %%
# display contents of the directed graph
print(f"src --> dst kind a c")
print(f"------------------------------------------------------")
for src, dst in order_book_dg.edges():
print(
f"{src:5s} --> {dst:5s} {order_book_dg.edges[(src, dst)]['kind']}"
+ f"{order_book_dg.edges[(src, dst)]['a']: 16f} {order_book_dg.edges[(src, dst)]['capacity']: 16f} "
)
# %%
draw_dg(order_book_dg, 0.05)
plt.show()
# %%
order_book_dg = order_book_to_dg(order_book)
nx.negative_edge_cycle(order_book_dg, weight="weight", heuristic=True)
# %%
# compute the sum of weights given a list of nodes
def sum_weights(cycle):
return sum(
[
order_book_dg.edges[edge]["weight"]
for edge in zip(cycle, cycle[1:] + cycle[:1])
]
)
order_book_dg = order_book_to_dg(order_book)
arb = nx.find_negative_cycle(order_book_dg, weight="weight", source="USD")[:-1]
bp = 10000 * (np.exp(-sum_weights(arb)) - 1)
for src, dst in zip(arb, arb[1:] + arb[:1]):
order_book_dg[src][dst]["width"] = 5
ax = draw_dg(order_book_dg, 0.05)
ax.set_title(
f"Trading cycle with {len(list(arb))} trades: {' -> '.join(list(arb))}\n\n Return = {bp:6.3f} basis points "
)
plt.show()
# %%
# This cell iterates over all simple cycles in a directed graph. This
# can a long time for a large, well connected graph.
# convert order book to a directed graph
order_book_dg = order_book_to_dg(order_book)
# compute the sum of weights given a list of nodes
def sum_weights(cycle):
return sum(
[
order_book_dg.edges[edge]["weight"]
for edge in zip(cycle, cycle[1:] + cycle[:1])
]
)
# create a dictionary of all simple cycles and sum of weights
cycles = {
tuple(cycle): 10000 * (np.exp(-sum_weights(cycle)) - 1)
for cycle in nx.simple_cycles(order_book_dg)
}
print(
f"There are {len(cycles)} distinct simple cycles in the order book, {len([cycle for cycle in cycles if cycles[cycle] > 0])} of which have positive return."
)
# create histogram
plt.hist(cycles.values(), bins=int(np.sqrt(len(cycles))))
ax = plt.gca()
ax.set_ylabel("count")
ax.set_xlabel("Basis Points")
ax.set_title("Histogram of Returns for all Simple Cycles")
ax.grid(True)
ax.axvline(0, color="r")
plt.show()
# %%
arbitrage = [
cycle for cycle in sorted(cycles, key=cycles.get, reverse=True) if cycles[cycle] > 0
]
n_cycles_to_list = 5
print(f"Top {n_cycles_to_list}\n")
print(f"Basis Points Arbitrage Cycle")
for cycle in arbitrage[0 : min(n_cycles_to_list, len(arbitrage))]:
t = list(cycle)
t.append(cycle[0])
print(f"{cycles[cycle]:6.3f} {len(t)} trades: {' -> '.join(t)}")
# %%
n_cycles_to_show = 1
for cycle in arbitrage[0 : min(n_cycles_to_show, len(arbitrage))]:
# get fresh graph to color nodes
order_book_dg = order_book_to_dg(order_book)
# color nodes red
for node in cycle:
order_book_dg.nodes[node]["color"] = "red"
# makes lines wide
for edge in zip(cycle, cycle[1:] + cycle[:1]):
order_book_dg.edges[edge]["width"] = 4
ax = draw_dg(order_book_dg, rad=0.05)
t = list(cycle)
t.append(cycle[0])
ax.set_title(
f"Trading cycle with {len(t)} trades: {' -> '.join(t)}\n\n Return = {cycles[cycle]:6.3f} basis points "
)
plt.savefig("crypto3.pdf", bbox_inches="tight")
plt.show()
# %%
def crypto_model(order_book_dg, T=10, v0=100.0):
m = AMPL()
m.read("crypto_model.mod")
m.set["NODES"] = order_book_dg.nodes
m.set["EDGES"] = order_book_dg.edges
m.param["T"] = T
m.param["a"] = [
order_book_dg.edges[(src, dst)]["a"] for (src, dst) in order_book_dg.edges
]
m.param["c"] = [
order_book_dg.edges[(src, dst)]["capacity"]
for (src, dst) in order_book_dg.edges
]
m.param["v0"] = v0
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m
# %%
order_book_dg = order_book_to_dg(order_book)
v0 = 10000.0
T = 8
m = crypto_model(order_book_dg, T=T, v0=v0)
vT = m.obj["wealth"].value()
print(f"Starting wealth = {v0:0.2f} USD")
print(f"Weath after {T:2d} transactions = {vT:0.2f} USD")
print(f"Return = {10000 * (vT - v0)/v0:0.3f} basis points")
# %%
NODES = m.set["NODES"].to_list()
T0 = m.set["T0"].to_list()
v = m.var["v"].to_dict()
for node in NODES:
print(f"{node:5s}", end="")
for t in T0:
print(f" {v[node, t]:11.5f}", end="")
print()
# %%
T1 = m.set["T1"].to_list()
EDGES = m.set["EDGES"].to_list()
x = m.var["x"].to_dict()
a = m.param["a"].to_dict()
print("\nTransaction Events")
for t in T1:
print(f"t = {t}")
for src, dst in EDGES:
if x[src, dst, t] > 1e-6:
print(
f" {src:8s} -> {dst:8s}: {x[src, dst, t]:14.6f} {a[src, dst] * x[src, dst, t]:14.6f}"
)
print()
# %%
# add comment in the text to remind the reader about bids and asks
# for each currency we took only one ask and one bid, this is why we are unique between each pair of nodes
z = m.var["z"].to_dict()
# report what orders to issue
for src, dst in EDGES:
if z[src, dst] > 0.0000002:
order_book_dg.nodes[src]["color"] = "red"
order_book_dg.nodes[dst]["color"] = "red"
order_book_dg[src][dst]["width"] = 4
draw_dg(order_book_dg, 0.05)
# %%
# report what orders to issue
c = m.param["c"].to_dict()
print("Trading Summary for the Order Book")
print(f" Order Book Type Capacity Traded")
for src, dst in EDGES:
if z[src, dst] > 0.0000002:
kind = order_book_dg.edges[(src, dst)]["kind"]
s = f"{src:>5s} -> {dst:<5s} {kind} {c[src, dst]:12.5f} {z[src, dst]:14.5f}"
s += " >>> "
if kind == "ask":
base = dst
quote = src
symbol = base + "/" + quote
price = 1.0 / order_book_dg.edges[(src, dst)]["a"]
volume = z[src, dst] / price
s += f"sell {volume:15.6f} {symbol:11s} at {price:12.6f}"
if kind == "bid":
base = src
quote = dst
symbol = base + "/" + quote
price = order_book_dg.edges[(src, dst)]["a"]
volume = z[src, dst]
s += f"buy {volume:16.6f} {symbol:11s} at {price:12.6f}"
print(s)
# %%
# display currency balances
balances = pd.DataFrame()
for node in order_book_dg.nodes:
if sum(v[node, t] for t in T0) > 0.0000002:
for t in T0:
balances.loc[t, node] = v[node, t]
balances.plot(
kind="bar",
subplots=True,
figsize=(8, 10),
xlabel="Transaction",
ylabel="Currency Units",
)
plt.gcf().tight_layout()
plt.show()
# %%
import pandas as pd
def get_order_book(exchange, exchange_dg):
def get_orders(base, quote, limit=1):
"""
Return order book data for a specified symbol.
"""
result = exchange.fetch_order_book("/".join([base, quote]), limit)
if not result["asks"] or not result["bids"]:
result = None
else:
result["base"], result["quote"] = base, quote
result["timestamp"] = exchange.milliseconds()
result["bid_price"], result["bid_volume"] = result["bids"][0]
result["ask_price"], result["ask_volume"] = result["asks"][0]
return result
# fetch order book data and store in a dictionary
order_book = filter(
lambda r: r is not None,
[get_orders(base, quote) for quote, base in exchange_dg.edges()],
)
# convert to pandas dataframe
order_book = pd.DataFrame(order_book)
order_book["timestamp"] = pd.to_datetime(order_book["timestamp"], unit="ms")
return order_book[
[
"symbol",
"timestamp",
"base",
"quote",
"bid_price",
"bid_volume",
"ask_price",
"ask_volume",
]
]
minimum_in_degree = 5
# get graph of market symbols with mininum_in_degree for base currencies
exchange_dg = get_exchange_dg(exchange, minimum_in_degree)
# get order book for all markets in the graph
order_book = get_order_book(exchange, exchange_dg)
order_book_dg = order_book_to_dg(order_book)
# find trades
v0 = 10000.0
m = crypto_model(order_book_dg, T=12, v0=v0)
vT = m.obj["wealth"].value()
print(f"Potential Return = {10000*(vT - v0)/v0:0.3f} basis points")
display(order_book)
# %%
from datetime import datetime
import time
import glob
# get graph of market symbols with mininum_in_degree for base currencies
minimum_in_degree = 5
exchange_dg = get_exchange_dg(exchange, minimum_in_degree)
# search time
search_time = 20
timeout = time.time() + search_time
# threshold in basis points
arb_threshold = 1.0
# wait for arbitrage opportunity
print(f"Search for {search_time} seconds.")
while time.time() <= timeout:
# print("bp = ", end="")
order_book = get_order_book(exchange, exchange_dg)
order_book_dg = order_book_to_dg(order_book)
v0 = 10000.0
m = crypto_model(order_book_dg, T=12, v0=10000)
vT = m.obj["wealth"].value()
bp = 10000 * (vT - v0) / vT
print(f"bp = {bp:0.3f}")
if bp >= arb_threshold:
print("arbitrage found!")
fname = f"{exchange} orderbook {datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.csv".replace(
" ", "_"
)
order_book.to_csv(fname)
print(f"order book saved to: {fname}")
print("Search complete.")
補足:電力需給計画問題 power-network.py 16 セル ・ 205 行 ・ モデル 3
この節のモデル(3)
AMPLopf1.mod
# Indexing sets
set NODES;
set EDGES within {NODES,NODES};
# Parameters
param d{NODES};
param p_min{NODES};
param p_max{NODES};
param c_var{NODES};
param is_generator{NODES};
param energy_type{NODES} symbolic;
param b{EDGES};
param f_max{EDGES};
# Declare decision variables
var p{i in NODES} >= p_min[i], <= p_max[i];
var theta{NODES};
var fabs{(i,j) in EDGES} >= 0, <= f_max[i, j];
var fp{EDGES} >= 0;
var fm{EDGES} >= 0;
# Declare objective value
minimize energy_cost: sum{i in NODES: is_generator[i] == 1} c_var[i] * p[i];
# Auxiliary variables for incoming and outgoing flows
var incoming_flow{i in NODES} = sum{j in NODES: (j,i) in EDGES} (fp[j, i] - fm[j, i]);
var outgoing_flow{i in NODES} = sum{j in NODES: (i,j) in EDGES} (fp[i, j] - fm[i, j]);
# Constraints
s.t. flow_conservation{i in NODES}:
outgoing_flow[i] - incoming_flow[i] == p[i] - d[i];
s.t. susceptance{(i,j) in EDGES}:
fp[i, j] - fm[i, j] == b[i, j] * (theta[i] - theta[j]);
s.t. abs_flow{(i,j) in EDGES}:
fabs[i, j] == fp[i, j] + fm[i, j];
AMPLopf2.mod
# Indexing sets
set NODES;
set EDGES within {NODES,NODES};
# Parameters
param d{NODES};
param p_min{NODES};
param p_max{NODES};
param c_var{NODES};
param is_generator{NODES};
param energy_type{NODES} symbolic;
param b{EDGES};
param f_max{EDGES};
param max_gas_plants;
param max_coal_plants;
# Declare decision variables
var p{i in NODES} >= 0;
var theta{NODES};
var x{NODES} binary;
var fabs{(i,j) in EDGES} >= 0, <= f_max[i, j];
var fp{EDGES} >= 0;
var fm{EDGES} >= 0;
# Declare objective value
minimize energy_cost: sum{i in NODES: is_generator[i] == 1} c_var[i] * p[i];
# Auxiliary variables for incoming and outgoing flows
var incoming_flow{i in NODES} = sum{j in NODES: (j,i) in EDGES} (fp[j, i] - fm[j, i]);
var outgoing_flow{i in NODES} = sum{j in NODES: (i,j) in EDGES} (fp[i, j] - fm[i, j]);
# Constraints
s.t. flow_conservation{i in NODES}:
outgoing_flow[i] - incoming_flow[i] == p[i] - d[i];
s.t. susceptance{(i,j) in EDGES}:
fp[i, j] - fm[i, j] == b[i, j] * (theta[i] - theta[j]);
s.t. abs_flow{(i,j) in EDGES}:
fabs[i, j] == fp[i, j] + fm[i, j];
s.t. generation_upper_bound{i in NODES}: p[i] <= p_max[i] * x[i];
s.t. generation_lower_bound{i in NODES}: p[i] >= p_min[i] * x[i];
s.t. gas_plants_limit: sum{i in NODES: energy_type[i] == 'gas'} x[i] <= max_gas_plants;
s.t. coal_plants_limit: sum{i in NODES: energy_type[i] == 'coal'} x[i] <= max_coal_plants;
AMPLopf3.mod
# Indexing sets
set NODES;
set EDGES within {NODES,NODES};
# Parameters
param d{NODES};
param p_min{NODES};
param p_max{NODES};
param c_var{NODES};
param is_generator{NODES};
param energy_type{NODES} symbolic;
param b{EDGES};
param f_max{EDGES};
param max_gas_plants;
param max_coal_plants;
# Big-Ms
param M0;
param M1;
param M2;
# Declare decision variables
var p{i in NODES} >= 0;
var theta{NODES};
var x{NODES} binary;
var fabs{(i,j) in EDGES} >= 0, <= f_max[i, j];
var fp{EDGES} >= 0;
var fm{EDGES} >= 0;
var y binary;
# Declare objective value
minimize energy_cost: sum{i in NODES: is_generator[i] == 1} c_var[i] * p[i];
# Auxiliary variables for incoming and outgoing flows
var incoming_flow{i in NODES} = sum{j in NODES: (j,i) in EDGES} (fp[j, i] - fm[j, i]);
var outgoing_flow{i in NODES} = sum{j in NODES: (i,j) in EDGES} (fp[i, j] - fm[i, j]);
# Constraints
s.t. flow_conservation{i in NODES}:
outgoing_flow[i] - incoming_flow[i] == p[i] - d[i];
s.t. susceptance{(i,j) in EDGES}:
fp[i, j] - fm[i, j] == b[i, j] * (theta[i] - theta[j]);
s.t. abs_flow{(i,j) in EDGES}:
fabs[i, j] == fp[i, j] + fm[i, j];
s.t. generation_upper_bound{i in NODES}: p[i] <= p_max[i] * x[i];
s.t. generation_lower_bound{i in NODES}: p[i] >= p_min[i] * x[i];
s.t. gas_plants_limit: sum{i in NODES: energy_type[i] == 'gas'} x[i] <= max_gas_plants + (1 - y) * M0;
s.t. coal_plants_limit: sum{i in NODES: energy_type[i] == 'coal'} x[i] <= max_coal_plants + (1 - y) * M1;
s.t. renewable_energy_production:
sum{i in NODES: energy_type[i] in {'solar', 'wind', 'hydro'}} p[i] <= 1000 + y * M2;
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
# %%
# Download the data
base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/dev/notebooks/04/"
nodes_df = pd.read_csv(base_url + "nodes.csv").set_index(["node_id", "instance"])
edges_df = pd.read_csv(base_url + "edges.csv").set_index(["node_id1", "node_id2"])
# Replace 'na' by an empty string
nodes_df.fillna("", inplace=True)
# Split the initial nodes data frame by instance
nodes_by_instance = [
y.reset_index(level=1).drop("instance", axis=1)
for x, y in nodes_df.groupby("instance")
]
I = [{"nodes": n, "edges": edges_df} for n in nodes_by_instance]
# Initialize a network for demonstration purposes
network = I[0]
# %%
def visualize_network(network, edge_flows=None, ax=None):
"""Visualize a network instance, highlighting the generators in orange and the load buses in green."""
plt.figure(figsize=[12, 10])
g = nx.DiGraph(list(network["edges"].index))
pos = nx.layout.kamada_kawai_layout(g, weight=None)
color_mapping = {
"solar": "#ffcb36",
"wind": "white",
"hydro": "#a5efff",
"coal": "#686868",
"gas": "#00ab4e",
"": "#b6b6b6",
}
vertex2color = {
k: color_mapping[v] for k, v in network["nodes"]["energy_type"].items()
}
v2c_list = [vertex2color[i] for i in g.nodes] # Order based on networkx
nodes = nx.draw_networkx_nodes(
g,
pos,
node_size=250,
node_color=v2c_list,
linewidths=2,
)
edges = nx.draw_networkx_edges(
g,
pos,
width=2,
edge_color="#595959",
)
# Gives node colors
ax = plt.gca()
ax.collections[0].set_edgecolor("#595959")
ax.set_axis_off()
# %%
visualize_network(network)
# %%
example_nodes = network["nodes"]
example_nodes[example_nodes.is_generator]
# %%
example_nodes[~example_nodes.is_generator]
# %%
edges_df
# %%
def OPF1(network):
"""
Input:
- network: a dictionary containing:
- a dictionary of nodes with a dictionary of attributes
- a dictionary of edges with a dictionary of attributes
Output:
- total energy dispatching cost
"""
nodes = network["nodes"]
edges = network["edges"]
m = AMPL()
m.read("opf1.mod")
m.set_data(nodes, "NODES")
m.set_data(edges, "EDGES")
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m.obj["energy_cost"].value()
# %%
OPF1_results = [OPF1(instance) for instance in I]
print(f"The average objective value over all instances is: {np.mean(OPF1_results):.2f}")
# %%
def OPF2(network, max_gas_plants, max_coal_plants):
"""
Input:
- network: a dictionary containing:
- a dictionary of nodes with a dictionary of attributes
- a dictionary of edges with a dictionary of attributes
Output:
- total energy dispatching cost
"""
nodes = network["nodes"]
edges = network["edges"]
m = AMPL()
m.read("opf2.mod")
m.set_data(nodes, "NODES")
m.set_data(edges, "EDGES")
m.param["max_gas_plants"] = max_gas_plants
m.param["max_coal_plants"] = max_coal_plants
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m.obj["energy_cost"].value()
# %%
max_gas_plants = 2
max_coal_plants = 1
OPF2_results = [OPF2(instance, max_gas_plants, max_coal_plants) for instance in I]
print(f"The average objective value over all instances is: {np.mean(OPF2_results):.2f}")
# %%
def OPF3(network, max_gas_plants, max_coal_plants):
"""
Input:
- network: a dictionary containing:
- a dictionary of nodes with a dictionary of attributes
- a dictionary of edges with a dictionary of attributes
Output:
- total energy dispatching cost
"""
nodes = network["nodes"]
edges = network["edges"]
m = AMPL()
m.read("opf3.mod")
m.set_data(nodes, "NODES")
m.set_data(edges, "EDGES")
m.param["max_gas_plants"] = max_gas_plants
m.param["max_coal_plants"] = max_coal_plants
m.param["M0"] = 4
m.param["M1"] = 3
m.param["M2"] = nodes["p_max"].sum()
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
return m.obj["energy_cost"].value()
# %%
OPF3_results = [OPF3(instance, max_gas_plants, max_coal_plants) for instance in I]
print(f"The average objective value over all instances is: {np.mean(OPF3_results):.2f}")
# %%
objs = [OPF1_results, OPF2_results, OPF3_results]
# %%
plt.plot(objs[0], color="blue", label="OPF1")
plt.plot(objs[1], color="green", label="OPF2")
plt.plot(objs[2], color="orange", label="OPF3")
plt.title("Optimal objective values over all instances and models")
plt.xlabel("Instance number")
plt.ylabel("Optimal objective value")
plt.legend()
plt.show()
補足:外国為替の裁定取引 forex-arbitrage.py 9 セル ・ 165 行 ・ モデル 1
この節のモデル(1)
AMPLarbitrage.mod
set T0;
set T1;
# currency *nodes*
set NODES;
# paths between currency nodes i -> j
set ARCS within {NODES,NODES};
param T;
param R symbolic;
param a{NODES, NODES};
# w[i, t] amount of currency i on hand after transaction t
var w{NODES, T0} >= 0;
# x[m, n, t] amount of currency m converted to currency n in transaction t t
var x{ARCS, T1} >= 0;
# start with assignment of 100 units of a selected reserve currency
s.t. initial_condition{i in NODES}:
w[i, 0] == (if i == R then 100 else 0);
# no shorting constraint
s.t. max_trade {j in NODES, t in T1}:
w[j, t-1] >= sum{i in NODES: i != j} x[i, j, t];
# one round of transactions
s.t. balances {j in NODES, t in T1}:
w[j, t] ==
w[j, t-1] -
sum{i in NODES: i != j} x[i, j, t] +
sum{i in NODES: i != j} a[j, i] * x[j, i, t];
maximize wealth: w[R, T];
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import io
import networkx as nx
import numpy as np
import pandas as pd
# %%
df = pd.DataFrame(
[[1.0, 0.5, 100], [2.0, 1.0, 1 / 0.0075], [0.01, 0.0075, 1.0]],
columns=["USD", "EUR", "JPY"],
index=["USD", "EUR", "JPY"],
).T
display(df)
# USD -> EUR -> USD
print(df.loc["USD", "EUR"] * df.loc["EUR", "USD"])
# USD -> JPY -> USD
print(df.loc["USD", "JPY"] * df.loc["JPY", "USD"])
# EUR -> JPY -> EUR
print(df.loc["EUR", "JPY"] * df.loc["JPY", "EUR"])
# %%
I = "USD"
J = "JPY"
K = "EUR"
print(df.loc[I, K] * df.loc[K, J] * df.loc[J, I])
# %%
def arbitrage(T, df, R="EUR"):
m = AMPL()
m.read("arbitrage.mod")
T0 = list(range(0, T + 1))
T1 = list(range(1, T + 1))
NODES = df.index
ARCS = [(i, j) for i in NODES for j in NODES if i != j]
m.set["T0"] = T0
m.set["T1"] = T1
m.set["NODES"] = NODES
m.set["ARCS"] = ARCS
m.param["T"] = T
m.param["R"] = R
m.param["a"] = df
m.solve(solver=SOLVER)
assert m.solve_result == "solved", m.solve_result
x = m.var["x"].to_dict()
w = m.var["w"].to_dict()
for t in T0:
print(f"\nt = {t}\n")
if t >= 1:
for i, j in ARCS:
if x[i, j, t] > 0:
print(
f"{j} -> {i} Convert {x[i, j, t]} {j} to {df.loc[i,j]*x[i,j,t]} {i}"
)
print()
for i in NODES:
print(f"w[{i},{t}] = {w[i, t]:9.2f} ")
return m
m = arbitrage(3, df, "EUR")
w = m.var["w"].to_dict()
print(w["EUR", 0])
print(w["EUR", 3])
# %%
def display_graph(m):
m_w = m.var["w"].to_dict()
m_x = m.var["x"].to_dict()
T0 = m.set["T0"].to_list()
T1 = m.set["T1"].to_list()
NODES = m.set["NODES"].to_list()
ARCS = m.set["ARCS"].to_list()
path = []
for t in T0:
for i in NODES:
if m_w[i, t] >= 1e-6:
path.append(f"{m_w[i, t]} {i}")
path = " -> ".join(path)
print("\n", path)
G = nx.DiGraph()
for i in NODES:
G.add_node(i)
nodelist = set()
edge_labels = dict()
for t in T1:
for i, j in ARCS:
if m_x[i, j, t] > 0.1:
nodelist.add(i)
nodelist.add(j)
y = m_w[j, t - 1]
x = m_w[j, t]
G.add_edge(j, i)
edge_labels[(j, i)] = df.loc[i, j]
nodelist = list(nodelist)
pos = nx.spring_layout(G)
nx.draw(
G,
pos,
with_labels=True,
node_size=2000,
nodelist=nodelist,
node_color="lightblue",
node_shape="s",
arrowsize=20,
label=path,
)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
display_graph(m)
# %%
# data extracted 2022-03-17
bloomberg = """
USD EUR JPY GBP CHF CAD AUD HKD
USD - 1.1096 0.0084 1.3148 1.0677 0.7915 0.7376 0.1279
EUR 0.9012 - 0.0076 1.1849 0.9622 0.7133 0.6647 0.1153
JPY 118.6100 131.6097 - 155.9484 126.6389 93.8816 87.4867 15.1724
GBP 0.7606 0.8439 0.0064 - 0.8121 0.6020 0.5610 0.0973
CHF 0.9366 1.0393 0.0079 1.2314 - 0.7413 0.6908 0.1198
CAD 1.2634 1.4019 0.0107 1.6611 1.3489 - 0.9319 0.1616
AUD 1.3557 1.5043 0.0114 1.7825 1.4475 1.0731 - 0.1734
HKD 7.8175 8.6743 0.0659 10.2784 8.3467 6.1877 5.7662 -
"""
df = pd.read_csv(io.StringIO(bloomberg.replace("-", "1.0")), sep="\t", index_col=0)
display(df)
# %%
m = arbitrage(3, df, "USD")
# %%
display_graph(m)
この章のデータファイル(13)
- Binance_US_orderbook_20230312_161833.csv
- Binance_US_orderbook_20230313_034827.csv
- Binance_US_orderbook_20230313_152602.csv
- Binance_US_orderbook_20230313_152609.csv
- Binance_US_orderbook_20230313_152613.csv
- Binance_US_orderbook_20230313_152616.csv
- Binance_US_orderbook_20230313_152620.csv
- Binance_US_orderbook_20230416_214743.csv
- Binance_US_orderbook_saved.csv
- arb_ts.txt
- dina_times.xlsx
- edges.csv
- nodes.csv
第5章凸最適化6 ファイル▶ 講義動画(15:21)
ミルクのプーリング問題:非凸な非線形最適化 milk-pooling.py 14 セル ・ 496 行
# %%
# install dependencies and select solver
SOLVER_LO = "cbc"
SOLVER_GNLO = "couenne"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from itertools import product
# %%
customers = pd.DataFrame(
{
"Customer 1": {"min_fat": 0.045, "price": 52.0, "demand": 6000.0},
"Customer 2": {"min_fat": 0.030, "price": 48.0, "demand": 2500.0},
"Customer 3": {"min_fat": 0.040, "price": 50.0, "demand": 4000.0},
}
).T
suppliers = pd.DataFrame(
{
"Farm A": {"fat": 0.045, "cost": 45.0, "location": "local"},
"Farm B": {"fat": 0.030, "cost": 42.0, "location": "local"},
"Farm C": {"fat": 0.033, "cost": 37.0, "location": "remote"},
"Farm D": {"fat": 0.050, "cost": 45.0, "location": "remote"},
},
).T
local_suppliers = suppliers[suppliers["location"] == "local"]
remote_suppliers = suppliers[suppliers["location"] == "remote"]
print("\nCustomers")
display(customers)
print("\nSuppliers")
display(suppliers)
# %%
model = AMPL()
model.eval(
"""
# define sources and customers
set L;
set C;
param price{C};
param demand{C};
param min_fat{C};
param cost{L};
param fat{L};
# define local -> customer flowrates
var z{L cross C} >= 0;
maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l]);
subject to demand_req{c in C}:
sum{l in L} z[l, c] <= demand[c];
subject to fat_content{c in C}:
sum{l in L} z[l, c] * fat[l] >= sum{l in L} z[l, c] * min_fat[c];
"""
)
model.set_data(customers, "C")
model.set_data(local_suppliers.drop(columns=["location"]), "L")
model.solve(solver=SOLVER_LO, verbose=False)
assert model.solve_result == "solved", model.solve_result
# report results
print(f"\nProfit = {model.obj['profit'].value():0.2f}\n")
# create dataframe of results
z = model.var["z"]
L = model.set["L"]
C = model.set["C"]
print("Blending Plan")
Z = pd.DataFrame(
[[l, c, round(z[l, c].value(), 1)] for l in L.members() for c in C.members()],
columns=["supplier", "customer", ""],
)
Z = Z.pivot_table(index="customer", columns="supplier")
Z["Total"] = Z.sum(axis=1)
Z["fat content"] = [
sum(z[l, c].value() * suppliers.loc[l, "fat"] for l in L.members())
/ sum(z[l, c].value() for l in L.members())
for c in C.members()
]
Z["min_fat"] = customers["min_fat"]
display(Z)
# %%
model = AMPL()
model.eval(
"""
# define sources and customers
set S;
set C;
param price{C};
param demand{C};
param min_fat{C};
param cost{S};
param fat{S};
# define local -> customer flowrates
var z{S cross C} >= 0;
maximize profit: sum{s in S, c in C} z[s, c]*(price[c] - cost[s]);
subject to demand_req{c in C}:
sum{s in S} z[s, c] <= demand[c];
subject to quality{c in C}:
sum{s in S} z[s, c] * fat[s] >= sum{s in S} z[s, c] * min_fat[c];
"""
)
model.set_data(customers, "C")
model.set_data(suppliers.drop(columns=["location"]), "S")
model.solve(solver=SOLVER_LO, verbose=False)
assert model.solve_result == "solved", model.solve_result
# report results
print(f"\nProfit = {model.obj['profit'].value():0.2f}\n")
# create dataframe of results
z = model.var["z"]
S = model.set["S"]
C = model.set["C"]
print("Blending Plan")
Z = pd.DataFrame(
[[s, c, round(z[s, c].value(), 1)] for s in S.members() for c in C.members()],
columns=["supplier", "customer", ""],
)
Z = Z.pivot_table(index="customer", columns="supplier")
Z["Total"] = Z.sum(axis=1)
Z["fat content"] = [
sum(z[s, c].value() * suppliers.loc[s, "fat"] for s in S.members())
/ sum(z[s, c].value() for s in S.members())
for c in C.members()
]
Z["min_fat"] = customers["min_fat"]
display(Z)
# %%
model_p_fixed = AMPL()
model_p_fixed.eval(
"""
# define sources
set L;
set R;
# define customers
set C;
# define flowrates
var x{R} >= 0;
var y{C} >= 0;
var z{L cross C} >= 0;
param p >= 0;
param price{C};
param demand{C};
param min_fat{C};
param cost{L union R};
param fat{L union R};
maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l])
+ sum{c in C} price[c]*y[c]
- sum{r in R} cost[r]*x[r];
subject to customer_demand{c in C}:
y[c] + sum{l in L} z[l, c] <= demand[c];
subject to pool_balance:
sum{r in R} x[r] = sum{c in C} y[c];
subject to pool_quality:
sum{r in R} fat[r]*x[r] = p*sum{c in C} y[c];
subject to customer_quality{c in C}:
p*y[c] + sum{l in L} fat[l]*z[l,c] >= min_fat[c]*(sum{l in L} z[l, c] + y[c]);
"""
)
model_p_fixed.set_data(customers, "C")
model_p_fixed.set_data(local_suppliers.drop(columns=["location"]), "L")
model_p_fixed.set_data(remote_suppliers.drop(columns=["location"]), "R")
# solve milk pooling problem for a fixed pool composition p
def f(p):
model_p_fixed.param["p"] = p
model_p_fixed.solve(solver=SOLVER_LO, verbose=False)
assert model_p_fixed.solve_result == "solved", model_p_fixed.solve_result
return model_p_fixed
# %%
p_plot = np.linspace(0.025, 0.055, 200)
f_plot = [f(p).obj["profit"].value() for p in p_plot]
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit f")
ax.grid(True)
plt.show()
# %%
def milk_pooling_convex():
m = AMPL()
m.eval(
"""
# define sources
set L;
set R;
# define customers
set C;
param price{C};
param demand{C};
param min_fat{C};
param cost{L union R};
param fat{L union R} default 0;
# define flowrates
var x{R} >= 0;
var y{c in C} >= 0 <= demand[c];
var z{L cross C} >= 0;
# composition of the pool
var p >= min{r in R} fat[r] <= max{r in R} fat[r];
# w[c] to replace bilinear terms p * y[c]
var w{C} >= 0;
maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l])
+ sum{c in C} price[c]*y[c]
- sum{r in R} cost[r]*x[r];
subject to customer_demand{c in C}:
y[c] + sum{l in L} z[l, c] <= demand[c];
subject to pool_balance:
sum{r in R} x[r] = sum{c in C} y[c];
subject to pool_quality:
sum{r in R} fat[r]*x[r] = sum{c in C} w[c];
subject to customer_quality{c in C}:
w[c] + sum{l in L} fat[l]*z[l,c] >= min_fat[c]*(sum{l in L} z[l, c] + y[c]);
subject to
mccormick_ll{c in C}: w[c] >= y[c].lb0*p + p.lb0*y[c] - p.lb0*y[c].lb0;
mccormick_hh{c in C}: w[c] >= y[c].ub0*p + p.ub0*y[c] - p.ub0*y[c].ub0;
mccormick_lh{c in C}: w[c] <= y[c].ub0*p + p.lb0*y[c] - p.lb0*y[c].ub0;
mccormick_hl{c in C}: w[c] <= y[c].lb0*p + p.ub0*y[c] - p.ub0*y[c].lb0;
"""
)
m.set_data(customers, "C")
m.set_data(local_suppliers.drop(columns=["location"]), "L")
m.set_data(remote_suppliers.drop(columns=["location"]), "R")
m.solve(solver=SOLVER_LO, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
# %%
def report_solution(m, model_title):
x = m.var["x"]
y = m.var["y"]
z = m.var["z"]
if model_title == "Milk Pooling Model":
p = m.param["p"]
else:
p = m.var["p"]
L = m.set["L"]
R = m.set["R"]
C_model = m.set["C"]
# Supplier report
S = suppliers.copy()
for l in L.members():
for c in C_model.members():
S.loc[l, c] = z[l, c].value()
for r in R.members():
S.loc[r, "Pool"] = x[r].value()
S = S.fillna(0)
S["Amount"] = S[C_model.members()].sum(axis=1) + S["Pool"]
S["Expense"] = S["Amount"] * S["cost"]
# Customer report
C = customers.copy()
for c in C_model.members():
for l in L.members():
C.loc[c, l] = z[l, c].value()
for c in C_model.members():
C.loc[c, "Pool"] = y[c].value()
C = C.fillna(0)
C["Amount"] = C[L.members()].sum(axis=1) + C["Pool"]
C["fat delivered"] = (
sum(C[l] * S.loc[l, "fat"] for l in L.members()) + C["Pool"] * p.value()
) / C["Amount"]
C["Income"] = C["Amount"] * C["price"]
print(model_title)
print(f"\nPool composition = {p.value():0.2f}")
print(f"Profit = {m.obj['profit'].value():0.2f}")
print(f"\nSupplier Report\n")
display(S.round(4))
print(f"\nCustomer Report\n")
display(C.round(4))
m_convex = milk_pooling_convex()
report_solution(m_convex, "Milk Pooling Model - Convex Approximation")
# %%
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit")
ax.grid(True)
ax.plot(m_convex.var["p"].value(), m_convex.obj["profit"].value(), "ro", ms=10)
ax.axhline(m_convex.obj["profit"].value(), color="r", linestyle="--")
ax.axvline(m_convex.var["p"].value(), color="r", linestyle="--")
ax.annotate(
"convex approximation",
xy=(m_convex.var["p"].value(), m_convex.obj["profit"].value()),
xytext=(0.036, 106000),
ha="right",
fontsize=14,
arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)
# %%
p = m_convex.var["p"].value()
m_convex_profit = m_convex.obj["profit"].value()
m_est = f(p)
m_est_profit = m_est.obj["profit"].value()
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit")
ax.grid(True)
ax.plot(p, m_convex_profit, "ro", ms=10)
ax.axhline(m_convex_profit, color="r", linestyle="--")
ax.axvline(p, color="r", linestyle="--")
ax.annotate(
"convex approximation",
xy=(p, m_convex_profit),
xytext=(0.036, 106000),
ha="right",
fontsize=14,
arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)
ax.plot(p, m_est_profit, "go", ms=10)
ax.axhline(m_est_profit, color="g", linestyle="--")
ax.annotate(
"local maxima",
xy=(p, m_est_profit),
xytext=(0.045, 105000),
ha="left",
fontsize=14,
arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)
plt.show()
# %%
report_solution(m_est, "Milk Pooling Model")
# %%
def milk_pooling_bilinear():
m = AMPL()
m.eval(
"""
# define sources
set L;
set R;
# define customers
set C;
param price{C};
param demand{C};
param min_fat{C};
param cost{L union R};
param fat{L union R};
# define flowrates
var x{R} >= 0;
var y{C} >= 0;
var z{L cross C} >= 0;
# composition of the pool
var p >= min{r in R} fat[r] <= max{r in R} fat[r];
maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l])
+ sum{c in C} price[c]*y[c]
- sum{r in R} cost[r]*x[r];
subject to customer_demand{c in C}:
y[c] + sum{l in L} z[l, c] <= demand[c];
subject to pool_balance:
sum{r in R} x[r] = sum{c in C} y[c];
subject to pool_quality:
sum{r in R} fat[r]*x[r] = p*sum{c in C} y[c];
subject to customer_quality{c in C}:
p*y[c] + sum{l in L} fat[l]*z[l,c] >= min_fat[c]*(sum{l in L} z[l, c] + y[c]);
"""
)
m.set_data(customers, "C")
m.set_data(local_suppliers.drop(columns=["location"]), "L")
m.set_data(remote_suppliers.drop(columns=["location"]), "R")
m.solve(solver=SOLVER_GNLO, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
# %%
m_global = milk_pooling_bilinear()
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit")
ax.grid(True)
ax.plot(p, m_convex_profit, "ro", ms=10)
ax.axhline(m_convex_profit, color="r", linestyle="--")
ax.axvline(p, color="r", linestyle="--")
ax.annotate(
"convex approximation",
xy=(p, m_convex_profit),
xytext=(0.036, 106000),
ha="right",
fontsize=14,
arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)
ax.plot(p, m_est_profit, "go", ms=10)
ax.axhline(m_est_profit, color="g", linestyle="--")
ax.annotate(
"local maxima",
xy=(p, m_est_profit),
xytext=(0.045, 105000),
ha="left",
fontsize=14,
arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)
m_global_p = m_global.var["p"].value()
m_global_profit = m_global.obj["profit"].value()
ax.plot(m_global_p, m_global_profit, "bo", ms=10)
ax.axhline(m_global_profit, color="b", linestyle="--")
ax.annotate(
"global maxima",
xy=(m_global_p, m_global_profit),
xytext=(0.025, 95000),
ha="left",
fontsize=14,
arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)
report_solution(m_global, "Milk Pooling Model - Bilinear")
最小二乗回帰 ols-regression.py 6 セル ・ 165 行
# %%
# install AMPL and solvers
SOLVER_LO = "cbc"
SOLVER_QO = "ipopt"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
from sklearn.datasets import make_regression
import numpy as np
import matplotlib.pyplot as plt
n_features = 1
n_samples = 500
noise = 75
# generate regression dataset
np.random.seed(2022)
X, y = make_regression(n_samples=n_samples, n_features=n_features, noise=noise)
# %%
if n_features == 1:
plt.scatter(X, y, alpha=0.3)
plt.xlabel("X")
plt.ylabel("y")
plt.grid(True)
plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))))
plt.title("histogram y - mean(y)")
plt.ylabel("counts")
plt.show()
# %%
def ols_regression(X, y):
m = AMPL()
m.eval(
"""
reset;
set I;
set J;
var e{I};
var m{J};
var b;
param X{I, J};
param y{I};
subject to residuals{i in I}:
e[i] = y[i] - sum{j in J} X[i,j]*m[j] - b;
minimize sum_of_square_errors:
sum{i in I} e[i]**2;
"""
)
n, k = X.shape
m.set["I"] = list(range(n))
m.set["J"] = list(range(k))
m.param["X"] = X
m.param["y"] = y
m.solve(solver=SOLVER_QO, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
m = ols_regression(X, y)
m_ols = [m.var["m"][j].value() for j in m.set["J"].members()]
b_ols = m.var["b"].value()
print("OLS Regression\n")
print("m:", *m_ols)
print("b:", b_ols)
print("Sum of error squares:", m.obj["sum_of_square_errors"].value())
# %%
def lad_regression(X, y):
m = AMPL()
m.eval(
"""
reset;
set I;
set J;
var ep{I} >= 0;
var em{I} >= 0;
var m{J};
var b;
param X{I, J};
param y{I};
subject to residuals{i in I}:
ep[i] - em[i] = y[i] - sum{j in J} X[i,j]*m[j] - b;
minimize sum_of_abs_errors:
sum{i in I} (ep[i] + em[i]);
"""
)
n, k = X.shape
m.set["I"] = list(range(n))
m.set["J"] = list(range(k))
m.param["X"] = X
m.param["y"] = y
m.solve(solver=SOLVER_LO, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
m = lad_regression(X, y)
m_lad = [m.var["m"][j].value() for j in m.set["J"].members()]
b_lad = m.var["b"].value()
print("\nLAD Regression\n")
print("m:", *m_lad)
print("b:", b_lad)
print("Sum of abs squares:", m.obj["sum_of_abs_errors"].value())
# %%
y_fit = np.array([sum(x[j] * m_ols[j] for j in range(X.shape[1])) + b_ols for x in X])
y_fit2 = np.array([sum(x[j] * m_lad[j] for j in range(X.shape[1])) + b_lad for x in X])
if n_features == 1:
plt.scatter(X, y, alpha=0.3, label="data")
plt.plot(X, y_fit, "r", label="y_fit (OLS)")
plt.plot(X, y_fit2, "g", label="y_fit (LAD)")
plt.xlabel("X")
plt.ylabel("y")
plt.grid(True)
plt.legend()
plt.figure()
plt.hist(y - np.mean(y), bins=int(np.sqrt(len(y))), alpha=0.5, label="y - mean(y)")
plt.hist(
y - y_fit,
bins=int(np.sqrt(len(y))),
color="r",
alpha=0.8,
label="y - y_fit (OLS)",
)
plt.hist(
y - y_fit2,
bins=int(np.sqrt(len(y))),
color="g",
alpha=0.8,
label="y - y_fit (LAD)",
)
plt.title("histogram of residuals")
plt.ylabel("counts")
plt.legend()
plt.show()
マーコウィッツのポートフォリオ最適化モデル markowitz_portfolio.py 3 セル ・ 92 行
# %%
# Install AMPL and solvers
SOLVER_QO = "ipopt"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
from IPython.display import Markdown, HTML
import numpy as np
import pandas as pd
# %%
# Specify the initial capital, the risk threshold, and the guaranteed return rate.
C = 1
gamma = 1
R = 1.01
# Specify the number of assets, their expected return, and their covariance matrix.
n = 3
mu = np.array([1.2, 1.1, 1.3])
Sigma = np.matrix([[1.5, 0.5, 2], [0.5, 2, 0], [2, 0, 5]])
Sigma_df = pd.DataFrame(Sigma, index=range(n), columns=range(n))
# If you want to change the covariance matrix Sigma, ensure you input a semi-definite positive one.
# The easiest way to generate a random covariance matrix is first generating a random m x m matrix A
# and then taking the matrix A^T A (which is always semi-definite positive)
# m = 3
# A = np.random.rand(m, m)
# Sigma = A.T @ A
def markowitz(gamma, mu, Sigma):
m = AMPL()
m.eval(
"""
reset;
# Assets
set A;
param Sigma{A, A};
param mu{A};
param C;
param R;
param gamma;
var xtilde >= 0;
var x{A} >= 0;
maximize objective:
sum{i in A} mu[i]*x[i] + R*xtilde;
subject to bounded_variance:
sum{i in A, j in A} x[i] * Sigma[i,j] * x[j] <= gamma**2;
subject to total_assets:
sum{i in A} x[i] + xtilde = C;
"""
)
m.set["A"] = list(range(n))
m.param["C"] = C
m.param["R"] = R
m.param["mu"] = mu
m.param["gamma"] = gamma
m.param["Sigma"] = Sigma_df
m.solve(solver=SOLVER_QO, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
model = markowitz(gamma, mu, Sigma)
x = model.var["x"]
display(
Markdown(
f"**Solution:** $\\tilde x = {model.var['xtilde'].value():.3f}$, $x_1 = {x[0].value():.3f}$, $x_2 = {x[1].value():.3f}$, $x_3 = {x[2].value():.3f}$"
)
)
display(
Markdown(
f"**Maximizes objective value to:** ${model.obj['objective'].value():.2f}$"
)
)
2値分類のためのサポートベクターマシン svm.py 20 セル ・ 665 行
# %%
# install AMPL and solvers
#%pip install -q amplpy pandas numpy matplotlib scikit-learn
SOLVER_LO = "cbc"
SOLVER_NLO = "ipopt"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
# read data set
df = pd.read_csv(
"https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/datasets/data_banknote_authentication.txt",
header=None,
)
df.columns = ["variance", "skewness", "curtosis", "entropy", "class"]
df.name = "Banknotes"
# show a few rows
df.head()
# %%
# get a statistical description of the data set
df.describe()
# %%
# create training and validation test sets
df_train, df_test = train_test_split(df, test_size=0.2)
# select training features
features = ["variance", "skewness"]
# separate into features and outputs
X_train = df_train[features]
y_train = 1 - 2 * df_train["class"]
# separate into features and outputs
X_test = df_test[features]
y_test = 1 - 2 * df_test["class"]
# %%
def scatter_labeled_data(X, y, labels=["+1", "-1"], colors=["g", "r"], **kwargs):
"""
Creates a scatter plot for labeled data with default labels and colors.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Target vector as a Series.
labels : list, optional
Labels for the positive and negative classes. Default is ["+1", "-1"].
colors : list, optional
Colors for the positive and negative classes. Default is ["g", "r"].
**kwargs : dict
Additional keyword arguments for the scatter plot.
Returns:
None
"""
# Prepend keyword arguments for all scatter plots
kw = {"x": 0, "y": 1, "kind": "scatter", "alpha": 0.4}
kw.update(kwargs)
# Ignore warnings from matplotlib scatter plot
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
kw["ax"] = X[y > 0].plot(**kw, c=colors[0], label=labels[0])
X[y < 0].plot(**kw, c=colors[1], label=labels[1])
# %%
# plot training and test sets in two axes
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
scatter_labeled_data(
X_train,
y_train,
labels=["genuine", "counterfeit"],
ax=ax[0],
title="Training Set",
)
scatter_labeled_data(
X_test,
y_test,
labels=["genuine", "counterfeit"],
ax=ax[1],
title="Test Set",
)
# %%
# import required libraries
import pandas as pd
import numpy as np
# Linear Support Vector Machine (SVM) class
class LinearSVM:
# Initialize the Linear SVM with weights and bias
def __init__(self, w, b):
"""
Args:
w (Pandas Series or dictionary): Weights of the SVM
b (float): Bias of the SVM
"""
self.w = pd.Series(w)
self.b = float(b)
# Call method to compute the decision function
def __call__(self, X):
"""
Args:
X (pandas.DataFrame): Input data
Returns:
numpy.array: Array of decision function values
"""
return np.sign(X.dot(self.w) + self.b)
# Representation method for the Linear SVM class
def __repr__(self):
"""
Returns:
str: String representation of the Linear SVM
"""
return f"LinearSvm(w = {self.w.to_dict()}, b = {self.b})"
# %%
# Visual estimaate of w and b for a linear classifier
w = pd.Series({"variance": 1, "skewness": 0})
b = 0
# create an instance of LinearSVM
svm = LinearSVM(w, b)
print(svm)
# predictions for the training set
y_pred = svm(X_test)
# fraction of correct predictions
accuracy = sum(y_pred == y_test) / len(y_test)
print(f"Accuracy = {100 * accuracy: 0.1f}%")
# %%
def scatter_comparison(X, y, y_pred):
"""
Creates scatter plots comparing actual and predicted outcomes for both training and test sets.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Actual target vector as a Series.
y_pred : Series
Predicted target vector as a Series.
Returns:
None
"""
xmin, ymin = X.min()
xmax, ymax = X.max()
xlim = [xmin - 0.05 * (xmax - xmin), xmax + 0.05 * (xmax - xmin)]
ylim = [ymin - 0.05 * (ymax - ymin), ymax + 0.05 * (ymax - ymin)]
# Plot training and test sets
labels = ["genuine", "counterfeit"]
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
scatter_labeled_data(
X, y, labels, ["g", "r"], ax=ax[0], xlim=xlim, ylim=ylim, title="Actual"
)
scatter_labeled_data(
X,
y_pred,
labels,
["c", "m"],
ax=ax[1],
xlim=xlim,
ylim=ylim,
title="Prediction",
)
# Plot actual positives and actual negatives
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
scatter_labeled_data(
X[y > 0],
y_pred[y > 0],
["true positive", "false negative"],
["c", "m"],
xlim=xlim,
ylim=ylim,
ax=ax[0],
title="Actual Positives",
)
scatter_labeled_data(
X[y < 0],
y_pred[y < 0],
["false positive", "true negative"],
["c", "m"],
xlim=xlim,
ylim=ylim,
ax=ax[1],
title="Actual Negatives",
)
# %%
scatter_comparison(X_test, y_test, y_pred)
# %%
def validate(y_true, y_pred, verbose=True):
"""
This function calculates and displays the sensitivity, precision, and Matthews correlation coefficient
(MCC) for a binary classifier based on its true labels (y_true) and predicted labels (y_pred).
Args:
y_true (array-like): A list or array containing the true labels of the samples.
y_pred (array-like): A list or array containing the predicted labels of the samples.
verbose (bool, optional): If True, the function prints and displays the calculated metrics and
confusion matrix. Defaults to True.
Returns:
float: The calculated Matthews correlation coefficient (MCC).
"""
# Calculate the elements of the confusion matrix
true_positives = sum((y_true > 0) & (y_pred > 0))
false_negatives = sum((y_true > 0) & (y_pred < 0))
false_positives = sum((y_true < 0) & (y_pred > 0))
true_negatives = sum((y_true < 0) & (y_pred < 0))
total = true_positives + true_negatives + false_positives + false_negatives
# Calculate the Matthews correlation coefficient (MCC)
mcc_numerator = (true_positives * true_negatives) - (
false_positives * false_negatives
)
mcc_denominator = np.sqrt(
(true_positives + false_positives)
* (true_positives + false_negatives)
* (true_negatives + false_positives)
* (true_negatives + false_negatives)
)
mcc = mcc_numerator / mcc_denominator
if verbose:
print(f"Matthews correlation coefficient (MCC) = {mcc:0.3f}")
# report sensitivity and precision, and accuracy
sensitivity = true_positives / (true_positives + false_negatives)
precision = true_positives / (true_positives + false_positives)
accuracy = (true_positives + true_negatives) / total
print(f"Sensitivity = {100 * sensitivity: 0.1f}%")
print(f"Precision = {100 * precision: 0.1f}%")
print(f"Accuracy = {100 * accuracy: 0.1f}%")
# Display the binary confusion matrix
confusion_matrix = pd.DataFrame(
[
[true_positives, false_negatives],
[false_positives, true_negatives],
],
index=["Actual Positive", "Actual Negative"],
columns=["Predicted Positive", "Predicted Negative"],
)
display(confusion_matrix)
return mcc
# %%
def test(svm, X_test, y_test):
y_pred = svm(X_test)
print(svm, "\n")
validate(y_test, y_pred)
scatter_comparison(X_test, y_test, y_pred)
# train and test
svm = LinearSVM({"variance": 1, "skewness": 0}, 0.0)
test(svm, X_test, y_test)
# %%
def svm_factory_lp(X, y, lambd=1):
"""
Creates a linear support vector machine (SVM) model using linear programming.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Target vector as a Series.
lambd : float, optional
Regularization parameter. Default is 1.
Returns:
LinearSvm :
A trained linear SVM model.
"""
m = AMPL()
m.eval(
"""
set P;
set N;
param lambd;
param X{N,P};
param y{N};
# Decision variables
var wp{P} >= 0;
var wn{P} >= 0;
var b;
var z{N} >= 0;
var w{p in P} = wp[p] - wn[p];
minimize lasso: sum{i in N} z[i] / card(N)
+ lambd * sum{p in P} (wp[p]+wn[p]);
subject to hingeloss{i in N}:
z[i] >= 1-y[i]*(sum{p in P} w[p]*X[i,p] + b);
"""
)
# Use dataframe columns and index to index variables and constraints
m.set["P"] = list(X.columns)
m.set["N"] = np.array(X.index)
m.param["lambd"] = lambd
m.param["y"] = y
m.param["X"] = X
# Solve QP with the interior point method
m.solve(solver=SOLVER_NLO, verbose=False)
assert m.solve_result == "solved", m.solve_result
w = pd.Series([m.var["w"][p].value() for p in X.columns], index=X.columns)
b = m.var["b"].value()
return LinearSVM(w, b)
# Train and test
svm_lp = svm_factory_lp(X_train, y_train)
test(svm_lp, X_test, y_test)
# %%
def svm_factory_qp(X, y, c=1):
"""
Creates a linear support vector machine (SVM) model using quadratic programming.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Target vector as a Series.
c : float, optional
Regularization parameter. Default is 1.
Returns:
LinearSvm :
A trained linear SVM model.
"""
m = AMPL()
m.eval(
"""
set P;
set N;
param c;
param X{N,P};
param y{N};
# Decision variables
var b;
var z{N} >= 0;
var w{P};
minimize qp: c / card(N) * sum{i in N} z[i]
+ sum{p in P} w[p]^2;
subject to hingeloss{i in N}:
z[i] >= 1-y[i]*(sum{p in P} w[p]*X[i,p] + b);
"""
)
# Use dataframe columns and index to index variables and constraints
m.set["P"] = list(X.columns)
m.set["N"] = np.array(X.index)
m.param["c"] = c
m.param["y"] = y
m.param["X"] = X
# Solve QP with the interior point method
m.solve(solver=SOLVER_NLO, verbose=False)
assert m.solve_result == "solved", m.solve_result
P = m.set["P"].members()
# Extract solution
w = pd.Series([m.var["w"][p].value() for p in X.columns], index=X.columns)
b = m.var["b"].value()
return LinearSVM(w, b)
# Train and test
svm_lp = svm_factory_qp(X_train, y_train)
test(svm_lp, X_test, y_test)
# %%
def svm_factory_dual(X, y, c=1):
"""
Creates a linear support vector machine (SVM) model using the dual formulation
and quadratic programming.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Target vector as a Series.
c : float, optional
Regularization parameter. Default is 1.
Returns:
LinearSvm :
A trained linear SVM model.
"""
m = AMPL()
m.eval(
"""
set P;
set N;
param y{N};
param F{P,N};
param C;
# Decision variables
var w{P};
var a{N} >= 0 <= C;
minimize qp: 1/2 * sum{p in P} w[p]^2 - sum{i in N} a[i];
subject to bias:
sum{i in N} y[i] * a[i] = 0;
subject to projection{p in P}:
w[p] = sum{i in N} F[p,i] * a[i];
"""
)
# Use dataframe columns and index to index variables and constraints
m.set["P"] = list(X.columns)
m.set["N"] = np.array(X.index)
# Model parameters
C = c / len(X.index)
m.param["C"] = C
m.param["y"] = y
m.param["F"] = X.mul(y, axis=0).T
# Solve QP with the interior point method
m.solve(solver=SOLVER_NLO, verbose=False)
assert m.solve_result == "solved", m.solve_result
P = m.set["P"].members()
N = m.set["N"].members()
# Extract solution
w = pd.Series([m.var["w"][p].value() for p in X.columns], index=X.columns)
a = pd.Series([m.var["a"][i].value() for i in X.index], index=X.index)
# Find alpha closest to the center of [0, c/n]
i = a.index[(a - C / 2).abs().argmin()]
b = y.loc[i] - X.loc[i, :].dot(w)
return LinearSVM(w, b)
# Train and test
svm_lp = svm_factory_dual(X_train, y_train)
test(svm_lp, X_test, y_test)
# %%
import pandas as pd
import numpy as np
class KernelSVM:
"""
Kernel Support Vector Machine (SVM) class.
"""
def __init__(self, X, y, a, b, kernel):
"""
Initialize the Kernel SVM with weights and bias.
:param X: numpy array or list, training data.
:param y: numpy array or list, target labels.
:param a: numpy array or list, alpha values for the support vectors.
:param b: float, bias value.
:param kernel: function, kernel function to be used in the SVM.
"""
self.X = np.array(X)
self.u = np.multiply(np.array(a), np.array(y))
self.b = b
self.kernel = kernel
def __call__(self, Z):
"""
Compute the decision function.
:param Z: pandas DataFrame, test data.
:return: pandas Series, predicted labels.
"""
K = [
[self.kernel(self.X[i, :], Z.loc[j, :]) for j in Z.index]
for i in range(len(self.X))
]
y_pred = np.sign((self.u @ K) + self.b)
return pd.Series(y_pred, index=Z.index)
def __repr__(self):
"""
Returns:
str: String representation of the Linear SVM
"""
return f"KernelSvm(b = {self.b})"
# %%
def svm_factory_kernel(X, y, c=1, tol=1e-8, kernel=lambda x, z: x @ z):
"""
Creates a linear support vector machine (SVM) model using the dual formulation
and quadratic programming.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Target vector as a Series.
c : float, optional
Regularization parameter. Default is 1.
Returns:
LinearSvm :
A trained linear SVM model.
"""
# Convert to numpy arrays for speed improvement
n, p = X.shape
X_ = X.to_numpy()
y_ = y.to_numpy()
# Gram matrix
G = np.zeros((n, n))
for i in range(n):
for j in range(i, n):
G[j, i] = G[i, j] = y_[i] * y_[j] * kernel(X_[i, :], X_[j, :])
# Factor the Gram matrix
eigvals, eigvecs = np.linalg.eigh(G)
idx = eigvals >= tol * max(eigvals)
F = pd.DataFrame(eigvecs[:, idx] @ np.diag(np.sqrt(eigvals[idx])), index=X.index)
# Build model
m = AMPL()
m.eval(
"""
set Q;
set N;
param y{N};
param F{N,Q};
param C;
# Decision variables
var u{Q};
var a{N} >= 0 <= C;
minimize qp: 1/2 * sum{q in Q} u[q]^2 - sum{i in N} a[i];
subject to bias:
sum{i in N} y[i] * a[i] = 0;
subject to projection{q in Q}:
u[q] = sum{i in N} F[i,q] * a[i];
"""
)
# Use dataframe columns and index to index variables and constraints
m.set["Q"] = list(F.columns)
m.set["N"] = np.array(F.index)
# Model parameters
C = c / len(F.index)
m.param["C"] = C
m.param["y"] = y
m.param["F"] = F
# Solve QP with the interior point method
m.solve(solver=SOLVER_NLO, verbose=False)
assert m.solve_result == "solved", m.solve_result
# Extract solution
a = pd.Series([m.var["a"][i].value() for i in X.index], index=X.index)
# Find b by locating a closest to the center of [0, c/n]
j = a.index[(a - C / 2).abs().argmin()]
b = y.loc[j] - sum(
[a[i] * y.loc[i] * kernel(X.loc[i, :], X.loc[j, :]) for i in X.index]
)
# Display the support vectors
y_support = pd.Series(
[1 if a[i] > 1e-4 * C else -1 for i in X.index], index=X.index
)
scatter_labeled_data(
X,
y_support,
colors=["b", "y"],
labels=["Support Vector", ""],
title="Support Vectors",
)
# Find support vectors
SV = [i for i in X.index if a[i] > 1e-3 * C]
return KernelSVM(X.loc[SV, :], y.loc[SV], a.loc[SV], b, kernel)
# %%
svm_kernel = svm_factory_kernel(X_train, y_train)
test(svm_kernel, X_test, y_test)
# %%
quadratic = lambda x, z: (1 + x @ z) ** 2
svm_kernel = svm_factory_kernel(X_train, y_train, kernel=quadratic)
test(svm_kernel, X_test, y_test)
# %%
cubic = lambda x, z: (1 + x @ z) ** 3
svm_kernel = svm_factory_kernel(X_train, y_train, kernel=cubic)
test(svm_kernel, X_test, y_test)
補足:製油所の生産と潜在価格 refinery-production.py 7 セル ・ 148 行
# %%
# install AMPL and solvers
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import pandas as pd
products = pd.DataFrame(
{
"gasoline": {"capacity": 24000, "price": 108},
"kerosine": {"capacity": 2000, "price": 72},
"fuel oil": {"capacity": 6000, "price": 63},
"residual": {"capacity": 2500, "price": 30},
}
).T
crudes = pd.DataFrame(
{
"crude 1": {"available": 28000, "price": 72, "process_cost": 1.5},
"crude 2": {"available": 15000, "price": 45, "process_cost": 3},
}
).T
# note: volumetric yields may not add to 100%
yields = pd.DataFrame(
{
"crude 1": {"gasoline": 80, "kerosine": 5, "fuel oil": 10, "residual": 5},
"crude 2": {"gasoline": 44, "kerosine": 10, "fuel oil": 36, "residual": 10},
}
).T
display(products)
display(crudes)
display(yields)
# %%
m = AMPL()
m.eval(
"""
set CRUDES;
set PRODUCTS;
param price{PRODUCTS union CRUDES};
param process_cost{CRUDES};
param yields{PRODUCTS, CRUDES};
param available{CRUDES};
param capacity{PRODUCTS};
# decision variables
var x{c in CRUDES} >= 0 <= available[c];
var y{p in PRODUCTS} >= 0 <= capacity[p];
# objective
var revenue = sum{p in PRODUCTS} price[p]*y[p];
var feed_cost = sum{c in CRUDES} price[c]*x[c];
var total_process_cost = sum{c in CRUDES} process_cost[c]*x[c];
maximize profit: revenue - feed_cost - total_process_cost;
# constraints
subject to balances{p in PRODUCTS}:
y[p] = sum{c in CRUDES} yields[p,c]*x[c] / 100;
"""
)
m.set_data(crudes, "CRUDES")
m.set_data(products, "PRODUCTS")
m.param["yields"] = yields.T
# solution
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
print(f"Profit: {m.obj['profit'].value():0.2f}\n")
# %%
import numpy as np
import cvxpy as cp
# decision variables
x = cp.Variable(len(crudes.index), pos=True, name="crudes")
y = cp.Variable(len(products.index), pos=True, name="products")
# objective
revenue = products["price"].to_numpy().T @ y
feed_cost = crudes["price"].to_numpy().T @ x
process_cost = crudes["process_cost"].to_numpy().T @ x
profit = revenue - feed_cost - process_cost
objective = cp.Maximize(profit)
# constraints
balances = y == yields.to_numpy().T @ x / 100
feeds = x <= crudes["available"].to_numpy()
capacity = y <= products["capacity"].to_numpy()
constraints = [balances, feeds, capacity]
# solution
problem = cp.Problem(objective, constraints)
problem.solve()
# %%
results_crudes = crudes
results_crudes["consumption"] = x.value
results_crudes["shadow price"] = feeds.dual_value
display(results_crudes.round(1))
# %%
results_products = products
results_products["production"] = y.value
results_products["unused capacity"] = products["capacity"] - y.value
results_products["shadow price"] = capacity.dual_value
display(results_products.round(1))
# %%
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(8, 6))
ylim = 24000
xlim = 32000
ax.axvline(crudes["available"][0], linestyle="--", label="Crude 1")
ax.axhline(crudes["available"][1], linestyle="--", label="Crude 2")
xplot = np.linspace(0, xlim)
for product in products.index:
b = 100 * products.loc[product, "capacity"] / yields[product][1]
m = -yields[product][0] / yields[product][1]
line = ax.plot(xplot, m * xplot + b, label=product)
ax.fill_between(xplot, m * xplot + b, 30000, color=line[0].get_color(), alpha=0.2)
ax.plot(x.value[0], x.value[1], "ro", ms=10, label="max profit")
ax.set_title("Feasible operating regime")
ax.set_xlabel(crudes.index[0])
ax.set_ylabel(crudes.index[1])
ax.legend()
ax.set_xlim(0, xlim)
ax.set_ylim(0, ylim)
補足:カッティングストック問題 cutting-stock.py 19 セル ・ 726 行
# %%
# install AMPL and solvers
SOLVER_MILO = "highs"
SOLVER_MINLO = "ipopt"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
stocks = {
"A": {"length": 5, "cost": 6},
"B": {"length": 6, "cost": 7},
"C": {"length": 9, "cost": 10},
}
finish = {
"S": {"length": 2, "demand": 20},
"M": {"length": 3, "demand": 10},
"L": {"length": 4, "demand": 20},
}
# %%
def make_patterns(stocks, finish):
"""
Generates patterns of feasible cuts from stock lengths to meet specified finish lengths.
Parameters:
stocks (dict): A dictionary where keys are stock identifiers and values are dictionaries
with key 'length' representing the length of each stock.
finish (dict): A dictionary where keys are finish identifiers and values are dictionaries
with key 'length' representing the required finish lengths.
Returns:
patterns (list): A list of dictionaries, where each dictionary represents a pattern of cuts.
Each pattern dictionary contains 'stock' (the stock identifier) and 'cuts'
(a dictionary where keys are finish identifiers and the value is the number
of cuts from the stock for each finish).
"""
patterns = []
for f in finish:
feasible = False
for s in stocks:
# max number of f that fit on s
num_cuts = int(stocks[s]["length"] / finish[f]["length"])
# make pattern and add to list of patterns
if num_cuts > 0:
feasible = True
cuts_dict = {key: 0 for key in finish.keys()}
cuts_dict[f] = num_cuts
patterns.append({"stock": s, "cuts": cuts_dict})
if not feasible:
print(f"No feasible pattern was found for {f}")
return []
return patterns
patterns = make_patterns(stocks, finish)
display(patterns)
# %%
import matplotlib.pyplot as plt
def plot_patterns(stocks, finish, patterns):
# set up figure parameters
lw = 0.6
cmap = plt.get_cmap("tab10")
colors = {f: cmap(k % 10) for k, f in enumerate(finish.keys())}
fig, ax = plt.subplots(1, 1, figsize=(8, 0.05 + 0.4 * len(patterns)))
for k, pattern in enumerate(patterns):
# get stock key/name
s = pattern["stock"]
# plot stock as a grey background
y_lo = (-k - lw / 2, -k - lw / 2)
y_hi = (-k + lw / 2, -k + lw / 2)
ax.fill_between((0, stocks[s]["length"]), y_lo, y_hi, color="k", alpha=0.1)
# overlay finished parts
xa = 0
for f, n in pattern["cuts"].items():
for j in range(n):
xb = xa + finish[f]["length"]
ax.fill_between((xa, xb), y_lo, y_hi, alpha=1.0, color=colors[f])
ax.plot((xb, xb), (y_lo[0], y_hi[0]), "w", lw=1, solid_capstyle="butt")
ax.text(
(xa + xb) / 2,
-k,
f,
ha="center",
va="center",
fontsize=6,
color="w",
weight="bold",
)
xa = xb
# clean up axes
ax.spines[["top", "right", "left", "bottom"]].set_visible(False)
ax.set_yticks(
range(0, -len(patterns), -1),
[pattern["stock"] for pattern in patterns],
fontsize=8,
)
return ax
ax = plot_patterns(stocks, finish, patterns)
# %%
# Given dictionaries of stocks and finished parts, and a list of patterns,
# find minimum choice of patterns to cut
def cut_patterns(stocks, finish, patterns):
m = AMPL()
m.eval(
"""
set S;
set F;
set P;
param c{P};
param a{F, P};
param demand_finish{F};
var x{P} integer >= 0;
minimize cost:
sum{p in P} c[p]*x[p];
subject to demand{f in F}:
sum{p in P} a[f,p]*x[p] >= demand_finish[f];
"""
)
m.set["S"] = list(stocks.keys())
m.set["F"] = list(finish.keys())
m.set["P"] = list(range(len(patterns)))
s = {p: patterns[p]["stock"] for p in range(len(patterns))}
c = {p: stocks[s[p]]["cost"] for p in range(len(patterns))}
m.param["c"] = c
a = {
(f, p): patterns[p]["cuts"][f]
for p in range(len(patterns))
for f in finish.keys()
}
m.param["a"] = a
m.param["demand_finish"] = {
f_part: finish[f_part]["demand"] for f_part in finish.keys()
}
m.solve(solver=SOLVER_MILO, verbose=False)
assert m.solve_result == "solved", m.solve_result
return [m.var["x"][p].value() for p in range(len(patterns))], m.obj["cost"].value()
x, cost = cut_patterns(stocks, finish, patterns)
# %%
def plot_nonzero_patterns(stocks, finish, patterns, x, cost):
k = [j for j, _ in enumerate(x) if _ > 0]
ax = plot_patterns(stocks, finish, [patterns[j] for j in k])
ticks = [
f"{x[k]} x {pattern['stock']}" for k, pattern in enumerate(patterns) if x[k] > 0
]
ax.set_yticks(range(0, -len(k), -1), ticks, fontsize=8)
ax.set_title(f"Cost = {round(cost,2)}", fontsize=10)
return ax
ax = plot_nonzero_patterns(stocks, finish, patterns, x, cost)
# %%
def bilinear_cut_stock(stocks, finish, Np=len(finish)):
m = AMPL()
m.eval(
"""
set S;
set F;
set P;
param c{S};
# length stock
param length_s{S};
# length finished pieces
param length_f{F};
param demand_finish{F};
param a_upper_bound{F};
# sum of all finished parts
param f_total_demand;
var a{f in F, p in P} integer >= 0 <= a_upper_bound[f];
var b{S, P} binary;
var x{P} integer >= 0 <= f_total_demand;
minimize cost:
sum{p in P, s in S} c[s] * b[s,p] * x[p];
subject to assign_each_stock_to_pattern{p in P}:
sum{s in S} b[s,p] = 1;
subject to feasible_pattern{p in P}:
sum{f in F} a[f,p] * length_f[f] <= sum{s in S} b[s,p] * length_s[s];
subject to demand{f in F}:
sum{p in P} a[f,p]*x[p] >= demand_finish[f];
# order the patterns to reduce symmetries
subject to order{p in P : p >= 1}:
x[p] <= x[p-1];
subject to max_patterns:
sum{p in P} x[p] <= f_total_demand;
"""
)
m.set["S"] = list(stocks.keys())
m.set["F"] = list(finish.keys())
m.set["P"] = list(range(Np))
m.param["c"] = {s: stocks[s]["cost"] for s in list(stocks.keys())}
m.param["length_s"] = {s: stocks[s]["length"] for s in stocks.keys()}
m.param["length_f"] = {f: finish[f]["length"] for f in finish.keys()}
m.param["demand_finish"] = {f: finish[f]["demand"] for f in finish.keys()}
m.eval("let f_total_demand := max{f in F} demand_finish[f];")
# or m.param['f_total_demand'] = max([finish[f]['demand'] for f in finish.keys()])
a_upper_bound = {
f: max([int(stocks[s]["length"] / finish[f]["length"]) for s in stocks.keys()])
for f in finish.keys()
}
m.param["a_upper_bound"] = a_upper_bound
m.solve(solver=SOLVER_MINLO, verbose=False)
assert m.solve_result == "solved", m.solve_result
cost = m.obj["cost"].value()
x = [round(m.var["x"][p].value()) for p in range(Np)]
# Retrieve the patterns
patterns = []
for p in range(Np):
a = {f: round(m.var["a"][f, p].value()) for f in finish.keys()}
patterns.append(
{
"stock": [s for s in stocks.keys() if m.var["b"][s, p].value() > 0][0],
"cuts": a,
}
)
return patterns, x, cost
patterns, x, cost = bilinear_cut_stock(stocks, finish, 2)
plot_nonzero_patterns(stocks, finish, patterns, x, cost)
# %%
pattern_bilinear_prob = AMPL()
pattern_bilinear_prob.option["solver"] = SOLVER_MINLO
pattern_bilinear_prob.eval(
"""
set S;
set F;
set P;
param c{P union S};
# length stock
param length_s{S};
# length finished pieces
param length_f{F};
param demand_finish{F};
param a{F, P};
param ap_upper_bound{F};
var ap{f in F} integer >= 0 <= ap_upper_bound[f];
var bp{S} binary;
var x{P} integer >= 0;
var xp integer >= 0;
minimize cost:
sum{p in P} c[p] * x[p] + xp * sum{s in S} bp[s]*c[s];
subject to assign_each_stock_to_pattern:
sum{s in S} bp[s] = 1;
subject to add_pattern:
sum{f in F} ap[f] * length_f[f] <= sum{s in S} bp[s] * length_s[s];
subject to demand{f in F}:
sum{p in P} a[f,p]*x[p] + ap[f]*xp >= demand_finish[f];
"""
)
def generate_pattern_bilinear(stocks, finish, patterns):
m = pattern_bilinear_prob
m.eval("reset data;")
m.set["S"] = list(stocks.keys())
m.set["F"] = list(finish.keys())
m.set["P"] = list(range(len(patterns)))
s = {p: patterns[p]["stock"] for p in range(len(patterns))}
c = {p: stocks[s[p]]["cost"] for p in range(len(patterns))}
cstocks = {s: stocks[s]["cost"] for s in list(stocks.keys())}
c.update(cstocks)
m.param["c"] = c
a = {
(f, p): patterns[p]["cuts"][f]
for p in range(len(patterns))
for f in finish.keys()
}
m.param["a"] = a
m.param["length_s"] = {s: stocks[s]["length"] for s in stocks.keys()}
m.param["length_f"] = {f: finish[f]["length"] for f in finish.keys()}
m.param["demand_finish"] = {f: finish[f]["demand"] for f in finish.keys()}
ap_upper_bound = {
f: max([int(stocks[s]["length"] / finish[f]["length"]) for s in stocks.keys()])
for f in finish.keys()
}
m.param["ap_upper_bound"] = ap_upper_bound
m.solve(verbose=False)
assert m.solve_result == "solved", m.solve_result
bp_values = dict(m.var["bp"].get_values())
ap_values = dict(m.var["ap"].get_values())
# Retrieve the patterns
new_pattern = {
"stock": [s for s in stocks.keys() if bp_values[s] > 0.5][0],
"cuts": {f: round(ap_values[f]) for f in finish.keys()},
}
return new_pattern
# %%
stocks = {
"A": {"length": 5, "cost": 6},
"B": {"length": 6, "cost": 7},
"C": {"length": 9, "cost": 10},
}
finish = {
"S": {"length": 2, "demand": 20},
"M": {"length": 3, "demand": 10},
"L": {"length": 4, "demand": 20},
}
patterns = make_patterns(stocks, finish)
generate_pattern_bilinear(stocks, finish, patterns)
# %%
new_pattern_prob = AMPL()
new_pattern_prob.option["solver"] = SOLVER_MILO
new_pattern_prob.eval(
"""
set F;
param c;
param ap_upper_bound{F};
param demand_dual{F};
# length stock
param length_s;
# length finished pieces
param length_f{F};
# Define second problems with new pattern in stock s
var ap{f in F} integer >= 0 <= ap_upper_bound[f];
maximize marginal_cost:
sum{f in F} ap[f] * demand_dual[f] - c;
subject to stock_length:
sum{f in F} ap[f] * length_f[f] <= length_s;
"""
)
def new_pattern_problem(finish, length_s, cost_s, ap_upper_bound, demand_duals):
m = new_pattern_prob
m.eval("reset data;")
m.set["F"] = list(finish.keys())
m.param["c"] = cost_s
m.param["length_s"] = length_s
m.param["length_f"] = {f: finish[f]["length"] for f in finish.keys()}
m.param["ap_upper_bound"] = ap_upper_bound
m.param["demand_dual"] = demand_duals
m.solve(verbose=False)
assert m.solve_result == "solved", m.solve_result
marg_cost = m.obj["marginal_cost"].value()
pattern = {f: round(m.var["ap"][f].value()) for f in finish.keys()}
return marg_cost, pattern
generate_pattern_dual_prob = AMPL()
generate_pattern_dual_prob.option["solver"] = SOLVER_MILO
generate_pattern_dual_prob.eval(
"""
set F;
set P;
param c{P};
param demand_finish{F};
# how many F pieces are returned from pattern p
param a{F, P};
# Define first problem with known patterns
var x{P} >= 0; # relaxed integrality
minimize cost:
sum{p in P} c[p] * x[p];
subject to demand{f in F}:
sum{p in P} a[f,p]*x[p] >= demand_finish[f];
"""
)
def generate_pattern_dual(stocks, finish, patterns):
m = generate_pattern_dual_prob
m.set["F"] = list(finish.keys())
m.set["P"] = list(range(len(patterns)))
s = {p: patterns[p]["stock"] for p in range(len(patterns))}
c = {p: stocks[s[p]]["cost"] for p in range(len(patterns))}
m.param["c"] = c
a = {
(f, p): patterns[p]["cuts"][f]
for p in range(len(patterns))
for f in finish.keys()
}
m.param["a"] = a
m.param["demand_finish"] = {f: finish[f]["demand"] for f in finish.keys()}
m.solve(verbose=False)
assert m.solve_result == "solved", m.solve_result
dual_values = dict(m.getConstraint("demand").get_values(suffixes="dual"))
ap_upper_bound = {
f: max([int(stocks[s]["length"] / finish[f]["length"]) for s in stocks.keys()])
for f in finish.keys()
}
demand_duals = {f: dual_values[f] for f in finish.keys()}
# use get_values() for getting the duals
marginal_values = {}
pattern = {}
for s in stocks.keys():
marginal_values[s], pattern[s] = new_pattern_problem(
finish, stocks[s]["length"], stocks[s]["cost"], ap_upper_bound, demand_duals
)
s = max(marginal_values, key=marginal_values.get)
new_pattern = {"stock": s, "cuts": pattern[s]}
return new_pattern
# %%
stocks = {
"A": {"length": 5, "cost": 6},
"B": {"length": 6, "cost": 7},
"C": {"length": 9, "cost": 10},
}
finish = {
"S": {"length": 2, "demand": 20},
"M": {"length": 3, "demand": 10},
"L": {"length": 4, "demand": 20},
}
patterns = make_patterns(stocks, finish)
generate_pattern_dual(stocks, finish, patterns)
# %%
stocks = {
"log": {"length": 100, "cost": 1},
}
finish = {
1: {"length": 75.0, "demand": 38},
2: {"length": 75.0, "demand": 44},
3: {"length": 75.0, "demand": 30},
4: {"length": 75.0, "demand": 41},
5: {"length": 75.0, "demand": 36},
6: {"length": 53.8, "demand": 33},
7: {"length": 53.0, "demand": 36},
8: {"length": 51.0, "demand": 41},
9: {"length": 50.2, "demand": 35},
10: {"length": 32.2, "demand": 37},
11: {"length": 30.8, "demand": 44},
12: {"length": 29.8, "demand": 49},
13: {"length": 20.1, "demand": 37},
14: {"length": 16.2, "demand": 36},
15: {"length": 14.5, "demand": 42},
16: {"length": 11.0, "demand": 33},
17: {"length": 8.6, "demand": 47},
18: {"length": 8.2, "demand": 35},
19: {"length": 6.6, "demand": 49},
20: {"length": 5.1, "demand": 42},
}
patterns = make_patterns(stocks, finish)
print("Testing generate_patterns_bilinear: ", end="")
generate_pattern_bilinear(stocks, finish, patterns)
print("Testing generate_patterns_dual: ", end="")
generate_pattern_dual(stocks, finish, patterns)
# %%
def cut_stock(stocks, finish):
# Generate initial set of patterns
patterns = make_patterns(stocks, finish)
# Phase 1: Generate patterns using dual method
print("Phase 1 ", end=".")
new_pattern = generate_pattern_dual(stocks, finish, patterns)
while new_pattern not in patterns:
patterns.append(new_pattern)
new_pattern = generate_pattern_dual(stocks, finish, patterns)
print(end=".")
x, cost = cut_patterns(stocks, finish, patterns)
print(f" Cost = {cost}")
# Phase 2: Generate patterns using bilinear method
print("Phase 2 ", end=".")
new_pattern = generate_pattern_bilinear(stocks, finish, patterns)
while new_pattern not in patterns:
patterns.append(new_pattern)
new_pattern = generate_pattern_bilinear(stocks, finish, patterns)
print(end=".")
x, cost = cut_patterns(stocks, finish, patterns)
print(f" Cost = {cost}")
# Get the indices of non-zero patterns
non_zero_indices = [index for index, value in enumerate(x) if value > 0]
# Return only the non-zero patterns, their corresponding values, and the cost
return (
[patterns[index] for index in non_zero_indices],
[x[index] for index in non_zero_indices],
cost,
)
stocks = {
"A": {"length": 5, "cost": 6},
"B": {"length": 6, "cost": 7},
"C": {"length": 9, "cost": 10},
}
finish = {
"S": {"length": 2, "demand": 20},
"M": {"length": 3, "demand": 10},
"L": {"length": 4, "demand": 20},
}
patterns, x, cost = cut_stock(stocks, finish)
plot_nonzero_patterns(stocks, finish, patterns, x, cost)
# %%
stocks = {
"log": {"length": 100, "cost": 1},
}
finish = {
1: {"length": 75.0, "demand": 38},
2: {"length": 75.0, "demand": 44},
3: {"length": 75.0, "demand": 30},
4: {"length": 75.0, "demand": 41},
5: {"length": 75.0, "demand": 36},
6: {"length": 53.8, "demand": 33},
7: {"length": 53.0, "demand": 36},
8: {"length": 51.0, "demand": 41},
9: {"length": 50.2, "demand": 35},
10: {"length": 32.2, "demand": 37},
11: {"length": 30.8, "demand": 44},
12: {"length": 29.8, "demand": 49},
13: {"length": 20.1, "demand": 37},
14: {"length": 16.2, "demand": 36},
15: {"length": 14.5, "demand": 42},
16: {"length": 11.0, "demand": 33},
17: {"length": 8.6, "demand": 47},
18: {"length": 8.2, "demand": 35},
19: {"length": 6.6, "demand": 49},
20: {"length": 5.1, "demand": 42},
}
patterns, x, cost = cut_stock(stocks, finish)
plot_nonzero_patterns(stocks, finish, patterns, x, cost)
# %%
stocks = {
"roll": {"length": 5600, "cost": 1},
}
finish = {
1380: {"length": 1380, "demand": 22},
1520: {"length": 1520, "demand": 25},
1560: {"length": 1560, "demand": 12},
1710: {"length": 1710, "demand": 14},
1820: {"length": 1820, "demand": 18},
1880: {"length": 1880, "demand": 18},
1930: {"length": 1930, "demand": 20},
2000: {"length": 2000, "demand": 10},
2050: {"length": 2050, "demand": 12},
2100: {"length": 2100, "demand": 14},
2140: {"length": 2140, "demand": 16},
2150: {"length": 2150, "demand": 18},
2200: {"length": 2200, "demand": 20},
}
patterns, x, cost = cut_stock(stocks, finish)
plot_nonzero_patterns(stocks, finish, patterns, x, cost)
# %%
import pandas as pd
def read_google_sheet(sheet_id, sheet_name):
"""
Reads a Google Sheet and returns a pandas DataFrame.
This function reads a Google Sheet with the specified sheet ID and sheet name,
and returns a pandas DataFrame with the data. The column names are converted to
lowercase.
Args:
sheet_id (str): The Google Sheet ID.
sheet_name (str): The name of the sheet to read.
Returns:
df (pd.DataFrame): A pandas DataFrame containing the data from the Google Sheet.
"""
url = f"https://docs.google.com/spreadsheets/d/{sheet_id}/gviz/tq?tqx=out:csv&sheet={sheet_name}"
df = pd.read_csv(url)
df.columns = map(str.lower, df.columns)
return df
# %%
# Google Sheet ID
sheet_id = "1ZX7KJ2kwTGgyqEv_a3LOG0nQSxsc38Ykk53A7vGWAFU"
# read settings
settings_df = read_google_sheet(sheet_id, "settings")
print("\nSettings")
display(settings_df)
# read parts
finish_df = read_google_sheet(sheet_id, "finish")
print("\nFinish")
display(finish_df)
# read and display stocks
stocks_df = read_google_sheet(sheet_id, "stocks")
# stocks = stocks.drop(["price"], axis=1)
if not "price" in stocks_df.columns:
stocks["price"] = stocks_df["length"]
print("\nStocks")
display(stocks_df)
# %%
kinds = tuple(set(finish_df["kind"]))
kerf = 0.25
for kind in kinds:
print(f"Kind = {kind}")
finish = dict()
for i in finish_df.loc[finish_df["kind"] == kind].index:
finish[finish_df.loc[i, "label"]] = {
"length": finish_df.loc[i, "length"] + kerf,
"demand": finish_df.loc[i, "quantity"],
}
stocks = dict()
for i in stocks_df.loc[stocks_df["kind"] == kind].index:
stocks[stocks_df.loc[i, "length"]] = {
"length": stocks_df.loc[i, "length"] + 0 * kerf,
"cost": stocks_df.loc[i, "price"],
}
patterns, x, cost = cut_stock(stocks, finish)
plot_nonzero_patterns(stocks, finish, patterns, x, cost)
# %%
df = pd.DataFrame(patterns)
df["cuts"] = x
df["stock"] = df["stock"].astype(str)
df = df.pivot_table(index="stock", values="cuts", aggfunc="sum")
df.index = df.index.astype(int)
df = df.sort_index()
df
第6章錐最適化7 ファイル▶ 講義動画(20:22)
経済的発注量 economic-order-quantity.py 11 セル ・ 291 行 ・ モデル 4
この節のモデル(4)
AMPLeoq_soc_basic.mod
param h; # cost of holding one item for one year
param c; # cost of processing one order
param d; # annual demand
# define variables for conic constraints
var u >= 0;
var v >= 0;
var t >= 0;
# relationships for conic constraints to decision variables
s.t. u_eq:
u == 2;
# conic constraint
s.t. q:
t^2 >= u^2 + v^2;
# linear objective
minimize eoq:
((h + 2*c*d)*t + (h - 2*c*d)*v)/4;
AMPLeoq_soc.mod
param h; # cost of holding one item for one year
param c; # cost of processing one order
param d; # annual demand
# define variables for conic constraints
var v >= 0;
var t >= 0;
# conic constraint
s.t. q:
-t <= -sqrt(2^2 + v^2);
# linear objective
minimize eoq:
((h + 2*c*d)*t + (h - 2*c*d)*v)/4;
AMPLeoq_rsoc.mod
param h; # cost of holding one item for one year
param c; # cost of processing one order
param d; # annual demand
# define variables for conic constraints
var x >= 0;
var y >= 0;
# conic constraint
s.t. q:
x*y >= 1;
# linear objective
minimize eoq:
h*x/2 + c*d*y;
AMPLeoq_multi_rsoc.mod
set ITEMS;
param b0; # resource total
param b{ITEMS}; # resource per unit of each item
param h{ITEMS}; # cost of holding each item for one year
param c{ITEMS}; # cost of processing one order
param d{ITEMS}; # annual demand of each item
# define variables for conic constraints
var x {ITEMS} >= 0;
var y {ITEMS} >= 0;
# conic constraints
s.t. q {i in ITEMS}:
x[i]*y[i] >= 1;
# resource capacity
s.t. r:
sum {i in ITEMS} (b[i]*x[i]) <= b0;
# linear objective
minimize eoq:
sum {i in ITEMS}
(h[i]*x[i]/2 + c[i]*d[i]*y[i]);
# %%
# install dependencies and select solver
SOLVER_CONIC = "mosek" # mosek, ipopt, knitro
SOLVER_NLO = "ipopt"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "mosek"], # modules to install. ipopt is part of coin
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
import numpy as np
import pandas as pd
# %%
import matplotlib.pyplot as plt
import numpy as np
h = 0.75 # cost of holding one item for one year
c = 500.0 # cost of processing one order
d = 10000.0 # annual demand
eoq = np.sqrt(2 * c * d / h)
fopt = np.sqrt(2 * c * d * h)
print(f"Optimal order size = {eoq:0.1f} items with cost {fopt:0.2f}")
x = np.linspace(100, 10000, 1000)
f = h * x / 2 + c * d / x
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, f, lw=3, label="total cost")
ax.plot(x, h * x / 2, "--", lw=1, label="holding costs")
ax.plot(x, c * d / x, "--", lw=1, label="ordering costs")
ax.set_xlabel("x = order size")
ax.set_ylabel("cost")
ax.plot(eoq, fopt, "ro", ms=10, label="EOQ")
ax.legend(loc="lower right")
ax.annotate(
f"EOQ = {eoq:0.2f}",
xy=(eoq, 0),
xytext=(1.2 * eoq, 0.2 * fopt),
arrowprops=dict(facecolor="black", shrink=0.15, width=1, headwidth=6),
)
ax.plot([eoq, eoq, 0], [0, fopt, fopt], "r--")
ax.set_xlim(0, 10000)
ax.set_ylim(0, 6000)
# %%
import matplotlib.pyplot as plt
import numpy as np
h = 0.75 # cost of holding one item for one year
c = 500.0 # cost of processing one order
d = 10000.0 # annual demand
x = np.linspace(100, 8000)
y = (fopt - h * x / 2) / (c * d)
eoq = np.sqrt(2 * c * d / h)
fopt = np.sqrt(2 * c * d * h)
yopt = (fopt - h * eoq / 2) / (c * d)
fig, ax = plt.subplots(figsize=(8, 6))
ax.plot(x, 1 / x, lw=3, label="x y = 1")
ax.plot(x, (fopt - h * x / 2) / (c * d), "g", lw=3)
for f in fopt * np.linspace(0, 3, 11):
ax.plot(x, (f - h * x / 2) / (c * d), "g--", alpha=0.5)
ax.plot(eoq, yopt, "ro", ms=10)
ax.annotate(
f"EOQ = {eoq:0.2f}",
xy=(eoq, 0),
xytext=(1.2 * eoq, 0.2 * yopt),
arrowprops=dict(facecolor="black", shrink=0.15, width=1, headwidth=6),
)
ax.annotate(
"",
xytext=(4800, 0.0006),
xy=(4000, 1 / 3000),
arrowprops=dict(facecolor="black", shrink=0.05, width=1, headwidth=6),
)
ax.text(4800, 0.0005, "decreasing objective")
ax.fill_between(x, 1 / x, 0.0008, alpha=0.2, label="x y > 1")
ax.plot([eoq, eoq], [0, yopt], "r--")
ax.set_xlim(0, 8000)
ax.set_ylim(0, 0.0008)
ax.set_xlabel("x = order size")
ax.set_ylabel("y")
ax.legend()
# %%
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
import mpl_toolkits.mplot3d.art3d as art3d
from matplotlib.patches import Rectangle
t_max = 4
w = 2
n = 40
fig = plt.figure(figsize=(9, 7))
ax = plt.axes(projection="3d")
for t in np.linspace(0, t_max, n + 1):
if t < w:
a = np.linspace(0, 2 * np.pi, 30)
u = t * np.cos(a)
v = t * np.sin(a)
ax.plot3D(u, v, t, "b", lw=0.3)
else:
b = np.arccos(w / t)
a = np.linspace(b, 2 * np.pi - b, 30)
u = t * np.cos(a)
v = t * np.sin(a)
ax.plot3D(u, v, t, "b", lw=0.3)
ax.plot3D([2, 2], [t * np.sin(b), -t * np.sin(b)], [t, t], "b", lw=0.3)
t = np.linspace(w, t_max)
v = t * np.sin(np.arccos(w / t))
u = w * np.array([1] * len(t))
ax.plot3D(u, v, t, "b")
ax.plot3D(u, -v, t, "b")
ax.plot3D([0, t_max + 0.5], [0, 0], [0, 0], "k", lw=3, alpha=0.4)
ax.plot3D([0, 0], [0, t_max + 1], [0, 0], "k", lw=3, alpha=0.4)
ax.plot3D([0, 0], [0, 0], [0, t_max + 1], "k", lw=3, alpha=0.4)
ax.text3D(t_max + 1, 0, 0.5, "u", fontsize=24)
ax.text3D(0, t_max, 0.5, "v", fontsize=24)
ax.text3D(0, 0, t_max + 1.5, "t", fontsize=24)
ax.view_init(elev=20, azim=40)
r = Rectangle((-t_max, 0), 2 * t_max, t_max + 1, alpha=0.2)
ax.add_patch(r)
art3d.pathpatch_2d_to_3d(r, z=w, zdir="x")
ax.grid(False)
ax.axis("off")
ax.set_xlabel("u")
ax.set_ylabel("v")
ax.set_xlim(-3, 3)
ax.set_ylim(-3, 3)
ax.set_zlim(1, 4)
plt.show()
# %%
h = 0.75 # cost of holding one item for one year
c = 500.0 # cost of processing one order
d = 10000.0 # annual demand
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("eoq_soc_basic.mod")
# load the data
ampl.param["h"] = h
ampl.param["c"] = c
ampl.param["d"] = d
# solve
ampl.solve(solver=SOLVER_NLO, verbose=False)
assert ampl.solve_result == "solved", ampl.solve_result
# solution
print(f"\nEOQ = { ampl.get_value('(t + v)/2') :.2f}")
# %%
h = 0.75 # cost of holding one item for one year
c = 500.0 # cost of processing one order
d = 10000.0 # annual demand
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("eoq_soc.mod")
# load the data
ampl.param["h"] = h
ampl.param["c"] = c
ampl.param["d"] = d
# solve
ampl.solve(solver=SOLVER_NLO, verbose=False)
assert ampl.solve_result == "solved", ampl.solve_result
# solution
print(f"\nEOQ = { ampl.get_value('(t + v)/2') :.2f}")
# %%
h = 0.75 # cost of holding one item for one year
c = 500.0 # cost of processing one order
d = 10000.0 # annual demand
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("eoq_rsoc.mod")
# load the data
ampl.param["h"] = h
ampl.param["c"] = c
ampl.param["d"] = d
# solve
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
# solution
print(f"\nEOQ = { ampl.get_value('x') :.2f}")
# %%
import pandas as pd
df = pd.DataFrame(
{
"all weather": {"h": 1.0, "c": 200, "d": 1300, "b": 3},
"truck": {"h": 2.8, "c": 250, "d": 700, "b": 8},
"heavy duty": {"h": 1.2, "c": 200, "d": 500, "b": 5},
"low cost": {"h": 0.8, "c": 180, "d": 2000, "b": 3},
}
).T
display(df)
# %%
import numpy as np
display(df)
def eoq(df, b):
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("eoq_multi_rsoc.mod")
# load the data
ampl.set["ITEMS"] = list(df.index)
ampl.set_data(df, "ITEMS")
ampl.param["b0"] = b
# solve
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl
def eoq_display_results(df, ampl):
x = ampl.get_variable("x")
dfx = x.to_dict()
results = pd.DataFrame(
[[i, dfx[i], dfx[i] * df.loc[i, "b"]] for i in df.index],
columns=["product", "EOQ", "Space Req'd"],
).round(1)
results.set_index("product", inplace=True)
display(results)
results.plot(
y=["EOQ", "Space Req'd"],
kind="bar",
subplots=True,
layout=(2, 1),
figsize=(10, 6),
)
m = eoq(df, 4000)
eoq_display_results(df, m)
# %%
n = 30
df_large = pd.DataFrame()
df_large["h"] = np.random.uniform(0.5, 2.0, n)
df_large["c"] = np.random.randint(300, 500, n)
df_large["d"] = np.random.randint(100, 5000, n)
df_large["b"] = np.random.uniform(10, 50)
df_large.set_index(pd.Series(f"product {i:03d}" for i in range(n)), inplace=True)
df_large
m = eoq(df_large, 100000)
eoq_display_results(df_large, m)
ケリー基準 kelly-criterion.py 5 セル ・ 115 行 ・ モデル 2
この節のモデル(2)
AMPLkelly.mod
# parameter values
param b;
param p;
# decision variables
var q1;
var q2;
var w >= 0;
# objective
maximize ElogR:
p*q1 + (1-p)*q2;
# conic constraints
s.t. T1: 1 + b*w >= exp( q1 );
s.t. T2: 1 - w >= exp( q2 );
AMPLkelly_rc.mod
# parameter values
param b;
param p;
param lambd;
# decision variables
var q1;
var q2;
var w >= 0;
# objective
maximize ElogR:
p*q1 + (1-p)*q2;
# conic constraints
s.t. T1: 1 + b*w >= exp( q1 );
s.t. T2: 1 - w >= exp( q2 );
# risk constraints
var u1 >= 0;
var u2 >= 0;
s.t. R0: u1 + u2 <= 1;
s.t. R1: u1 >= exp(log(p) - lambd*q1);
s.t. R2: u2 >= exp(log(1 - p) - lambd*q2);
# %%
# install dependencies and select solver
SOLVER_CONIC = "mosek" # ipopt, mosek, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "mosek"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
import numpy as np
import pandas as pd
# %%
# parameter values
b = 1.25
p = 0.51
# conic optimization solution to Kelly's problem
def kelly(p, b):
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("kelly.mod")
# load the data
ampl.param["b"] = b
ampl.param["p"] = p
# solve
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl.get_value("w")
w_conic = kelly(p, b)
print(f"Conic optimization solution for w: {w_conic: 0.4f}")
# analytical solution to Kelly's problem
w_analytical = p - (1 - p) / b if p * (b + 1) > 1 else 0
print(f"Analytical solution for w: {w_analytical: 0.4f}")
# %%
import numpy as np
# parameter values
b = 1.25
p = 0.51
lambd = 3
# conic optimization solution to Kelly's problem
def kelly_rc(p, b, lambd):
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("kelly_rc.mod")
# load the data
ampl.param["b"] = b
ampl.param["p"] = p
ampl.param["lambd"] = lambd
# solve
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl.get_value("w")
w_rc = kelly_rc(p, b, lambd)
print(f"Risk-constrainend solution for w: {w_rc: 0.4f}")
# solution to Kelly's problem
w_analytical = p - (1 - p) / b if p * (b + 1) >= 1 else 0
print(f"Analytical solution for w: {w_analytical: 0.4f}")
# %%
import numpy as np
import matplotlib.pyplot as plt
def kelly_sim(p, b, lambd=0, K=None, ax=None):
w = kelly_rc(p, b, lambd)
m = p * np.log((1 + b * w)) + (1 - p) * np.log((1 - w))
if K is None:
K = int(np.log(10) / m)
if ax is None:
_, ax = plt.subplots(1, 1)
# monte carlo simulation and plotting
for n in range(0, 100):
W = [1]
R = [[1 - w, 1 + w * b][z] for z in np.random.binomial(1, p, size=K)]
R.insert(0, 1)
ax.semilogy(np.cumprod(R), alpha=0.3)
ax.semilogy(np.linspace(0, K), np.exp(m * np.linspace(0, K)), "r", lw=3)
ax.set_title(f"Kelly Criterion: E[logR] = {np.exp(m):0.5f}")
s = f" p = {p:0.3f} \n b = {b:0.3f} \n $\lambda$ = {lambd:0.3f} \n w = {w:0.3f}"
ax.text(0.1, 0.95, s, transform=ax.transAxes, va="top")
ax.set_xlabel("k")
ax.set_ylabel("Wealth")
ax.grid(True)
ax.set_ylim(0.01, 1e6)
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
kelly_sim(p, b, lambd=0, K=80, ax=ax[0])
kelly_sim(p, b, lambd=3, K=80, ax=ax[1])
マーコウィッツのポートフォリオ最適化:再訪 markowitz_portfolio_revisited.py 4 セル ・ 116 行 ・ モデル 1
この節のモデル(1)
AMPLmarkowitz_portfolio_revisited.mod
# Specify the initial capital, the risk tolerance, and the guaranteed return rate.
param C;
param alpha;
param R;
# Specify the number of assets, their expected return, and their covariance matrix.
param n;
param mu{1..n};
param Sigma{1..n, 1..n};
var xtilde >= 0;
var x{1..n} >= 0;
var s >= 0;
maximize Objective:
sum {i in 1..n} mu[i]*x[i] + R*xtilde - alpha*s;
s.t. BoundedVariance:
sum {i in 1..n, j in 1..n} x[i]*Sigma[i,j]*x[j] <= s;
s.t. TotalAssets:
sum {i in 1..n} x[i] + xtilde == C;
# %%
# install dependencies and select solver
SOLVER_CONIC = "mosek" # ipopt, mosek, gurobi, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "mosek"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
from IPython.display import Markdown, HTML
import numpy as np
import matplotlib.pyplot as plt
# %%
# Specify the initial capital, the risk tolerance, and the guaranteed return rate.
C = 1
alpha = 0.1
R = 1.05
# Specify the number of assets, their expected return, and their covariance matrix.
n = 3
mu = np.array([1.25, 1.15, 1.35])
Sigma = np.array([[1.5, 0.5, 2], [0.5, 2, 0], [2, 0, 5]])
# If you want to change the covariance matrix Sigma, ensure you input a semi-definite positive one.
# The easiest way to generate a random covariance matrix is first generating a random m x m matrix A
# and then taking the matrix A^T A (which is always semi-definite positive)
# m = 3
# A = np.random.rand(m, m)
# Sigma = A.T @ A
#
# Moreover, in practive such a matrix A, called factor, can be low-rank,
# see https://docs.mosek.com/modeling-cookbook/qcqo.html#example-factor-model.
# This would provide better numerical properties for the proper conic formulation
# y=Ax, |y|^2 <= s,
# corresponding to the mathematical formulation above.
def markowitz_revisited(alpha, mu, Sigma):
ampl = AMPL()
ampl.read("markowitz_portfolio_revisited.mod")
ampl.param["C"] = C
ampl.param["alpha"] = alpha
ampl.param["R"] = R
ampl.param["n"] = n
ampl.param["mu"] = mu
ampl.param["Sigma"] = {
(i + 1, j + 1): Sigma[i][j] for i in range(n) for j in range(n)
}
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl
ampl = markowitz_revisited(alpha, mu, Sigma)
xtilde = ampl.get_variable("xtilde").value()
x = ampl.get_variable("x").to_dict()
display(Markdown(f"**Solver status:** *{ampl.solve_result}*"))
display(
Markdown(
f"**Solution:** $\\tilde x = {xtilde:.3f}$"
f" $x_1 = {x[1]:.3f}$, $x_2 = {x[2]:.3f}$, $x_3 = {x[3]:.3f}$"
)
)
display(
Markdown(
f"**Maximizes objective value to:**"
f" ${ampl.get_objective('Objective').value():.2f}$"
)
)
# %%
alpha_values = [
0.005,
0.01,
0.02,
0.03,
0.04,
0.05,
0.06,
0.07,
0.08,
0.09,
0.1,
0.11,
0.12,
0.13,
0.14,
0.15,
0.16,
0.17,
0.18,
0.19,
0.20,
0.25,
0.5,
]
objective = []
for alpha in alpha_values:
ampl = markowitz_revisited(alpha, mu, Sigma)
objective.append(round(ampl.get_objective("Objective").value(), 3))
plt.plot(alpha_values, objective)
plt.xlabel(r"Risk tolerance $\alpha$")
plt.ylabel("Optimal objective value")
plt.show()
多層断熱材の最適設計 building-insulation.py 8 セル ・ 241 行
# %%
# install dependencies and select solver
SOLVER_CONIC = "mosek" # ipopt, mosek, gurobi, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "mosek"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
# application parameters
alpha = 30 # $ K / W annualized cost per sq meter per W/sq m/K
beta = 0.05 # equivalent annual cost factor
R0 = 2.0 # Watts/K/m**2
T = 0.30 # maximum insulation thickness
# material properties
k = 0.030 # thermal conductivity as installed
a = 5.0 # installation cost per square meter
b = 150.0 # installed material cost per cubic meter
# %%
import matplotlib.pyplot as plt
import numpy as np
f = lambda x: alpha / (R0 + x / k)
g = lambda x: beta * (a + b * x)
# solution
xopt = -k * R0 + np.sqrt(alpha * k / beta / b)
print(f"The optimal cost is equal to {f(xopt) + g(xopt):0.5f} per sq. meter")
print(f"The optimal thickness is {xopt:0.5f} meters\n")
# plotting
x = np.linspace(0, 1, 201)
fig, ax = plt.subplots(1, 1, figsize=(6.5, 4))
ax.plot(x, f(x), label="energy")
ax.plot(x, g(x), label="insulation")
ax.plot(x, f(x) + g(x), label="total", lw=3)
ax.plot(xopt, f(xopt) + g(xopt), ".", ms=10, label="minimum")
ax.legend()
ax.plot([0, xopt], [f(xopt) + g(xopt)] * 2, "r--")
ax.plot([xopt] * 2, [0, f(xopt) + g(xopt)], "r--")
ax.text(0, f(xopt) + g(xopt) + 0.3, f"{f(xopt) + g(xopt):0.3f}")
ax.text(xopt, 0.3, f"{xopt:0.3f}")
ax.set_xlabel("Insulation thickness [m]")
ax.set_ylabel("Cost ")
ax.set_title("Annualized costs of insulation and energy per sq. meter")
ax.grid(True)
# %%
ampl = AMPL()
ampl.eval(
r"""
# application parameters
param alpha; # $ K / W annualized cost per sq meter per W/sq m/K
param beta; # equivalent annual cost factor
param R0; # Watts/K/m**2
param T; # maximum insulation thickness
# material properties
param k; # thermal conductivity as installed
param a; # installation cost per square meter
param b; # installed material cost per cubic meter
# decision variables
var R >= 0;
var U >= 0;
var x >= 0 <= T;
# objective
minimize cost: alpha*U + beta*(a + b*x);
# insulation model
s.t. r: R == R0 + x/k;
# conic constraint
s.t. q: R*U >= 1;
"""
)
ampl.param["alpha"] = alpha
ampl.param["beta"] = beta
ampl.param["R0"] = R0
ampl.param["T"] = T
ampl.param["k"] = k
ampl.param["a"] = a
ampl.param["b"] = b
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
print(
f"The optimal cost is equal to {ampl.get_objective('cost').value():0.5f} per sq. meter"
)
print(f"The optimal thickness is xopt = {ampl.get_value('x'):0.5f} meters")
# %%
def insulate(df, alpha, beta, R0, T):
ampl = AMPL()
ampl.eval(
r"""
# application parameters
param alpha; # $ K / W annualized cost per sq meter per W/sq m/K
param beta; # equivalent annual cost factor
param R0; # Watts/K/m**2
param T; # maximum insulation thickness
# material properties
set MAT;
param k{MAT}; # thermal conductivity as installed
param a{MAT}; # installation cost per square meter
param b{MAT}; # installed material cost per cubic meter
# decision variables
var R >= 0;
var U >= 0;
var x{MAT} >= 0;
var y{MAT} binary;
# objective
minimize cost:
alpha*U + beta * sum {i in MAT} (a[i] + b[i]*x[i]);
# insulation model
s.t. insulation: R == R0 + sum {i in MAT} x[i]/k[i];
# total thickness limit
s.t. thickness: sum {i in MAT} x[i] <= T;
# layer model
s.t. layers {i in MAT}:
x[i] <= T * y[i];
# conic constraint
s.t. q: R*U >= 1;
"""
)
ampl.param["alpha"] = alpha
ampl.param["beta"] = beta
ampl.param["R0"] = R0
ampl.param["T"] = T
ampl.set["MAT"] = list(df.index)
ampl.set_data(df, "MAT")
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
df["x_opt"] = ampl.get_variable("x").to_pandas()
print(
f"\nThe optimal cost is equal to"
f" {ampl.get_objective('cost').value():0.5f} per sq. meter"
)
display(df.round(5))
return ampl
# %%
import pandas as pd
# application parameters
alpha = 30 # $ K / W annualized cost per sq meter per W/sq m/K
beta = 0.05 # equivalent annual cost factor
R0 = 2.0 # Watts/K/m**2
T = 0.30 # maximum insulation thickness
df = pd.DataFrame(
{
"Mineral Wool": {"k": 0.030, "a": 5.0, "b": 150.0},
"Rigid Foam (high R)": {"k": 0.015, "a": 8.0, "b": 180.0},
"Rigid Foam (low R)": {"k": 0.3, "a": 8.0, "b": 120.0},
}
).T
m = insulate(df, alpha, beta, R0, T)
# %%
# application parameters
alpha = 30 # $ K / W annualized cost per sq meter per W/sq m/K
beta = 0.05 # equivalent annual cost factor
R0 = 2.0 # Watts/K/m**2
T = 0.15 # maximum insulation thickness
df = pd.DataFrame(
{
"Foam": {"k": 0.015, "a": 0.0, "b": 110.0},
"Wool": {"k": 0.010, "a": 0.0, "b": 200.0},
}
).T
m = insulate(df, alpha, beta, R0, T)
# %%
import numpy as np
import matplotlib.pyplot as plt
k = list(df["k"])
a = list(df["a"])
b = list(df["b"])
f = lambda x0, x1: alpha / (R0 + x0 / k[0] + x1 / k[1]) + beta * (
a[0] + b[0] * x0 + a[1] + b[1] * x1
)
x0 = np.linspace(0, 1.1 * T, 201)
x1 = np.linspace(0, 1.1 * T, 201)
X0, X1 = np.meshgrid(x0, x1)
fig, ax = plt.subplots(1, 1)
ax.contour(x0, x1, f(X0, X1), 50)
ax.set_xlim(min(x0), max(x0))
ax.set_ylim(min(x1), max(x1))
ax.plot([0, T], [T, 0], "g", lw=2.5)
ax.set_aspect(1)
x = df["x_opt"].to_list()
ax.plot(x[0], x[1], "r.", ms=20)
ax.text(x[0], x[1], f" ({x[0]:0.4f}, {x[1]:0.4f})")
ax.set_xlabel(r"$x_0$")
ax.set_ylabel(r"$x_1$")
ax.set_title("Contours of Constant Cost")
plt.show()
錐最適化によるサポートベクターマシンの学習 svm-conic.py 15 セル ・ 439 行 ・ モデル 2
この節のモデル(2)
AMPLsvm_conic_primal.mod
param p;
param n;
param c;
param F{1..n, 1..p+1};
# decision variables
var r;
var w{1..p+1};
var z{1..n} >= 0;
# objective
minimize primal:
r + (c / n) * sum {i in 1..n} z[i];
# constraints
s.t. qr:
r >= sum {j in 1..p+1} w[j]^2;
s.t. d{i in 1..n}:
z[i] + sum {j in 1..p+1} F[i, j] * w[j] >= 1;
AMPLsvm_conic_dual.mod
param p;
param n;
param c;
param F{1..n, 1..p+1};
# decision variables
var r;
var a{1..n} >=0 <=c/n;
var z{1..p+1};
# objective
minimize dual:
r - sum {i in 1..n} a[i];
# constraints
s.t. d{j in 1..p+1}:
z[j] == sum {i in 1..n} F[i, j] * a[i];
s.t. q:
r >= sum {j in 1..p+1} z[j]^2;
# %%
# install dependencies and select solver
SOLVER_CONIC = "mosek" # ipopt, mosek, gurobi, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "mosek"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
# read data set
df = pd.read_csv(
"https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/datasets/data_banknote_authentication.txt",
header=None,
)
df.columns = ["variance", "skewness", "curtosis", "entropy", "class"]
df.name = "Banknotes"
# %%
# create training and validation test sets
df_train, df_test = train_test_split(df, test_size=0.2)
# select training features
features = ["variance", "skewness"]
# separate into features and outputs
X_train = df_train[features]
y_train = 1 - 2 * df_train["class"]
# separate into features and outputs
X_test = df_test[features]
y_test = 1 - 2 * df_test["class"]
# %%
def scatter_labeled_data(X, y, labels=["+1", "-1"], colors=["g", "r"], **kwargs):
"""
Creates a scatter plot for labeled data with default labels and colors.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Target vector as a Series.
labels : list, optional
Labels for the positive and negative classes. Default is ["+1", "-1"].
colors : list, optional
Colors for the positive and negative classes. Default is ["g", "r"].
**kwargs : dict
Additional keyword arguments for the scatter plot.
Returns:
None
"""
# Prepend keyword arguments for all scatter plots
kw = {"x": 0, "y": 1, "kind": "scatter", "alpha": 0.4}
kw.update(kwargs)
# Ignore warnings from matplotlib scatter plot
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
kw["ax"] = X[y > 0].plot(**kw, c=colors[0], label=labels[0])
X[y < 0].plot(**kw, c=colors[1], label=labels[1])
# plot training and test sets in two axes
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
scatter_labeled_data(
X_train,
y_train,
labels=["genuine", "counterfeit"],
ax=ax[0],
title="Training Set",
)
scatter_labeled_data(
X_test,
y_test,
labels=["genuine", "counterfeit"],
ax=ax[1],
title="Test Set",
)
def scatter_comparison(X, y, y_pred):
"""
Creates scatter plots comparing actual and predicted outcomes for both training and test sets.
Parameters:
X : DataFrame
Feature matrix as a DataFrame.
y : Series
Actual target vector as a Series.
y_pred : Series
Predicted target vector as a Series.
Returns:
None
"""
xmin, ymin = X.min()
xmax, ymax = X.max()
xlim = [xmin - 0.05 * (xmax - xmin), xmax + 0.05 * (xmax - xmin)]
ylim = [ymin - 0.05 * (ymax - ymin), ymax + 0.05 * (ymax - ymin)]
# Plot training and test sets
labels = ["genuine", "counterfeit"]
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
scatter_labeled_data(
X, y, labels, ["g", "r"], ax=ax[0], xlim=xlim, ylim=ylim, title="Actual"
)
scatter_labeled_data(
X,
y_pred,
labels,
["c", "m"],
ax=ax[1],
xlim=xlim,
ylim=ylim,
title="Prediction",
)
# Plot actual positives and actual negatives
fig, ax = plt.subplots(1, 2, figsize=(10, 4))
scatter_labeled_data(
X[y > 0],
y_pred[y > 0],
["true positive", "false negative"],
["c", "m"],
xlim=xlim,
ylim=ylim,
ax=ax[0],
title="Actual Positives",
)
scatter_labeled_data(
X[y < 0],
y_pred[y < 0],
["false positive", "true negative"],
["c", "m"],
xlim=xlim,
ylim=ylim,
ax=ax[1],
title="Actual Negatives",
)
# %%
def validate(y_true, y_pred, verbose=True):
"""
This function calculates and displays the sensitivity, precision, and Matthews correlation coefficient
(MCC) for a binary classifier based on its true labels (y_true) and predicted labels (y_pred).
Args:
y_true (array-like): A list or array containing the true labels of the samples.
y_pred (array-like): A list or array containing the predicted labels of the samples.
verbose (bool, optional): If True, the function prints and displays the calculated metrics and
confusion matrix. Defaults to True.
Returns:
float: The calculated Matthews correlation coefficient (MCC).
"""
# Calculate the elements of the confusion matrix
true_positives = sum((y_true > 0) & (y_pred > 0))
false_negatives = sum((y_true > 0) & (y_pred < 0))
false_positives = sum((y_true < 0) & (y_pred > 0))
true_negatives = sum((y_true < 0) & (y_pred < 0))
total = true_positives + true_negatives + false_positives + false_negatives
# Calculate the Matthews correlation coefficient (MCC)
mcc_numerator = (true_positives * true_negatives) - (
false_positives * false_negatives
)
mcc_denominator = np.sqrt(
(true_positives + false_positives)
* (true_positives + false_negatives)
* (true_negatives + false_positives)
* (true_negatives + false_negatives)
)
mcc = mcc_numerator / mcc_denominator
if verbose:
print(f"Matthews correlation coefficient (MCC) = {mcc:0.3f}")
# report sensitivity and precision, and accuracy
sensitivity = true_positives / (true_positives + false_negatives)
precision = true_positives / (true_positives + false_positives)
accuracy = (true_positives + true_negatives) / total
print(f"Sensitivity = {100 * sensitivity: 0.1f}%")
print(f"Precision = {100 * precision: 0.1f}%")
print(f"Accuracy = {100 * accuracy: 0.1f}%")
# Display the binary confusion matrix
confusion_matrix = pd.DataFrame(
[
[true_positives, false_negatives],
[false_positives, true_negatives],
],
index=["Actual Positive", "Actual Negative"],
columns=["Predicted Positive", "Predicted Negative"],
)
display(confusion_matrix)
return mcc
# %%
def test(svm, X_test, y_test):
y_pred = svm(X_test)
print(svm, "\n")
validate(y_test, y_pred)
scatter_comparison(X_test, y_test, y_pred)
# %%
import pandas as pd
import numpy as np
# Linear Support Vector Machine (SVM) class
class LinearSVM:
# Initialize the Linear SVM with weights and bias
def __init__(self, w, b):
"""
Args:
w (Pandas Series or dictionary): Weights of the SVM
b (float): Bias of the SVM
"""
self.w = pd.Series(w)
self.b = float(b)
# Call method to compute the decision function
def __call__(self, X):
"""
Args:
X (pandas.DataFrame): Input data
Returns:
numpy.array: Array of decision function values
"""
return np.sign(X.dot(self.w) + self.b)
# Representation method for the Linear SVM class
def __repr__(self):
"""
Returns:
str: String representation of the Linear SVM
"""
return f"LinearSvm(w = {self.w.to_dict()}, b = {self.b})"
# %%
def conicSvmFactory(X, y, c=1):
# create data matrix F
n, p = X.shape
F = np.array(
[y.iloc[i] * np.append(1, X.iloc[i, :].to_numpy()) for i in range(n)]
) # Appending 1's to features
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("svm_conic_primal.mod")
# load the data
ampl.param["p"] = p
ampl.param["n"] = n
ampl.param["c"] = c
ampl.param["F"] = {(i + 1, j + 1): F[i, j] for i in range(n) for j in range(p + 1)}
# solve
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
# return svm
wd = ampl.get_variable("w")
w = wd.to_dict()
b = w[1]
w = pd.Series({k: w[j + 2] for j, k in enumerate(X.columns)})
return LinearSVM(w, b)
svm_v2 = conicSvmFactory(X_train, y_train, c=10)
print(svm_v2.w)
print(svm_v2.b)
# %%
y_pred = svm_v2(X_test)
validate(y_test, y_pred)
scatter_comparison(X_test, y_test, y_pred)
# %%
def conicDualSVMFactory(X, y, c=1):
n, p = X.shape
F = np.array(
[y.iloc[i] * np.append(1, X.iloc[i, :].to_numpy()) for i in range(n)]
) # Appending 1's to features
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("svm_conic_dual.mod")
# load the data
ampl.param["p"] = p
ampl.param["n"] = n
ampl.param["c"] = c
ampl.param["F"] = {(i + 1, j + 1): F[i, j] for i in range(n) for j in range(p + 1)}
# solve
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
# return svm
ad = ampl.get_variable("a")
a = ad.to_dict()
# get the support
S = [i for i in range(n) if (a[i + 1] > 0)]
# create and return linear SVM
w_bar = sum(a[i + 1] * F[i, :] for i in S)
w = pd.Series({k: w_bar[j + 1] for j, k in enumerate(X.columns)})
b = w_bar[0]
y_support = pd.Series([1 if a[i + 1] > 0 else -1 for i in range(n)], index=X.index)
scatter_labeled_data(
X,
y_support,
colors=["b", "y"],
labels=["Support Vector", ""],
title="Support Vectors",
)
return LinearSVM(w, b)
svm_v3 = conicDualSVMFactory(X_train, y_train, c=10)
print(svm_v3.w, svm_v3.b)
# %%
y_pred = svm_v3(X_test)
validate(y_test, y_pred)
scatter_comparison(X_test, y_test, y_pred)
# %%
def kernelSVMFactory(X, y, c, tol=1e-8, kernel=lambda x, z: (x @ z)):
n, p = X.shape
# convert to numpy arrays for speed
X_ = np.hstack([np.ones((n, 1)), X.to_numpy()])
y_ = y.to_numpy()
# kernel matrix
G = [
[y_[i] * y_[j] * kernel(X_[i, :], X_[j, :]) for j in range(n)] for i in range(n)
]
# spectral factors for a positive semi-definite matrix
eigvals, V = np.linalg.eigh(G)
idx = eigvals >= tol * max(eigvals)
F = V[:, idx] @ np.diag(np.sqrt(eigvals[idx]))
q = sum(idx)
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("svm_conic_dual.mod")
# load the data
ampl.param["p"] = q - 1.0
ampl.param["n"] = n
ampl.param["c"] = c
ampl.param["F"] = {(i + 1, j + 1): F[i, j] for i in range(n) for j in range(q)}
# solve
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
# return svm
ad = ampl.get_variable("a")
a = ad.to_dict()
y_support = pd.Series(
[1 if a[i + 1] > 1e-3 * c / n else -1 for i in range(n)], index=X.index
)
scatter_labeled_data(
X,
y_support,
colors=["b", "y"],
labels=["Support Vector", ""],
title="Support Vectors",
)
# get indices of the support vectors
SV = [i for i in range(n) if (a[i + 1] > 1e-3)]
def kernelSVM(Z):
nz, pz = Z.shape
Z_ = np.hstack([np.ones((nz, 1)), Z.to_numpy()])
y_pred = pd.Series(
[
np.sign(sum(a[i + 1] * y_[i] * kernel(X_[i, :], Z_[j, :]) for i in SV))
for j in range(nz)
],
index=Z.index,
)
return y_pred
return kernelSVM
# %%
svm = kernelSVMFactory(X_train, y_train, c=10, kernel=lambda x, z: x @ z)
y_pred = svm(X_test)
validate(y_test, y_pred)
scatter_comparison(X_test, y_test, y_pred)
# %%
rbf = lambda x, z: np.exp(-10 * np.linalg.norm(x - z) ** 2)
svm = kernelSVMFactory(X_train, y_train, c=10, kernel=rbf)
y_pred = svm(X_test)
validate(y_test, y_pred)
scatter_comparison(X_test, y_test, y_pred)
# %%
poly = lambda x, z: (1 + (x @ z)) ** 2
svm = kernelSVMFactory(X_train, y_train, c=10, kernel=poly)
y_pred = svm(X_test)
validate(y_test, y_pred)
scatter_comparison(X_test, y_test, y_pred)
補足:Luenberger の投資ホイール investment-wheel.py 7 セル ・ 173 行 ・ モデル 2
この節のモデル(2)
AMPLwheel.mod
set S;
param p{S};
param b{S};
# decision variables
var w{S} >= 0;
var q{S};
# objective
maximize ElogR: sum {s in S} p[s]*q[s];
# expression for returns
var R{s in S} = 1 + b[s]*w[s] - sum {t in S} w[t];
# constraints
s.t. SumW: sum {s in S} w[s] <= 1;
s.t. Conic{s in S}: R[s] >= exp(q[s]);
AMPLwheel_risk_averse.mod
set S;
param p{S};
param b{S};
param lambd;
# decision variables
var w{S} >= 0;
var q{S};
# objective
maximize ElogR: sum {s in S} p[s]*q[s];
# expression for returns
var R{s in S} = 1 + b[s]*w[s] - sum {t in S} w[t];
# constraints
s.t. SumW: sum {s in S} w[s] <= 1;
s.t. Conic{s in S}: R[s] >= exp(q[s]);
# risk constraints
var u{S};
s.t. SumU: sum {s in S} u[s] <= 1;
s.t. Risk{s in S}: u[s] >= exp(log(p[s]) - lambd*q[s]);
# %%
# install dependencies and select solver
SOLVER_CONIC = "mosek" ## ipopt, mosek, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "mosek"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
# specify the investment wheel
wheel = {
"A": {"p": 1 / 2, "b": 3},
"B": {"p": 1 / 3, "b": 2},
"C": {"p": 1 / 6, "b": 6},
}
# %%
import numpy as np
import matplotlib.pyplot as plt
import bisect
import ipywidgets as widgets
def wheel_sim(w, T, N):
# set of wheel sectors
S = list(wheel.keys())
# odds, probability, and quantiles
b = {s: wheel[s]["b"] for s in S}
p = {s: wheel[s]["p"] for s in S}
q = np.cumsum(list(p.values()))
# gross return for each sector
R = {s: 1 + w[s] * b[s] - sum(w.values()) for s in S}
# set up plot and colors
_, ax = plt.subplots(1, 1, figsize=(8, 3))
colors = {s: ax.semilogy(0, 1, ".", ms=10)[0].get_color() for s in S}
# repeat the simulation N times
for _ in range(N):
wealth = 1.0
for k in range(T):
# spin the wheel
spin = np.random.uniform()
s = S[bisect.bisect_left(q, spin)]
wealth_next = wealth * R[s]
# add to plot
ax.semilogy([k, k + 1], [wealth, wealth_next], c=colors[s], alpha=0.4)
ax.semilogy(k + 1, wealth_next, ".", ms=4, c=colors[s], alpha=0.4)
wealth = wealth_next
# compute expected log return
ElogR = sum(p[s] * np.log(R[s]) for s in S)
ax.plot(np.exp(ElogR * np.linspace(0, T, T + 1)), lw=5, alpha=0.5)
ax.set_title(f"E[log(R)] = {ElogR:0.5f}")
ax.legend([f"$w_{s}$ = {w[s]:0.3f}" for s in S])
ax.set_xlim(0, T)
ax.set_ylim(0.01, 1000.0)
ax.set_ylabel("Wealth")
ax.set_xlabel("Stages")
ax.grid(True)
return ax
wheel_sim({"A": 0.33, "B": 0.33, "C": 0.33}, 40, 20)
@widgets.interact_manual(
wA=widgets.FloatSlider(min=0.0, max=1.0, step=0.01, value=0.333),
wB=widgets.FloatSlider(min=0.0, max=1.0, step=0.01, value=0.333),
wC=widgets.FloatSlider(min=0.0, max=1.0, step=0.01, value=0.333),
)
def wheel_interact1(wA, wB, wC):
w = {"A": wA, "B": wB, "C": wC}
wheel_sim(w, 40, 20)
# %%
def wheel_model(wheel):
ampl = AMPL()
ampl.read("wheel.mod")
ampl.set["S"] = list(wheel.keys())
ampl.param["p"] = {s: wheel[s]["p"] for s in wheel.keys()}
ampl.param["b"] = {s: wheel[s]["b"] for s in wheel.keys()}
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl
m = wheel_model(wheel)
w = m.get_variable("w").to_dict()
print(f"Expected Log Return = {m.get_objective('ElogR').value(): 0.5f}\n")
for s in wheel.keys():
print(
f"Sector {s}: p = {wheel[s]['p']:0.3f} b = {wheel[s]['b']:0.2f} w = {w[s]:0.3f}"
)
wheel_sim(w, 40, 20)
# %%
def wheel_rc_model(wheel, lambd=0):
ampl = AMPL()
ampl.read("wheel_risk_averse.mod")
ampl.set["S"] = list(wheel.keys())
ampl.param["p"] = {s: wheel[s]["p"] for s in wheel.keys()}
ampl.param["b"] = {s: wheel[s]["b"] for s in wheel.keys()}
ampl.param["lambd"] = lambd
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
return (
ampl.get_variable("w").to_dict(),
ampl.get_objective("ElogR").value(),
)
lambd = 2
w, obj = wheel_rc_model(wheel, lambd)
print(f"Risk-aversion lambda = {lambd:0.3f}")
print(f"Expected Log Gross Return = {obj:0.5f}\n")
for s in wheel.keys():
print(
f"Sector {s}: p = {wheel[s]['p']:0.4f} b = {wheel[s]['b']:0.2f} w = {w[s]:0.5f}"
)
wheel_sim(w, 40, 20)
# %%
@widgets.interact_manual(
lambd=widgets.FloatSlider(min=0.0, max=20.0, step=0.1, value=2),
)
def wheel_interact2(lambd):
w, _ = wheel_rc_model(wheel, lambd)
wheel_sim(w, 40, 20)
# %%
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 1, figsize=(10, 4))
v = np.linspace(-1, 5)
lambd = np.exp(v)
results = [wheel_rc_model(wheel, _) for _ in lambd]
ax[0].semilogx(lambd, [np.exp(obj) for _, obj in results])
ax[0].set_title("investment wheel return / spin")
ax[0].grid(True)
ax[1].semilogx(lambd, [[w[s] for s in wheel.keys()] for w, _ in results])
ax[1].set_title("investment weights")
ax[1].set_xlabel("risk aversion $\lambda$")
ax[1].legend(
[f"(p, b) = ({wheel[s]['p']:0.3f}, {wheel[s]['b']:0.1f})" for s in wheel.keys()],
bbox_to_anchor=(1.05, 1.05),
)
ax[1].grid(True)
ax[1].set_ylim(0, 0.6)
fig.tight_layout()
補足:リスク回避を伴う最適成長ポートフォリオ optimal-growth-portfolios.py 13 セル ・ 266 行 ・ モデル 1
この節のモデル(1)
AMPLkelly_portfolio.mod
param Rf;
param EM;
param lambd;
# index lists
set T;
set N;
param Rloc{T, N};
# decision variables
var q{T};
var w{N} >= 0;
# objective
maximize ElogR:
sum {t in T} q[t] / card(T);
# conic constraints on return
var R{t in T}
= Rf + sum {n in N} w[n]*(Rloc[t, n] - Rf);
s.t. C{t in T}:
R[t] >= exp(q[t]);
# risk constraints
var u{T};
s.t. USum:
sum {t in T} u[t] / card(T) <= Rf**(-lambd);
s.t. RT{t in T}:
u[t] >= exp( -lambd*q[t] );
# equity multiplier constraint
s.t. WSum:
sum {n in N} w[n] <= EM;
# %%
# install dependencies and select solver
SOLVER_CONIC = "mosek" # ipopt, mosek, knitro
SOLVER_NLO = "ipopt"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "mosek"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magic
# %%
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime
import yfinance as yf
# symbols as used by Yahoo Finance
symbols = {
# selected indices
"^GSPC": "S&P 500",
"^IXIC": "Nasdaq",
"^DJI": "Dow Jones Industrial",
"^RUT": "Russell 2000",
# selected stocks
"AXP": "American Express",
"AMGN": "Amgen",
"AAPL": "Apple",
"BA": "Boeing",
"CAT": "Caterpillar",
"CVX": "Chevron",
"JPM": "JPMorgan Chase",
"MCD": "McDonald's",
"MMM": "3 M",
"MSFT": "Microsoft",
"PG": "Proctor & Gamble",
"XOM": "ExxonMobil",
}
# years of testing and training data
n_test = 1
n_train = 2
# get today's date
today = datetime.datetime.today().date()
# Fix the day for consistent output and testing
today = datetime.datetime(2023, 6, 6).date()
# training data dates
end = today - datetime.timedelta(int(n_test * 365))
start = end - datetime.timedelta(int((n_test + n_train) * 365))
# get training data
S = yf.download(list(symbols.keys()), start=start, end=end, auto_adjust=True)["Close"]
# compute gross returns
R = S / S.shift(1)
R.dropna(inplace=True)
# %%
# plot
fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
S.divide(S.iloc[0] / 100).plot(ax=ax[0], grid=True, title="Normalized Prices")
ax[0].legend(loc="center left", bbox_to_anchor=(1.0, 0.5), prop={"size": 8})
R.plot(ax=ax[1], grid=True, title="Gross Returns", alpha=0.5).legend([])
fig.tight_layout()
# %%
def kelly_portfolio(R, Rf=1, EM=1, lambd=0):
ampl = AMPL()
ampl.read("kelly_portfolio.mod")
ampl.param["Rf"] = Rf
ampl.param["EM"] = EM
ampl.param["lambd"] = lambd
# index lists
ampl.set["T"] = [str(t) for t in R.index]
ampl.set["N"] = [str(n) for n in R.columns]
ampl.param["Rloc"] = {
(str(t), str(n)): R.at[t, n]
for i, t in enumerate(R.index)
for j, n in enumerate(R.columns)
}
ampl.solve(solver=SOLVER_CONIC)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl
# %%
def kelly_report(ampl):
# print report
s = f"""
Risk Free Return = {100*(np.exp(252*np.log(ampl.get_value('Rf'))) - 1):0.2f}
Equity Multiplier Limit = {ampl.get_value('EM'):0.5f}
Risk Aversion = {ampl.get_value('lambd'):0.5f}
Portfolio
"""
w = ampl.get_variable("w").to_dict()
Rvar = ampl.get_variable("R").to_dict()
s += "\n".join([f"{n:8s} {symbols[n]:30s} {100*w[n]:8.2f} %" for n in w.keys()])
s += f"""
{'':8s} {'Risk Free':30s} {100*(1 - sum(w[n] for n in w.keys())):8.2f} %
Annualized return = {100*(np.exp(252*ampl.get_value('ElogR')) - 1):0.2f} %
"""
print(s)
df = pd.DataFrame(
pd.Series([Rvar[str(t)] for t in R.index]), columns=["Kelly Portfolio"]
)
df.index = R.index ## original index are the DateTimeStamps
fix, ax = plt.subplots(1, 1, figsize=(8, 8))
S.divide(S.iloc[0] / 100).plot(
ax=ax,
logy=True,
grid=True,
title="Normalized Prices",
alpha=0.6,
lw=0.4,
ls="--",
)
df.cumprod().multiply(100).plot(ax=ax, lw=3, grid=True)
ax.legend(
[symbols[n] for n in R.columns] + ["Kelly Portfolio"],
bbox_to_anchor=(1.05, 1.05),
)
d = S.index[-1]
print(d)
for n in w.keys():
y = 100 * S[n].iloc[-1] / S[n].iloc[0]
print(n, 100 * S[n].iloc[-1] / S[n].iloc[0])
ax.text(d, y, n)
# %%
# parameter values
Rf = np.exp(np.log(1.0) / 252)
EM = 1
lambd = 10
m = kelly_portfolio(R, Rf, EM, lambd)
kelly_report(m)
# %%
S.head()
# %%
lambd = 10 ** np.linspace(0, 3)
results = [kelly_portfolio(R, Rf=1, EM=1, lambd=_) for _ in lambd]
# %%
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 1, figsize=(8, 4), sharex=True)
ax[0].semilogx(
[m.get_value("lambd") for m in results],
[100 * (np.exp(252 * m.get_value("ElogR")) - 1) for m in results],
)
ax[0].set_title("Portfolio Return vs Risk Aversion")
ax[0].set_ylabel("annual %")
ax[0].grid(True)
ax[1].semilogx(
[m.get_value("lambd") for m in results],
[
[w[str(n)] for n in R.columns]
for m in results
for w in [m.get_variable("w").to_dict()]
],
)
ax[1].set_ylabel("weights")
ax[1].set_xlabel("risk aversion $\lambda$")
ax[1].legend([symbols[n] for n in R.columns], bbox_to_anchor=(1.05, 1.05))
ax[1].grid(True)
ax[1].set_ylim(0, EM)
fig.tight_layout()
# %%
EM = np.linspace(0.0 + 1e-1, 2.0)
results = [kelly_portfolio(R, Rf=1, EM=_, lambd=10) for _ in EM]
# %%
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 1, figsize=(8, 4), sharex=True)
ax[0].plot(
[m.get_value("EM") for m in results],
[100 * (np.exp(252 * m.get_value("ElogR")) - 1) for m in results],
)
ax[0].set_title("Portfolio Return vs Equity Multiplier")
ax[0].set_ylabel("annual return %")
ax[0].grid(True)
ax[1].plot(
[m.get_value("EM") for m in results],
[
[w[str(n)] for n in R.columns]
for m in results
for w in [m.get_variable("w").to_dict()]
],
)
ax[1].set_ylabel("weights")
ax[1].set_xlabel("Equity Multiplier")
ax[1].legend([symbols[n] for n in R.columns], bbox_to_anchor=(1.05, 1.05))
ax[1].grid(True)
ax[1].set_ylim(
0,
)
fig.tight_layout()
# %%
Rf = np.exp(np.log(1 + np.linspace(0, 0.20)) / 252)
results = [kelly_portfolio(R, Rf=_, EM=1, lambd=10) for _ in Rf]
# %%
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 1, figsize=(8, 4), sharex=True)
Rf = np.exp(252 * np.log(np.array([_.get_value("Rf") for _ in results])))
ax[0].plot(Rf, [100 * (np.exp(252 * m.get_value("ElogR")) - 1) for m in results])
ax[0].set_title("Portfolio Return vs Risk-free Rate")
ax[0].set_ylabel("annual return %")
ax[0].grid(True)
ax[1].plot(
Rf,
[
[w[str(n)] for n in R.columns]
for m in results
for w in [m.get_variable("w").to_dict()]
],
)
ax[1].set_ylabel("weights")
ax[1].set_xlabel("Risk-free Rate")
ax[1].legend([symbols[n] for n in R.columns], bbox_to_anchor=(1.05, 1.05))
ax[1].grid(True)
ax[1].set_ylim(
0,
)
fig.tight_layout()
第7章不確実性の考慮:最適化と現実の出会い2 ファイル▶ 講義動画(19:39)
機材割当問題 fleet-assignment.py 15 セル ・ 257 行 ・ モデル 2
この節のモデル(2)
AMPLfleet_assign.mod
set FLIGHTS;
set PAIRS in {FLIGHTS, FLIGHTS};
var x{PAIRS} binary;
var p{FLIGHTS} binary;
var q{FLIGHTS} binary;
s.t. Sources{f in FLIGHTS}:
p[f] + sum {(f1, f) in PAIRS} x[f1, f] == 1;
s.t. Sinks{f in FLIGHTS}:
q[f] + sum {(f, f2) in PAIRS} x[f, f2] == 1;
minimize Airplanes:
sum {f in FLIGHTS} p[f];
AMPLfleet_assign_minrisk.mod
set FLIGHTS;
set PAIRS in {FLIGHTS, FLIGHTS};
param N_planes;
param weight{PAIRS};
var x{PAIRS} binary;
var p{FLIGHTS} binary;
var q{FLIGHTS} binary;
s.t. Sources{f in FLIGHTS}:
p[f] + sum {(f1, f) in PAIRS} x[f1, f] == 1;
s.t. Sinks{f in FLIGHTS}:
q[f] + sum {(f, f2) in PAIRS} x[f, f2] == 1;
s.t. MinAirplanes:
sum {f in FLIGHTS} p[f] <= N_planes;
minimize Risk:
sum {(f1, f2) in PAIRS} weight[f1, f2] * x[f1, f2];
# %%
# install dependencies and select solver
SOLVER = "highs" # highs, scip, cbc, mosek, gurobi, cplex, xpress, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from numpy.random import RandomState
# python generator creates departure and arrival times for a single airport
def generate_flights(
N_flights=30, min_duration=1, max_duration=4, max_departure=24, seed=0
):
rs = RandomState(seed)
for flight in range(N_flights):
end_flight = max_departure + 1
while end_flight > max_departure:
start_flight = np.floor(max_departure * rs.rand())
end_flight = start_flight + 3 * np.ceil(
(max_duration + 1 - min_duration) * rs.rand()
)
yield flight + 1, int(start_flight), int(end_flight)
# generate flight data
FlightData = pd.DataFrame(
[[flight, departure, arrival] for flight, departure, arrival in generate_flights()]
)
FlightData.columns = ["Flight", "Departure", "Arrival"]
FlightData.set_index("Flight", inplace=True)
FlightData.head()
# %%
# visualize flight data
def draw_flights(FlightData):
bar_style = {"alpha": 1.0, "lw": 10, "solid_capstyle": "butt"}
text_style = {
"fontsize": 7,
"color": "white",
"weight": "bold",
"ha": "center",
"va": "center",
}
fig = plt.figure(figsize=(12, 7))
ax = fig.add_subplot(111, xlabel="Departure/Arrival Time", title="Flight schedule")
ax.get_yaxis().set_visible(False)
for flight, row in FlightData.iterrows():
departure, arrival = row
ax.plot([departure, arrival], [flight] * 2, "gray", **bar_style)
ax.text((departure + arrival) / 2, flight, f"Flight {flight}", **text_style)
for hr in range(25):
ax.axvline(hr, alpha=0.1)
ax.set_xlim(-1, 25)
ax.set_xticks([4 * i for i in range(7)])
return ax
ax = draw_flights(FlightData)
# %%
min_time = 1
def feasible_flight_pairs(FlightData, min_time=1):
# return a dictionary of turnaound times index by flight pairs
turnaround = (
lambda pair: FlightData.loc[pair[1], "Departure"]
- FlightData.loc[pair[0], "Arrival"]
)
pairs = filter(
lambda pair: turnaround(pair) >= min_time,
[(i, j) for i in FlightData.index for j in FlightData.index if i != j],
)
return {pair: turnaround(pair) for pair in pairs}
flight_pairs = feasible_flight_pairs(FlightData).keys()
# %%
import networkx as nx
dg = nx.DiGraph()
for flight in FlightData.index:
dg.add_node(flight)
for pair, dur in feasible_flight_pairs(FlightData).items():
dg.add_edge(pair[0], pair[1], color="r" if dur <= min_time else "g")
size = int(1.5 * np.sqrt(len(FlightData)))
fig = plt.figure(figsize=(size, size))
pos = nx.circular_layout(dg)
nx.draw_networkx_nodes(dg, pos=pos, node_size=500, alpha=0.8)
nx.draw_networkx_labels(dg, pos=pos, font_color="w")
nx.draw_networkx_edges(
dg, pos=pos, width=0.5, edge_color=[dg.edges[u, v]["color"] for u, v in dg.edges]
)
# %%
in_nodes = {flight: set() for flight in FlightData.index}
out_nodes = {flight: set() for flight in FlightData.index}
for flight1, flight2 in flight_pairs:
in_nodes[flight2].add(flight1)
out_nodes[flight1].add(flight2)
# %%
ampl = AMPL()
ampl.read("fleet_assign.mod")
ampl.set["FLIGHTS"] = list(FlightData.index)
ampl.set["PAIRS"] = list(flight_pairs)
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
print(f"Minimum airplanes required = {ampl.get_value('Airplanes')}")
x = ampl.get_variable("x").to_dict()
p = ampl.get_variable("p").to_dict()
q = ampl.get_variable("q").to_dict()
# %%
import networkx as nx
dg_soln = nx.DiGraph()
for flight in FlightData.index:
dg_soln.add_node(flight)
for pair, dur in feasible_flight_pairs(FlightData).items():
if x[pair[0], pair[1]] > 0.5:
dg_soln.add_edge(pair[0], pair[1], color="r" if dur <= min_time else "g")
size = int(1.5 * np.sqrt(len(FlightData)))
fig = plt.figure(figsize=(size, size))
nx.draw_networkx_nodes(dg_soln, pos=pos, node_size=500, alpha=0.8)
nx.draw_networkx_labels(dg_soln, pos=pos, font_color="w")
nx.draw_networkx_edges(
dg_soln,
pos=pos,
width=3,
edge_color=[dg_soln.edges[u, v]["color"] for u, v in dg_soln.edges],
)
nx.draw_networkx_edges(
dg, pos=pos, width=0.5, edge_color=[dg.edges[u, v]["color"] for u, v in dg.edges]
)
nx.draw_networkx_edges(
dg_soln,
pos=pos,
width=3,
edge_color=[dg_soln.edges[u, v]["color"] for u, v in dg_soln.edges],
)
# %%
ax = draw_flights(FlightData)
for flight1, flight2 in flight_pairs:
if x[flight1, flight2] > 0.5:
arr = FlightData.loc[flight1, "Arrival"]
dep = FlightData.loc[flight2, "Departure"]
c = "r" if dep - arr <= min_time else "g"
ax.plot([arr, dep], [flight1, flight2], color=c, lw=4, alpha=0.4)
for flight in FlightData.index:
if p[flight] > 0.5:
dep = FlightData.loc[flight, "Departure"]
ax.plot([-1, dep], [flight] * 2, "g", lw=4, alpha=0.4)
if q[flight] > 0.5:
arr = FlightData.loc[flight, "Arrival"]
ax.plot([arr, 25], [flight] * 2, "g", lw=4, alpha=0.4)
# %%
FlightSchedule = FlightData.copy()
# create a generator of aircraft ids
aircraft = (f"A{n+1:02d}" for n in range(len(FlightData.index)))
# traverse each path through the graph
for f in FlightData.index:
if p[f] > 0.5:
id = next(aircraft)
FlightSchedule.loc[f, "Aircraft"] = id
while q[f] < 0.5:
f = next(filter(lambda _: x[f, _] > 0.5, out_nodes[f]))
FlightSchedule.loc[f, "Aircraft"] = id
FlightSchedule = FlightSchedule[["Aircraft", "Departure", "Arrival"]]
display(FlightSchedule)
# %%
AircraftSchedule = FlightSchedule.copy()
AircraftSchedule["Flight"] = AircraftSchedule.index
AircraftSchedule = AircraftSchedule.sort_values(["Aircraft", "Departure"])
AircraftSchedule.index = pd.MultiIndex.from_frame(
AircraftSchedule[["Aircraft", "Flight"]]
)
AircraftSchedule = AircraftSchedule[["Departure", "Arrival"]]
display(AircraftSchedule)
# %%
def schedule(FlightData, N_planes, min_time=1):
pairs = feasible_flight_pairs(FlightData, min_time)
weights = {pair: int(pairs[pair] <= min_time) for pair in pairs}
ampl = AMPL()
ampl.read("fleet_assign_minrisk.mod")
ampl.set["FLIGHTS"] = list(FlightData.index)
ampl.set["PAIRS"] = list(pairs.keys())
ampl.param["N_planes"] = N_planes
ampl.param["weight"] = weights
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
x = ampl.get_variable("x").to_dict()
p = ampl.get_variable("p").to_dict()
q = ampl.get_variable("q").to_dict()
ax = draw_flights(FlightData)
for flight1, flight2 in pairs.keys():
if x[flight1, flight2] > 0.5:
arr = FlightData.loc[flight1, "Arrival"]
dep = FlightData.loc[flight2, "Departure"]
c = "r" if dep - arr <= min_time else "g"
ax.plot([arr, dep], [flight1, flight2], color=c, lw=4, alpha=0.4)
for flight in FlightData.index:
if p[flight] > 0.5:
dep = FlightData.loc[flight, "Departure"]
ax.plot([-1, dep], [flight] * 2, "g", lw=4, alpha=0.4)
if q[flight] > 0.5:
arr = FlightData.loc[flight, "Arrival"]
ax.plot([arr, 25], [flight] * 2, "g", lw=4, alpha=0.4)
return ampl
# %%
m = schedule(FlightData, N_planes=14, min_time=1)
# %%
m = schedule(FlightData, N_planes=15, min_time=1)
# %%
m = schedule(FlightData, N_planes=15, min_time=2)
シミュレーションによるBIM生産計画のロバスト性分析 bim-robustness-analysis.py 7 セル ・ 275 行 ・ モデル 2
この節のモデル(2)
AMPLproduct_inventory.mod
set PERIODS;
set PRODUCTS;
param first symbolic;
param prev_period{PERIODS} symbolic;
param last symbolic;
param stock_limit;
param month_budget;
param pi{PERIODS, PRODUCTS}; # acquisition price
param h{PERIODS, PRODUCTS}; # holding cost
param delta{PERIODS, PRODUCTS}; # demand
param existing{PRODUCTS};
param desired{PRODUCTS};
var x{PERIODS, PRODUCTS} >= 0;
var s{PERIODS, PRODUCTS} >= 0;
var acquisition_cost
= sum {t in PERIODS, p in PRODUCTS} pi[t,p] * x[t,p];
var inventory_cost
= sum {t in PERIODS, p in PRODUCTS} h[t,p] * s[t,p];
minimize TotalCost: acquisition_cost + inventory_cost;
s.t. Balance{t in PERIODS, p in PRODUCTS}:
(if t==first then existing[p] else s[prev_period[t],p])
+ x[t,p] == delta[t,p] + s[t,p];
s.t. Finish{p in PRODUCTS}:
s[last,p] >= desired[p];
s.t. Inventory{t in PERIODS}:
sum {p in PRODUCTS} s[t,p] <= stock_limit;
s.t. Budget{t in PERIODS}:
sum {p in PRODUCTS} pi[t,p]*x[t,p] <= month_budget;
AMPLproduct_demand_missed_in_period.mod
set PRODUCTS;
set MATERIALS;
param avail{MATERIALS};
param use{MATERIALS, PRODUCTS};
param demand_chips{PRODUCTS};
# Decision variable: nb of chips to produce >= 0
var x{PRODUCTS} >= 0;
# Decision variable: missed demand
var s{PRODUCTS} >= 0;
# Constraint: per resource we cannot use more than there is
s.t. ResourceConstraint{i in MATERIALS}:
sum {p in PRODUCTS} x[p] * use[i, p] <= avail[i];
# Constraint: production + missed demand = total demand in this period
s.t. ProducedPlusUnmet{p in PRODUCTS}:
x[p] + s[p] == demand_chips[p];
# Objective - minimize the missed demand
minimize TotalUnmet:
sum {p in PRODUCTS} s[p];
# %%
# install dependencies and select solver
SOLVER = "cbc" # highs, scip, cbc, mosek, gurobi, cplex, xpress, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
from io import StringIO
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({"font.size": 14})
demand_data = """
chip, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
logic, 88, 125, 260, 217, 238, 286, 248, 238, 265, 293, 259, 244
memory, 47, 62, 81, 65, 95, 118, 86, 89, 82, 82, 84, 66
"""
demand_chips = pd.read_csv(StringIO(demand_data), index_col="chip")
display(demand_chips)
price_data = """
product, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
copper, 1, 1, 1, 2, 2, 3, 3, 2, 2, 1, 1, 2
silicon, 4, 3, 3, 3, 5, 5, 6, 5, 4, 3, 3, 5
germanium, 5, 5, 5, 3, 3, 3, 3, 2, 3, 4, 5, 6
plastic, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1
"""
price = pd.read_csv(StringIO(price_data), index_col="product")
display(price)
use = dict()
use["logic"] = {"silicon": 1, "plastic": 1, "copper": 4}
use["memory"] = {"germanium": 1, "plastic": 1, "copper": 2}
use = pd.DataFrame.from_dict(use).fillna(0).astype(int)
material_demand = use.dot(demand_chips)
existing = pd.Series(
{"silicon": 1000, "germanium": 1500, "plastic": 1750, "copper": 4800}
)
eot_inventory = pd.Series(
{"silicon": 500, "germanium": 500, "plastic": 1000, "copper": 2000}
)
# %%
# we store all the problem data in one object to easily perform folding-horizon simulations
def initialize_problem_data():
problem_data = {
"price": price.copy(deep=True),
"inventory_cost": 0.05,
"material_demand": material_demand.copy(deep=True),
"demand_chips_ref": demand_chips.copy(deep=True),
"demand_chips_simulation": demand_chips.copy(deep=True),
"use": use.copy(deep=True),
"existing": existing.copy(deep=True),
"eot_inventory": eot_inventory.copy(deep=True),
"stock_limit": 9000,
"month_budget": 2500,
}
return problem_data
def ShowTable(X, I, J):
return pd.DataFrame.from_records(
[[X[i, j] for j in J] for i in I], index=I, columns=J
).round(decimals=2)
# %%
def BIMProductAcquisitionAndInventory(problem_data):
demand = problem_data["use"].dot(problem_data["demand_chips_ref"])
acquisition_price = problem_data["price"]
existing = problem_data["existing"]
desired = problem_data["eot_inventory"]
stock_limit = problem_data["stock_limit"]
month_budget = problem_data["month_budget"]
ampl = AMPL()
ampl.read("product_inventory.mod")
periods = list(demand.columns)
products = list(demand.index)
ampl.set["PERIODS"] = periods
ampl.set["PRODUCTS"] = products
ampl.param["first"] = periods[0]
ampl.param["prev_period"] = {j: i for i, j in zip(periods, periods[1:])}
ampl.param["last"] = periods[-1]
ampl.param["stock_limit"] = stock_limit
ampl.param["month_budget"] = month_budget
ampl.param["pi"] = acquisition_price.T
ampl.param["h"] = {(t, p): 0.05 for p in products for t in periods}
ampl.param["delta"] = demand.T
ampl.param["existing"] = existing
ampl.param["desired"] = desired
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl, products, periods
problem_data = initialize_problem_data()
m, products, periods = BIMProductAcquisitionAndInventory(problem_data)
print(f"The optimal solution yields a total cost of {m.get_value('TotalCost'):.2f}\n")
x = m.get_variable("x").to_dict()
# x.index = pd.MultiIndex.from_tuples(x.index)
problem_data["purchases"] = ShowTable(x, periods, products).T
s = m.get_variable("s").to_dict()
problem_data["stock"] = ShowTable(s, periods, products).T
display(problem_data["purchases"])
display(problem_data["stock"])
# %%
def minimize_missed_demand_in_period(
inventory, missed_demand, purchases, existing, demand_chips, use, period=None
):
periods = inventory.columns
first = periods[0]
prev = {j: i for i, j in zip(periods, periods[1:])}
last = periods[-1]
ampl = AMPL()
ampl.read("product_demand_missed_in_period.mod")
products = list(use.columns)
materials = list(use.index)
ampl.set["PRODUCTS"] = products
ampl.set["MATERIALS"] = materials
ampl.param["avail"] = {
i: inventory.loc[i, prev[period]] + purchases.loc[i, period] for i in materials
}
ampl.param["use"] = {(i, p): use.at[i, p] for i in materials for p in products}
ampl.param["demand_chips"] = demand_chips.loc[:, period]
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
x = ampl.get_variable("x").to_dict()
s = ampl.get_variable("s").to_dict()
# update inventory
for i in materials:
inventory.loc[i, period] = (
inventory.loc[i, prev[period]]
+ purchases.loc[i, period]
- sum([x[p] * use.loc[i, p] for p in products])
)
# update missed demand
for p in products:
missed_demand.loc[p, period] = s[p]
return 0
def simulation_per_trajectory(purchases, existing, demand_chips, use):
# Set up the table to store inventory evolution
inventory = pd.DataFrame(index=purchases.index, columns=purchases.columns)
inventory = pd.concat(
[pd.DataFrame(existing, index=existing.index, columns=["existing"]), inventory],
axis=1,
)
# Set up the DF to store missed demand information
missed_demand = pd.DataFrame(
np.zeros((len(demand_chips.index), len(purchases.columns))),
index=demand_chips.index,
columns=purchases.columns,
)
# Proper simulation
for period in inventory.columns[1:]:
minimize_missed_demand_in_period(
inventory, missed_demand, purchases, existing, demand_chips, use, period
)
return inventory.iloc[:, 1:], missed_demand
def simulate_performance(problem_data, n=50, rho=0.05, seed=0):
rng = np.random.default_rng(seed)
results = []
for i in range(n):
perturbed_demand = problem_data["demand_chips_simulation"].applymap(
lambda x: x * (1 + rho * (1 - 2 * rng.random()))
)
inv, md = simulation_per_trajectory(
problem_data["purchases"], problem_data["existing"], perturbed_demand, use
)
results.append({"inventory": inv, "missing_demand": md})
MissingDemand = pd.concat(
[i["missing_demand"] for i in results], keys=[i for i in range(len(results))]
)
MissingDemand = MissingDemand.astype("float").swaplevel()
InventoryEvolution = pd.concat(
[i["inventory"] for i in results], keys=[i for i in range(len(results))]
)
InventoryEvolution = InventoryEvolution.astype("float").swaplevel()
return {"MissingDemand": MissingDemand, "InventoryEvolution": InventoryEvolution}
def report(MissingDemand, InventoryEvolution, problem_data):
# list to store DFs with per-group computed quantiles at various levels
average_missed_demand = MissingDemand.groupby(level=0).mean().transpose()
# build a plot with as many subplots as there are chip types
fig, axis = plt.subplots(figsize=(11, 4))
average_missed_demand.plot(ax=axis, drawstyle="steps-mid", grid=True)
plt.xticks(
ticks=np.arange(len(average_missed_demand.index)),
labels=average_missed_demand.index,
)
# axis.set_title("Missed demand of chips under " + str(rho * 100) + "% uncertainty")
fig.tight_layout(pad=3.0)
plt.savefig("bim_robust_missed_demand.pdf")
realized_inv_cost = (
InventoryEvolution.groupby(level=0).mean().sum(axis=1).sum()
* problem_data["inventory_cost"]
)
print(
f'Purchasing cost: {(problem_data["price"] * problem_data["purchases"]).sum().sum():.2f}'
)
print(
f'Theoretical inventory cost: {(problem_data["stock"] * problem_data["inventory_cost"]).sum().sum():.2f}\n'
)
print(f"Simulated realized inventory cost: {realized_inv_cost:.2f}")
print(
f"Simulated average missed demand for logic chips is {MissingDemand.groupby(level = 0).mean().sum(axis = 1)[0]:.3f} and for memory chips is {MissingDemand.groupby(level = 0).mean().sum(axis = 1)[1]:.3f}\n"
)
print(
"Plot of missed chips demand over time under "
+ str(rho * 100)
+ "% uncertainty\n"
)
plt.show()
# %%
rho = 0.08
N_sim = 50
problem_data["demand_chips_ref"] = demand_chips
m, products, periods = BIMProductAcquisitionAndInventory(problem_data)
x = m.get_variable("x").to_dict()
problem_data["purchases"] = ShowTable(x, periods, products).T
s = m.get_variable("s").to_dict()
problem_data["stock"] = ShowTable(s, periods, products).T
SimResults = simulate_performance(problem_data, N_sim, rho)
# %%
report(SimResults["MissingDemand"], SimResults["InventoryEvolution"], problem_data)
第8章ロバスト最適化:単一段階問題1 ファイル▶ 講義動画(19:50)
ロバスト最適化によるBIMモデル(基数制約付き・球型不確実性集合を含む) bim-robust-optimization.py 19 セル ・ 321 行 ・ モデル 5
この節のモデル(5)
AMPLBIM_robust_box.mod
set CHIPS;
param profits{CHIPS};
param copper{CHIPS};
var x{CHIPS} >= 0, integer;
maximize Profit: sum {c in CHIPS} profits[c] * x[c];
s.t. Silicon: x['logic'] <= 1000;
s.t. Germanium: x['memory'] <= 1500;
s.t. Plastic: sum {c in CHIPS} x[c] <= 1750;
param lower{CHIPS};
param upper{CHIPS};
var y{CHIPS} >= 0;
var w{CHIPS} >= 0;
s.t. RobustCopper:
sum {c in CHIPS} (upper[c]*y[c] - lower[c]*w[c]) <= 4800;
s.t. PerVariable{c in CHIPS}:
x[c] == y[c] - w[c];
AMPLBIM_robust_cardinality.mod
set CHIPS;
param profits{CHIPS};
param copper{CHIPS};
var x{CHIPS} >= 0, integer;
maximize Profit: sum {c in CHIPS} profits[c] * x[c];
s.t. Silicon: x['logic'] <= 1000;
s.t. Germanium: x['memory'] <= 1500;
s.t. Plastic: sum {c in CHIPS} x[c] <= 1750;
param Gamma;
param delta;
var t{CHIPS} >= 0;
var lam >= 0;
s.t. RobustCopper:
sum {c in CHIPS} copper[c] * x[c]
+ Gamma * lam
+ sum {c in CHIPS} t[c]
<= 4800;
s.t. UpRule{c in CHIPS}:
t[c] >= delta * x[c] - lam;
s.t. DownRule{c in CHIPS}:
t[c] >= -delta * x[c] - lam;
AMPLBIM_robust_cardinality_adversarial.mod
set CHIPS;
param profits{CHIPS};
param copper{CHIPS};
var x{CHIPS} >= 0;
maximize Profit: sum {c in CHIPS} profits[c] * x[c];
s.t. Silicon: x['logic'] <= 1000;
s.t. Germanium: x['memory'] <= 1500;
s.t. Plastic: sum {c in CHIPS} x[c] <= 1750;
set CUTS;
param Z{CUTS, CHIPS};
s.t. Balance{i in CUTS}:
sum {c in CHIPS}
copper[c] * x[c] * (1 + Z[i, c]) <= 4800;
AMPLBIM_robust_cardinality_pessimizer.mod
set CHIPS;
param copper{CHIPS};
var z{CHIPS};
var u{CHIPS} >= 0;
s.t. AbsValue1{i in CHIPS}:
z[i] <= u[i];
s.t. AbsValue2{i in CHIPS}:
-z[i] <= u[i];
s.t. AbsValueLE1{i in CHIPS}:
u[i] <= 1.0;
param x{CHIPS};
param Gamma;
param delta;
s.t. Budget:
sum {i in CHIPS} u[i] <= Gamma;
maximize Violation:
-4800
+ sum {c in CHIPS}
copper[c] * x[c] * (1 + delta * z[c]);
AMPLBIM_robust_ball.mod
set CHIPS;
param profits{CHIPS};
param copper{CHIPS};
var x{CHIPS} >= 0;
maximize Profit: sum {c in CHIPS} profits[c] * x[c];
s.t. Silicon: x['logic'] <= 1000;
s.t. Germanium: x['memory'] <= 1500;
s.t. Plastic: sum {c in CHIPS} x[c] <= 1750;
param radius;
var y >= 0;
var w{CHIPS} >= 0;
s.t. Copper:
y == 4800 - sum {c in CHIPS} copper[c] * x[c];
s.t. X2W{i in CHIPS}:
w[i] == radius * x[i];
s.t. Robust:
y^2 >= sum {c in CHIPS} w[c]^2;
# %%
# install dependencies and select solver
SOLVER_MILP = "highs" # highs, scip, cbc, mosek, gurobi
SOLVER_NLO = "ipopt"
SOLVER_MINLO = "bonmin" # mosek, scip, gurobi, knitro
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["coin", "highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register notebook magics
# %%
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# %%
ampl.eval(r"""
set CHIPS;
param profits{CHIPS};
param copper{CHIPS};
var x{CHIPS} >= 0;
maximize Profit: sum {c in CHIPS} profits[c] * x[c];
s.t. Silicon: x['logic'] <= 1000;
s.t. Germanium: x['memory'] <= 1500;
s.t. Plastic: sum {c in CHIPS} x[c] <= 1750;
s.t. Copper: sum {c in CHIPS} copper[c] * x[c] <= 4800;
""")
# %%
chips = ["logic", "memory"]
profits = {"logic": 12, "memory": 9}
copper = {"logic": 4, "memory": 2}
ampl.set["CHIPS"] = chips
ampl.param["profits"] = profits
ampl.param["copper"] = copper
ampl.option["solver"] = SOLVER_MILP
ampl.solve()
x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
# %%
def ShowDuals(ampl):
import fractions
# display all duals
print("The dual variable corresponding to:\n")
for name, con in ampl.get_constraints():
print(
"- the constraint on",
name,
"is equal to ",
str(fractions.Fraction(con.dual())),
)
ShowDuals(ampl)
# %%
plt.rcParams.update({"font.size": 12})
seed = 0
rng = np.random.default_rng(seed)
n = 2000
f = rng.lognormal(np.log(4.0), 0.005, n)
g = rng.lognormal(np.log(2.0), 0.005, n)
plt.figure()
plt.plot(f, g, ".")
plt.xlabel("Copper gr needed for logic chips")
plt.ylabel("Copper gr needed for memory chips")
plt.show()
# %%
plt.figure()
plt.plot(f, g, ".")
currentAxis = plt.gca()
currentAxis.add_patch(
patches.Rectangle(
(min(f), min(g)),
max(f) - min(f),
max(g) - min(g),
fill=False,
color="r",
)
)
plt.xlabel("Copper gr needed for logic chips")
plt.ylabel("Copper gr needed for memory chips")
plt.show()
# calculate the upper and lower bounds for each uncertain parameter
lower = {"logic": min(f), "memory": min(g)}
upper = {"logic": max(f), "memory": max(g)}
print("Lower bounds", lower)
print("Upper bounds", upper)
# %%
def BIMWithBoxUncertainty(lower, upper, int_x=False):
ampl = AMPL()
ampl.read("BIM_robust_box.mod")
ampl.set["CHIPS"] = chips
ampl.param["profits"] = profits
ampl.param["copper"] = copper
ampl.param["lower"] = lower
ampl.param["upper"] = upper
if not int_x:
ampl.eval("let {i in CHIPS} x[i].relax := 1;")
ampl.solve(solver=SOLVER_MILP)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl
ampl = BIMWithBoxUncertainty(lower, upper)
x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
# %%
# The parameter delta allows you to tune the amount of uncertainty.
# In particular, if you take delta=0, you obtain the same result as the nominal model.
delta = 0.05
def BIMWithSymmetricalBoxUncertainty(delta, int_x=False):
lower = {chip: copper[chip] - delta for chip in chips}
upper = {chip: copper[chip] + delta for chip in chips}
return BIMWithBoxUncertainty(lower, upper, int_x)
ampl = BIMWithSymmetricalBoxUncertainty(delta)
x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
# %%
ampl = BIMWithBoxUncertainty(lower, upper, True)
x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
# %%
import pandas as pd
df = pd.DataFrame()
for delta in np.linspace(0, 0.5, 21):
ampl = BIMWithSymmetricalBoxUncertainty(delta, True)
x = ampl.get_variable("x").to_dict()
results = [ampl.get_value("Profit")] + [x[str(i)] for i in chips]
df.at[delta, "profit"] = results[0]
df.at[delta, chips[0]] = results[1]
df.at[delta, chips[1]] = results[2]
df
# %%
df[["profit"]].plot()
plt.ylim([16001, 17999])
plt.xlabel("Margin $\delta$ of the uncertainty box")
plt.ylabel("Profit")
plt.show()
df[["logic", "memory"]].plot()
plt.xlabel("Margin $\delta$ of the uncertainty box")
plt.ylabel("Optimal number of produced chips")
plt.show()
# %%
def BIMWithBudgetUncertainty(delta, gamma):
ampl = AMPL()
ampl.read("BIM_robust_cardinality.mod")
ampl.set["CHIPS"] = chips
ampl.param["profits"] = profits
ampl.param["copper"] = copper
ampl.param["delta"] = delta
ampl.param["Gamma"] = gamma
ampl.option["solver"] = SOLVER_MILP
ampl.solve()
return ampl
ampl = BIMWithBudgetUncertainty(0.01, 2)
x = ampl.get_variable("x").to_dict()
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
# %%
def BIMWithSetOfScenarios(Z=[{"logic": 0, "memory": 0}]):
ampl = AMPL()
ampl.read("BIM_robust_cardinality_adversarial.mod")
ampl.set["CHIPS"] = chips
ampl.param["profits"] = profits
ampl.param["copper"] = copper
dfZ = pd.DataFrame(Z)
ampl.set["CUTS"] = list(dfZ.index)
ampl.param["Z"] = dfZ.T.unstack(1)
ampl.option["solver"] = SOLVER_MILP
ampl.solve()
return ampl
# %%
def BIMPessimization(x, delta, gamma):
ampl = AMPL()
ampl.read("BIM_robust_cardinality_pessimizer.mod")
ampl.set["CHIPS"] = chips
ampl.param["copper"] = copper
ampl.param["x"] = x
ampl.param["Gamma"] = gamma
ampl.param["delta"] = delta
ampl.option["solver"] = SOLVER_MILP
ampl.solve()
worst_z = ampl.get_variable("z").to_dict()
return worst_z, ampl.get_value("Violation")
# %%
# Parameters
adversarial_converged = False
stopping_precision = 0.1
max_iterations = 5
adversarial_iterations = 0
delta = 0.2
gamma = 1.5
chips = ["logic", "memory"]
# Initialize the null scenario - no perturbation
Z = [{"logic": 0, "memory": 0}]
while (not adversarial_converged) and (adversarial_iterations < max_iterations):
# Building and solving the master problem
ampl = BIMWithSetOfScenarios(Z)
# Saving the current solution
x = ampl.get_variable("x").to_dict()
print(f"\nIteration #{adversarial_iterations}")
print(f"Current solution: ")
for c in chips:
print(f"x['{c}']= {x[c]:.2f}")
# Pessimization
worst_z, constraint_violation = BIMPessimization(x, delta, gamma)
# If pessimization yields no violation, stop the procedure, otherwise add a scenario and repeat
if constraint_violation < stopping_precision:
print("No violation found. Stopping the procedure.")
adversarial_converged = True
else:
print(
f"Violation found: z['logic'] = {worst_z['logic']}, z['memory'] = {worst_z['memory']}, "
f"constraint violation: {constraint_violation:6.2f}"
)
Z.append(worst_z)
adversarial_iterations += 1
# %%
def BIMWithBallUncertainty(radius, SOLVER, int_x=False):
ampl = AMPL()
ampl.read("BIM_robust_ball.mod")
if int_x:
ampl.eval("redeclare var x{CHIPS} >= 0, integer;")
ampl.set["CHIPS"] = chips
ampl.param["profits"] = profits
ampl.param["copper"] = copper
ampl.param["radius"] = radius
ampl.option["solver"] = SOLVER
ampl.solve()
return ampl
# %%
radius = 0.05
ampl = BIMWithBallUncertainty(radius, SOLVER_NLO)
x = ampl.get_variable("x").to_dict()
print(f"Solver: {SOLVER_NLO}, solver status:", ampl.solve_result)
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
# %%
ampl = BIMWithBallUncertainty(radius, SOLVER_MINLO, True)
x = ampl.get_variable("x").to_dict()
print(f"Solver: {SOLVER_MINLO}, solver status:", ampl.solve_result)
print(f"x = ({x})")
print(f'optimal value = {ampl.obj["Profit"].value():.2f}')
第9章確率的最適化:単一段階問題4 ファイル▶ 講義動画(21:22)
ポップアップショップ pop-up_shop.py 6 セル ・ 119 行 ・ モデル 2
この節のモデル(2)
AMPLpop.mod
param r;
param c;
param w;
# set of scenarios
set S;
param p{S};
param d{S};
# decision variables
var x >= 0;
var y{S} >= 0;
var f{S};
# objective
maximize EV: sum{s in S} p[s] * f[s];
# constraints
s.t. profit {s in S}: f[s] == r * y[s] + w * (x - y[s]) - c * x;
s.t. sales_less_than_order {s in S}: y[s] <= x;
s.t. sales_less_than_demand {s in S}: y[s] <= d[s];
AMPLpop_evpi.mod
param r;
param c;
param w;
# set of scenarios
set S;
param p{S};
param d{S};
# decision variables
var x{S} >= 0;
var y{S} >= 0;
var f{S};
# objective
maximize EV: sum{s in S} p[s] * f[s];
# constraints
s.t. profit {s in S}: f[s] == r * y[s] + w * (x[s] - y[s]) - c * x[s];
s.t. sales_less_than_order {s in S}: y[s] <= x[s];
s.t. sales_less_than_demand {s in S}: y[s] <= d[s];
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import pandas as pd
# %%
# price information
r = 40
c = 12
w = 2
# scenario information
scenarios = {
"sunny skies": {"probability": 0.10, "demand": 650},
"good weather": {"probability": 0.60, "demand": 400},
"poor weather": {"probability": 0.30, "demand": 200},
}
df = pd.DataFrame.from_dict(scenarios).T
display(df)
expected_demand = sum(df["probability"] * df["demand"])
print(f"Expected demand = {expected_demand}")
# %%
df["order"] = expected_demand
df["sold"] = df[["demand", "order"]].min(axis=1)
df["salvage"] = df["order"] - df["sold"]
df["profit"] = r * df["sold"] + w * df["salvage"] - c * df["order"]
EVM = sum(df["probability"] * df["profit"])
display(df)
print(f"Expected value of the mean demand (EVM) = {EVM}")
# %%
# price and scenario information
r = 40
c = 12
w = 2
scenarios = {
"sunny skies": {"demand": 650, "probability": 0.1},
"good weather": {"demand": 400, "probability": 0.6},
"poor weather": {"demand": 200, "probability": 0.3},
}
# create a data frame with the data and rename the columns to match the model
scenarios_df = pd.DataFrame.from_dict(scenarios).T.rename(
columns={"demand": "d", "probability": "p"}
)
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("pop.mod")
# load the data
ampl.param["r"] = r
ampl.param["c"] = c
ampl.param["w"] = w
ampl.set_data(scenarios_df, "S")
# solve the problem
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
print("Solver Termination Condition:", ampl.solve_result)
print()
# display solution using Pandas
df = pd.DataFrame.from_dict(scenarios).T
df["order"] = ampl.var["x"].value()
df["sold"] = ampl.var["y"].get_values().toPandas()
df["salvage"] = df["order"] - df["sold"]
df["profit"] = ampl.var["f"].get_values().toPandas()
display(df)
print("Expected Profit:", ampl.obj["EV"].value())
# %%
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("pop_evpi.mod")
# load the data
ampl.param["r"] = r
ampl.param["c"] = c
ampl.param["w"] = w
ampl.set_data(scenarios_df, "S")
# solve the problem
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
print("Solver Termination Condition:", ampl.solve_result)
print()
# display solution using Pandas
df = pd.DataFrame.from_dict(scenarios).T
df["order"] = ampl.var["x"].get_values().toPandas()
df["sold"] = ampl.var["y"].get_values().toPandas()
df["salvage"] = df["order"] - df["sold"]
df["salvage"] = df["salvage"].round(2)
df["profit"] = ampl.var["f"].get_values().toPandas()
display(df)
print("Expected Profit:", ampl.obj["EV"].value())
確率制約付きマーコウィッツのポートフォリオ最適化 markowitz_portfolio_with_chance_constraint.py 4 セル ・ 81 行 ・ モデル 1
この節のモデル(1)
AMPLmarkowitz_chanceconstraints.mod
set N;
param Sigma{N, N};
param mu{N};
param C;
param R;
param gamma;
param phi_val;
param alpha;
var x_tilde >= 0;
var x{N} >= 0;
maximize expected_return:
sum{i in N} mu[i] * x[i];
subject to bounded_variance:
phi_val * (sum{i in N, j in N} x[i] * Sigma[i, j] * x[j]) <= sum{i in N} mu[i] * x[i] - alpha;
subject to total_assets:
sum{i in N} x[i] + x_tilde = C;
# %%
# Install AMPL and solvers
SOLVER = "scip"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["scip"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
from IPython.display import Markdown, HTML
import pandas as pd
import numpy as np
# %%
# we import the inverse CDF or quantile function for the standard normal norm.ppf() from scipy.stats
from scipy.stats import norm
# We set our risk threshold and risk levels (sometimes you may get an infeasible problem if the chance
# constraint becomes too tight!)
alpha = 0.6
beta = 0.3
# We specify the initial capital, the risk-free return the number of risky assets, their expected returns, and their covariance matrix.
C = 1
R = 1.05
n = 3
mu = np.array([1.25, 1.15, 1.35])
Sigma = np.array([[1.5, 0.5, 2], [0.5, 2, 0], [2, 0, 5]])
# Check how dramatically the optimal solution changes if we assume i.i.d. deviations for the returns.
# Sigma = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
# If you want to change covariance matrix, make sure you input a semi-definite positive one.
# The easiest way to generate a random covariance matrix is first generating a random m x m matrix A
# and then taking the matrix A^T A (which is always semi-definite positive)
# m = 3
# A = np.random.rand(m, m)
# Sigma = A.T @ A
# %%
def markowitz_chanceconstraints(alpha, beta, mu, Sigma):
m = AMPL()
m.read("markowitz_chanceconstraints.mod")
Sigma_df = pd.DataFrame(Sigma, index=range(n), columns=range(n))
phi_val = norm.ppf(1 - beta)
m.set["N"] = range(n)
m.param["phi_val"] = phi_val
m.param["alpha"] = alpha
m.param["C"] = C
m.param["R"] = R
m.param["mu"] = mu
m.param["Sigma"] = Sigma_df
m.solve(solver=SOLVER)
return m.solve_result, m
solve_result, model = markowitz_chanceconstraints(alpha, beta, mu, Sigma)
assert solve_result == "solved", solve_result
x_tilde = model.var["x_tilde"].value()
x = model.var["x"].to_dict()
display(Markdown(f"**Solver result:** *{solve_result}*"))
display(
Markdown(
f"**Solution:** $\\tilde x = {x_tilde:.3f}$, $x_1 = {x[0]:.3f}$, $x_2 = {x[1]:.3f}$, $x_3 = {x[2]:.3f}$"
)
)
display(
Markdown(
f"**Maximizes objective value to:** ${model.obj['expected_return'].value():.2f}$"
)
)
水産物流通センターの在庫最適化 seafood.py 7 セル ・ 226 行 ・ モデル 2
この節のモデル(2)
AMPLseafood.mod
param c;
param p;
param h;
# key parameter for possible parametric study
param mean_demand;
# first stage variables
var x >= 0;
var first_stage_profit = -c * x;
# second stage variables and constraints
var y >= 0;
var z >= 0;
s.t. cant_sell_fish_i_dont_have: y <= mean_demand;
s.t. fish_do_not_disappear: y + z == x;
var second_stage_profit = p * y - h * z;
# objective
maximize total_profit: first_stage_profit + second_stage_profit;
AMPLseafood_2.mod
param N; # number of samples
param c;
param p;
param h;
set indices := 1..N;
param xi{indices};
# first stage variable: x (amount of fish bought)
var x;
var first_stage_profit = -c * x;
# second stage variables: y (sold) and z (unsold)
var y{indices} >= 0;
var z{indices} >= 0;
# second stage constraints
s.t. cantsoldthingsfishdonthave {i in indices}: y[i] <= xi[i];
s.t. fishdonotdisappear {i in indices}: y[i] + z[i] == x;
var second_stage_profit = sum{i in indices}(p * y[i] - h * z[i]) / N;
# objective
maximize total_expected_profit: first_stage_profit + second_stage_profit;
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
import scipy.stats as stats
# %%
# Setting parameters
c = 10
p = 25
h = 3
distributions = {
"Uniform": stats.uniform(loc=25, scale=150),
"Pareto": stats.pareto(scale=50, b=2),
"Weibull": stats.weibull_min(scale=112.838, c=2),
}
for name, distribution in distributions.items():
print(f"Mean of {name} distribution = {distribution.mean():0.2f}")
# show PDFs
x = np.linspace(0, 250, 1000)
fig, ax = plt.subplots(1, 1, figsize=(10, 4))
lines = []
for name, distribution in distributions.items():
ax.plot(x, distribution.pdf(x), lw=3, label=name)
ax.legend()
fig.tight_layout()
plt.show()
# quantile
q = (p - c) / (p + h)
# show CDFs and graphical solutions
extraticks = [q]
fig, ax = plt.subplots(1, 1, figsize=(10, 4))
ax.axhline(q, linestyle="--", color="k")
for name, distribution in distributions.items():
x_opt = distribution.ppf(q)
(line,) = ax.plot(x, distribution.cdf(x), lw=3, label=name)
c = line.get_color()
ax.plot([x_opt] * 2, [-0.05, q], color=c)
ax.plot(x_opt, q, ".", color=c, ms=15)
plt.yticks(list(plt.yticks()[0]) + [q], list(plt.yticks()[1]) + [" q "])
plt.ylim(-0.05, 1.1)
ax.legend()
fig.tight_layout()
print(f"The quantile of interest given the parameters is equal to q = {q:.4f}.\n")
for name, distribution in distributions.items():
x_opt = distribution.ppf(q)
print(f"The optimal solution for {name} distribution is: {x_opt:0.2f} tons")
# %%
# problem data
c = 10
p = 25
h = 3
mean_demand = 100
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("seafood.mod")
# Load the data
ampl.param["c"] = c
ampl.param["p"] = p
ampl.param["h"] = h
ampl.param["mean_demand"] = mean_demand
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
print("solve_result", ampl.solve_result)
print("solve_message", ampl.get_value("solve_message"))
print(
f"Optimal solution for determistic demand equal to the average demand = {ampl.var['x'].value():.1f} tons"
)
print(f"Optimal deterministic profit = {ampl.obj['total_profit'].value():.0f}€")
# %%
# SAA of the two-stage stochastic LP to calculate the expected profit when buying the average
def NaiveSeafoodStockSAA(N, sample, distributiontype):
ampl = AMPL()
ampl.read("seafood_2.mod")
# Load the data
ampl.param["N"] = N
ampl.param["xi"] = sample
ampl.param["c"] = c
ampl.param["p"] = p
ampl.param["h"] = h
ampl.var["x"].fix(100)
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
total_expected_profit = ampl.obj["total_expected_profit"].value()
print(f"- {distributiontype}-distributed demand: {total_expected_profit:.2f}€")
return total_expected_profit
np.random.seed(0)
N = 7500
print(
f"Approximate expected optimal profit calculate with {N} samples when assuming the average demand with"
)
samples = np.random.uniform(low=25.0, high=175.0, size=N)
naiveprofit_uniform = NaiveSeafoodStockSAA(N, samples, "Uniform")
shape = 2
xm = 50
samples = (np.random.pareto(a=shape, size=N) + 1) * xm
naiveprofit_pareto = NaiveSeafoodStockSAA(N, samples, "Pareto")
shape = 2
scale = 113
samples = scale * np.random.weibull(a=shape, size=N)
naiveprofit_weibull = NaiveSeafoodStockSAA(N, samples, "Weibull")
# %%
# Two-stage stochastic LP using SAA
def SeafoodStockSAA(N, sample, distributiontype, printflag=True):
ampl = AMPL()
ampl.read("seafood_2.mod")
# Load the data
ampl.param["N"] = int(N)
ampl.param["xi"] = sample
ampl.param["c"] = c
ampl.param["p"] = p
ampl.param["h"] = h
ampl.solve(solver=SOLVER)
assert ampl.solve_result == "solved", ampl.solve_result
xval = ampl.var["x"].value()
total_expected_profit = ampl.obj["total_expected_profit"].value()
if printflag:
print(
f"Approximate solution in the case of {distributiontype} distribution using N={N:.0f} samples"
)
print(f"Approximate optimal solution: x = {xval:.2f} tons")
print(f"Approximate expected optimal profit: {total_expected_profit:.2f}€")
return total_expected_profit, xval
np.random.seed(1)
N = 5000
samples = np.random.uniform(low=25.0, high=175.0, size=N)
smartprofit_uniform, x = SeafoodStockSAA(N, samples, "uniform")
print(
f"Value of the stochastic solution: {smartprofit_uniform:.2f}-{naiveprofit_uniform:.2f} = {smartprofit_uniform-naiveprofit_uniform:.2f}€\n"
)
shape = 2
xm = 50
samples = (np.random.pareto(a=shape, size=N) + 1) * xm
smartprofit_pareto, x = SeafoodStockSAA(N, samples, "Pareto")
print(
f"Value of the stochastic solution: {smartprofit_pareto:.2f}-{naiveprofit_pareto:.2f} = {smartprofit_pareto-naiveprofit_pareto:.2f}€\n"
)
shape = 2
scale = 113
samples = scale * np.random.weibull(a=shape, size=N)
smartprofit_weibull, x = SeafoodStockSAA(N, samples, "Weibull")
print(
f"Value of the stochastic solution: {smartprofit_weibull:.2f}-{naiveprofit_weibull:.2f} = {smartprofit_weibull-naiveprofit_weibull:.2f}€\n"
)
# %%
shape = 2
xm = 50
scale = 113
levels = 75
table = np.zeros((levels, 7))
for i, N in enumerate(np.linspace(25, 2500, levels, dtype=int)):
np.random.seed(0)
samples = np.random.uniform(low=25.0, high=175.0, size=N)
profit_uniform, xu = SeafoodStockSAA(N, samples, "uniform", False)
samples = (np.random.pareto(a=shape, size=N) + 1) * xm
profit_pareto, xp = SeafoodStockSAA(N, samples, "Pareto", False)
samples = scale * np.random.weibull(a=shape, size=N)
profit_weibull, xw = SeafoodStockSAA(N, samples, "Weibull", False)
table[i] = [N, xu, xp, xw, profit_uniform, profit_pareto, profit_weibull]
fig, ax = plt.subplots(1, 1, figsize=(10, 4))
ax.plot(table[:, 0], table[:, 1], "-b", label="SAA-approximated solution Uniform")
ax.axhline(y=105.36, color="b", linestyle="--", label="optimal solution Uniform")
ax.plot(table[:, 0], table[:, 2], "-g", label="SAA-approximated solution Pareto")
ax.axhline(y=73.38, color="g", linestyle="--", label="optimal solution Pareto")
ax.plot(table[:, 0], table[:, 3], "-r", label="SAA-approximated solution Weibull")
ax.axhline(y=98.84, color="r", linestyle="--", label="optimal solution Weibull")
ax.legend(loc="upper right")
plt.ylim(65, 135)
fig.tight_layout()
エネルギーシステムにおける経済負荷配分 economicdispatch.py 12 セル ・ 195 行 ・ モデル 1
この節のモデル(1)
AMPLeconomic_dispatch.mod
param N; # number of samples
param samples{1..N};
param eps;
param Delta;
set V;
param c{V};
param d{V};
param p_min{V};
param p_max{V};
param sum_pmax = sum{i in V} p_max[i];
param sum_d = sum{i in V} d[i];
param M{j in 1..N} = samples[j] + sum_pmax + sum_d - Delta;
var p{i in V} >= p_min[i], <= p_max[i];
var u{i in 1..N} binary;
minimize my_objective: sum{i in V}(c[i] * p[i]);
s.t. supply_demand_leq {j in 1..N}:
samples[j] + sum{i in V} p[i] - sum{i in V} d[i] <= Delta + M[j] * u[j];
s.t. supply_demand_geq {j in 1..N}:
samples[j] + sum{i in V} p[i] - sum{i in V} d[i] >= - Delta - M[j] * u[j];
s.t. success_probability: sum{j in 1..N} u[j] <= eps * N;
# %%
# install AMPL and solvers
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# %%
def read_economic_dispatch_data():
# Read local nodes.csv if exists
base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/notebooks/09/"
nodes_df = pd.read_csv(base_url + "nodes.csv", index_col=0)[
["node_id", "d", "p_min", "p_max", "c_var"]
]
wind_production_samples_df = pd.read_csv(base_url + "discrete_wind.csv").T
# Read data
nodes = nodes_df.set_index("node_id").T.to_dict()
wind_production_samples = list(wind_production_samples_df.to_dict().values())
wind_production_samples = [sum(d.values()) for d in wind_production_samples]
return nodes, wind_production_samples
nodes, wind_production_samples = read_economic_dispatch_data()
# %%
wind_production_samples[4] # fifth outcome
# %%
sns.set_style("darkgrid")
sns.histplot(
wind_production_samples, kde=True, stat="density", kde_kws=dict(cut=1)
).set_title("wind production")
plt.show()
# %%
nodes[0] # first node properties
# %%
df_nodes = pd.DataFrame.from_dict(nodes, orient="index")
df_nodes["type"] = "consumer"
df_nodes.loc[df_nodes.p_max > 0, "type"] = "producer"
np.random.seed(2023)
df_nodes["x"] = np.random.randint(0, 100, len(nodes))
df_nodes["y"] = np.random.randint(0, 100, len(nodes))
df_nodes["size"] = df_nodes[["d", "p_max"]].max(axis=1)
def ShowInstance(df_nodes):
# Define the size of the figure
fig, ax = plt.subplots(figsize=(8, 6))
# Set the scales of the x and y axes
ax.set_xlim([min(df_nodes["x"]) - 10, max(df_nodes["x"]) + 10])
ax.set_ylim([min(df_nodes["y"]) - 10, max(df_nodes["y"]) + 10])
# Create a scatter plot with bubbles proportional to size
# ax.scatter(df_nodes['x'], df_nodes['y'], s=df_nodes['size']*1)
for (category, group), z, color in zip(
df_nodes.groupby("type"), [2, 1], ["red", "green"]
):
ax.scatter(
group.x,
group.y,
s=group["size"] * 1,
label=category,
alpha=0.2,
zorder=z,
color=color,
)
if "sol" in group:
ax.scatter(
group.x,
group.y,
s=group["sol"] * 1,
label=None,
alpha=1,
zorder=z,
color=color,
)
plt.legend()
# Show the chart
plt.show()
ShowInstance(df_nodes)
# %%
def economic_dispatch(nodes_df, samples, eps, Delta):
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("economic_dispatch.mod")
# Load the data
ampl.set["V"] = nodes_df["node_id"]
ampl.param["c"] = nodes_df["c_var"]
ampl.param["p_min"] = nodes_df["p_min"]
ampl.param["p_max"] = nodes_df["p_max"]
ampl.param["d"] = nodes_df["d"]
ampl.param["N"] = len(samples)
ampl.param["samples"] = samples
ampl.param["eps"] = eps
ampl.param["Delta"] = Delta
# Set solver
ampl.option["solver"] = SOLVER
return ampl
# %%
# Data
eps = 0.20
Delta = 1000
N = 500
base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/refs/heads/dev/notebooks/09/"
# Dataframe with node information
nodes_df = pd.read_csv(base_url + "nodes.csv", index_col=0)[
["node_id", "d", "p_min", "p_max", "c_var"]
]
# Solve model and report the solution
model = economic_dispatch(nodes_df, wind_production_samples, eps, Delta)
model.solve()
sum_production = model.get_value("sum{i in V} p[i]")
sum_demand = sum(nodes_df["d"])
print(f"Total energy demand: {sum_demand:.3f}")
print(f"Total optimal energy production: {sum_production:.3f}")
print(f"Total energy production cost: {model.obj['my_objective'].value():.3f}")
# %%
df_nodes["sol"] = model.var["p"].to_pandas()
ShowInstance(df_nodes)
# %%
fixed_Delta = 1000
feas_eps = []
feas_objs = []
eps = 0
model = economic_dispatch(nodes_df, wind_production_samples, eps, fixed_Delta)
for eps in np.linspace(0, 1, num=20):
model.param["eps"] = eps
model.solve()
assert model.solve_result == "solved", model.solve_result
if model.solve_result == "solved":
feas_eps.append(eps)
feas_objs.append(model.obj["my_objective"].value())
plt.plot(feas_eps, feas_objs, marker="o", linestyle="--")
plt.xlabel("$\epsilon$")
plt.ylabel("objective value")
plt.show()
# %%
fixed_eps = 0.02
feas_Deltas = []
feas_objs = []
Delta = 0
model = economic_dispatch(nodes_df, wind_production_samples, fixed_eps, Delta)
for Delta in np.linspace(0, 2000, num=20):
model.param["Delta"] = Delta
model.solve()
assert model.solve_result in ["solved", "infeasible"], model.solve_result
if model.solve_result == "solved":
feas_Deltas.append(Delta)
feas_objs.append(model.obj["my_objective"].value())
plt.plot(feas_Deltas, feas_objs, marker="o", linestyle="--")
plt.xlabel("$\Delta$")
plt.ylabel("objective value")
plt.show()
この章のデータファイル(2)
第10章2段階問題5 ファイル▶ 講義動画(25:28)
航空機の座席配分問題 airline-seating.py 13 セル ・ 382 行 ・ モデル 3
この節のモデル(3)
AMPLairline_deterministic.mod
param capacity;
set CLASSES;
param seat_factor{CLASSES};
param demand{CLASSES};
param revenue_factor{CLASSES};
# first stage variables and constraints
var seats{CLASSES} integer >= 0;
s.t. plane_seats: sum{c in CLASSES}(seats[c] * seat_factor[c]) <= capacity;
# second stage variable and constraints
var tickets{CLASSES} integer >= 0;
s.t. demand_limits {c in CLASSES}: tickets[c] <= demand[c];
s.t. seat_limits {c in CLASSES}: tickets[c] <= seats[c];
# objective
maximize revenue: sum{c in CLASSES}(tickets[c] * revenue_factor[c]);
AMPLairline_stochastic.mod
param capacity;
set CLASSES;
set SCENARIOS;
param demand{CLASSES, SCENARIOS};
param seat_factor{CLASSES};
param revenue_factor{CLASSES};
# first stage variables and constraints
var seats{CLASSES} integer >= 0;
s.t. plane_seats: sum{c in CLASSES}(seats[c] * seat_factor[c]) <= capacity;
# second stage variable and constraints
var tickets{CLASSES, SCENARIOS} integer >= 0;
s.t. demand_limits {c in CLASSES, s in SCENARIOS}: tickets[c, s] <= demand[c, s];
s.t. seat_limits {c in CLASSES, s in SCENARIOS}: tickets[c, s] <= seats[c];
# objective
maximize revenue: sum{c in CLASSES, s in SCENARIOS}(tickets[c, s] * revenue_factor[c]);
AMPLairline_final.mod
param capacity;
set CLASSES;
set SCENARIOS;
param nSCENARIOS := card(SCENARIOS);
param bigM;
param demand{CLASSES, SCENARIOS};
param seat_factor{CLASSES};
param revenue_factor{CLASSES};
param first_class_id symbolic;
param business_class_id symbolic;
param first_class_demand_cover_prop;
param business_class_demand_cover_prop;
# first stage variables and constraints
var seats{CLASSES} integer >= 0;
s.t. plane_seats: sum{c in CLASSES}(seats[c] * seat_factor[c]) <= capacity;
# second stage variable and constraints
var tickets{CLASSES, SCENARIOS} integer >= 0;
var first_class {SCENARIOS} binary;
var business_class {SCENARIOS} binary;
s.t. demand_limits {c in CLASSES, s in SCENARIOS}: tickets[c, s] <= demand[c, s];
s.t. seat_limits {c in CLASSES, s in SCENARIOS}: tickets[c, s] <= seats[c];
s.t. first_class_loyality {s in SCENARIOS}:
seats[first_class_id] + bigM * first_class[s] >= demand[first_class_id, s];
s.t. first_class_loyality_rate:
sum{s in SCENARIOS} first_class[s] <= (1 - first_class_demand_cover_prop) * nSCENARIOS;
s.t. business_class_loyality {s in SCENARIOS}:
seats[first_class_id] + seats[business_class_id] + bigM * business_class[s] >=
demand[business_class_id, s] + demand[first_class_id, s];
s.t. business_class_loyality_rate:
sum{s in SCENARIOS} business_class[s] <= (1 - business_class_demand_cover_prop) * nSCENARIOS;
# objective
maximize revenue: sum{c in CLASSES, s in SCENARIOS}(tickets[c, s] * revenue_factor[c]);
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %%
# scenario data
demand = pd.DataFrame(
{
"morning and evening": {"F": 20, "B": 50, "E": 200},
"weekend": {"F": 10, "B": 24, "E": 175},
"midday": {"F": 6, "B": 10, "E": 150},
}
).T
# global revenue and seat factor data
capacity = 200
revenue_factor = pd.Series({"F": 3.0, "B": 2.0, "E": 1.0})
seat_factor = pd.Series({"F": 2.0, "B": 1.5, "E": 1.0})
# %%
# function to report analytics for any given seat allocations
def seat_report(seats, demand):
classes = seats.index
# report seat allocation
equivalent_seats = pd.DataFrame(
{
"seat allocation": {c: seats[c] for c in classes},
"economy equivalent seat allocation": {
c: seats[c] * seat_factor[c] for c in classes
},
}
).T
equivalent_seats["TOTAL"] = equivalent_seats.sum(axis=1)
print("\nSeat Allocation")
display(equivalent_seats)
# tickets sold is the minimum of available seats and demand
tickets = pd.DataFrame()
for c in classes:
tickets[c] = np.minimum(seats[c], demand[c])
print("\nTickets Sold")
display(tickets)
# seats unsold
unsold = pd.DataFrame()
for c in classes:
unsold[c] = seats[c] - tickets[c]
print("\nSeats not Sold")
display(unsold)
# spillage (unmet demand)
spillage = demand - tickets
print("\nSpillage (Unfulfilled Demand)")
display(spillage)
# compute revenue
revenue = tickets.dot(revenue_factor)
print(
f"\nExpected Revenue (in units of economy ticket price): {revenue.mean():.2f}"
)
# charts
fig, ax = plt.subplots(2, 1, figsize=(8, 6))
revenue.plot(ax=ax[0], kind="barh", title="Revenue by Scenario")
ax[0].plot([revenue.mean()] * 2, ax[0].get_ylim(), "--", lw=1.4)
ax[0].set_xlabel("Revenue")
tickets[classes].plot(
ax=ax[1], kind="barh", rot=0, stacked=False, title="Demand Scenarios"
)
demand[classes].plot(
ax=ax[1],
kind="barh",
rot=0,
stacked=False,
title="Demand Scenarios",
alpha=0.2,
)
for c in classes:
ax[1].plot([seats[c]] * 2, ax[1].get_ylim(), "--", lw=1.4)
ax[1].set_xlabel("Seats")
fig.tight_layout()
return
# a trial solution
seats_all_economy = pd.Series({"F": 0, "B": 0, "E": 200})
seat_report(seats_all_economy, demand)
# %%
def airline_deterministic(demand):
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("airline_deterministic.mod")
# load the data
ampl.set["CLASSES"] = demand.columns.tolist()
ampl.param["demand"] = demand.mean()
ampl.param["revenue_factor"] = revenue_factor
ampl.param["seat_factor"] = seat_factor
ampl.param["capacity"] = capacity
return ampl
# Solve a given model and return a Pandas series of the seats for each class
def airline_solve(model):
model.solve(solver=SOLVER)
assert model.solve_result == "solved", model.solve_result
return pd.Series(model.var["seats"].to_dict()).reindex(index=["F", "B", "E"])
# Solve deterministic model to obtain the expectation of the expected value problem (EEV)
model_eev = airline_deterministic(demand)
seats_eev = airline_solve(model_eev)
seat_report(seats_eev, demand)
# %%
def airline_stochastic(demand):
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("airline_stochastic.mod")
# load the data
ampl.set["CLASSES"] = demand.columns.tolist()
ampl.set["SCENARIOS"] = demand.index.values.tolist()
ampl.param["demand"] = demand.T
ampl.param["revenue_factor"] = revenue_factor
ampl.param["seat_factor"] = seat_factor
ampl.param["capacity"] = capacity
return ampl
# create and solve model for the three scenarios defined above
model_stochastic = airline_stochastic(demand)
seats_stochastic = airline_solve(model_stochastic)
seat_report(seats_stochastic, demand)
# %%
# import the scipy.stats.norm object needed to use the quantile function of the standard normal distribution
from scipy.stats import norm
# define the mean and standard deviation of the demand for each class
mu = demand.mean()
sigma = {"F": 4, "B": 16, "E": 20}
display(pd.DataFrame({"mu": mu, "sigma": sigma}))
# create a new model with chance constraints that takes as input also
# the target quality of service (QoS) levels for classes F and B
def airline_cc(demand, QoSF=0.98, QoSFB=0.95):
# create two-stage stochastic model as before
m = airline_stochastic(demand)
# add equivalent counterparts of the two chance constraints to the first stage problem
# the two coefficients related the inverse CDF of the standard normal are computed using the norm.ppf function
first_class = "s.t. first_class: seats['F'] - {} >= {};".format(
mu["F"], norm.ppf(QoSF) * sigma["F"]
)
m.eval(first_class)
business_class = "s.t. business_class: seats['F'] + seats['B'] - {} >= {};".format(
mu["F"] + mu["B"], norm.ppf(QoSFB) * np.sqrt(sigma["F"] ** 2 + sigma["B"] ** 2)
)
m.eval(business_class)
print(m.con["first_class"])
print(m.con["business_class"])
return m
# create and solve model
model_cc = airline_cc(demand)
seats_cc = airline_solve(model_cc)
seat_report(seats_cc, demand)
# %%
# sample size
N = 1000
# define the mean mu and standard deviation sigma of the demand for each class
mu = demand.mean()
sigma = {"F": 4, "B": 16, "E": 20}
classes = demand.columns
# build covariance matrix from covariances and correlations
s = np.array(list(sigma.values()))
S = np.diag(s) @ np.diag(s)
print("\nModel Covariance")
df = pd.DataFrame(S, index=classes, columns=classes)
display(df)
# generate N samples, round each demand entry to nearest integer, and correct non-negative values
seed = 0
rng = np.random.default_rng(seed)
samples = rng.multivariate_normal(list(mu), S, N).round()
demand_saa = pd.DataFrame(samples, columns=classes)
demand_saa[demand_saa < 0] = 0
# report sample means and standard deviations for each class
demand_saa_stats = pd.DataFrame(
{
"mu (mean)": mu,
"sample mean": demand_saa.mean(),
"sigma (std)": sigma,
"sample std": demand_saa.std(),
}
)
display(demand_saa_stats)
fig, ax = plt.subplots(1, 3, figsize=(10, 3))
for i, ci in enumerate(classes):
demand_saa[ci].hist(ax=ax[i], bins=20)
ax[i].set_title(f"Histogram demand class {ci}")
fig.tight_layout()
# %%
# function to report analytics for SAA case
def seat_report_saa(seats, demand):
classes = seats.index
# report seat allocation
equivalent_seats = pd.DataFrame(
{
"seat allocation": {c: seats[c] for c in classes},
"economy equivalent seat allocation": {
c: seats[c] * seat_factor[c] for c in classes
},
}
).T
equivalent_seats["TOTAL"] = equivalent_seats.sum(axis=1)
print("\nSeat Allocation")
display(equivalent_seats)
# tickets sold
tickets = pd.DataFrame()
for c in classes:
tickets[c] = np.minimum(seats[c], demand[c])
print("\nMean Tickets Sold")
display(tickets.mean())
# seats unsold
unsold = pd.DataFrame()
for c in classes:
unsold[c] = seats[c] - tickets[c]
print("\nMean Seats not Sold")
display(unsold.mean())
# spillage (unmet demand)
spillage = demand - tickets
print("\nMean Spillage (Unfulfilled Demand)")
display(spillage.mean())
# compute revenue
revenue = tickets.dot(revenue_factor)
print(
f"\nExpected Revenue (in units of economy ticket price): {revenue.mean():.2f}"
)
# charts
fig, ax = plt.subplots(1, 1, figsize=(8, 4))
revenue.hist(ax=ax, bins=20)
ax.set_title("Revenue Histogram")
fig, ax = plt.subplots(1, 3, figsize=(12, 3))
for i, c in enumerate(classes):
tickets[c].hist(ax=ax[i], bins=20, alpha=0.4)
demand[c].hist(ax=ax[i], alpha=0.4)
ax[i].legend(["Tickets Sold", "Demand"])
ax[i].set_xlim(0, 300)
fig.tight_layout()
return
# %%
model_ssa = airline_stochastic(demand_saa)
seats_saa = airline_solve(model_ssa)
seat_report_saa(seats_saa, demand_saa)
# %%
# sample size
N = 1000
# define the mean mu and standard deviation sigma of the demand for each class
mu = demand.mean()
sigma = {"F": 4, "B": 16, "E": 20}
display(pd.DataFrame({"mu": mu, "sigma": sigma}))
# correlation matrix
P = np.array([[1, 0.6, 0.2], [0.6, 1, 0.4], [0.2, 0.4, 1]])
# build covariance matrix from covariances and correlations
s = np.array(list(sigma.values()))
S = np.diag(s) @ P @ np.diag(s)
# create samples
np.random.seed(1)
samples = np.random.multivariate_normal(list(mu), S, N).round()
# truncate to integers and non-negative values
classes = demand.columns
demand_saa = pd.DataFrame(samples, columns=classes)
demand_saa[demand_saa < 0] = 0
df = pd.DataFrame(mu, columns=["mu"])
df["sample means"] = demand_saa.mean()
display(df)
df = pd.DataFrame(pd.Series(sigma), columns=["sigma"])
df["sample std dev"] = demand_saa.std()
display(df)
print("\nModel Covariance")
df = pd.DataFrame(S, index=classes, columns=classes)
display(df)
print("\nSample Covariance")
display(pd.DataFrame(demand_saa.cov()))
fig, ax = plt.subplots(3, 3, figsize=(10, 10))
for i, ci in enumerate(classes):
for j, cj in enumerate(classes):
if i == j:
demand_saa[ci].hist(ax=ax[i, i], bins=20)
ax[i, i].set_title(f"Histogram {ci}")
else:
ax[i, j].plot(demand_saa[ci], demand_saa[cj], ".", alpha=0.4)
ax[i, j].set_xlabel(ci)
ax[i, j].set_ylabel(cj)
ax[i, j].set_title(f"Convariance: {ci} vs {cj}")
fig.tight_layout()
# %%
model_ssa = airline_stochastic(demand_saa)
seats_saa = airline_solve(model_ssa)
seat_report_saa(seats_saa, demand_saa)
# %%
# define big M constant for chance constraints counterparts
bigM = 100
def airline_final(demand):
# Create AMPL instance and load the model
ampl = AMPL()
ampl.read("airline_final.mod")
# load the data
ampl.set["CLASSES"] = demand.columns.tolist()
ampl.set["SCENARIOS"] = demand.index.values.tolist()
ampl.param["demand"] = demand.T
ampl.param["revenue_factor"] = revenue_factor
ampl.param["seat_factor"] = seat_factor
ampl.param["capacity"] = capacity
ampl.param["bigM"] = bigM
ampl.param["first_class_id"] = "F"
ampl.param["business_class_id"] = "B"
ampl.param["first_class_demand_cover_prop"] = 0.98
ampl.param["business_class_demand_cover_prop"] = 0.95
return ampl
# create model
model = airline_final(demand_saa)
seats = airline_solve(model)
seat_report_saa(seats, demand_saa)
リコース行動を伴う最適潮流計算問題 opf-ldr.py 9 セル ・ 230 行 ・ モデル 1
この節のモデル(1)
AMPLopf_ldr.mod
# Define sets
set T;
set V;
set E within V cross V;
set SWH;
set CG;
set NG;
# Define parameters
param uniformparticipationfactors;
param p_min{V} >= 0;
param p_max{i in V} >= p_min[i];
param is_generator{V};
param energy_type{V} symbolic;
param c{V};
param d{V};
param abs_total_imbalance{T} >= 0;
param total_imbalance{T};
param nT := card(T);
param b{E};
param f_max{E};
param imbalances{T, V};
# Declare decision variables
var p{i in V} >= p_min[i], <= p_max[i];
var r{V, T} >= 0;
var alpha{V} >= 0, <= 1;
var theta{V, T};
var f{E, T};
# Declare objective function including the recourse actions
minimize obj:
sum{i in V: is_generator[i] == 1} c[i] * p[i] +
1 / nT * sum{t in T, i in V: energy_type[i] == "coal" or energy_type[i] == "gas"}
2 * c[i] * alpha[i] * abs_total_imbalance[t];
# Declare constraints
s.t. windsolarhydro_nopartecipationfactors {i in SWH}: alpha[i] = 0;
s.t. load_nopartecipationfactors {i in NG}: alpha[i] = 0;
s.t. sum_one: sum{i in V} alpha[i] = 1;
s.t. uniformparticipationfactors_check {i in CG}:
uniformparticipationfactors == 1 ==> alpha[i] = 1 / card(CG);
# Second-stage production levels must also meet generator limits
s.t. power_withrecourse {i in V, t in T}:
r[i, t] = p[i] - alpha[i] * total_imbalance[t];
s.t. generation_upper_bound_withrecourse {i in CG, t in T}:
r[i, t] <= p_max[i];
s.t. generation_lower_bound_withrecourse {i in CG, t in T}:
r[i, t] >= p_min[i];
# Expressions for outgoing and incoming flows
s.t. flow_conservation {i in V, t in T}:
sum{(j, i) in E} f[j, i, t] -
sum{(i, j) in E} f[i, j, t]
== r[i, t] + imbalances[t, i] - d[i];
s.t. susceptance {(i, j) in E, t in T}:
f[i, j, t] = b[i, j] * (theta[i, t] - theta[j, t]);
s.t. flows_upper_bound {(i, j) in E, t in T}:
f[i, j, t] <= f_max[i, j];
s.t. flows_lower_bound {(i, j) in E, t in T}:
-f[i, j, t] <= f_max[i, j];
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
# Load packages
from IPython.display import Markdown, HTML
import numpy as np
import numpy.random as rnd
import pandas as pd
import matplotlib.pyplot as plt
from ast import literal_eval as make_tuple
def get_firststagecost(model):
return model.get_value("sum{i in V: is_generator[i]==1} c[i]*p[i]")
def get_optimal_production_levels(model):
q = model.get_data("{i in CG} p[i]")
q = q.to_list()
q = [i[1] for i in q]
return [np.round(i, 2) for i in q]
def get_participation_factors(model):
q = [i[1] for i in model.get_data("{i in CG} alpha[i]")]
return [np.round(i, 2) for i in q]
def get_averagerecoursecost(model, df, T, abstotalimbalances):
q_alpha = [i[1] for i in model.var["alpha"].get_values()]
averagerecoursecost = (
1
/ T
* sum(
sum(
2 * df.iloc[i]["c"] * q_alpha[i] * abstotalimbalances[t]
for i in df.index.values
)
for t in range(T)
)
)
return averagerecoursecost
# %%
# Download the data
base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/dev/notebooks/10/"
nodes_df = pd.read_csv(base_url + "nodes.csv").set_index("node_id")
edges_df = pd.read_csv(base_url + "edges.csv").set_index(["node_id1", "node_id2"])
# Replace 'na' by an empty string
nodes_df.fillna("", inplace=True)
# Rename column acording to the model
nodes_df.rename(columns={"c_var": "c"}, inplace=True)
# Remove unused column
nodes_df.drop(["c_fixed"], axis=1, inplace=True)
network = {"nodes": nodes_df, "edges": edges_df}
# %%
# Define an OPF problem with recourse actions for the conventional generators based on participation factors
def OPF_participationfactors(
network,
imbalances,
totalimbalances,
abstotalimbalances,
uniformparticipationfactors=False,
):
nimbalances = len(imbalances)
temp = {}
for i, j in enumerate(imbalances):
for k, v in j.items():
temp[i, k] = v
imbalances = temp
nodes_df = network["nodes"]
edges_df = network["edges"]
ampl = AMPL()
ampl.read("opf_ldr.mod")
# load data in pandas data frames
ampl.set_data(nodes_df, "V")
ampl.set_data(edges_df, "E")
# data for remaining sets
ampl.set["T"] = list(range(nimbalances))
ampl.set["SWH"] = nodes_df[
nodes_df["energy_type"].isin(["wind", "solar", "hydro"])
].index
ampl.set["CG"] = nodes_df[nodes_df["energy_type"].isin(["coal", "gas"])].index
ampl.set["NG"] = nodes_df[nodes_df["energy_type"].eq("")].index
# data for parameters
ampl.param["abs_total_imbalance"] = abstotalimbalances
ampl.param["total_imbalance"] = totalimbalances
ampl.param["uniformparticipationfactors"] = 1 if uniformparticipationfactors else 0
ampl.param["imbalances"] = imbalances
ampl.option["presolve"] = 0 # or change presolve_eps
ampl.solve(solver="highs", verbose=False)
assert ampl.solve_result == "solved", ampl.solve_result
return ampl
# %%
# Define the set of nodes with possible deviations from forecasts, i.e. those with either a wind or a solar generator
SW = {48, 53, 58, 60, 64, 65}
SW_df = nodes_df[nodes_df.index.isin(SW)]
# Define the number of scenarios and the random seed
T = 100
seed = 0
rng = np.random.default_rng(seed)
# Imbalances are generated uniformly at random assuming the realized
# wind or solar power is between 0.5 and 1.5 times the forecasted value
imbalances = [
{
i: (
rng.uniform(-nodes_df["p_min"][i] / 2, nodes_df["p_min"][i] / 2)
if i in SW
else 0
)
for i in nodes_df.index
}
for t in range(T)
]
totalimbalances = {t: sum(imbalances[t].values()) for t in range(len(imbalances))}
abstotalimbalances = {t: abs(totalimbalances[t]) for t in range(len(totalimbalances))}
# %%
# Define trivial arrays for the case of perfect forecast and no need of recourse actions
zeroimbalances = [{i: 0 for i in nodes_df.index}]
zerototalimbalances = {0: sum(zeroimbalances[0].values())}
zeroabstotalimbalances = {0: abs(zerototalimbalances[0])}
# Solve the model
m = OPF_participationfactors(
network,
zeroimbalances,
zerototalimbalances,
zeroabstotalimbalances,
uniformparticipationfactors=True,
)
firststagecost = get_firststagecost(m)
print(f"First-stage energy production cost = {firststagecost:.2f}")
print(
f"The optimal production levels for the conventional generators are: {get_optimal_production_levels(m)}"
)
# %%
averagerecoursecost = get_averagerecoursecost(m, nodes_df, T, abstotalimbalances)
averagetotalcost = m.obj["obj"].value() + averagerecoursecost
print(
f"Average energy production cost due to recourse actions = {averagerecoursecost:.2f} (but including many infeasible scenarios!)"
)
print(
f"Average total cost = {averagetotalcost:.2f} (but including many infeasible scenarios!)"
)
# %%
m = OPF_participationfactors(
network,
imbalances,
totalimbalances,
abstotalimbalances,
uniformparticipationfactors=True,
)
print(
"The optimal production levels for the conventional generators are",
get_optimal_production_levels(m),
)
q = [i[1] for i in m.get_data("{i in CG} alpha[i]")]
print(
"The participation factors for the conventional generators are",
[np.round(i, 2) for i in q],
)
firststagecost = get_firststagecost(m)
averagerecoursecost = get_averagerecoursecost(m, nodes_df, T, abstotalimbalances)
print(f"\nFirst-stage energy production cost = {firststagecost:.2f}")
print(
f"Average energy production cost due to recourse actions = {averagerecoursecost:.2f}"
)
print(f"Total cost = {m.obj['obj'].value():.2f}")
# %%
m = OPF_participationfactors(
network,
imbalances,
totalimbalances,
abstotalimbalances,
uniformparticipationfactors=False,
)
print(
"The optimal production levels for the conventional generators are",
get_optimal_production_levels(m),
)
print(
"The optimal participation factors for the conventional generators are",
get_participation_factors(m),
)
firststagecost = get_firststagecost(m)
averagerecoursecost = get_averagerecoursecost(m, nodes_df, T, abstotalimbalances)
print(f"\nFirst-stage energy production cost = {firststagecost:.2f}")
print(
f"Average energy production cost due to recourse actions = {averagerecoursecost:.2f}"
)
print(f"Total cost = {m.obj['obj'].value():.2f}")
2段階の生産計画 ccg.py 13 セル ・ 376 行 ・ モデル 4
この節のモデル(4)
AMPLmax_min_profit.mod
set I;
set J;
set SK;
param R{SK, I};
param c{I};
# first stage variables
var x{I} >= 0;
var tau;
set SCENARIOS;
param t{SCENARIOS, SK};
param S{SCENARIOS, SK, J};
# second stage variables
var y{SCENARIOS, J} >= 0;
s.t. stage_net_profit {s in SCENARIOS}:
y[s, "y3"] >= tau;
s.t. model_constraints {s in SCENARIOS, k in SK}:
sum{i in I}(R[k, i] * x[i]) +
sum{j in J}(S[s, k, j] * y[s, j])
<= t[s, k];
maximize worst_case_profit: sum{i in I} c[i] * x[i] + tau;
AMPLmax_avg_profit.mod
set I;
set J;
set SK;
param R{SK, I};
param c{I};
# first stage variables
var x{I} >= 0;
var tau;
set SCENARIOS;
param t{SCENARIOS, SK};
param S{SCENARIOS, SK, J};
# second stage variables
var y{SCENARIOS, J} >= 0;
s.t. stage_net_profit {s in SCENARIOS}:
y[s, "y3"] >= tau;
s.t. model_constraints {s in SCENARIOS, k in SK}:
sum{i in I}(R[k, i] * x[i]) +
sum{j in J}(S[s, k, j] * y[s, j])
<= t[s, k];
maximize avg_profit: sum{i in I} c[i] * x[i] + sum{s in SCENARIOS} y[s, "y3"] / card(SCENARIOS);
AMPLmax_profit_fixed_x.mod
set I;
set J;
set SK;
param worst_case;
param R{SK, I};
param c{I};
# first stage variables
var x{I} >= 0;
var tau;
set SCENARIOS;
param t{SCENARIOS, SK};
param S{SCENARIOS, SK, J};
# second stage variables
var y{SCENARIOS, J} >= 0;
s.t. stage_net_profit {s in SCENARIOS}:
y[s, "y3"] >= tau;
s.t. model_constraints {s in SCENARIOS, k in SK}:
sum{i in I}(R[k, i] * x[i]) +
sum{j in J}(S[s, k, j] * y[s, j])
<= t[s, k];
var worst_case_minded = sum{i in I} c[i] * x[i] + tau;
var average_case_minded = sum{i in I} c[i] * x[i] + sum{s in SCENARIOS} y[s, "y3"] / card(SCENARIOS);
maximize profit: if worst_case==1 then worst_case_minded else average_case_minded;
AMPLpessimization_problem.mod
param big_M;
param Gamma;
# indices for the variables
set Z_INDICES;
# indices for the scenarios
set SCENARIOS;
param z_max{Z_INDICES};
var z{i in Z_INDICES} >= -z_max[i], <= z_max[i];
var z_abs{Z_INDICES} >= 0;
var theta;
s.t. z_bound{i in Z_INDICES}: z[i] <= z_abs[i];
s.t. z_budget: sum{i in Z_INDICES} z_abs[i] / z_max[i] <= Gamma;
set LKEYS;
param L{SCENARIOS, LKEYS, Z_INDICES};
param R{SCENARIOS, LKEYS};
# second stage variables
var u{SCENARIOS, LKEYS} binary;
# hack for faster CCG convergence
# only care for violations related to the 'actual' constraints, not the profit constraint
s.t. at_least_one_violated{s in SCENARIOS}:
sum{k in LKEYS: k != "profit"} u[s, k] <= card(LKEYS) - 2;
s.t. model_constraints{s in SCENARIOS, k in LKEYS}:
sum{i in Z_INDICES} L[s, k, i] * z[i] - theta >= R[s, k] - u[s, k] * big_M;
# worst case profit
maximize max_violation: theta;
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %%
# Function to return the vectors and matrices c, q, R, S, t evaluated for a specific realization (z_A, z_B, z_D)
def model_params(z_A=0, z_B=0, z_D=0):
c = {"x": -10}
q = {"y1": 0, "y2": 0, "y3": 1}
R = {
"profit": {"x": 0},
"demand": {"x": 0},
"labor A": {"x": 0},
"labor B": {"x": 0},
"raw materials": {"x": -1},
}
S = {
"profit": {
"y1": -(140 - 50 * z_A - 80 * z_B),
"y2": -(120 - 50 * z_A - 40 * z_B),
"y3": 1,
},
"demand": {"y1": -1, "y2": 0, "y3": 0},
"labor A": {"y1": 1, "y2": 1 + z_A, "y3": 0},
"labor B": {"y1": 2 + 2 * z_B, "y2": 1 + z_B, "y3": 0},
"raw materials": {"y1": 10, "y2": 9, "y3": 0},
}
t = {
"profit": 0,
"demand": -20 * (1 + z_D),
"labor A": 80,
"labor B": 100,
"raw materials": 0,
}
return c, q, R, S, t
c, q, R, S, t = model_params()
print(f"c = {c}")
print(f"q = {q}")
print(f"R = {R}")
print(f"S = {S}")
print(f"t = {t}")
# %%
# Sample the random variables z_A, z_B, z_D uniformly in the given set
def z_sample(seed):
rng = np.random.default_rng(seed)
while True:
sample = {
"z_A": 0.15 * rng.uniform(low=-1, high=1),
"z_B": 0.25 * rng.uniform(low=-1, high=1),
"z_D": 0.25 * rng.uniform(low=-1, high=1),
}
if (
abs(sample["z_A"]) / 0.15
+ abs(sample["z_B"]) / 0.25
+ abs(sample["z_D"]) / 0.25
<= 2
):
break
return sample
# Convert the data of a double nested dictionary into a dictionary with compound keys
# For example {a: {b: c}} will be converted into {(a, b): c}
def flatten_dict(D):
N = {}
for k1, v1 in D.items():
for k2, v2 in v1.items():
N[(k1, k2)] = v2
return N
# Aggregate data generated based on a list of sample parameters Z.
# S and t sets are generated for each sample and agregated in a dictionary
# with an aditional key to denote the scenario.
def scenarios_data(Z):
S = {}
t = {}
for i, z in enumerate(Z):
c0, q0, R0, S0, t0 = model_params(**z)
for k1, v1 in S0.items():
for k2, v2 in v1.items():
S[(i, k1, k2)] = v2
for k, v in t0.items():
t[(i, k)] = v
return S, t
# Function to solve the robust problem using the sampled realizations
def max_min_profit(Z):
c, q, R, S, t = model_params()
R = flatten_dict(R)
# get model parameters for all the scenarios
Sd, td = scenarios_data(Z)
m = AMPL()
m.read("max_min_profit.mod")
m.set["I"] = c.keys()
m.set["J"] = q.keys()
m.set["SCENARIOS"] = list(range(len(Z)))
m.set["SK"] = S.keys()
m.param["c"] = c
m.param["R"] = R
m.param["S"] = Sd
m.param["t"] = td
# solve the problem
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
# %%
# Get a sample of 1000 realizations of the random variables z_A, z_B, z_D
N = 1000
Z = [z_sample(j) for j in range(N)]
# Solve the nominal problem
print("\nSolution to the nominal problem")
m = max_min_profit([{"z_A": 0, "z_B": 0, "z_D": 0}])
print(f"Objective value: {m.obj['worst_case_profit'].value():.2f}")
print(f"Optimal solution: x = {m.var['x'].to_list()[0][1]:.2f}")
# Solve the robust problem using the sampled realizations
print("\nSolution to the robust problem using sampling")
m = max_min_profit(Z)
print(f"Objective value: {m.obj['worst_case_profit'].value():.2f}")
print(f"Optimal solution: x = {m.var['x'].to_list()[0][1]:.2f}")
# %%
def max_avg_profit(Z):
c, q, R, S, t = model_params()
R = flatten_dict(R)
Sd, td = scenarios_data(Z)
m = AMPL()
m.read("max_avg_profit.mod")
m.set["I"] = c.keys()
m.set["J"] = q.keys()
m.set["SCENARIOS"] = list(range(len(Z)))
m.set["SK"] = S.keys()
m.param["c"] = c
m.param["R"] = R
m.param["S"] = Sd
m.param["t"] = td
# solve the problem
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
# %%
m = max_avg_profit(Z)
print(f"Objective value: {m.obj['avg_profit'].value():.2f}")
print(f"Optimal solution: x = {m.var['x'].to_list()[0][1]:.2f}")
# Store the per-scenario profit realizations into a numpy array
avg_case_ps = np.zeros(len(Z))
for s in range(len(Z)):
mystr = "sum{i in I} (c[i] * x[i]) + y[%d, 'y3'];" % (s,)
avg_case_ps[s] = m.get_value(mystr)
# %%
def max_profit_fixed_x(Z, fixed_x_value, worst_case=True):
c, q, R, S, t = model_params()
R = flatten_dict(R)
Sd, td = scenarios_data(Z)
m = AMPL()
m.read("max_profit_fixed_x.mod")
m.set["I"] = list(c.keys())
m.set["J"] = list(q.keys())
m.set["SCENARIOS"] = list(range(len(Z)))
m.set["SK"] = list(S.keys())
m.param["R"] = R
m.param["c"] = c
m.param["S"] = Sd
m.param["t"] = td
m.param["worst_case"] = 1 if worst_case else 0
for i in list(c.keys()):
m.var["x"][i].fix(fixed_x_value)
# solve the problem
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
return m
# %%
xopt_rob = 547.81
print(
f"\nSolving for the average with optimal-worst-case first-stage decision x = {xopt_rob}"
)
m = max_profit_fixed_x(Z, xopt_rob, worst_case=False)
print(f"Objective value: {m.obj['profit'].value():.2f} (average profit)")
# Extracting the per-scenario realizations of the worst-case optimal solution
worst_case_ps = np.zeros(len(Z))
for s in range(len(Z)):
mystr = "sum{i in I} (c[i] * x[i]) + y[%d, 'y3'];" % (s,)
worst_case_ps[s] = m.get_value(mystr)
xopt_avg = 637.08
print(
f"\nSolving for the worst-case with optimal-average first-stage decision x = {xopt_avg}"
)
m = max_profit_fixed_x(Z, xopt_avg, worst_case=True)
print(f"Objective value: {m.obj['profit'].value():.2f} (worst-case profit)")
# %%
# Collecting the per-scenario optimal values of both the stochastic and robust problems
data = pd.DataFrame({"Robust": worst_case_ps, "Stochastic": avg_case_ps})
# Plotting the results in a histogram
fig, ax = plt.subplots(figsize=(10, 6))
data.plot.hist(bins=20, alpha=0.5, ax=ax)
ax.set_xlabel("Profit")
plt.show()
# %%
def subproblem_params(dec):
Left = {
"demand": {"z_A": 0, "z_B": 0, "z_D": 20},
"profit": {
"z_A": (50 * dec["y1"] + 50 * dec["y2"]),
"z_B": (80 * dec["y1"] + 40 * dec["y2"]),
"z_D": 0,
},
"labor A": {"z_A": dec["y1"] + dec["y2"], "z_B": 0, "z_D": 0},
"labor B": {"z_A": 0, "z_B": 2 * dec["y1"] + dec["y2"], "z_D": 0},
}
Right = {
"demand": dec["y1"] - 20,
"profit": 140 * dec["y1"] + 120 * dec["y2"] - dec["y3"],
"labor A": 80 - dec["y1"] - dec["y2"],
"labor B": 100 - 2 * dec["y1"] - dec["y2"],
}
return Left, Right
def subproblem_data(master_solution):
L = {}
R = {}
for s in range(len(master_solution)):
L0, R0 = subproblem_params(master_solution[s])
for k1, v1 in L0.items():
for k2, v2 in v1.items():
L[(s, k1, k2)] = v2
for k, v in R0.items():
R[(s, k)] = v
return L, R
# %%
def pessimization_problem(
master_solution,
z_A_max=0.15,
z_B_max=0.25,
z_D_max=0.5,
Gamma=2,
):
z_max = {"z_A": z_A_max, "z_B": z_B_max, "z_D": z_D_max}
big_M = 1000
L, R = subproblem_params(master_solution[0])
Ld, Rd = subproblem_data(master_solution)
m = AMPL()
m.read("pessimization_problem.mod")
m.set["Z_INDICES"] = z_max.keys()
m.set["SCENARIOS"] = range(len(master_solution))
m.set["LKEYS"] = L.keys()
m.param["z_max"] = z_max
m.param["Gamma"] = Gamma
m.param["L"] = Ld
m.param["R"] = Rd
m.param["big_M"] = big_M
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
theta = m.var["theta"].value()
z = m.var["z"].to_dict()
return theta, z["z_A"], z["z_B"], z["z_D"]
# %%
ccg_converged = False
stopping_precision = 0.1
max_iterations = 50
ccg_iterations = 0
# Initialize the null scenario - no perturbation
Z = [{"z_A": 0, "z_B": 0, "z_D": 0}]
while (not ccg_converged) and (ccg_iterations < max_iterations):
# Building and solving the master problem
m = max_min_profit(Z)
# Exporting the data from the master problem into a list of dictionaries
c, q, *_ = model_params()
master_solution = []
print(f"\nIteration #{ccg_iterations}")
for s in range(len(Z)):
single_solution = {}
for x_key in c.keys():
single_solution[x_key] = m.var["x"][x_key].value()
for y_key in q.keys():
single_solution[y_key] = m.var["y"][s, y_key].value()
master_solution.append(single_solution)
print(f'Current solution: x = {master_solution[0]["x"]:.2f}')
# Pessimization
theta_opt, z_A, z_B, z_D = pessimization_problem(
master_solution, 0.15, 0.25, 0.25, 2
)
# If pessimization yields no violation, stop the procedure, otherwise add a scenario and repeat
if theta_opt < stopping_precision:
print("No violation found. Stopping the procedure.")
ccg_converged = True
else:
print(
f"Violation found: z_A = {z_A:4.2f}, z_B = {z_B:4.2f}, z_D = {z_D:4.2f}"
)
print(f"Constraint violation: {theta_opt:6.2f}")
Z.append({"z_A": z_A, "z_B": z_B, "z_D": z_D})
ccg_iterations += 1
補足:農家の問題とその変種 farmer.py 13 セル ・ 229 行 ・ モデル 1
この節のモデル(1)
AMPLfarmer.mod
set CROPS;
set SCENARIOS;
param bound;
param total_land;
param planting_cost{CROPS};
param sell_price{CROPS};
param buy_cost{CROPS};
param required{CROPS};
param demand{CROPS};
param excess_price{CROPS};
param yields{SCENARIOS, CROPS};
# first stage variables
var acres{CROPS} >= 0, <= total_land;
# second stage variables (all units in tons)
var grow{SCENARIOS, CROPS} >= 0, <= bound;
var buy{SCENARIOS, CROPS} >= 0, <= bound;
var sell{SCENARIOS, CROPS} >= 0, <= bound;
var excess{SCENARIOS, CROPS} >= 0, <= bound;
# first stage model
s.t. limit_on_planted_land: sum{c in CROPS} acres[c] <= total_land;
# second stage model
s.t. crop_yield {s in SCENARIOS, c in CROPS}:
grow[s, c] == yields[s, c] * acres[c];
s.t. balance {s in SCENARIOS, c in CROPS}:
grow[s, c] + buy[s, c] == sell[s, c] + required[c] + excess[s, c];
# the selling quota.
# we assume that the excess has smaller sell price,
# so it's optimized out if possible.
s.t. quota {s in SCENARIOS, c in CROPS}:
sell[s, c] <= demand[c];
# expressions for objective functions
var expense {s in SCENARIOS, c in CROPS} =
planting_cost[c] * acres[c] + buy_cost[c] * buy[s, c];
var revenue {s in SCENARIOS, c in CROPS} =
sell_price[c] * sell[s, c] + excess_price[c] * excess[s, c];
var scenario_profit {s in SCENARIOS} =
sum{c in CROPS}(revenue[s, c] - expense[s, c]);
# %%
# install dependencies and select solver
SOLVER = "cbc"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["cbc"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %%
yields = pd.DataFrame(
{
"good": {"wheat": 3.0, "corn": 3.6, "beets": 24},
"average": {"wheat": 2.5, "corn": 3.0, "beets": 20},
"poor": {"wheat": 2.0, "corn": 2.4, "beets": 16},
}
).T
display(yields)
# %%
crops = pd.DataFrame(
{
"wheat": {
"planting_cost": 150,
"sell_price": 170,
"buy_cost": 238,
"required": 200,
},
"corn": {
"planting_cost": 230,
"sell_price": 150,
"buy_cost": 210,
"required": 240,
},
"beets": {
"planting_cost": 260,
"sell_price": 36,
"demand": 6000,
"excess_price": 10,
},
}
).T
# fill NaN
bigM = 20000
crops["buy_cost"].fillna(bigM, inplace=True)
crops["demand"].fillna(bigM, inplace=True)
crops["required"].fillna(0, inplace=True)
crops["excess_price"].fillna(0, inplace=True)
display(crops)
# %%
def farmer(crops, yields, total_land=500):
bound = yields.max().max() * total_land
m = AMPL()
m.read("farmer.mod")
# The 'crops' data frame has an AMPL indexing set as index ('CROPS') and AMPL parameters as
# columns ('planting_cost', 'sell_price', 'buy_cost', 'required', 'demand' and 'excess_price').
# It's possible to load all the data in the data frame with the following instruction
m.set_data(crops, "CROPS")
# The 'yields' data frame has an AMPL indexing set as index ('SCENARIOS') and another AMPL
# indexing set as columns ('CROPS').
# We first need to load the data for 'SCENARIOS'.
m.set["SCENARIOS"] = yields.index
# Now we can load the data from the 'yields' data frame.
m.param["yields"] = yields
m.param["bound"] = bound
m.param["total_land"] = total_land
return m
# %%
def farm_report(m):
print(f"Objective = {m.obj['objective'].value():0.2f}")
# indexed by scenarios
df_scenarios = m.var["scenario_profit"].to_pandas()
df_scenarios.index.names = ["scenario"]
df_scenarios.rename(columns={df_scenarios.columns[0]: "profit"}, inplace=True)
# indexed by crops
df_crops = m.var["acres"].to_pandas()
df_crops.index.names = ["crop"]
df_crops.rename(columns={df_crops.columns[0]: "acres"}, inplace=True)
# indexed by scenarios and crops
df_sc = m.var["grow"].to_pandas()
df_sc.index.names = ["scenario", "crop"]
df_sc.rename(columns={df_sc.columns[0]: "grow"}, inplace=True)
df_sc["buy"] = m.var["buy"].to_pandas()
df_sc["sell"] = m.var["sell"].to_pandas()
df_sc["excess"] = m.var["excess"].to_pandas()
df_sc["expense"] = m.var["expense"].to_pandas()
df_sc["revenue"] = m.var["revenue"].to_pandas()
df_sc["profit"] = df_sc["revenue"] - df_sc["expense"]
display(df_scenarios)
display(df_crops)
display(df_sc)
# %%
m = farmer(crops, pd.DataFrame(yields.mean(), columns=["mean"]).T)
m.eval("maximize objective: sum{s in SCENARIOS} scenario_profit[s];")
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
farm_report(m)
# %%
# maximize mean profit
m = farmer(crops, yields)
m.eval(
"maximize objective: (sum{s in SCENARIOS} scenario_profit[s]) / card(SCENARIOS);"
)
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
farm_report(m)
# %%
# find worst case profit
m = farmer(crops, yields)
m.eval("var worst_case_profit;")
m.eval(
"s.t. lower_bound_profit{s in SCENARIOS}: worst_case_profit <= scenario_profit[s];"
)
m.eval("maximize objective: worst_case_profit;")
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
farm_report(m)
# %%
worst_case_profit = m.var["worst_case_profit"].value()
# maximize expected profit subject to worst case as lower bound
m = farmer(crops, yields)
m.eval("param worst_case_profit;")
m.param["worst_case_profit"] = worst_case_profit
m.eval(
"s.t. lower_bound_profit{s in SCENARIOS}: worst_case_profit <= scenario_profit[s];"
)
m.eval(
"maximize objective: (sum{s in SCENARIOS} scenario_profit[s]) / card(SCENARIOS);"
)
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
farm_report(m)
# %%
df = pd.DataFrame()
for wc in np.linspace(48820, 59950, 50):
m = farmer(crops, yields)
m.eval("param wc;")
m.param["wc"] = wc
m.eval("s.t. min_profit{s in SCENARIOS}: scenario_profit[s] >= wc;")
# maximize mean profit
m.eval(
"maximize objective: (sum{s in SCENARIOS} scenario_profit[s]) / card(SCENARIOS);"
)
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
df.loc[wc, "return"] = m.obj["objective"].value()
df.loc[wc, "wc"] = wc
df.plot(x="wc", y="return", xlabel="worst case", ylabel="mean return", grid=True)
# %%
df = pd.DataFrame()
for wc in np.linspace(56750, 56820, 50):
m = farmer(crops, yields)
m.eval("param wc;")
m.param["wc"] = wc
m.eval("s.t. min_profit{s in SCENARIOS}: scenario_profit[s] >= wc;")
# maximize mean profit
m.eval(
"maximize objective: (sum{s in SCENARIOS} scenario_profit[s]) / card(SCENARIOS);"
)
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
df.loc[wc, "return"] = m.obj["objective"].value()
df.loc[wc, "wc"] = wc
df.plot(x="wc", y="return", xlabel="worst case", ylabel="mean return", grid=True)
# %%
wc = 56800
m = farmer(crops, yields)
m.eval("param wc;")
m.param["wc"] = wc
m.eval("s.t. min_profit{s in SCENARIOS}: scenario_profit[s] >= wc;")
# maximize mean profit
m.eval(
"maximize objective: (sum{s in SCENARIOS} scenario_profit[s]) / card(SCENARIOS);"
)
m.solve(solver=SOLVER, verbose=False)
assert m.solve_result == "solved", m.solve_result
farm_report(m)
補足:風力出力抑制を伴う2段階の電力需給最適化 opf-wind-curtailment.py 11 セル ・ 175 行 ・ モデル 1
この節のモデル(1)
AMPLuc_windcurtailment.mod
set T;
set V;
set E within {V, V};
set W;
set NW;
param d{V};
param p_min{V};
param p_max{V};
param c_var{V};
param is_generator{V};
param energy_type{V} symbolic;
param c_fixed{V};
param b{E};
param f_max{E};
param vmax{W};
param samples{W, T};
param g{W, T};
param M;
# Declare decision variables
# Binary variable indicating whether a generator is on or off
var x{V} binary;
# Power generation of each generator
var p{V, T} >= 0;
# Voltage angle of each node
var theta{V, T};
# Power flow on each edge
var f{(i,j) in E, T} <= f_max[i,j], >= -f_max[i,j];
# Binary variable indicating whether a wind turbine is curtailed (0) or not (1)
var y{W, T} binary;
# Objective function, with the goal of minimizing the total cost of generation
var term1 =
sum{i in V: energy_type[i] in {"coal", "gas"}} M * x[i];
var term2{t in T} =
sum{i in V: is_generator[i] == 1} c_var[i] * p[i, t];
minimize objective:
term1 + sum{t in T} term2[t] / card(T);
# Declare constraints
# Wind power output is equal to the wind speed times the wind turbine capacity, if the wind turbine is not curtailed
s.t. wind_speed_to_power{i in W, t in T}:
p[i, t] == (1 - y[i, t]) * g[i, t];
s.t. wind_curtailment{i in W, t in T}:
samples[i, t] <= vmax[i] + y[i, t] * M;
s.t. generation_upper_bound{i in NW, t in T}:
p[i, t] <= x[i] * p_max[i];
s.t. generation_lower_bound{i in NW, t in T}:
p[i, t] >= x[i] * p_min[i];
# Net flow in every node must be equal to the power generation minus the demand in that node
var incoming_flow{i in V, t in T} = sum{j in V: (j, i) in E} f[j, i, t];
var outgoing_flow{i in V, t in T} = sum{j in V: (i, j) in E} f[i, j, t];
s.t. flow_conservation{i in V, t in T}:
incoming_flow[i, t] - outgoing_flow[i, t] == p[i, t] - d[i];
s.t. susceptance{(i,j) in E, t in T}:
f[i, j, t] == b[i, j] * (theta[i, t] - theta[j, t]);
# %%
# install dependencies and select solver
SOLVER = "highs"
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
# %%
# Load packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
import time
# Download the data
base_url = "https://raw.githubusercontent.com/ampl/mo-book.ampl.com/dev/notebooks/10/"
nodes_df = pd.read_csv(base_url + "nodes.csv").set_index("node_id")
edges_df = pd.read_csv(base_url + "edges.csv").set_index(["node_id1", "node_id2"])
# Replace 'na' by an empty string
nodes_df.fillna("", inplace=True)
network = {"nodes": nodes_df, "edges": edges_df}
# %%
edges_df
# %%
nodes_df
# %%
nodes_df[nodes_df.is_generator]
# %%
def g_offshore(v):
return np.piecewise(
v, [v <= 3.5, v > 15], [0, 600, lambda v: 0.18007 * v**3 - 7.72049]
)
def g_onshore(v):
return np.piecewise(
v, [v <= 3, v > 14], [0, 450, lambda v: 0.16563 * v**3 - 4.4718]
)
# assign wind generators
g_func = {64: g_onshore, 65: g_offshore}
# show plots
v = np.linspace(0, 20, 1000)
for i in g_func.keys():
plt.plot(v, g_func[i](v), label=i)
plt.legend()
plt.xlabel("Wind Speed")
plt.ylabel("Power Output")
# %%
def UC_windcurtailment(network, samples, g, vmax):
df_nodes = network["nodes"]
df_edges = network["edges"]
# Define a model
model = AMPL()
model.read("uc_windcurtailment.mod")
model.set_data(df_nodes, "V")
model.set_data(df_edges, "E")
model.set["T"] = range(samples.shape[1])
model.set["W"] = df_nodes.index[df_nodes["energy_type"] == "wind"]
model.set["NW"] = df_nodes.index[df_nodes["energy_type"] != "wind"]
model.param["M"] = 1000
model.param["samples"] = samples
model.param["g"] = g
model.param["vmax"] = vmax
model.option["solver"] = SOLVER
return model
# %%
seed = 0
rng = np.random.default_rng(seed)
scale64 = 15
shape64 = 2.6
scale65 = 18
shape65 = 3
nsamples = 100
samples = [
{64: scale64 * rng.weibull(shape64), 65: scale65 * rng.weibull(shape65)}
for i in range(nsamples)
]
g = [{k: g_func[k](s[k]) for k in s} for s in samples]
df_samples = pd.DataFrame(samples).T
df_g = pd.DataFrame(g).T
# Maximum wind speeds for each wind generator
vmax = {64: 20.0, 65: 22.0}
model = UC_windcurtailment(network, df_samples, df_g, vmax)
model.solve(verbose=False)
assert model.solve_result == "solved", model.solve_result
print(f"Objective value: {model.obj['objective'].value():.2f}")
y = model.var["y"].to_pandas()
y.index.names = ["W", "T"]
y = y.rename(columns={y.columns[0]: "y"})
W = [64, 65]
for w in W:
q = f"W == {w}"
v = y.query(q)["y"].sum()
print(f"Number of scenarios wind tubine {w} is active: {v:2.0f} out of {nsamples}")
# %%
def UC_windcurtailment_fixed_x(network, samples, g, vmax, fixed_x=None):
model = UC_windcurtailment(network, samples, g, vmax)
df_nodes = network["nodes"]
G = df_nodes.query('is_generator and energy_type != "wind"').index
if fixed_x is not None:
for i in G:
model.var["x"][i].fix(fixed_x[i])
return model
# %%
T = len(samples)
mean_sample = [
{i: np.array([samples[t][i] for t in range(T)]).mean() for i in samples[0].keys()}
]
g = [{k: g_func[k](s[k]) for k in s} for s in mean_sample]
df_samples = pd.DataFrame(mean_sample).T
df_g = pd.DataFrame(g).T
m_nominal = UC_windcurtailment_fixed_x(network, df_samples, df_g, vmax)
m_nominal.solve(verbose=False)
assert m_nominal.solve_result == "solved", m_nominal.solve_result
print(f"Nominal objective = {m_nominal.obj['objective'].value():0.2f}")
fixed_x = m_nominal.var["x"].to_dict()
# %%
# Variable to count the number of infeasible second stage problems
n_infeasible = 0
for t in range(T):
sample = [samples[t]]
g = [{k: g_func[k](s[k]) for k in s} for s in sample]
df_samples = pd.DataFrame(sample).T
df_g = pd.DataFrame(g).T
m_single = UC_windcurtailment_fixed_x(network, df_samples, df_g, vmax, fixed_x)
m_single.solve(verbose=False)
n_infeasible += 1 if m_single.solve_result == "infeasible" else 0
print(f"The second stage problem is infeasible in {n_infeasible} out of {T} instances")
該当するファイルはありません。