Algorithm Search⌘K

Algorithmadvanced

Transformation-based reversible synthesis

Also called MMD algorithm, Miller-Maslov-Dueck synthesis.

Miller, Maslov and Dueck's method that walks the truth table in order and adds Toffoli gates to map each row to itself, always ending with a correct circuit.

Time
O(n 4^n) worst
Space
O(n 2^n) circuitO(2^n) tables
Where
n = the number of lines
Properties
deterministicnot exactiterative
Origin
D. Michael Miller, Dmitri Maslov, Gerhard W. Dueck, 2003

Transformation-based synthesis, from Miller, Maslov and Dueck (DAC 2003), builds a circuit of multiple-control Toffoli gates for a reversible function given as a truth table. It reads the rows in increasing order. For row ii, it adds gates at the outputs that change the current output of that row into ii, with controls chosen so that the rows already done do not change. When every row maps to itself, the gates, read backward, form a circuit for the function. It needs no search and no extra lines, always ends with a correct circuit, and uses at most (n−1)2n+1(n - 1) 2^n + 1 gates on nn lines. The bidirectional form also adds gates at the inputs when that is cheaper.

In plain words

Write the function as a table: input pattern on the left, output pattern on the right, one row per pattern. Change the right column, one gate at a time, until it equals the left column. Then the gates you used, in reverse order, compute the function.

Go down the rows from the top. In the current row, flip the bits that are wrong. Choose each flip so that it fires only on patterns at least as large as this row, so it cannot spoil the rows above, which already match. When you reach the last row it is right by itself, because every other pattern is already used.

The problem

Given a permutation ff of {0,…,2n−1}\{0, \dots, 2^n - 1\}, a reversible function on nn lines, find a circuit of NOT, CNOT, Toffoli and larger Toffoli gates on the same nn lines that computes it, with few gates. The problem page defines the gates and the costs. Here a gate T(C;t)T(C; t) flips line tt when every line in the set CC is 1, and line tt is bit tt of the number.

The algorithm

The algorithm keeps the current table out\mathit{out} and its inverse inv\mathit{inv}. A gate GG added at the outputs replaces out\mathit{out} by G∘outG \circ \mathit{out}. A gate added at the inputs replaces out\mathit{out} by out∘G\mathit{out} \circ G, which is the same as replacing inv\mathit{inv} by G∘invG \circ \mathit{inv}, since every gate is its own inverse. Row ii is done when out[i]=i\mathit{out}[i] = i. Write dd for the Hamming distance and ones(x)\mathrm{ones}(x) for the set of lines where xx is 1.

  1. SYNTHESIZE(f, bidirectional)
  2. 1out ← f; inv ← f⁻¹
  3. 2for i ← 0 to 2^n − 1:
  4. 3if out[i] = i: continue
  5. 4if bidirectional and d(i, inv[i]) < d(i, out[i]): a ← inv (gates at the inputs) else a ← out (gates at the outputs); v ← a[i]
  6. 5for each line t with i_t = 1 and v_t = 0: add the gate T(ones(v); t), with v as read on L4
  7. 6for each line t with i_t = 0 and v_t = 1: add the gate T(ones(i); t)
  8. 7apply each new gate G to every entry of a, a[x] ← G(a[x]), and recompute the other table as the inverse of a
  9. 8record the new gates on the chosen side
  10. 9return the input-side gates in the order found, then the output-side gates in reverse order

Why the controls are safe. At row ii, rows 0,…,i−10, \dots, i - 1 are done, and the tables are bijections, so v=a[i]≥iv = a[i] \ge i. A gate of line L5 has the controls ones(v)\mathrm{ones}(v). It fires on a value xx only if xx has all bits of vv, so x≥v≥ix \ge v \ge i, and the done rows hold values below ii. The values it meets in row ii only gain bits, so they keep all bits of vv, and it fires there. A gate of line L6 has the controls ones(i)\mathrm{ones}(i). It fires on xx only if x≥ix \ge i, and after L5 the value of row ii has every bit of ii. In both cases the target is not a control. All gates of line L5 take the controls ones(v)\mathrm{ones}(v) of the value read on line L4, not of the value after the previous gate; both choices are correct, but the counts under What is measured are for this one.

