Fewer-T multi-controlled Z, 6 data qubits, 1 spare

Multi-controlled Z submission #25

zihan_chen · submitted · verified 7 d ago · Accepted CC BY 4.0

T gates27
Operations61
Ancilla wires1

Verifier report

n data
6
t
27
gates
61
ancillas
1
measurements
1
records
2
records nonzero
2
simulated instructions
3968
check
all 64 inputs x 2 measurement records equal c_r U_N on data with live workspace |0>, sum |c_r|^2 = 1
verify seconds
0.05
View raw report
{
 "n_data": 6,
 "t": 27,
 "gates": 61,
 "ancillas": 1,
 "measurements": 1,
 "records": 2,
 "records_nonzero": 2,
 "simulated_instructions": 3968,
 "check": "all 64 inputs x 2 measurement records equal c_r U_N on data with live workspace |0>, sum |c_r|^2 = 1",
 "verify_seconds": 0.05
}

Submission file

Download submission JSON under Creative Commons Attribution 4.0 International (license file)

sha256 aa50a4db120c5f83251c08b2e3b3399bcf31574dee7b35f8588df14bffd53d06 · 619 bytes · verifier 0183d00bf58d

License

License: Creative Commons Attribution 4.0 International (CC BY 4.0, the default). Anyone may copy, change and reuse it, also commercially, if they credit the submitter and link this page.

Credit: zihan_chen, QArena submission Multi-controlled Z #25, with a link to this page. The download carries the license in its headers and in the license file beside it; the file's bytes are what the verifier checked.

Builds on

This submission names no earlier submission.

Cited by

No other submission names this submission yet.

How citations count

Attached code

ladder.py 6.3 KB

#!/usr/bin/env python3
"""Construct a temporary-AND ladder and Gidney--Jones six-T CCCZ.

Sources: C. Gidney, arXiv:1709.06648; C. Gidney and N. C. Jones,
arXiv:2106.11513 (CC BY 4.0). Original implementation of the published
construction; QArena's official example was used to cross-check conventions.
No contestant artifact is used. See README.md for provenance and derivation.
"""
import argparse
import json
from pathlib import Path


