Algorithm Search⌘K

Data structureresearch

Majority-inverter graph

Also called MIG.

A Boolean network of three-input majority nodes with inverted edges, with an algebra of five axioms for restructuring, from Amaru, Gaillardon and De Micheli.

Time
O(N) levelsO(1) expected majO(N 2^n / w) simulate
Space
O(N) nodes
Where
N = the number of majority nodes; n = the number of primary inputs; w = the number of bits in a machine word
Properties
not concurrentnot externalpersistent
Origin
Luca Amaru, Pierre Emmanuel Gaillardon, Giovanni De Micheli, 2014

A majority-inverter graph, or MIG, is a Boolean network in which every inner node is the majority of three inputs and every edge may carry an inverter. The majority ⟨xyz⟩=xy+xz+yz\langle x y z \rangle = xy + xz + yz is 1 when at least two of its inputs are 1. With one input fixed to 0 it is AND, and with one input fixed to 1 it is OR, so every and-inverter graph is an MIG with the same number of nodes. Amaru, Gaillardon and De Micheli gave the MIG an algebra of five axioms, and they restructure the graph by applying these axioms, mainly to make it shallower.

In plain words

Build a circuit from one kind of gate that takes three wires and outputs the value that at least two of them carry. A dot on a wire flips its value. If you tie one input of the gate to 0, it becomes an AND gate. If you tie it to 1, it becomes an OR gate. So this gate can do all that an AND gate can do, and often more in one step: one gate gives the carry of an adder.

As with AND gates, keep a dictionary of the gates you have built, keyed by their three input wires, and reuse a gate when you see it again.

A small set of rules says when two drawings of majority gates compute the same thing. Tools apply these rules to move late signals near the output and so make the circuit faster.

The abstract type

An MIG over the inputs x1,…,xnx_1, \ldots, x_n stores a set of nodes, each one a Boolean function of the inputs. A literal names a node and a phase, as on the AIG page. The operations are:

  • INPUT(i): the literal of xix_i.
  • MAJ(a, b, c): a literal whose function is ⟨fafbfc⟩\langle f_a f_b f_c \rangle. NOT is free. AND(a, b) is MAJ(a, b, 0) and OR(a, b) is MAJ(a, b, 1).
  • SIMULATE(o_1, ..., o_k): the truth tables of the given literals.
  • LEVELS: the depth of each node, the number of majority nodes on the longest path from an input.

The contract of MAJ is that the function is right, that the result is the same for all six orders of a,b,ca, b, c and for the call on ¬a,¬b,¬c\neg a, \neg b, \neg c with the phase flipped, and that no node is added twice for the same normal form. As in an AIG, two literals with the same function can still differ.

The equalities that the tools use are the axioms Ω\Omega of the TCAD 2016 paper. For all functions x,y,z,u,vx, y, z, u, v:

axiom identity
Ω.C\Omega.C, commutativity ⟨xyz⟩=⟨yxz⟩=⟨zyx⟩\langle x y z \rangle = \langle y x z \rangle = \langle z y x \rangle
Ω.M\Omega.M, majority ⟨xxz⟩=x\langle x x z \rangle = x and ⟨xxˉz⟩=z\langle x \bar{x} z \rangle = z
Ω.A\Omega.A, associativity ⟨xu⟨yuz⟩⟩=⟨zu⟨yux⟩⟩\langle x u \langle y u z \rangle \rangle = \langle z u \langle y u x \rangle \rangle
Ω.D\Omega.D, distributivity ⟨xy⟨uvz⟩⟩=⟨⟨xyu⟩⟨xyv⟩z⟩\langle x y \langle u v z \rangle \rangle = \langle \langle x y u \rangle \langle x y v \rangle z \rangle
Ω.I\Omega.I, inverter propagation ⟨xyz⟩‾=⟨xˉyˉzˉ⟩\overline{\langle x y z \rangle} = \langle \bar{x} \bar{y} \bar{z} \rangle

