"""グラフ彩色の定式化比較実験（10gcp-j.tex 表 table:gcp_comparison）

    AMPL_LICFILE=~/Documents/ampl/ampl.lic ../../.venv/bin/python exp_gcp.py 1

引数は乱数の種と頂点数のリスト。デモライセンス（2000変数・制約まで）では n>=20 で
サイズ制限に達するので、ライセンスファイルを指定して実行する。
"""
import random
import sys
import time
from amplpy import AMPL

TLIM = 30


def make_data(n, prob):
    V = list(range(1, n + 1))
    E = [(i, j) for i in V for j in V if i < j and random.random() < prob]
    return V, E


def new(modfile):
    ampl = AMPL()
    ampl.read(modfile)
    ampl.option["solver"] = "highs"
    ampl.option["highs_options"] = "time_limit=%d" % TLIM
    return ampl


def check(E, color):
    """color: 点 -> 色ラベル。正しい彩色なら使用色数、不正なら None"""
    bad = [(i, j) for (i, j) in E if color[i] == color[j]]
    return None if bad else len(set(color.values()))


def standard(V, E, K):
    a = new("gcp.mod")
    a.set["V"] = V; a.set["E"] = E; a.param["K"] = K
    t = time.time(); a.solve(verbose=False); t = time.time() - t
    x = a.var["x"].get_values().to_dict()
    color = {i: k for (i, k), v in x.items() if v > .5}
    return t, a.solve_result, a.get_objective("NumColors").value(), check(E, color)


def binary_search(V, E, UB):
    a = new("gcp_fixed_k.mod")
    a.set["V"] = V; a.set["E"] = E
    LB = 0
    t0 = time.time(); ok = True
    color = {i: i for i in V}  # 自明な n 彩色
    while UB - LB > 1:
        K = (UB + LB) // 2
        rest = TLIM - (time.time() - t0)
        if rest <= 0:
            ok = False; break
        a.option["highs_options"] = "time_limit=%g" % rest
        a.param["K"] = K
        a.solve(verbose=False)
        if a.solve_result == "solved" and a.get_objective("BadEdges").value() < .5:
            UB = K
            x = a.var["x"].get_values().to_dict()
            color = {i: k for (i, k), v in x.items() if v > .5}
        elif a.solve_result == "solved":
            LB = K
        else:
            ok = False; break
    return time.time() - t0, "solved" if ok else "limit", UB, check(E, color)


def partial_order(V, E, K):
    a = new("gcp_partial_order.mod")
    a.param["n"] = len(V); a.set["E"] = E; a.param["K"] = K
    t = time.time(); a.solve(verbose=False); t = time.time() - t
    x = a.var["x"].get_values().to_dict()
    color = {i: k for (i, k), v in x.items() if v > .5}
    return t, a.solve_result, a.get_objective("NumColors").value(), check(E, color)


def representative(V, E):
    a = new("gcp_representative.mod")
    a.param["n"] = len(V); a.set["E"] = E
    t = time.time(); a.solve(verbose=False); t = time.time() - t
    x = a.var["x"].get_values().to_dict()
    # 点 j の色 = 割り当てられた代表点 i（複数あれば最小の i）
    color = {}
    for (i, j), v in sorted(x.items()):
        if v > .5 and j not in color:
            color[j] = i
    reps_ok = all(x[color[j], color[j]] > .5 for j in V)
    c = check(E, color)
    return t, a.solve_result, a.get_objective("NumColors").value(), \
        (c if reps_ok else None)


def greedy(V, E):
    """次数の大きい順に、使える最小の色を塗る貪欲法（彩色数の上界）"""
    adj = {i: set() for i in V}
    for (i, j) in E:
        adj[i].add(j); adj[j].add(i)
    color = {}
    for i in sorted(V, key=lambda v: -len(adj[v])):
        used = {color[j] for j in adj[i] if j in color}
        color[i] = min(k for k in range(1, len(V) + 1) if k not in used)
    return max(color.values())


def lp_bound(mod, V, E, K=None):
    a = new(mod)
    a.option["relax_integrality"] = 1
    if mod == "gcp.mod":
        a.set["V"] = V
    else:
        a.param["n"] = len(V)
    a.set["E"] = E
    if K is not None:
        a.param["K"] = K
    a.solve(verbose=False)
    return a.get_objective("NumColors").value()


def fmt(r):
    t, st, obj, valid = r
    s = "%6.2f秒 %-7s 値=%g" % (t, st, obj)
    if valid is None:
        s += " [彩色が不正/未検証]"
    return s


if __name__ == "__main__":
    seed = int(sys.argv[1]) if len(sys.argv) > 1 else 1
    ns = [int(a) for a in sys.argv[2:]] or [15, 20, 25, 30, 35, 40]
    for n in ns:
        random.seed(seed)
        V, E = make_data(n, .5)
        K = greedy(V, E)  # 色数の上限 = 貪欲法で得た彩色数
        print("n=%d |E|=%d K=%d  LP: 標準=%.2f 半順序=%.2f 代表点=%.2f"
              % (n, len(E), K, lp_bound("gcp.mod", V, E, K),
                 lp_bound("gcp_partial_order.mod", V, E, K),
                 lp_bound("gcp_representative.mod", V, E)), flush=True)
        print("  標準    :", fmt(standard(V, E, K)), flush=True)
        print("  二分探索:", fmt(binary_search(V, E, K)), flush=True)
        print("  半順序  :", fmt(partial_order(V, E, K)), flush=True)
        print("  代表点  :", fmt(representative(V, E)), flush=True)
