# 出典: mo-notebooks/05/milk-pooling.ipynb

# %%
# install dependencies and select solver

SOLVER_LO = "cbc"
SOLVER_GNLO = "couenne"

from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["coin"],  # modules to install
    license_uuid="default",  # license to use
)  # instantiate AMPL object and register magics

# %%
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from itertools import product

# %%
customers = pd.DataFrame(
    {
        "Customer 1": {"min_fat": 0.045, "price": 52.0, "demand": 6000.0},
        "Customer 2": {"min_fat": 0.030, "price": 48.0, "demand": 2500.0},
        "Customer 3": {"min_fat": 0.040, "price": 50.0, "demand": 4000.0},
    }
).T

suppliers = pd.DataFrame(
    {
        "Farm A": {"fat": 0.045, "cost": 45.0, "location": "local"},
        "Farm B": {"fat": 0.030, "cost": 42.0, "location": "local"},
        "Farm C": {"fat": 0.033, "cost": 37.0, "location": "remote"},
        "Farm D": {"fat": 0.050, "cost": 45.0, "location": "remote"},
    },
).T

local_suppliers = suppliers[suppliers["location"] == "local"]
remote_suppliers = suppliers[suppliers["location"] == "remote"]

print("\nCustomers")
display(customers)

print("\nSuppliers")
display(suppliers)

# %%
model = AMPL()
model.eval(
    """
    # define sources and customers
    set L;
    set C;

    param price{C};
    param demand{C};
    param min_fat{C};
    param cost{L};
    param fat{L};

    # define local -> customer flowrates
    var z{L cross C} >= 0;

    maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l]);

    subject to demand_req{c in C}:
        sum{l in L} z[l, c] <= demand[c];

    subject to fat_content{c in C}:
        sum{l in L} z[l, c] * fat[l] >= sum{l in L} z[l, c] * min_fat[c];
"""
)

model.set_data(customers, "C")
model.set_data(local_suppliers.drop(columns=["location"]), "L")

model.solve(solver=SOLVER_LO, verbose=False)
assert model.solve_result == "solved", model.solve_result

# report results
print(f"\nProfit = {model.obj['profit'].value():0.2f}\n")

# create dataframe of results
z = model.var["z"]
L = model.set["L"]
C = model.set["C"]

print("Blending Plan")
Z = pd.DataFrame(
    [[l, c, round(z[l, c].value(), 1)] for l in L.members() for c in C.members()],
    columns=["supplier", "customer", ""],
)
Z = Z.pivot_table(index="customer", columns="supplier")
Z["Total"] = Z.sum(axis=1)
Z["fat content"] = [
    sum(z[l, c].value() * suppliers.loc[l, "fat"] for l in L.members())
    / sum(z[l, c].value() for l in L.members())
    for c in C.members()
]
Z["min_fat"] = customers["min_fat"]

display(Z)

# %%
model = AMPL()
model.eval(
    """
    # define sources and customers
    set S;
    set C;

    param price{C};
    param demand{C};
    param min_fat{C};
    param cost{S};
    param fat{S};

    # define local -> customer flowrates
    var z{S cross C} >= 0;

    maximize profit: sum{s in S, c in C} z[s, c]*(price[c] - cost[s]);

    subject to demand_req{c in C}:
        sum{s in S} z[s, c] <= demand[c];

    subject to quality{c in C}:
        sum{s in S} z[s, c] * fat[s] >= sum{s in S} z[s, c] * min_fat[c];
"""
)

model.set_data(customers, "C")
model.set_data(suppliers.drop(columns=["location"]), "S")

model.solve(solver=SOLVER_LO, verbose=False)
assert model.solve_result == "solved", model.solve_result

# report results
print(f"\nProfit = {model.obj['profit'].value():0.2f}\n")

# create dataframe of results
z = model.var["z"]
S = model.set["S"]
C = model.set["C"]

print("Blending Plan")
Z = pd.DataFrame(
    [[s, c, round(z[s, c].value(), 1)] for s in S.members() for c in C.members()],
    columns=["supplier", "customer", ""],
)
Z = Z.pivot_table(index="customer", columns="supplier")
Z["Total"] = Z.sum(axis=1)
Z["fat content"] = [
    sum(z[s, c].value() * suppliers.loc[s, "fat"] for s in S.members())
    / sum(z[s, c].value() for s in S.members())
    for c in C.members()
]
Z["min_fat"] = customers["min_fat"]

display(Z)