The paper also derives three rules from them. Relevance, Ψ.R\Psi.R, says that ⟨xyz⟩=⟨xyzx/yˉ⟩\langle x y z \rangle = \langle x y z_{x/\bar{y}} \rangle, where zx/yˉz_{x/\bar{y}} is zz with every xx replaced by yˉ\bar{y}: the value of zz matters only where x≠yx \ne y. Complementary associativity, Ψ.C\Psi.C, says that ⟨xu⟨yuˉz⟩⟩=⟨xu⟨yxz⟩⟩\langle x u \langle y \bar{u} z \rangle \rangle = \langle x u \langle y x z \rangle \rangle. Substitution, Ψ.S\Psi.S, splits a node on a variable vv and a second signal uu. The authors prove that Ω\Omega is sound and complete for the functions of majority and complement: two MIGs compute the same function if and only if a finite sequence of axioms turns one into the other. These identities are the laws of the median operation in Knuth's treatment, Section 7.1.1 of Volume 4A.

Representation

A literal is the integer 2v+c2v + c as in the AIG: node 0 is the constant 0, so literal 1 is the constant 1, nodes 1 to nn are the inputs, and every later node vv holds three fanin literals of older nodes. A node is stored in a normal form. Its fanins a<b<ca < b < c are sorted, lie on three different nodes, and at most one of them is complemented. A hash table maps the triple (a,b,c)(a, b, c) to vv. The constant 1 counts as a complemented edge to node 0, so an AND node is stored as (0,a,b)(0, a, b) and an OR node as (1,a,b)(1, a, b).

Operations

  1. MAJ(a, b, c)
  2. 1sort a, b, c so that a ≤ b ≤ c ▷ Ω.C
  3. 2if a = b or b = c then return b ▷ Ω.M, ⟨x x z⟩ = x
  4. 3if a = b xor 1 then return c; if b = c xor 1 then return a ▷ Ω.M, ⟨x x̄ z⟩ = z
  5. 4if two or more of a, b, c are odd then return MAJ(a xor 1, b xor 1, c xor 1) xor 1 ▷ Ω.I
  6. 5if T holds the key (a, b, c) then return 2·T[a, b, c] ▷ structural hashing
  7. 6v ← a new node with fanins (a, b, c); T[a, b, c] ← v; return 2v
  8. SIMULATE(o_1, ..., o_k) ▷ truth tables as integers of 2^n bits
  9. 7val[0] ← 0; val[i] ← the table of x_i for i = 1 to n
  10. 8for v ← n + 1 to the last node: val[v] ← ⟨lit(a_v) lit(b_v) lit(c_v)⟩ bitwise
  11. 9return lit(o_1), ..., lit(o_k) ▷ lit(2u + c) = val[u], complemented if c = 1

Line L1 applies Ω.C\Omega.C, so that the six orders of a call give one key. In sorted order the two literals of one node are next to each other, so lines L2 and L3 find every pair on one node and apply Ω.M\Omega.M. After them the three fanins lie on three different nodes. Line L4 applies Ω.I\Omega.I when it lowers the number of complemented fanins, which leaves at most one. The inner call does not reach line L4 again. Line L8 computes the majority of three words with (x∧y)∨(x∧z)∨(y∧z)(x \wedge y) \vee (x \wedge z) \vee (y \wedge z), so all 2n2^n points are simulated at once.

The axioms Ω.A\Omega.A and Ω.D\Omega.D are not applied by MAJ. They change the shape of the graph over more than one node, and an optimizer applies them where they lower the depth or the size.

Example

Build a full adder over a,b,ca, b, c with the literals 2, 4 and 6. The carry is one majority node, and the sum a⊕b⊕ca \oplus b \oplus c takes two more.

step call normal form result nodes
1 MAJ(2, 4, 6), the carry ⟨abc⟩\langle a b c \rangle (2, 4, 6) new node 4, literal 8 1
2 MAJ(2, 4, 7), the inner node ⟨abcˉ⟩\langle a b \bar{c} \rangle (2, 4, 7) new node 5, literal 10 2
3 MAJ(9, 6, 10), the sum ⟨carry‾ c ⟨abcˉ⟩⟩\langle \overline{\text{carry}}\, c\, \langle a b \bar{c} \rangle \rangle (6, 9, 10) new node 6, literal 12 3
4 MAJ(4, 6, 2), the carry again (2, 4, 6) found node 4, literal 8 3
5 MAJ(3, 5, 7), the complement of the carry (2, 4, 6) by L4 literal 9 3

