"""輸送問題（1.4 節）と双対問題（1.5 節）."""
from amplpy import AMPL
import pandas as pd

ampl = AMPL()
ampl.read("transp.mod")

customer_df = pd.DataFrame(
    [(1, 80), (2, 270), (3, 250), (4, 160), (5, 180)],
    columns=["I", "d"]).set_index("I")
factory_df = pd.DataFrame(
    [(1, 500), (2, 500), (3, 500)],
    columns=["J", "M"]).set_index("J")
c = {(1,1):4,    (1,2):6,    (1,3):9,
     (2,1):5,    (2,2):4,    (2,3):7,
     (3,1):6,    (3,2):3,    (3,3):4,
     (4,1):8,    (4,2):5,    (4,3):3,
     (5,1):10,   (5,2):8,    (5,3):4,
     }

ampl.set_data(customer_df, "I")
ampl.set_data(factory_df, "J")
ampl.get_parameter("c").set_values(c)

ampl.option["solver"] = "highs"
ampl.solve()
assert ampl.solve_result == "solved"

print("Optimal value:", ampl.get_objective("Cost").value())
EPS = 1.e-6
xs = ampl.get_variable("x").get_values().to_pandas()
for (i, j), row in xs.iterrows():
    if row["x.val"] > EPS:
        print("sending quantity %10s from factory %3s to customer %3s"
              % (row["x.val"], j, i))

# --- 双対問題（1.5 節）---
print()
print(ampl.get_data("{i in I} Demand[i].slack",
                    "{i in I} Demand[i].dual").to_pandas())
print()
print(ampl.get_data("{j in J} Capacity[j].slack",
                    "{j in J} Capacity[j].dual").to_pandas())
