"""(S,l) 不等式による切除平面法（7.x 節）.

標準定式化の線形最適化緩和の下界が、施設配置定式化と同じところまで上がることを確かめる。
"""
import random
from amplpy import AMPL

random.seed(7)
T = 5
P = ["A", "B"]
Ts = list(range(1, T+1))
d = {(t, p): random.randint(20, 60) for t in Ts for p in P}
f = {(t, p): 100 for t in Ts for p in P}
g = {(t, p): 5 for t in Ts for p in P}
c = {(t, p): 1 for t in Ts for p in P}
h = {(t, p): 2 for t in Ts for p in P}
M = {t: 200 for t in Ts}


def load(modfile):
    ampl = AMPL()
    ampl.read(modfile)
    ampl.param["T"] = T
    ampl.set["P"] = P
    for name, value in [("f", f), ("g", g), ("c", c),
                        ("d", d), ("h", h), ("M", M)]:
        ampl.param[name] = value
    ampl.option["solver"] = "highs"
    return ampl


D = {(t, l, p): sum(d[u, p] for u in range(t, l+1))
     for t in Ts for l in Ts for p in P}

ampl = load("mils.mod")
ampl.option["relax_integrality"] = 1
nCut = 0
while True:
    ampl.solve(verbose=False)
    assert ampl.solve_result == "solved"
    ys = ampl.get_variable("y").get_values().to_pandas()
    xs = ampl.get_variable("x").get_values().to_pandas()
    added = 0
    for p in P:
        for ell in Ts:
            lhs, S, Lst = 0, [], []
            for t in range(1, ell+1):
                yt = ys.loc[(t, p), "y.val"]
                xt = xs.loc[(t, p), "x.val"]
                if D[t, ell, p]*yt < xt:
                    S.append(t)
                    lhs += D[t, ell, p]*yt
                else:
                    Lst.append(t)
                    lhs += xt
            if lhs < D[1, ell, p] - 1.e-6 and S:
                nCut += 1
                ampl.param["nCut"] = nCut
                ampl.get_set("SS")[nCut].set_values(S)
                ampl.param["cutP"] = {nCut: p}
                ampl.param["cutL"] = {nCut: ell}
                added += 1
    if added == 0:
        break

print("追加した (S,l) 不等式:", nCut)
print("切除平面後の LP 下界: %.2f" % ampl.get_objective("Cost").value())
ampl.option["relax_integrality"] = 0
ampl.solve(verbose=False)
print("整数最適値          : %.2f" % ampl.get_objective("Cost").value())