SIMULATE gives 232 (the bits 11101000) for the carry and 150 (the bits 10010110) for the sum. The MIG has 3 nodes and depth 2, while the AIG of the same adder on the and-inverter graph page has 7 AND nodes and depth 4. No MIG with fewer than 3 nodes computes both outputs, because the sum of three inputs is not the majority of three literals. Steps 4 and 5 show Ω.C\Omega.C and Ω.I\Omega.I at work: a permuted call and the call on three complemented literals find node 4 again.

Ω.A\Omega.A lowers the depth when a late signal sits deep in the graph. Over seven inputs, let z=⟨pq⟨rt(p∧r)⟩⟩z = \langle p q \langle r t (p \wedge r) \rangle \rangle, which has depth 3. Then f=⟨xu⟨yuz⟩⟩f = \langle x u \langle y u z \rangle \rangle has depth 5, because zz enters at the bottom. Ω.A\Omega.A swaps xx and zz and gives ⟨zu⟨yux⟩⟩\langle z u \langle y u x \rangle \rangle, which has depth 4 and the same truth table.

Correctness

The full proof shows that every node stays in the normal form: three sorted fanins on three different older nodes, at most one of them complemented, and a table that maps each triple to its node and holds no other key. It then shows that MAJ returns a literal whose function is ⟨fafbfc⟩\langle f_a f_b f_c \rangle, since each line uses an axiom that is true for all values, and that MAJ gives the same literal for all orders of its inputs and the complemented literal for complemented inputs. So no two nodes have the same normal form. SIMULATE is right by induction on the node number. The five axioms hold for all 0 and 1 values, which the test file checks on all 232^3, 242^4 and 252^5 points.

Proof: MAJ keeps the normal form, computes the majority and merges permuted and complemented callsfull

We use the literal code of the page: literal 2u+c2u + c names node uu with phase cc, node 0 is the constant 0, and fℓf_\ell is the function of a literal ℓ\ell over the primary inputs, so fℓ⊕1=¬fℓf_{\ell \oplus 1} = \neg f_\ell. Write node(ℓ)=⌊ℓ/2⌋\mathrm{node}(\ell) = \lfloor \ell / 2 \rfloor and ⟨xyz⟩=xy+xz+yz\langle x y z \rangle = xy + xz + yz.

Invariant (N). Every node v>nv > n has fanins (a,b,c)(a, b, c) with a<b<ca < b < c, with node(a)\mathrm{node}(a), node(b)\mathrm{node}(b) and node(c)\mathrm{node}(c) distinct and smaller than vv, and with at most one of a,b,ca, b, c odd. The table TT maps each such triple to its node and holds no other key.

Lemma 1 (pairs on one node). After line L1 sorts a≤b≤ca \le b \le c, if two of the three literals lie on one node, then line L2 or line L3 returns.

Proof. The two literals of node uu are 2u2u and 2u+12u + 1, and no other literal lies between them. If aa and bb lie on one node, then a=ba = b or b=a⊕1b = a \oplus 1 with aa even, and lines L2 or L3 apply. The same holds for bb and cc. If aa and cc lie on one node, then a≤b≤c≤a+1a \le b \le c \le a + 1, so b=ab = a or b=cb = c, and line L2 applies. □\square

Lemma 2 (the function). MAJ(a, b, c) returns a literal rr with fr=⟨fafbfc⟩f_r = \langle f_a f_b f_c \rangle, and it keeps (N).

Proof. Sorting at line L1 does not change the function, since ⟨xyz⟩\langle x y z \rangle is symmetric. Line L2 returns bb when two inputs are equal, and ⟨xxz⟩=x\langle x x z \rangle = x, since at least two of the three values are the value of xx. Line L3 returns the third input when two inputs are complements, and ⟨xxˉz⟩=z\langle x \bar{x} z \rangle = z, since exactly one of x,xˉx, \bar{x} is 1. Past line L3, by Lemma 1, the three literals lie on three different nodes. If two or more are odd, line L4 calls MAJ on the three complements. These lie on the same three nodes, and at most one of them is odd, so the inner call passes lines L2 to L4 and reaches line L5. By induction on the depth of the calls, it returns a literal ss with fs=⟨faˉfbˉfcˉ⟩f_s = \langle \bar{f_a} \bar{f_b} \bar{f_c} \rangle, and fs⊕1=⟨faˉfbˉfcˉ⟩‾=⟨fafbfc⟩f_{s \oplus 1} = \overline{\langle \bar{f_a} \bar{f_b} \bar{f_c} \rangle} = \langle f_a f_b f_c \rangle, because complementing all three values of a majority complements the result: two or more ones become two or more zeros. At line L5 the triple is sorted, on three distinct nodes and has at most one odd literal. If TT holds it, TT maps it to a node whose fanins are exactly (a,b,c)(a, b, c) by (N), and that node computes ⟨fafbfc⟩\langle f_a f_b f_c \rangle. Otherwise line L6 makes a node with these fanins, which all lie on older nodes, and adds its key, so (N) holds again. □\square