The order of the output gates. Gates found at the outputs act on the table from outside, so the first one found is the last one the circuit applies. The gates found at the inputs act from inside, so the first one found is the first one applied. Line L9 puts them in this order.

A slip in the papers. The text of both papers (DAC 2003, Section 3.1, and TCAD 2005, Section III) gives the gates of line L5 the controls ones(i)\mathrm{ones}(i), which would contain the target. Their worked examples use ones(v)\mathrm{ones}(v), as here, and the proof needs it.

The code follows the basic algorithm of Section 3.1 with bidirectional=False, and the rule of Section 3.3 with bidirectional=True: at a tie it takes the outputs. It does not try other output orders, does not reduce the controls, and does not apply templates, the three improvements that the papers add.

Example

Take f=[1,0,3,2,5,7,4,6]f = [1, 0, 3, 2, 5, 7, 4, 6] on lines aa (bit 0), bb (bit 1) and cc (bit 2), the example of Maslov, Dueck and Miller (Table I). The columns show out\mathit{out} as cbacba after each gate of the basic algorithm.

row cbacba ff after NOT(aa) after T(c,b;a)T(c,b; a) after T(c,a;b)T(c,a; b) after T(c,b;a)T(c,b; a)
000 001 000 000 000 000
001 000 001 001 001 001
010 011 010 010 010 010
011 010 011 011 011 011
100 101 100 100 100 100
101 111 110 111 101 101
110 100 101 101 111 110
111 110 111 110 110 111

Row 0 holds 001, so line L6 clears bit aa with no controls: a NOT. Rows 1 to 4 are then done. Row 5 holds v=110v = 110 and needs 101101: line L5 sets aa with controls ones(110)={c,b}\mathrm{ones}(110) = \{c, b\}, and line L6 clears bb with controls ones(101)={c,a}\mathrm{ones}(101) = \{c, a\}. Row 6 holds 111 and needs 110: one gate clears aa with controls {c,b}\{c, b\}. Row 7 is then done by itself. Read backward, the circuit is T(c,b;a)T(c,b; a), T(c,a;b)T(c,a; b), T(c,b;a)T(c,b; a), NOT(aa), 4 gates, which is optimal for this function.

The bidirectional form. For f(x)=x−1 mod 8f(x) = x - 1 \bmod 8, that is [7,0,1,…,6][7, 0, 1, \dots, 6], the basic algorithm needs 3 NOT gates for row 0 alone and 7 gates in all. The bidirectional form sees that inv[0]=1\mathit{inv}[0] = 1 is one bit from 0, so it adds NOT(aa) at the inputs. Then row 1 holds 7 but inv[1]=3\mathit{inv}[1] = 3, one bit away, so it adds a CNOT from aa to bb at the inputs. Row 3 then holds 7, one bit from 3 on both sides, and the tie goes to the outputs: a Toffoli gate with controls a,ba, b and target cc. The 3 gates are optimal (Miller, Maslov and Dueck, Section 3.3).

Correctness

The proof file proves the following, for both forms. Each row step maps vv to ii with d(v,i)d(v, i) gates and fixes every value below ii. By induction over the rows, the rows above the current one stay done, the two tables stay inverse to each other, and the table always equals A∘f∘BA \circ f \circ B, where AA is the product of the output gates and BB that of the input gates. After the last row the table is the identity, so the circuit of line L9 computes ff. It uses only the nn lines of ff, with no extra line. Every row ii costs at most h(i)+1h(i) + 1 gates, where h(i)h(i) is the position of the highest 0 bit of ii, and summing over the rows gives at most (n−1)2n+1(n - 1) 2^n + 1 gates.

Proof: Transformation-based synthesis ends with a correct circuit of at most (n - 1) 2^n + 1 gatesfull

This file proves, for both the basic and the bidirectional form of the code, that the algorithm ends, that its output computes ff on the same nn lines with no extra line, and that the output has at most (n−1)2n+1(n - 1) 2^n + 1 gates.