# %%
model_p_fixed = AMPL()
model_p_fixed.eval(
    """
  # define sources
  set L;
  set R;

  # define customers
  set C;

  # define flowrates
  var x{R} >= 0;
  var y{C} >= 0;
  var z{L cross C} >= 0;

  param p >= 0;
  param price{C};
  param demand{C};
  param min_fat{C};
  param cost{L union R};
  param fat{L union R};

  maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l])
                    + sum{c in C} price[c]*y[c]
                    - sum{r in R} cost[r]*x[r];

  subject to customer_demand{c in C}:
      y[c] + sum{l in L} z[l, c] <= demand[c];

  subject to pool_balance:
    sum{r in R} x[r] = sum{c in C} y[c];

  subject to pool_quality:
    sum{r in R} fat[r]*x[r] = p*sum{c in C} y[c];

  subject to customer_quality{c in C}:
      p*y[c] + sum{l in L} fat[l]*z[l,c] >= min_fat[c]*(sum{l in L} z[l, c] + y[c]);
"""
)

model_p_fixed.set_data(customers, "C")
model_p_fixed.set_data(local_suppliers.drop(columns=["location"]), "L")
model_p_fixed.set_data(remote_suppliers.drop(columns=["location"]), "R")


# solve milk pooling problem for a fixed pool composition p
def f(p):
    model_p_fixed.param["p"] = p
    model_p_fixed.solve(solver=SOLVER_LO, verbose=False)
    assert model_p_fixed.solve_result == "solved", model_p_fixed.solve_result
    return model_p_fixed

# %%
p_plot = np.linspace(0.025, 0.055, 200)
f_plot = [f(p).obj["profit"].value() for p in p_plot]

fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit f")
ax.grid(True)
plt.show()

# %%
def milk_pooling_convex():
    m = AMPL()
    m.eval(
        """
    # define sources
    set L;
    set R;

    # define customers
    set C;

    param price{C};
    param demand{C};
    param min_fat{C};
    param cost{L union R};
    param fat{L union R} default 0;

    # define flowrates
    var x{R} >= 0;
    var y{c in C} >= 0 <= demand[c];
    var z{L cross C} >= 0;
    # composition of the pool
    var p >= min{r in R} fat[r] <= max{r in R} fat[r];

    # w[c] to replace bilinear terms p * y[c]
    var w{C} >= 0;

    maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l])
                      + sum{c in C} price[c]*y[c]
                      - sum{r in R} cost[r]*x[r];

    subject to customer_demand{c in C}:
        y[c] + sum{l in L} z[l, c] <= demand[c];

    subject to pool_balance:
      sum{r in R} x[r] = sum{c in C} y[c];

    subject to pool_quality:
      sum{r in R} fat[r]*x[r] = sum{c in C} w[c];

    subject to customer_quality{c in C}:
        w[c] + sum{l in L} fat[l]*z[l,c] >= min_fat[c]*(sum{l in L} z[l, c] + y[c]);

    subject to
      mccormick_ll{c in C}: w[c] >= y[c].lb0*p + p.lb0*y[c] - p.lb0*y[c].lb0;
      mccormick_hh{c in C}: w[c] >= y[c].ub0*p + p.ub0*y[c] - p.ub0*y[c].ub0;
      mccormick_lh{c in C}: w[c] <= y[c].ub0*p + p.lb0*y[c] - p.lb0*y[c].ub0;
      mccormick_hl{c in C}: w[c] <= y[c].lb0*p + p.ub0*y[c] - p.ub0*y[c].lb0;
  """
    )

    m.set_data(customers, "C")
    m.set_data(local_suppliers.drop(columns=["location"]), "L")
    m.set_data(remote_suppliers.drop(columns=["location"]), "R")

    m.solve(solver=SOLVER_LO, verbose=False)
    assert m.solve_result == "solved", m.solve_result
    return m

# %%
def report_solution(m, model_title):
    x = m.var["x"]
    y = m.var["y"]
    z = m.var["z"]
    if model_title == "Milk Pooling Model":
        p = m.param["p"]
    else:
        p = m.var["p"]
    L = m.set["L"]
    R = m.set["R"]
    C_model = m.set["C"]

    # Supplier report
    S = suppliers.copy()
    for l in L.members():
        for c in C_model.members():
            S.loc[l, c] = z[l, c].value()
    for r in R.members():
        S.loc[r, "Pool"] = x[r].value()
    S = S.fillna(0)
    S["Amount"] = S[C_model.members()].sum(axis=1) + S["Pool"]
    S["Expense"] = S["Amount"] * S["cost"]

    # Customer report
    C = customers.copy()
    for c in C_model.members():
        for l in L.members():
            C.loc[c, l] = z[l, c].value()
    for c in C_model.members():
        C.loc[c, "Pool"] = y[c].value()
    C = C.fillna(0)
    C["Amount"] = C[L.members()].sum(axis=1) + C["Pool"]
    C["fat delivered"] = (
        sum(C[l] * S.loc[l, "fat"] for l in L.members()) + C["Pool"] * p.value()
    ) / C["Amount"]
    C["Income"] = C["Amount"] * C["price"]

    print(model_title)
    print(f"\nPool composition = {p.value():0.2f}")
    print(f"Profit = {m.obj['profit'].value():0.2f}")
    print(f"\nSupplier Report\n")
    display(S.round(4))
    print(f"\nCustomer Report\n")
    display(C.round(4))