Lemma 3 (permutations and complements). For all literals, MAJ returns the same literal for every order of a,b,ca, b, c, and MAJ(a⊕1,b⊕1,c⊕1a \oplus 1, b \oplus 1, c \oplus 1) == MAJ(a,b,ca, b, c) ⊕1\oplus 1.

Proof. After line L1 the computation depends only on the sorted triple, which is the same for every order. For the second claim, let (a,b,c)(a, b, c) be sorted. If two literals lie on one node, complementing all three keeps each pair on its node and keeps the sorted order up to a swap inside a pair, which the tests of lines L2 and L3 do not see. So both calls return at the same test, one with the result bb or the third literal and the other with its complement. Otherwise the three nodes are distinct, so complementing every literal keeps the order of the nodes and the sorted order. Let kk be the number of odd literals in (a,b,c)(a, b, c), so the complements have 3−k3 - k. Exactly one of kk and 3−k3 - k is at least 2. The call with the larger count goes through line L4 to the call with the smaller count and flips its result, so the two results differ exactly in the phase. □\square

Theorem. Starting from an empty graph, every sequence of INPUT and MAJ calls keeps (N), each call returns a literal with the right function, and no two nodes have the same triple of fanins. SIMULATE returns the truth table of each requested literal.

Proof. The empty graph satisfies (N), and Lemma 2 keeps it and gives the functions. Line L6 adds a key only when TT does not hold it, so no two nodes share a triple. For SIMULATE, the fanins of node vv lie on nodes smaller than vv by (N), so when line L8 reaches vv the values of its fanins are their truth tables, by induction on vv, and the bitwise (x∧y)∨(x∧z)∨(y∧z)(x \wedge y) \vee (x \wedge z) \vee (y \wedge z) is the majority at each point. Line L9 complements the table of a node for an odd literal. ■\blacksquare

Complexity

MAJ sorts three numbers, makes at most one inner call and does one hash lookup, so it takes O(1)O(1) expected time. SIMULATE takes O(N2n/w)O(N 2^n / w) word operations for NN nodes and nn inputs. LEVELS is one pass in O(N)O(N). The space is three integers for each node and one table entry, O(N)O(N).

An MIG never needs more nodes than an AIG of the same function, and never more depth, because each AND node becomes one majority node with a constant input. The full adder shows that it can need fewer. A node costs three fanins in place of two, so the memory per node is higher.

Variants

  • Depth optimization. The 2014 and 2016 papers push critical signals up with Ω.A\Omega.A, Ψ.C\Psi.C and Ω.D\Omega.D from left to right, then clean up with Ω.M\Omega.M and Ω.D\Omega.D from right to left. The papers report depth and size results on benchmark circuits against AIG optimization in ABC. These are measured results, not proved bounds.
  • Size optimization. The same axioms, applied to remove nodes, with Ω.M\Omega.M and Ω.D\Omega.D from right to left as the main steps.
  • Cut rewriting. As in AIG rewriting, a small cut of a node is replaced by a smaller MIG of the same function, which exact synthesis finds for small numbers of inputs.
  • XOR-majority graphs. Adding a three-input XOR node gives a graph that suits arithmetic, since the sum of a full adder is then one node.
  • Mapping. An MIG can be mapped to cells or to lookup tables by technology mapping over cuts, in the same way as an AIG.

When to use it

