"""Reversible fanout scheduling for a four-bit residue oracle, all gates explicit."""
from itertools import product
import json
def circuit(bits,parallel):
    # Compute four one-hot predicate bits [x mod 4 == j] using negative controls.
    # A negative control is counted as a primitive in this abstract library.
    a,b=bits
    if parallel:
        wires=[a,b,0,0,0,0,0,0,0,0,0,0]
        layers=[[('c',0,2),('c',1,3)],[('c',0,4),('c',2,6),('c',1,5),('c',3,7)],
                [('t',2*j,2*j+1,8+j,j) for j in range(4)],
                [('c',0,4),('c',2,6),('c',1,5),('c',3,7)],[('c',0,2),('c',1,3)]]
    else:
        wires=[a,b,0,0,0,0];layers=[[('t',0,1,2+j,j)] for j in range(4)]
    for layer in layers:
        used=set()
        for g in layer:
            if g[0]=='c':
                _,x,y=g;assert not (used&{x,y});used.update((x,y));wires[y]^=wires[x]
            else:
                _,x,y,z,j=g;assert not (used&{x,y,z});used.update((x,y,z));wires[z]^=int(2*wires[x]+wires[y]==j)
    assert wires[:2]==list(bits) and not any(wires[2:-4])
    assert wires[-4:]==[int(2*a+b==j) for j in range(4)]
    return dict(gates=sum(map(len,layers)),depth=len(layers),wires=len(wires),ancillas=len(wires)-6)
if __name__=='__main__':
    print(json.dumps({str(p):[circuit(bits,p) for bits in product((0,1),repeat=2)][0] for p in (False,True)},indent=2))
