"""Partition phase space by the first live path and check a public graph instance."""
from collections import Counter,deque
from itertools import product
from pathlib import Path
import csv,json
def partition(paths,ps):
    dp={(1<<len(paths))-1:1};sizes=[]
    for p in ps:
        nxt=Counter()
        for r in range(p):
            survive=sum(1<<i for i,path in enumerate(paths) if all(x%p!=r for x in path))
            for m,n in dp.items():nxt[m&survive]+=n
        dp=nxt;sizes.append(len(dp))
    first=Counter()
    for mask,weight in dp.items():first[(mask&-mask).bit_length()-1]+=weight
    oracle=Counter()
    for phase in product(*(range(p) for p in ps)):
        i=next((j for j,path in enumerate(paths) if all(all(x%p!=r for x in path) for p,r in zip(ps,phase))),-1)
        oracle[i]+=1
    assert first==oracle
    return dict(first=dict(sorted(first.items())),states=sizes)
def graph():
    edges=[(int(r['u']),int(r['v'])) for r in csv.DictReader(Path(__file__).with_name('karate.csv').open())]
    adj={x:set() for e in edges for x in e}
    for x,y in edges:adj[x].add(y);adj[y].add(x)
    def connected(nodes,u,v):
        stack=[u];seen={u}
        while stack:
            x=stack.pop()
            for y in (adj[x]&nodes)-seen:stack.append(y);seen.add(y)
        return v in seen
    data={}
    for u,v in [(0,33),(1,3),(4,31)]:
        ps=(5,7,11)
        dom=[[a for a in range(p) if a not in (u%p,v%p)] for p in ps]
        survived=0;bad=None
        for phase in product(*dom):
            nodes={x for x in adj if all(x%p!=a for p,a in zip(ps,phase))}
            ok=connected(nodes,u,v)
            # Independent component closure by scanning all edges.
            comp={u}
            while True:
                old=len(comp)
                for x,y in edges:
                    if x in nodes and y in nodes and (x in comp or y in comp):comp.update((x,y))
                if len(comp)==old:break
            assert ok==(v in comp);survived+=ok
            if not ok and bad is None:bad=phase
        data[str((u,v))]=dict(connected=survived,phases=len(list(product(*dom))),first_failure=bad)
    return data
if __name__=='__main__':
    cases=[[(1,2),(2,4),(4,8)],[(1,),(2,),(3,),(4,)],[(1,2)]*4,[(1,),(2,),(3,),(4,),(5,),(6,)]]
    print(json.dumps(dict(cases=[partition(c,(3,5,7)) for c in cases],graph=graph()),indent=2))