Use an MIG when the target logic has majority gates, as in several proposed nanotechnologies, or when you want to restructure for depth with algebraic rules that are stronger than AND and OR rules. Arithmetic circuits gain most, since carries are majorities. Use an AIG when you need the common format of the tool chain, its large set of tested passes, and a node of two fanins. Use a BDD when you need a canonical form.

Pitfalls

  • Sorting without looking at pairs. The checks of lines L2 and L3 rely on the sorted order, which puts xx next to xˉ\bar{x}. A check of only a=ba = b misses ⟨xxˉz⟩\langle x \bar{x} z \rangle and keeps a node that is really a wire.
  • A normal form with complemented edges on both sides. Without line L4, ⟨xyz⟩\langle x y z \rangle and ⟨xˉyˉzˉ⟩‾\overline{\langle \bar{x} \bar{y} \bar{z} \rangle} get two nodes. The constant 1 must count as a complemented 0, or AND and OR nodes are stored in two forms.
  • Reading completeness as an algorithm. Completeness says that a sequence of axioms joins two equal MIGs. It does not say how to find a short sequence, or how to find the smallest MIG. The optimizers that apply the axioms are heuristics.
  • Counting depth with constant inputs. An AND node of an MIG has the constant 0 as a fanin. The constant is at level 0 and adds no depth, but a node with a constant input is still a node.

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.

majority_inverter_graph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/majority-inverter-graph/. The authors are listed in prov/AVZMQ8.jsonl.

"""A majority-inverter graph with complemented edges, a normal form and hashing.

A literal is 2 * id + c as on the and-inverter-graph page: node 0 is the
constant 0, so literal 1 is the constant 1, and nodes 1 to n are inputs.
Every later node is a majority M(a, b, c) of three literals of older
nodes. MAJ puts each call in a normal form before the hash lookup: the
fanins are sorted, the rules M(x, x, z) = x and M(x, not x, z) = z are
applied, and at most one fanin is complemented, using the axiom
not M(x, y, z) = M(not x, not y, not z). AND is M(a, b, 0) and OR is
M(a, b, 1).
"""

from typing import Iterable


def maj3(x: int, y: int, z: int) -> int:
    """Bitwise majority of three integers."""
    return (x & y) | (x & z) | (y & z)


class Mig:
    """A structurally hashed MIG over n primary inputs."""

    def __init__(self, n: int) -> None:
        self.n = n
        self.fanins: list[tuple[int, int, int]] = [(-1, -1, -1)] * (n + 1)
        self.table: dict[tuple[int, int, int], int] = {}

    def input(self, i: int) -> int:
        if not 1 <= i <= self.n:
            raise ValueError("no such input")
        return 2 * i

    def num_nodes(self) -> int:
        return len(self.fanins) - self.n - 1

    def maj(self, a: int, b: int, c: int) -> int:
        """The literal of M(a, b, c) in normal form."""
        a, b, c = sorted((a, b, c))  # @line L1
        if a == b or b == c:  # @line L2
            return b
        if a ^ 1 == b:  # @line L3
            return c
        if b ^ 1 == c:
            return a
        if (a & 1) + (b & 1) + (c & 1) >= 2:  # @line L4
            return self.maj(a ^ 1, b ^ 1, c ^ 1) ^ 1
        node = self.table.get((a, b, c))  # @line L5
        if node is not None:
            return 2 * node
        node = len(self.fanins)  # @line L6
        self.fanins.append((a, b, c))
        self.table[(a, b, c)] = node
        return 2 * node

    def and_(self, a: int, b: int) -> int:
        return self.maj(a, b, 0)

    def or_(self, a: int, b: int) -> int:
        return self.maj(a, b, 1)

    def simulate(self, outputs: Iterable[int]) -> list[int]:
        """Truth tables of the given literals over all 2^n points, x1 the high bit of the point."""
        full = (1 << (1 << self.n)) - 1
        val = [0] * len(self.fanins)  # @line L7
        for i in range(1, self.n + 1):
            t = 0
            for m in range(1 << self.n):
                if (m >> (self.n - i)) & 1:
                    t |= 1 << m
            val[i] = t

        def lit(x: int) -> int:
            return val[x >> 1] ^ (full if x & 1 else 0)

        for v in range(self.n + 1, len(self.fanins)):  # @line L8
            a, b, c = self.fanins[v]
            val[v] = maj3(lit(a), lit(b), lit(c))
        return [lit(o) for o in outputs]  # @line L9

    def levels(self) -> list[int]:
        lev = [0] * len(self.fanins)
        for v in range(self.n + 1, len(self.fanins)):
            lev[v] = 1 + max(lev[x >> 1] for x in self.fanins[v])
        return lev

    def depth(self, outputs: Iterable[int]) -> int:
        lev = self.levels()
        return max((lev[o >> 1] for o in outputs), default=0)
