import math, random
from amplpy import AMPL

def components(V, edges):
    adj = {i: set() for i in V}
    for (i, j) in edges:
        adj[i].add(j); adj[j].add(i)
    seen, comps = set(), []
    for v in V:
        if v in seen: continue
        stack, comp = [v], set()
        while stack:
            u = stack.pop()
            if u in comp: continue
            comp.add(u); seen.add(u)
            stack.extend(adj[u] - comp)
        comps.append(comp)
    return comps

def make_data(n):
    V = list(range(1, n+1))
    px = {i: random.random() for i in V}
    py = {i: random.random() for i in V}
    c = {(i,j): math.hypot(px[i]-px[j], py[i]-py[j])
         for i in V for j in V if i < j}
    return V, c

def solve_tsp(V, c):
    ampl = AMPL()
    ampl.read("tsp.mod")
    ampl.set["V"] = V
    ampl.param["c"] = c
    ampl.option["solver"] = "highs"
    EPS = 1.e-6
    nCut = 0
    ampl.option["relax_integrality"] = 1
    while True:
        ampl.solve(verbose=False)
        assert ampl.solve_result == "solved", ampl.solve_result
        xs = ampl.get_variable("x").get_values().to_pandas()
        edges = [(i, j) for (i, j), r in xs.iterrows() if r["x.val"] > EPS]
        comps = components(V, edges)
        if len(comps) == 1:
            if ampl.option["relax_integrality"] == 0:
                break
            ampl.option["relax_integrality"] = 0
        else:
            for comp in comps:
                nCut += 1
                ampl.param["nCut"] = nCut
                ampl.get_set("S")[nCut].set_values(sorted(comp))
    return ampl.get_objective("Length").value(), edges

random.seed(1)
V, c = make_data(20)
obj, edges = solve_tsp(V, c)
print("Opt.value=", round(obj, 4))
print("edges:", len(edges))