Notation. Values are numbers in {0,…,2n−1}\{0, \dots, 2^n - 1\}, and bit tt of xx is xtx_t. For x,yx, y write x⊇yx \supseteq y if xx has every 1-bit of yy; then x≥yx \ge y as numbers. T(C;t)T(C; t) with t∉Ct \notin C flips bit tt of xx when x⊇Cx \supseteq C (reading CC as a mask). Every such gate is a bijection and its own inverse. For 0≤i<2n−10 \le i < 2^n - 1, let h(i)h(i) be the position of the highest 0 bit of ii. Products of maps are composed right to left: (G∘H)(x)=G(H(x))(G \circ H)(x) = G(H(x)).

The row step

Lemma 1. Let v>iv > i, and let SS be the gates of lines L5 and L6: first T(ones(v);t)T(\mathrm{ones}(v); t) for each tt with it=1,vt=0i_t = 1, v_t = 0, then T(ones(i);t)T(\mathrm{ones}(i); t) for each tt with it=0,vt=1i_t = 0, v_t = 1. Then:

  1. no gate of SS has its target among its controls;
  2. applied in order, SS maps vv to ii;
  3. SS fixes every x<ix < i;
  4. ∣S∣=d(v,i)≤h(i)+1|S| = d(v, i) \le h(i) + 1.

Proof. (1) A gate of the first kind has target tt with vt=0v_t = 0, so t∉ones(v)t \notin \mathrm{ones}(v); one of the second kind has it=0i_t = 0, so t∉ones(i)t \notin \mathrm{ones}(i).

(2) During the first part, the value of the row starts at vv and only gains bits, so it stays ⊇v\supseteq v and each gate fires and sets its bit. After the first part the value is v∨iv \lor i (bitwise OR), which is ⊇i\supseteq i. During the second part, each gate clears a bit tt with it=0i_t = 0, so the value stays ⊇i\supseteq i, and each gate fires. At the end the bits set are exactly those of ii.

(3) Take x<ix < i, and follow it through SS. It is not changed by a gate of the first kind, since that would need x⊇vx \supseteq v, so x≥v>ix \ge v > i. It is not changed by a gate of the second kind, since that would need x⊇ix \supseteq i, so x≥ix \ge i. Since no gate changes it, every later gate sees the same xx, and xx is fixed.

(4) Each gate changes one bit that differs between vv and ii, and each differing bit gets one gate, so ∣S∣=d(v,i)|S| = d(v, i). Let pp be the highest bit where vv and ii differ. Since v>iv > i, vp=1v_p = 1 and ip=0i_p = 0, so p≤h(i)p \le h(i). Every differing bit is at a position ≤p\le p, so d(v,i)≤p+1≤h(i)+1d(v, i) \le p + 1 \le h(i) + 1. ∎

The loop

Let outi\mathit{out}_i and invi\mathit{inv}_i be the tables at the start of iteration ii of line L2, and let AiA_i and BiB_i be the products of the gates found so far at the outputs and at the inputs: each output gate GG found makes A←G∘AA \leftarrow G \circ A, and each input gate makes B←B∘GB \leftarrow B \circ G. A0=B0=idA_0 = B_0 = \mathrm{id}.

Lemma 2 (invariant). At the start of iteration ii:

  1. outi\mathit{out}_i is a bijection and invi\mathit{inv}_i is its inverse;
  2. outi=Ai∘f∘Bi\mathit{out}_i = A_i \circ f \circ B_i;
  3. outi[j]=j\mathit{out}_i[j] = j for every j<ij < i.

Proof. By induction on ii. At i=0i = 0, (1) and (2) hold by line L1, and (3) is empty.

Suppose it holds at ii. If outi[i]=i\mathit{out}_i[i] = i, nothing changes and (3) now holds for j≤ij \le i. Otherwise, by (1) and (3), outi[j]=j\mathit{out}_i[j] = j and invi[j]=j\mathit{inv}_i[j] = j for j<ij < i, so neither outi[i]\mathit{out}_i[i] nor invi[i]\mathit{inv}_i[i] is below ii; neither equals ii, since outi[i]≠i\mathit{out}_i[i] \ne i and invi\mathit{inv}_i is the inverse. So v=a[i]>iv = a[i] > i on either side, and Lemma 1 applies.

Output side (a=outa = \mathit{out}). Each gate GG of SS makes out←G∘out\mathit{out} \leftarrow G \circ \mathit{out} and A←G∘AA \leftarrow G \circ A, so (2) holds after it. A composition of bijections is a bijection, and the code rebuilds inv\mathit{inv} as its inverse, so (1) holds. By Lemma 1 (3), rows j<ij < i keep the value jj, and by Lemma 1 (2), row ii ends with the value ii.

