# 出典: mo-notebooks/09/pop-up_shop.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

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