import math, random
from amplpy import AMPL

def pareto_front(cand):
    front = []
    for (T1, C1) in sorted(set(cand)):
        if all(not (T2 <= T1 and C2 <= C1 and (T2, C2) != (T1, C1))
               for (T2, C2) in cand):
            front.append((T1, C1))
    return front

def base_model(n, c, t):
    ampl = AMPL()
    ampl.read("biobj_tsp.mod")
    ampl.param["n"] = n
    ampl.param["c"] = c
    ampl.param["t"] = t
    ampl.option["solver"] = "highs"
    return ampl

def optimize(ampl, cand):
    ampl.solve(verbose=False)
    assert ampl.solve_result == "solved", ampl.solve_result
    cand.append((ampl.get_variable("T").value(),
                 ampl.get_variable("C").value()))

random.seed(2)
n = 8
V = list(range(1, n+1))
px = {i: random.random()*100 for i in V}
py = {i: random.random()*100 for i in V}
c = {(i,j): round(math.hypot(px[i]-px[j], py[i]-py[j]), 1) for i in V for j in V if i != j}
t = {(i,j): round(random.random()*50 + 5, 1) for i in V for j in V if i != j}

# --- 線形和によるスカラー化 ---
def explore(ampl, C1, T1, C2, T2, front):
    if T2 <= T1: return front
    alpha = (C1 - C2) / (T2 - T1)
    init = list(front)
    ampl.param["alpha"] = alpha
    ampl.eval("objective Scalar;")
    optimize(ampl, front)
    front = pareto_front(front)
    if front == init: return front
    CM = ampl.get_variable("C").value(); TM = ampl.get_variable("T").value()
    if TM > T1: front = explore(ampl, C1, T1, CM, TM, front)
    if T2 > TM: front = explore(ampl, CM, TM, C2, T2, front)
    return front

ampl = base_model(n, c, t)
cand = []
ampl.eval("objective Time;"); optimize(ampl, cand)
T1 = ampl.get_variable("T").value(); C1 = ampl.get_variable("C").value()
ampl.eval("objective Cost;"); optimize(ampl, cand)
T2 = ampl.get_variable("T").value(); C2 = ampl.get_variable("C").value()
front = explore(ampl, C1, T1, C2, T2, pareto_front(cand))
print("scalarization front:", [(round(a,1), round(b,1)) for a,b in front])

# --- 制約を移動させる方法（イプシロン制約法） ---
ampl2 = base_model(n, c, t)
cand = []
ampl2.eval("objective Time;"); optimize(ampl2, cand)
ampl2.eval("objective Cost;"); optimize(ampl2, cand)
times = [ti for (ti, ci) in cand]
max_time, min_time = max(times), min(times)
segments = 5
delta = (max_time - min_time) / segments
ampl2.eval("objective Cost;")
for i in range(segments + 1):
    ampl2.param["time_ub"] = max_time - delta*i
    optimize(ampl2, cand)
print("epsilon front:", [(round(a,1), round(b,1)) for a,b in pareto_front(cand)])
