"""MAJ/UMA adder from XIV and exact forward/inverse checks on all pairs."""
from blocs import cx,apply
from fractions import Fraction
import json

def tof(a, b, c):
    return (1 << a | 1 << b, 1 << c)


def maj(a, b, c):
    return [cx(a, b), cx(a, c), tof(b, c, a)]


def uma(a, b, c):
    return [tof(b, c, a), cx(a, c), cx(c, b)]


def add(a, b, cin, cout=None):
    n = len(a)
    assert n == len(b)
    g = []
    for i in range(n):
        g += maj(a[i], b[i], cin if i == 0 else a[i - 1])
    if cout is not None:
        g.append(cx(a[-1], cout))
    for i in range(n - 1, -1, -1):
        g += uma(a[i], b[i], cin if i == 0 else a[i - 1])
    return g

def experiment():
    tests=0
    for n in range(1,7):
        a=list(range(n))
        b=list(range(n,2*n))
        cin,cout=2*n,2*n+1
        gates=add(a,b,cin,cout)
        for x in range(1<<n):
            for y in range(1<<n):
                start=x|(y<<n)
                correct=x|(((x+y)%(1<<n))<<n)|(((x+y)>>n)<<cout)
                assert apply(gates,start)==correct and apply(gates,correct,True)==start
                tests+=1
    return dict(adder_pairs=tests,unit_X_CNOT_threshold=str(Fraction(391428-35856,65736)))


if __name__=="__main__":print(json.dumps(experiment(),indent=2))