Input side (a=inva = \mathit{inv}). Each gate GG makes inv←G∘inv\mathit{inv} \leftarrow G \circ \mathit{inv}, and the code rebuilds out\mathit{out} as its inverse, so (1) holds and out←inv−1∘G−1=out∘G\mathit{out} \leftarrow \mathit{inv}^{-1} \circ G^{-1} = \mathit{out} \circ G, since G=G−1G = G^{-1}; with B←B∘GB \leftarrow B \circ G, (2) holds. By Lemma 1 (3), inv[j]=j\mathit{inv}[j] = j for j<ij < i, so out[j]=j\mathit{out}[j] = j; by Lemma 1 (2), inv[i]=i\mathit{inv}[i] = i, so out[i]=i\mathit{out}[i] = i. ∎

Theorem 3 (correctness). The algorithm ends, and the circuit it returns computes ff, on the nn lines of ff, with no extra line.

Proof. The loop runs 2n2^n times, and each iteration adds at most nn gates (Lemma 1 (4)), each applied to two tables of size 2n2^n, so it ends. By Lemma 2 at i=2ni = 2^n, out[j]=j\mathit{out}[j] = j for every jj, so A∘f∘B=idA \circ f \circ B = \mathrm{id} and f=A−1∘B−1f = A^{-1} \circ B^{-1}. Let the input gates be G1,…,GmG_1, \dots, G_m in the order found and the output gates H1,…,HkH_1, \dots, H_k. Then B=G1∘⋯∘GmB = G_1 \circ \cdots \circ G_m and A=Hk∘⋯∘H1A = H_k \circ \cdots \circ H_1, so, as each gate is its own inverse,

f=H1∘H2∘⋯∘Hk∘Gm∘⋯∘G1.f = H_1 \circ H_2 \circ \cdots \circ H_k \circ G_m \circ \cdots \circ G_1.

The rightmost factor acts first, so the circuit in time order is G1,…,Gm,Hk,…,H1G_1, \dots, G_m, H_k, \dots, H_1, which is what line L9 returns. Every gate is a valid gate on the nn lines (Lemma 1 (1)), and the tables never have more than 2n2^n entries, so no line is added. ∎

The gate bound

Theorem 4. Both forms use at most (n−1)2n+1(n - 1) 2^n + 1 gates.

Proof. By Lemma 2 and the proof above, iteration ii adds d(v,i)d(v, i) gates for some v>iv > i, or none. For i=2n−1i = 2^n - 1 it adds none: by Lemma 2 (3) all other values are taken, so out[2n−1]=2n−1\mathit{out}[2^n - 1] = 2^n - 1. For i<2n−1i < 2^n - 1 it adds at most h(i)+1h(i) + 1 (Lemma 1 (4)). The values i<2ni < 2^n whose highest 0 bit is at position zz have 1s above zz, a 0 at zz, and any bits below, so there are 2z2^z of them. So the total is at most

∑z=0n−1(z+1)2z=(n−1)2n+1.\sum_{z=0}^{n-1} (z + 1) 2^z = (n - 1) 2^n + 1.

The identity holds for n=1n = 1 (1=0⋅2+11 = 0 \cdot 2 + 1), and if it holds for nn, adding the term (n+1)2n(n + 1) 2^n gives (n−1)2n+1+(n+1)2n=n2n+1+1(n - 1) 2^n + 1 + (n + 1) 2^n = n 2^{n+1} + 1, the value for n+1n + 1. ∎

The bidirectional form changes only which value vv is used in a row, and both candidates are above ii, so the same bound holds. For the basic form the bound is reached: Maslov, Dueck and Miller (TCAD 2005, Theorem 1) give a function for each nn on which the basic form uses exactly (n−1)2n+1(n - 1) 2^n + 1 gates, and the test file checks their functions for n=3n = 3 (17 gates) and n=4n = 4 (49 gates). This says nothing about the best circuit for that function: for n=3n = 3 the best circuit has 6 gates.

What is not proved

Nothing here compares the output with an optimal circuit. The test file measures that gap on all 40,320 functions of 3 bits against a breadth-first search.

