# 出典: mo-notebooks/09/seafood.ipynb

# %%
# 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()