test_majority_inverter_graph.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/majority-inverter-graph/. The authors are listed in prov/AVZMQ8.jsonl.

import itertools
import random

from majority_inverter_graph import Mig, maj3


def M(x: int, y: int, z: int) -> int:
    return 1 if x + y + z >= 2 else 0


def points(k: int):
    return itertools.product((0, 1), repeat=k)


def test_axioms_on_all_assignments() -> None:
    for x, y, z in points(3):
        # commutativity
        assert M(x, y, z) == M(y, x, z) == M(z, y, x)
        # majority
        assert M(x, x, z) == x and M(x, 1 - x, z) == z
        # inverter propagation
        assert 1 - M(x, y, z) == M(1 - x, 1 - y, 1 - z)
        # AND and OR
        assert M(x, y, 0) == (x & y) and M(x, y, 1) == (x | y)
    for x, y, z, u in points(4):
        # associativity
        assert M(x, u, M(y, u, z)) == M(z, u, M(y, u, x))
        # complementary associativity
        assert M(x, u, M(y, 1 - u, z)) == M(x, u, M(y, x, z))
    for x, y, z, u, v in points(5):
        # distributivity
        assert M(x, y, M(u, v, z)) == M(M(x, y, u), M(x, y, v), z)


def test_relevance_for_every_function_of_three_inputs() -> None:
    # M(x, y, z) = M(x, y, z with x replaced by not y), for every z(x, y, w)
    for table in range(256):
        def z(x: int, y: int, w: int) -> int:
            return (table >> (4 * x + 2 * y + w)) & 1
        for x, y, w in points(3):
            assert M(x, y, z(x, y, w)) == M(x, y, z(1 - y, y, w))


def test_substitution_on_random_functions() -> None:
    rng = random.Random(3)
    for _ in range(500):
        tx, ty, tz = (rng.randrange(256) for _ in range(3))

        def f(v: int, u: int, w: int) -> int:
            def ev(t: int) -> int:
                return (t >> (4 * v + 2 * u + w)) & 1
            return M(ev(tx), ev(ty), ev(tz))

        for v, u, w in points(3):
            lhs = f(v, u, w)
            rhs = M(v, M(1 - v, f(u, u, w), u), M(1 - v, f(1 - u, u, w), 1 - u))
            assert lhs == rhs


def test_normal_form_merges_axiom_sides() -> None:
    g = Mig(3)
    x, y, z = 2, 4, 6
    m = g.maj(x, y, z)
    assert g.maj(y, x, z) == g.maj(z, y, x) == m
    assert g.maj(x, x, z) == x and g.maj(x, x ^ 1, z) == z
    assert g.maj(x ^ 1, y ^ 1, z ^ 1) == m ^ 1
    assert g.num_nodes() == 1
    for v in range(g.n + 1, len(g.fanins)):
        a, b, c = g.fanins[v]
        assert a < b < c and (a & 1) + (b & 1) + (c & 1) <= 1


def test_associativity_and_distributivity_as_graphs() -> None:
    g = Mig(5)
    x, y, z, u, v = (2 * i for i in range(1, 6))
    left = g.maj(x, u, g.maj(y, u, z))
    right = g.maj(z, u, g.maj(y, u, x))
    assert g.simulate([left]) == g.simulate([right])
    d1 = g.maj(x, y, g.maj(u, v, z))
    d2 = g.maj(g.maj(x, y, u), g.maj(x, y, v), z)
    assert g.simulate([d1]) == g.simulate([d2])


def test_full_adder_example() -> None:
    g = Mig(3)
    a, b, c = 2, 4, 6
    carry = g.maj(a, b, c)
    s = g.maj(carry ^ 1, c, g.maj(a, b, c ^ 1))
    assert g.num_nodes() == 3
    assert g.simulate([s, carry]) == [150, 232]
    assert g.depth([s, carry]) == 2