Complexity

The circuit has at most (n−1)2n+1(n - 1) 2^n + 1 gates. Each gate is applied to the 2n2^n entries of one table, and the inverse is rebuilt in O(2n)O(2^n), so the time is O(n2n⋅2n)=O(n4n)O(n 2^n \cdot 2^n) = O(n 4^n) in the worst case, and O(2n)O(2^n) times the number of gates in general. The input itself has n2nn 2^n bits. The tables take O(2n)O(2^n) words, and the circuit O(n2n)O(n 2^n) gates of one word each. Keeping only the table and applying the gates lazily to the rows as they are reached would save time on functions with short circuits; the code does the simple thing.

Properties

What is proved. For every reversible function on nn lines, both forms end with a circuit of multiple-control Toffoli gates on the same nn lines that computes it, with no extra line, and with at most (n−1)2n+1(n - 1) 2^n + 1 gates. The proof file has the details.

What is cited. The bound is tight for the basic algorithm: Maslov, Dueck and Miller (Theorem 1) build a function that needs exactly (n−1)2n+1(n - 1) 2^n + 1 gates for every nn, [7,1,4,3,0,2,6,5][7, 1, 4, 3, 0, 2, 6, 5] for n=3n = 3. Over all 40,320 functions of 3 bits, Miller, Maslov and Dueck (Table 4) report a mean of 8.67 gates for the basic algorithm, 6.53 with output permutation, control reduction and the bidirectional rule, and 6.18 with templates as well, against 5.63 for optimal circuits in a library that also has SWAP gates. Shende et al. (Table 1) give the optimal sizes with NOT, CNOT and Toffoli gates.

What is measured. The test file runs both forms on all 40,320 functions of 3 bits and checks every circuit against the truth table. The basic algorithm reproduces the distribution of Table 4, column (a), exactly: a mean of 8.67 gates, and 17 gates for one function. The bidirectional form, without the other improvements, has a mean of 7.37 gates and needs at most 15. A breadth-first search over all functions reproduces Shende et al.'s Table 1, a mean of 5.87 gates and at most 8. The basic algorithm is optimal on 3,484 functions (8.6%) and the bidirectional form on 10,828 (26.9%). On random functions of 4 to 7 lines both forms stay within the bound, and the 4-bit worst case of Maslov, Dueck and Miller takes exactly 49 gates. The test file runs in about 4 seconds.

Variants and improvements

  • Control input reduction. Any subset of the controls works if it still fires on the current row and on no done row. The papers pick the subset that most lowers the total Hamming distance of the table, which gives smaller gates and so a lower quantum cost.
  • Output permutation. Relabel the outputs first, trying all n!n! orders for small nn, and keep the smallest circuit; the relabeling is free if wires can be renamed, and costs SWAP gates if not.
  • Templates. A template is a circuit that computes the identity. When more than half of one appears in the output, it is replaced by the inverse of the rest. Maslov, Dueck and Miller (2005) list all templates with up to 6 gates, and template passes are still used after many synthesis methods.
  • Other gates. The same idea works with Toffoli gates with negative controls, with Fredkin gates, and with gates that change two lines at once (mEXOR gates), for which Maslov, Dueck and Miller give a variant with O(2n)O(2^n) gates.
  • Exact and other heuristics. For 3 and 4 bits, exact search finds optimal circuits, as on the problem page. For larger functions, cycle-based, ESOP-based and BDD-based methods scale further, at the price of extra lines (Saeedi and Markov, Section 4.3).

When to use it

Use it when the function is given as a truth table, nn is at most about 20, and no extra lines are allowed: it always gives a correct circuit on exactly nn lines, fast, and it is a good start for template simplification. For 3 or 4 bits, use exact search instead. For functions with many inputs, or when extra lines are cheap, a method that works from an ESOP or a BDD scales better.

