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 or not adj[v]: 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

random.seed(5)
n, m, Q = 10, 3, 100
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}
q = {1: 0}
for i in V[1:]:
    q[i] = random.randint(10, 40)

ampl = AMPL(); ampl.read("vrp.mod")
ampl.param["n"] = n; ampl.param["c"] = c; ampl.param["q"] = q
ampl.param["Q"] = Q; ampl.param["m"] = m
ampl.option["solver"] = "highs"

nCut = 0
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"] > .5 and i != 1 and j != 1]
    added = 0
    for S in components(V, edges):
        S_card = len(S)
        NS = int(math.ceil(sum(q[i] for i in S) / Q))
        S_edges = [(i, j) for i in S for j in S if i < j and (i, j) in edges]
        if S_card >= 2 and (len(S_edges) >= S_card or NS > 1):
            nCut += 1
            ampl.param["nCut"] = nCut
            ampl.get_set("S")[nCut].set_values(sorted(S))
            ampl.param["NS"] = {nCut: NS}
            added += 1
    if added == 0:
        break
print("cuts added:", nCut)
print("Opt.value=", round(ampl.get_objective("Length").value(), 2))
