# 出典: mo-notebooks/01/production-planning-basic.ipynb

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