Pitfalls

  • The order of the output gates. The gates found at the outputs must be reversed. Since every gate is its own inverse this is the only change needed, but forgetting it gives the circuit of a different function.
  • The controls of the gates that set bits. They must be the 1-bits of the current output vv, not of ii; see the slip in the papers above.
  • Large gates. The basic algorithm gives gates with up to n−1n - 1 controls. A gate with many controls costs many elementary gates, or extra lines, on real hardware, so the gate count alone flatters it; use control reduction and count the quantum cost.
  • Odd permutations. On n≥4n \ge 4 lines every NOT, CNOT and Toffoli gate is an even permutation, so for an odd permutation the circuit must contain a gate with n−1n - 1 controls, or one extra line. The algorithm handles this by itself, since it is free to use any number of controls, but a later step that breaks gates into Toffoli gates must keep this in mind.
  • Irreversible functions. The function must be a permutation. An irreversible one must first be embedded with constant inputs and garbage outputs, as on the problem page.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

transformation_based_reversible_synthesis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transformation-based-reversible-synthesis/. The authors are listed in prov/WZABZ7.jsonl.

"""Transformation-based synthesis of reversible circuits (Miller, Maslov and
Dueck, DAC 2003).

A reversible function on n lines is a permutation f of 0..2^n - 1, given as
the list [f(0), f(1), ...]. Line t is bit t of the number.

A gate is a pair (controls, target): controls is a bit mask, target is a line
not in it. The gate flips the target bit when every control bit is 1. With no
control it is NOT, with one CNOT, with two Toffoli. A circuit is a list of
gates; the first gate acts first.
"""


def apply_gate(gate, x):
    controls, target = gate
    if x & controls == controls:
        return x ^ (1 << target)
    return x


def run(circuit, x):
    """The output of the circuit on input x."""
    for gate in circuit:
        x = apply_gate(gate, x)
    return x


def table(circuit, n):
    """The truth table [C(0), C(1), ...] of a circuit on n lines."""
    return [run(circuit, x) for x in range(1 << n)]


def row_gates(v, i, n):
    """Gates that map the value v to i and fix every value below i, if v > i.

    First set the bits that i has and v lacks, with the bits of v as controls.
    Then clear the bits that v has and i lacks, with the bits of i as controls.
    """
    gates = []
    for t in range(n):  # @line L5
        if i >> t & 1 and not v >> t & 1:
            gates.append((v, t))
    w = v | i
    for t in range(n):  # @line L6
        if w >> t & 1 and not i >> t & 1:
            gates.append((i, t))
    return gates


def synthesis_steps(f, bidirectional=False):
    """Run the algorithm. Return a list with one (side, gates) per row.

    side is "out" or "in", and gates are the gates found for that row, in the
    order they were applied to the table.
    """
    size = len(f)
    n = size.bit_length() - 1
    if size != 1 << n or sorted(f) != list(range(size)):
        raise ValueError("f must be a permutation of 0..2^n - 1")
    out = list(f)  # @line L1
    inv = [0] * size
    for x, y in enumerate(out):
        inv[y] = x
    steps = []
    for i in range(size):  # @line L2
        if out[i] == i:  # @line L3
            steps.append(("out", []))
            continue
        j = inv[i]
        use_inputs = bidirectional and bin(i ^ j).count("1") < bin(i ^ out[i]).count("1")
        # a is the table to change and b its inverse. A gate G at the outputs
        # makes out <- G o out; a gate at the inputs makes inv <- G o inv.
        a, b = (inv, out) if use_inputs else (out, inv)  # @line L4
        gates = row_gates(a[i], i, n)
        for gate in gates:
            for x in range(size):  # @line L7
                a[x] = apply_gate(gate, a[x])
            for x in range(size):
                b[a[x]] = x
        steps.append(("in" if use_inputs else "out", gates))  # @line L8
    return steps


def synthesize(f, bidirectional=False):
    """Return a circuit of multiple-control Toffoli gates that computes f.

    With bidirectional=False, gates are added only at the outputs (the basic
    algorithm). With bidirectional=True, each row is fixed from the side that
    needs fewer gates.
    """
    at_inputs, at_outputs = [], []
    for side, gates in synthesis_steps(f, bidirectional):
        (at_inputs if side == "in" else at_outputs).extend(gates)
    # The output gates were found from the last gate of the circuit backward.
    return at_inputs + at_outputs[::-1]  # @line L9
test_transformation_based_reversible_synthesis.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transformation-based-reversible-synthesis/. The authors are listed in prov/WZABZ7.jsonl.

import random
from collections import Counter, deque
from itertools import permutations