m_convex = milk_pooling_convex()

report_solution(m_convex, "Milk Pooling Model - Convex Approximation")

# %%
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit")
ax.grid(True)

ax.plot(m_convex.var["p"].value(), m_convex.obj["profit"].value(), "ro", ms=10)
ax.axhline(m_convex.obj["profit"].value(), color="r", linestyle="--")
ax.axvline(m_convex.var["p"].value(), color="r", linestyle="--")
ax.annotate(
    "convex approximation",
    xy=(m_convex.var["p"].value(), m_convex.obj["profit"].value()),
    xytext=(0.036, 106000),
    ha="right",
    fontsize=14,
    arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)

# %%
p = m_convex.var["p"].value()
m_convex_profit = m_convex.obj["profit"].value()

m_est = f(p)
m_est_profit = m_est.obj["profit"].value()

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit")
ax.grid(True)

ax.plot(p, m_convex_profit, "ro", ms=10)
ax.axhline(m_convex_profit, color="r", linestyle="--")
ax.axvline(p, color="r", linestyle="--")
ax.annotate(
    "convex approximation",
    xy=(p, m_convex_profit),
    xytext=(0.036, 106000),
    ha="right",
    fontsize=14,
    arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)

ax.plot(p, m_est_profit, "go", ms=10)
ax.axhline(m_est_profit, color="g", linestyle="--")
ax.annotate(
    "local maxima",
    xy=(p, m_est_profit),
    xytext=(0.045, 105000),
    ha="left",
    fontsize=14,
    arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)
plt.show()

# %%
report_solution(m_est, "Milk Pooling Model")

# %%
def milk_pooling_bilinear():
    m = AMPL()
    m.eval(
        """
    # define sources
    set L;
    set R;

    # define customers
    set C;

    param price{C};
    param demand{C};
    param min_fat{C};
    param cost{L union R};
    param fat{L union R};

    # define flowrates
    var x{R} >= 0;
    var y{C} >= 0;
    var z{L cross C} >= 0;
    # composition of the pool
    var p >= min{r in R} fat[r] <= max{r in R} fat[r];

    maximize profit: sum{l in L, c in C} z[l, c]*(price[c] - cost[l])
                      + sum{c in C} price[c]*y[c]
                      - sum{r in R} cost[r]*x[r];

    subject to customer_demand{c in C}:
        y[c] + sum{l in L} z[l, c] <= demand[c];

    subject to pool_balance:
      sum{r in R} x[r] = sum{c in C} y[c];

    subject to pool_quality:
      sum{r in R} fat[r]*x[r] = p*sum{c in C} y[c];

    subject to customer_quality{c in C}:
        p*y[c] + sum{l in L} fat[l]*z[l,c] >= min_fat[c]*(sum{l in L} z[l, c] + y[c]);
  """
    )

    m.set_data(customers, "C")
    m.set_data(local_suppliers.drop(columns=["location"]), "L")
    m.set_data(remote_suppliers.drop(columns=["location"]), "R")

    m.solve(solver=SOLVER_GNLO, verbose=False)
    assert m.solve_result == "solved", m.solve_result
    return m

# %%
m_global = milk_pooling_bilinear()

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(p_plot, f_plot)
ax.set_title("Milk Pooling")
ax.set_xlabel("Pool composition p")
ax.set_ylabel("Profit")
ax.grid(True)

ax.plot(p, m_convex_profit, "ro", ms=10)
ax.axhline(m_convex_profit, color="r", linestyle="--")
ax.axvline(p, color="r", linestyle="--")
ax.annotate(
    "convex approximation",
    xy=(p, m_convex_profit),
    xytext=(0.036, 106000),
    ha="right",
    fontsize=14,
    arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)

ax.plot(p, m_est_profit, "go", ms=10)
ax.axhline(m_est_profit, color="g", linestyle="--")
ax.annotate(
    "local maxima",
    xy=(p, m_est_profit),
    xytext=(0.045, 105000),
    ha="left",
    fontsize=14,
    arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)

m_global_p = m_global.var["p"].value()
m_global_profit = m_global.obj["profit"].value()

ax.plot(m_global_p, m_global_profit, "bo", ms=10)
ax.axhline(m_global_profit, color="b", linestyle="--")
ax.annotate(
    "global maxima",
    xy=(m_global_p, m_global_profit),
    xytext=(0.025, 95000),
    ha="left",
    fontsize=14,
    arrowprops=dict(shrink=0.1, width=1, headwidth=5),
)

report_solution(m_global, "Milk Pooling Model - Bilinear")
