"""Same network topology, same two terminals, permuted modular labels."""
from itertools import product,permutations
from random import Random
from pathlib import Path
from collections import Counter
import csv,json
def run():
    edges=[(int(r['u']),int(r['v'])) for r in csv.DictReader(Path(__file__).with_name('karate.csv').open())]
    gs={x:set() for edge in edges for x in edge}
    for u,v in edges:gs[u].add(v);gs[v].add(u)
    out={};a,b=4,31
    for seed in (None,11,12,13):
        labels=list(range(len(gs)))
        if seed is not None:Random(seed).shuffle(labels)
        dom=[[r for r in range(p) if r not in (labels[a]%p,labels[b]%p)] for p in (5,7,11)]
        ok=total=0
        for rs in product(*dom):
            alive={x for x in gs if all(labels[x]%p!=r for p,r in zip((5,7,11),rs))}
            seen={a};stack=[a]
            while stack:
                x=stack.pop();new=(gs[x]&alive)-seen;seen.update(new);stack.extend(new)
            cc={a}
            while True:
                size=len(cc)
                for x,y in edges:
                    if x in alive and y in alive and (x in cc or y in cc):cc.update((x,y))
                if len(cc)==size:break
            assert cc==seen;total+=1;ok+=int(b in cc)
        out[str(seed)]=[ok,total]
    paths=[(1,2),(2,4),(4,8),(1,9)]
    systems=[]
    for ps in [(3,5,7),(7,5,3)]:
        states={15:1};counts=[]
        for p in ps:
            nxt=Counter()
            for mask,num in states.items():
                for r in range(p):
                    live=sum(1<<j for j,path in enumerate(paths) if all(x%p!=r for x in path))
                    nxt[mask&live]+=num
            states=nxt;counts.append(len(nxt))
        brute=Counter(sum(1<<i for i,path in enumerate(paths) if all(x%p!=r for x in path for p,r in zip(ps,phase))) for phase in product(*(range(p) for p in ps)))
        assert states==brute
        systems.append([counts,sorted(states.items())])
    assert systems[0][1]==systems[1][1]
    return dict(topologies=out,orders=systems)
if __name__=='__main__':print(json.dumps(run(),indent=2))