from transformation_based_reversible_synthesis import (
    apply_gate,
    row_gates,
    synthesis_steps,
    synthesize,
    table,
)


def all_gates(n):
    """Every multiple-control Toffoli gate on n lines."""
    gates = []
    for t in range(n):
        others = [b for b in range(n) if b != t]
        for m in range(1 << (n - 1)):
            c = 0
            for k, b in enumerate(others):
                if m >> k & 1:
                    c |= 1 << b
            gates.append((c, t))
    return gates


def optimal_sizes_3():
    """The least number of gates for every function of 3 bits, by BFS."""
    moves = [tuple(apply_gate(g, x) for x in range(8)) for g in all_gates(3)]
    start = tuple(range(8))
    dist = {start: 0}
    queue = deque([start])
    while queue:
        p = queue.popleft()
        for m in moves:
            q = tuple(m[v] for v in p)
            if q not in dist:
                dist[q] = dist[p] + 1
                queue.append(q)
    return dist


def check_gates(circuit, n):
    for controls, target in circuit:
        assert 0 <= target < n
        assert 0 <= controls < 1 << n
        assert not controls >> target & 1


def highest_zero(i, n):
    """The position of the highest 0 bit of i below bit n, or -1."""
    for t in range(n - 1, -1, -1):
        if not i >> t & 1:
            return t
    return -1


def test_paper_example_basic():
    # Maslov, Dueck and Miller, Table I: NOT(a) for row 0, then two gates for
    # row 5 and one for row 6, found from the outputs backward.
    f = [1, 0, 3, 2, 5, 7, 4, 6]
    assert synthesize(f) == [(0b110, 0), (0b101, 1), (0b110, 0), (0b000, 0)]


def test_decrement_needs_the_bidirectional_form():
    f = [7, 0, 1, 2, 3, 4, 5, 6]
    assert len(synthesize(f)) == 7
    circuit = synthesize(f, bidirectional=True)
    assert table(circuit, 3) == f
    assert len(circuit) == 3 == optimal_sizes_3()[tuple(f)]


def test_worst_case_functions():
    f3 = [7, 1, 4, 3, 0, 2, 6, 5]
    f4 = [15, 1, 12, 3, 5, 6, 8, 7, 0, 10, 13, 9, 2, 4, 14, 11]
    for f, n in [(f3, 3), (f4, 4)]:
        circuit = synthesize(f)
        assert table(circuit, n) == f
        assert len(circuit) == (n - 1) * 2 ** n + 1
    assert optimal_sizes_3()[tuple(f3)] == 6


def test_row_gates_fix_the_rows_below():
    n = 4
    for i in range(16):
        for v in range(i + 1, 16):
            gates = row_gates(v, i, n)
            assert len(gates) == bin(v ^ i).count("1") <= highest_zero(i, n) + 1
            check_gates(gates, n)
            x = v
            for g in gates:
                x = apply_gate(g, x)
            assert x == i
            for j in range(i):
                y = j
                for g in gates:
                    y = apply_gate(g, y)
                assert y == j


def test_all_permutations_of_three_bits():
    opt = optimal_sizes_3()
    assert len(opt) == 40320
    # Shende, Prasad, Markov and Hayes, Table 1, column CNT
    assert sorted(Counter(opt.values()).items()) == [
        (0, 1), (1, 12), (2, 102), (3, 625), (4, 2780),
        (5, 8921), (6, 17049), (7, 10253), (8, 577),
    ]
    basic, both = Counter(), Counter()
    hits = Counter()
    for p in permutations(range(8)):
        f = list(p)
        for bidirectional, sizes in [(False, basic), (True, both)]:
            steps = synthesis_steps(f, bidirectional)
            for i, (_, gates) in enumerate(steps):
                assert len(gates) <= highest_zero(i, 3) + 1
            circuit = synthesize(f, bidirectional)
            check_gates(circuit, 3)
            assert table(circuit, 3) == f
            assert opt[p] <= len(circuit) <= 17
            sizes[len(circuit)] += 1
            hits[bidirectional] += len(circuit) == opt[p]
    hits_basic, hits_both = hits[False], hits[True]
    # Miller, Maslov and Dueck, Table 4, column (a)
    assert [basic[k] for k in range(17, -1, -1)] == [
        1, 14, 92, 380, 1113, 2468, 4311, 6083, 7044,
        6754, 5379, 3549, 1922, 839, 286, 72, 12, 1,
    ]
    total_basic = sum(k * v for k, v in basic.items())
    total_both = sum(k * v for k, v in both.items())
    total_opt = sum(opt.values())
    assert (total_basic, total_both, total_opt) == (349632, 297272, 236497)
    assert (hits_basic, hits_both) == (3484, 10828)
    assert (max(basic), max(both)) == (17, 15)