def test_depth_example() -> None:
    g = Mig(7)
    x, u, y, p, q, r, t = (2 * i for i in range(1, 8))
    z = g.maj(p, q, g.maj(r, t, g.and_(p, r)))
    f = g.maj(x, u, g.maj(y, u, z))
    f2 = g.maj(z, u, g.maj(y, u, x))
    assert (g.depth([z]), g.depth([f]), g.depth([f2])) == (3, 5, 4)
    assert g.simulate([f]) == g.simulate([f2])


def random_formula(rng: random.Random, n: int, depth: int):
    if depth == 0 or rng.random() < 0.2:
        return ("x", rng.randrange(1, n + 1), rng.randrange(2))
    op = rng.choice(["maj", "and", "or"])
    k = 3 if op == "maj" else 2
    return (op, [random_formula(rng, n, depth - 1) for _ in range(k)], rng.randrange(2))


def evaluate(f, x) -> int:
    if f[0] == "x":
        return x[f[1] - 1] ^ f[2]
    v = [evaluate(h, x) for h in f[1]]
    if f[0] == "maj":
        r = M(*v)
    elif f[0] == "and":
        r = v[0] & v[1]
    else:
        r = v[0] | v[1]
    return r ^ f[2]


def build(g: Mig, f) -> int:
    if f[0] == "x":
        return g.input(f[1]) ^ f[2]
    args = [build(g, h) for h in f[1]]
    r = g.maj(*args) if f[0] == "maj" else (g.and_(*args) if f[0] == "and" else g.or_(*args))
    return r ^ f[2]


def test_random_formulas_against_truth_tables() -> None:
    rng = random.Random(17)
    for _ in range(600):
        n = rng.randrange(1, 6)
        g = Mig(n)
        forms = [random_formula(rng, n, rng.randrange(1, 5)) for _ in range(3)]
        outs = [build(g, f) for f in forms]
        for f, t in zip(forms, g.simulate(outs)):
            for m, x in enumerate(points(n)):
                assert (t >> m) & 1 == evaluate(f, x)
        size = g.num_nodes()
        assert [build(g, f) for f in forms] == outs and g.num_nodes() == size
        keys = list(g.fanins[g.n + 1:])
        assert len(keys) == len(set(keys))


def test_bitwise_majority() -> None:
    assert maj3(0b1100, 0b1010, 0b0110) == 0b1110

History

The majority function is the heart of threshold logic and of the early work on switching circuits, and the median laws of ⟨xyz⟩\langle x y z \rangle were studied by Birkhoff and Kiss and later by Knuth. Amaru, Gaillardon and De Micheli (DAC 2014) made the majority node the single gate of a logic network, gave it the axioms Ω\Omega and the derived rules Ψ\Psi, and showed depth optimization by axiom application. Their 2016 paper in IEEE TCAD proved that Ω\Omega is sound and complete. Later work added exact synthesis of small MIGs, cut rewriting and XOR-majority graphs, and the EPFL logic synthesis libraries made MIGs one of their main network types.

References

  1. Luca Amaru, Pierre-Emmanuel Gaillardon and Giovanni De Micheli, Majority-inverter graph, a novel data-structure and algorithms for efficient logic optimization, Proceedings of the 51st Design Automation Conference, 2014, the definition of the MIG, the axioms Omega, and the depth and size optimization by axiom application
  2. Luca Amaru, Pierre-Emmanuel Gaillardon and Giovanni De Micheli, Majority-inverter graph, a new paradigm for logic optimization, IEEE Transactions on Computer-Aided Design 35(5), 2016, pages 806 to 819, the axioms Omega, the derived rules Psi, the soundness and completeness of Omega, and the optimization algorithms
  3. Donald E. Knuth, The Art of Computer Programming, Volume 4A, Combinatorial Algorithms, Part 1, Addison-Wesley, 2011, Section 7.1.1, the median operation and its laws

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.levels
  • a full proof of time.maj
  • a full proof of time.simulate
  • a full proof of space.nodes
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)
WritingW4 complete
  • a review of the text: no review record reviews/AVZMQ8/text.yaml