# 出典: mo-notebooks/10/farmer.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

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