"""k-センター問題の定式化の比較実験

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

(P1)  kcenter.mod       : 本書の標準定式化（割当変数 x[i,j] と半径 z）
(P2)  kcenter_p2.mod    : Elloumi--Labbe--Pochet (2004)
(CP1) kcenter_cp1.mod   : Ales--Elloumi (2023) の改良版
(CP2) kcenter_cp2.mod   : Ales--Elloumi (2023) のコンパクト版
二分探索                : solve_kcenter.py と同じ kcover.mod による二分探索
"""
import math
import random
import sys
import time
from amplpy import AMPL

TLIM = 300


def make_data(n, seed):
    """単位正方形上のランダムな n 点（顧客 = 施設候補）。距離は 100 倍して整数に丸める"""
    random.seed(seed)
    pos = [(random.random(), random.random()) for _ in range(n)]
    I = J = list(range(1, n + 1))
    c = {(i, j): round(100 * math.dist(pos[i - 1], pos[j - 1])) for i in I for j in J}
    return I, J, c


def new(modfile, I, J, c, k, lp=False):
    a = AMPL()
    a.read(modfile)
    a.set["I"] = I
    a.set["J"] = J
    a.param["c"] = c
    a.param["k"] = k
    a.option["solver"] = "highs"
    a.option["highs_options"] = "time_limit=%d" % TLIM
    if lp:
        a.option["relax_integrality"] = 1
    return a


def set_D(a, c):
    D = sorted(set(c.values()))
    a.param["K"] = len(D) - 1
    a.param["D"] = dict(enumerate(D))
    return D


def radius(c, y):
    """開設施設 y から各顧客の最寄り施設までの距離の最大値（解の検証用）"""
    opened = [j for j, v in y.items() if v > .5]
    I = sorted({i for (i, _) in c})
    return max(min(c[i, j] for j in opened) for i in I)


def solve_formulation(name, mod, obj, I, J, c, k):
    a = new(mod, I, J, c, k)
    D = set_D(a, c) if mod != "kcenter.mod" else None
    t = time.time(); a.solve(verbose=False); t = time.time() - t
    v = a.get_objective(obj).value()
    if mod == "kcenter_cp2.mod":
        v = D[round(v)]
    y = a.var["y"].get_values().to_dict()
    # LP 緩和の値（CP2 は添字なので D 上に写さずそのまま）
    b = new(mod, I, J, c, k, lp=True)
    if D is not None:
        set_D(b, c)
    b.solve(verbose=False)
    lp = b.get_objective(obj).value()
    nv, nc = a.get_value("_nvars"), a.get_value("_ncons")
    return dict(name=name, time=t, status=a.solve_result, value=v,
                check=radius(c, y), lp=lp, nvars=nv, ncons=nc)


def binary_search(I, J, c, k, eps=1.e-4):
    """solve_kcenter.py と同じ連続値の二分探索"""
    a = new("kcover.mod", I, J, c, k)
    LB, UB = 0, max(c.values())
    t0 = time.time(); it = 0
    while UB - LB > eps:
        theta = (UB + LB) / 2.
        a.param["theta"] = theta
        a.solve(verbose=False); it += 1
        assert a.solve_result == "solved", a.solve_result
        if a.get_objective("Uncovered").value() > 0:
            LB = theta
        else:
            UB = theta
    return dict(name="二分探索", time=time.time() - t0, status="solved",
                value=UB, iters=it)


def binary_search_D(I, J, c, k):
    """距離の候補 D[0..K] 上での二分探索（反復回数は log2(K+1) 程度）"""
    a = new("kcover.mod", I, J, c, k)
    D = sorted(set(c.values()))
    lo, hi = -1, len(D) - 1       # D[lo] では被覆不能, D[hi] では被覆可能
    t0 = time.time(); it = 0
    while hi - lo > 1:
        mid = (lo + hi) // 2
        a.param["theta"] = D[mid]
        a.solve(verbose=False); it += 1
        assert a.solve_result == "solved", a.solve_result
        if a.get_objective("Uncovered").value() > .5:
            lo = mid
        else:
            hi = mid
    return dict(name="二分探索(D)", time=time.time() - t0, status="solved",
                value=D[hi], iters=it)


if __name__ == "__main__":
    cases = [(50, 5), (100, 5), (100, 10), (200, 5), (200, 10), (200, 20)]
    if len(sys.argv) > 1:
        cases = [tuple(map(int, s.split(","))) for s in sys.argv[1:]]
    for n, k in cases:
        I, J, c = make_data(n, 1)
        print("n=%d k=%d  異なる距離の数=%d" % (n, k, len(set(c.values()))), flush=True)
        for name, mod, obj in [("(P1)", "kcenter.mod", "MaxDist"),
                               ("(P2)", "kcenter_p2.mod", "Radius"),
                               ("(CP1)", "kcenter_cp1.mod", "Radius"),
                               ("(CP2)", "kcenter_cp2.mod", "RadiusIndex")]:
            r = solve_formulation(name, mod, obj, I, J, c, k)
            print("  %-6s %7.2f秒 %-8s 値=%-4g 検証=%-4g LP=%-7.2f 変数=%d 制約=%d"
                  % (r["name"], r["time"], r["status"], r["value"], r["check"],
                     r["lp"], r["nvars"], r["ncons"]), flush=True)
        for f in (binary_search, binary_search_D):
            r = f(I, J, c, k)
            print("  %-6s %7.2f秒 %-8s 値=%-4g 反復=%d"
                  % (r["name"], r["time"], r["status"], r["value"], r["iters"]),
                  flush=True)