def test_random_functions_on_more_lines():
    rng = random.Random(3)
    for n in [4, 5, 6, 7]:
        for _ in range(6 if n < 7 else 2):
            f = list(range(1 << n))
            rng.shuffle(f)
            for bidirectional in [False, True]:
                circuit = synthesize(f, bidirectional)
                check_gates(circuit, n)
                assert table(circuit, n) == f
                assert len(circuit) <= (n - 1) * 2 ** n + 1


def test_odd_permutations_need_a_gate_on_all_lines():
    # On 4 lines every gate with at most 2 controls is an even permutation,
    # so a circuit for an odd permutation must use a gate with 3 controls.
    rng = random.Random(5)
    for _ in range(30):
        f = list(range(16))
        rng.shuffle(f)
        seen = [False] * 16
        cycles = 0
        for s in range(16):
            if not seen[s]:
                cycles += 1
                x = s
                while not seen[x]:
                    seen[x] = True
                    x = f[x]
        odd = (16 - cycles) % 2 == 1
        circuit = synthesize(f, bidirectional=True)
        assert table(circuit, 4) == f
        if odd:
            assert any(bin(c).count("1") == 3 for c, _ in circuit)


def test_rejects_a_non_permutation():
    for f in [[0, 0], [0, 1, 2], [1, 2, 3, 4]]:
        try:
            synthesize(f)
        except ValueError:
            pass
        else:
            raise AssertionError("accepted %r" % (f,))

History

Before 2003, synthesis methods for reversible circuits searched over circuits, as Shende, Prasad, Markov and Hayes did for all functions of 3 bits, or built on spectral techniques and on rewriting rules for CNOT and Toffoli circuits, which the DAC paper cites. Miller, Maslov and Dueck presented the transformation-based method at DAC 2003: a greedy pass through the truth table that always ends with a correct circuit, with the bidirectional rule, output permutation, control reduction and templates on top. The journal version (Maslov, Dueck and Miller, TCAD 2005) proved the bound (n−1)2n+1(n - 1) 2^n + 1, showed that it is tight, and gave the full set of templates up to 6 gates. Many later methods start from the same idea of transforming the function into the identity.

References

  1. D. Michael Miller, Dmitri Maslov and Gerhard W. Dueck, A transformation based algorithm for reversible logic synthesis, Proceedings of the 40th Design Automation Conference (DAC 2003), pages 318 to 323, Section 3.1 (the basic algorithm, Table 1 and the function that needs (m - 1) 2^m + 1 gates), Section 3.2 (output permutation and control input reduction), Section 3.3 (the bidirectional algorithm, Table 3), Section 4 (templates), Section 5 and Table 4 (all 40,320 functions of 3 bits)
  2. Dmitri Maslov, Gerhard W. Dueck and D. Michael Miller, Toffoli network synthesis with templates, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 24(6), 2005, pages 807 to 817, Section III (the basic algorithm, Table I, Theorem 1 with the bound (n - 1) 2^n + 1 and the worst-case functions for 3 and 4 bits, Section III.B the bidirectional algorithm), the template sections
  3. Vivek V. Shende, Aditya K. Prasad, Igor L. Markov and John P. Hayes, Synthesis of reversible logic circuits, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 22(6), 2003, pages 710 to 722, Table 1 (the number of 3-wire functions whose optimal NOT, CNOT and Toffoli circuit has k gates), as numbered in arXiv version 4
  4. Mehdi Saeedi and Igor L. Markov, Synthesis and optimization of reversible circuits, a survey, ACM Computing Surveys 45(2), 2013, article 21 (arXiv:1110.2574), Section 4.3 (transformation-based methods and the other heuristics), Section 5 (post-synthesis optimization)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.circuit
  • a full proof of space.tables
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example