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

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