def temporary_and(a, b, t):
    return [['H', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['TDG', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['TDG', t], ['H', t], ['SDG', t]]


def cccz(a, b, c, d, t, rec, optimized=True):
    if optimized:
        # Exact search over the 64 T/TDG assignments of the published
        # parity network yields signs (+,-,+,+,-,+). Both CZ corrections
        # then fire on outcome 1, and the final SDG is unnecessary.
        return [['H', t], ['T', t], ['CX', b, t], ['TDG', t],
                ['CX', a, t], ['T', t], ['CX', b, t], ['CX', d, t],
                ['T', t], ['CX', c, t], ['TDG', t], ['CX', d, t],
                ['T', t], ['CX', c, t], ['MX', t],
                ['IF', [rec], 1, ['CZ', a, b]],
                ['IF', [rec], 1, ['CZ', c, d]]]
    return [['H', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['TDG', t], ['CX', a, t], ['T', t], ['CX', b, t],
            ['CX', d, t], ['TDG', t], ['CX', c, t], ['T', t],
            ['CX', d, t], ['TDG', t], ['CX', c, t], ['H', t],
            ['S', t], ['MX', t], ['IF', [rec], 0, ['CZ', a, b]],
            ['IF', [rec], 1, ['CZ', c, d]]]


def simplify(ops, n):
    """Remove CX into a freshly prepared |+>, and fuse H S before MX.

    For each outcome, <r_X| S H is proportional to <r_X| SDG with
    an outcome-dependent global phase. Thus both instruments have the same
    data map up to branch scalars, and the same outcome labeling.
    """
    out = []
    for op in ops:
        if op[0] == 'CX' and op[2] >= n and out and out[-1] == ['H', op[2]]:
            # All generated H here prepare a fresh zero workspace. This is
            # a construction-specific rewrite, not a generic circuit rule.
            continue
        out.append(op)
    i = 0
    while i + 2 < len(out):
        if (out[i][0] == 'H' and out[i+1] == ['S', out[i][1]]
                and out[i+2] == ['MX', out[i][1]]):
            out[i:i+2] = [['SDG', out[i][1]]]
        i += 1
    return out


def relative_ccx(a, b, t):
    """Four-T relative-phase Toffoli; its inverse cancels all relative phases."""
    return [['H', t], ['T', t], ['CX', b, t], ['TDG', t],
            ['CX', a, t], ['T', t], ['CX', b, t], ['TDG', t], ['H', t]]


def inverse(ops):
    adj = {'T': 'TDG', 'TDG': 'T', 'S': 'SDG', 'SDG': 'S'}
    return [[adj.get(g[0], g[0]), *g[1:]] for g in reversed(ops)]


def ccz(a, b, c, opened=()):
    """Seven-T, six-CX phase polynomial, with optional zero controls.

    Replacing an input bit x with 1-x flips the sign of every phase
    parity containing x, so negative controls need no explicit X gates.
    """
    opened = set(opened)
    def phase(wire, parity, coefficient):
        sign = coefficient * (-1 if len(opened.intersection(parity)) % 2 else 1)
        return ['T' if sign == 1 else 'TDG', wire]
    return [['CX', b, c], phase(c, [b,c], -1), ['CX', a, c],
            phase(c, [a,b,c], 1), ['CX', b, c], phase(c, [a,c], -1),
            ['CX', a, c], phase(b, [b], 1), phase(c, [c], 1),
            ['CX', a, b], phase(a, [a], 1), phase(b, [a,b], -1), ['CX', a, b]]


def construct(n, optimized=True, ancillas=None):
    if not 3 <= n <= 7:
        raise ValueError('n must be in [3,7]')
    if n in (5,6) and ancillas == 1:
        # When workspace n = x0*x1 is one, data wires 0 and 1 are known
        # to be one. Borrow them with relative-phase Toffolis, consume
        # them only in a phase controlled by n, and undo exactly.
        ops = temporary_and(0, 1, n)
        first = relative_ccx(2, 3, 0)
        ops += first
        if n == 5:
            ops += ccz(n, 0, 4, opened=[0])
        else:
            second = relative_ccx(4, 5, 1)
            ops += second + ccz(n, 0, 1, opened=[0,1]) + inverse(second)
        ops += inverse(first) + [['MX', n], ['IF', [0], 1, ['CZ', 0, 1]]]
        return {'ancillas': 1, 'ops': simplify(ops, n) if optimized else ops}
    if n == 6 and ancillas == 2:
        # Erase the first intermediate AND, reuse that workspace for CCCZ,
        # then recompute it to erase the remaining triple-AND. The first
        # and last CZ(0,1) feedbacks commute with everything between them
        # and combine into one parity-conditioned CZ.
        ops = temporary_and(0, 1, 6) + temporary_and(6, 2, 7)
        ops += [['MX', 6], ['RZ', 6]]
        ops += cccz(7, 3, 4, 5, 6, 1, optimized)
        ops += [['MX', 7], ['RZ', 6]]
        ops += temporary_and(0, 1, 6)
        ops += [['IF', [2], 1, ['CZ', 6, 2]], ['MX', 6],
                ['IF', [0, 3], 1, ['CZ', 0, 1]]]
        return {'ancillas': 2, 'ops': simplify(ops, n) if optimized else ops}
    if ancillas is not None and ancillas != max(1, n-3):
        raise ValueError('This ancilla limit is not implemented yet')
    if n == 3:
        ops = temporary_and(0, 1, n)
        ops += [['CZ', n, 2], ['MX', n], ['IF', [0], 1, ['CZ', 0, 1]]]
        ancillas = 1
    else:
        ancillas = n - 3
        ops, stack = [], []
        current = 0
        for j in range(n-4):
            t = n+j
            ops += temporary_and(current, j+1, t)
            stack.append((current, j+1, t))
            current = t
        ops += cccz(current, n-3, n-2, n-1, n+ancillas-1, 0, optimized)
        for rec, (a,b,t) in enumerate(reversed(stack), 1):
            ops += [['MX', t], ['IF', [rec], 1, ['CZ', a, b]]]
    return {'ancillas': ancillas, 'ops': simplify(ops, n) if optimized else ops}


def main():
    p = argparse.ArgumentParser()
    p.add_argument('n', type=int)
    p.add_argument('output', type=Path)
    p.add_argument('--baseline', action='store_true')
    p.add_argument('--ancillas', type=int)
    a = p.parse_args()
    art = construct(a.n, not a.baseline, a.ancillas)
    a.output.parent.mkdir(parents=True, exist_ok=True)
    a.output.write_text(json.dumps(art, separators=(',', ':'))+'\n')
    print(json.dumps({'output': str(a.output), 'gates': len(art['ops']),
                      't': sum(g[0] in ('T','TDG') for g in art['ops'])}))


if __name__ == '__main__':
    main()