from amplpy import AMPL

I = [1,2,3,4,5]
J = [1,2,3]
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}

def load(modfile, k):
    ampl = AMPL()
    ampl.read(modfile)
    ampl.set["I"] = I
    ampl.set["J"] = J
    ampl.param["c"] = c
    ampl.param["k"] = k
    ampl.option["solver"] = "highs"
    return ampl

for mod, obj in [("kmedian.mod","Cost"), ("kcenter.mod","MaxDist")]:
    a = load(mod, 2)
    a.solve(verbose=False)
    assert a.solve_result == "solved", a.solve_result
    print(mod, "->", obj, "=", a.get_objective(obj).value())

# 二分探索
ampl = load("kcover.mod", 2)
LB, UB = 0, max(c.values())
while UB - LB > 1.e-4:
    theta = (UB + LB) / 2.
    ampl.param["theta"] = theta
    ampl.solve(verbose=False)
    assert ampl.solve_result == "solved", ampl.solve_result
    if ampl.get_objective("Uncovered").value() > 0:
        LB = theta
    else:
        UB = theta
print("binary search theta =", UB)
