Algorithm Search⌘K

Algorithmcore

AIG balancing

Also called tree height reduction of AND trees.

Collects the maximal multi-input AND trees of an AIG and rebuilds each one over its distinct leaves, pairing the two lowest leaves first, so no node gets deeper or more numerous.

Time
O(N log k) expected worst
Space
O(N) extra
Where
N = the number of AND nodes of the input AIG; k = the largest number of leaves of one supergate
Properties
deterministicnot exactofflinerecursive
Origin
Alan Mishchenko, Satrajit Chatterjee, Robert Brayton, 2006

AIG balancing is a fast pass of multi-level logic synthesis that lowers the depth of an and-inverter graph. It cuts the AIG into supergates, maximal trees of AND nodes joined by plain edges, where every inner node has one fanout. Each supergate computes the AND of its leaves, and the order in which the two-input ANDs join the leaves does not change the function. So the algorithm rebuilds each supergate from the bottom up, always joining the two leaves of lowest level first, as Huffman's algorithm joins the two smallest weights. No node of the result is deeper than the node it replaces, and the number of AND nodes does not grow.

In plain words

A long chain of AND gates computes the same thing as a short, bushy tree of AND gates over the same inputs. The chain is slow, because a signal at the bottom goes through every gate. The tree is fast.

So find every place in the circuit where AND gates feed only each other with no inverter between them, and treat the whole group as one big AND gate with many inputs. Throw out repeated inputs. Then build it again from two-input gates, as a tree. Signals that come late should go through few gates, so join the two signals that are ready first, then the next two, and so on. Do this from the inputs up to the outputs, so each group sees the new, earlier times of the groups below it.

The problem

The input is an AIG with outputs o1,…,oko_1, \ldots, o_k. The output is an AIG with the same output functions. The level of an input is 0 and the level of an AND node is one more than the larger level of its two fanins, and the depth is the largest level of an output. The aim is a small depth, with no more AND nodes than before. Balancing only regroups AND trees. It does not use the distributive law or any Boolean identity other than x∧x=xx \wedge x = x, x∧¬x=0x \wedge \neg x = 0 and the order of the fanins, so it is a heuristic for the depth of the whole circuit.

The algorithm

  1. BALANCE(G, o_1, ..., o_k)
  2. 1H ← an empty AIG on the inputs of G; memo ← empty
  3. 2for each output o: the new output is BAL(node(o)), complemented if o is
  4. BAL(v) ▷ returns a literal of H with the function of v
  5. 3if v is an input or the constant then return the literal of v
  6. 4if memo holds v then return memo[v]
  7. 5leaves ← the leaf literals of the supergate of v
  8. 6S ← the set { BAL(node(ℓ)), complemented as ℓ is : ℓ in leaves }, without the constant 1
  9. 7if S holds 0, or some x and ¬x, then r ← 0
  10. else
  11. 8Q ← a priority queue of S keyed by the level in H
  12. 9while |Q| > 1: take the two lowest x and y out of Q; put AND_H(x, y) into Q
  13. 10r ← the one literal left in Q, or 1 if Q is empty
  14. 11memo[v] ← r; return r

The supergate of an AND node vv is found by a walk from vv down its fanins. The walk goes down a fanin edge when the edge has no inverter and leads to an AND node with exactly one fanout. Every other fanin is a leaf. The fanout counts are taken over the nodes that the outputs reach, and an output counts as a fanout. A node with two fanouts is never inside a supergate, so its logic is built once and shared.

Line L6 balances each leaf first, so the queue of line L8 knows the new levels of the leaves. As a set, SS drops leaves that appear twice. Line L7 finds a supergate that is 0 because it holds a literal and its complement. AND_H is the AND of the AIG page, with the trivial rules and structural hashing, so equal pairs in different supergates become one node.

Example

Take the chain o=a∧(b∧(c∧(d∧e)))o = a \wedge (b \wedge (c \wedge (d \wedge e))), with the literals 2, 4, 6, 8 and 10 for aa to ee. It has 4 AND nodes and depth 4. The supergate of the top node has the five leaves aa to ee, all at level 0.

step queue before (level, literal) pair taken new node level
1 (0, 2), (0, 4), (0, 6), (0, 8), (0, 10) aa, bb 12 1
2 (0, 6), (0, 8), (0, 10), (1, 12) cc, dd 14 1
3 (0, 10), (1, 12), (1, 14) ee, abab 16 2
4 (1, 14), (2, 16) cdcd, abeabe 18 3

The result (c∧d)∧(e∧(a∧b))(c \wedge d) \wedge (e \wedge (a \wedge b)) has 4 AND nodes and depth 3, which is ⌈log⁡25⌉\lceil \log_2 5 \rceil.

Levels of leaves matter when a leaf is shared. Let s=(a∧b)∧(c∧d)s = (a \wedge b) \wedge (c \wedge d) be an output and also a fanin of the second output o2=e∧(f∧s)o_2 = e \wedge (f \wedge s). The node ss has two fanouts, so it is a leaf of the supergate of o2o_2, at level 2. The supergate of o2o_2 has the leaves ee, ff at level 0 and ss at level 2. The queue joins ee and ff first, at level 1, and then joins that node with ss, at level 3. The depth falls from 4 to 3, and both graphs have 5 AND nodes.

Correctness

The full proof shows three facts. First, BAL(v) has the function of vv: the AND of a set of literals does not depend on the order or the grouping of the two-input ANDs, a repeated literal changes nothing, and a literal with its complement gives 0. Second, the level of BAL(v) in HH is at most the level of vv in GG. Write T(a1,…,am)=⌈log⁡2∑i2ai⌉T(a_1, \ldots, a_m) = \lceil \log_2 \sum_i 2^{a_i} \rceil. Every binary tree over leaves of levels aia_i has a root of level at least TT, since a node of level ℓ\ell over subtrees with sums S1S_1 and S2S_2 has 2ℓ≥2max⁡(S1,S2)≥S1+S22^\ell \ge 2 \max(S_1, S_2) \ge S_1 + S_2. The greedy pairing of line L9 never raises TT of the queue, which gives a root of level exactly TT, the greedy argument of Golumbic (1976). The new leaves are fewer and, by induction, not higher than the old ones, so their TT is not larger, and the old supergate was a tree over the old leaves. Third, each supergate with pp leaf edges has p−1p - 1 AND nodes in GG and gets at most p−1p - 1 new ones in HH, and every AND node of GG that the outputs reach lies in exactly one supergate.

Proof: Balancing keeps the functions and does not raise any level or the node countfull

We use the notation of the and-inverter graph page: fℓf_\ell is the function of a literal ℓ\ell, and levG\mathrm{lev}_G and levH\mathrm{lev}_H are the levels in the old graph GG and the new graph HH. Let VV be the set of AND nodes of GG that the outputs reach, with the fanout counts of the algorithm. For v∈Vv \in V, the supergate of vv is the tree found by line L5. Its inner nodes are vv and the AND nodes that the walk goes into, and its leaf edges are the fanins where the walk stops. We write p(v)p(v) for the number of leaf edges.

Lemma 1 (the supergate is a tree). Each node that the walk enters below vv is entered once, and fvf_v is the AND of fℓf_\ell over the leaf literals ℓ\ell, with repeats. The supergate has p(v)−1p(v) - 1 inner nodes.

Proof. The walk enters a node uu only through a fanin edge of a node already in the supergate, and uu has exactly one fanout, so it is entered through that edge only, once. So the inner nodes and their fanin edges form a binary tree with root vv and p(v)p(v) leaf edges, which has p(v)−1p(v) - 1 inner nodes. An inner node uu below vv is reached by an edge with no inverter, so the tree is a tree of ANDs, and fvf_v is the AND of its leaf literals. □\square

Lemma 2 (functions). BAL(v) returns a literal rr of HH with fr=fvf_r = f_v.

Proof. By induction on the level of vv in GG. For an input or the constant, line L3 is right. For an AND node, each leaf ℓ\ell comes from a node of smaller level, so by induction BAL(node(ℓ\ell)) has the function of node(ℓ\ell), and the literal put into SS at line L6 has the function fℓf_\ell. The AND of a collection of functions does not depend on repeats, and the constant 1 does not change it, so fv=⋀x∈Sfxf_v = \bigwedge_{x \in S} f_x, with the empty AND equal to 1. If SS holds 0 or both xx and ¬x\neg x, this AND is 0, which line L7 returns. Otherwise lines L8 to L10 replace two literals of QQ by a literal of their AND, by the AND page, until one is left, so the AND of QQ stays fvf_v. The memo of line L4 returns a value that was right when it was stored. □\square

For a finite list of integers a1,…,ama_1, \ldots, a_m with m≥1m \ge 1, let Σ=∑i2ai\Sigma = \sum_i 2^{a_i} and T(a)=⌈log⁡2Σ⌉T(a) = \lceil \log_2 \Sigma \rceil.

Lemma 3 (the lower bound). In any binary tree whose leaves have the levels a1,…,ama_1, \ldots, a_m and whose inner nodes have the level one more than the larger level of their two children, the root has a level of at least T(a)T(a).

Proof. We show 2lev(u)≥Σ(u)2^{\mathrm{lev}(u)} \ge \Sigma(u) for every node uu, where Σ(u)\Sigma(u) is the sum of 2ai2^{a_i} over the leaves below uu. For a leaf it is an equality. For an inner node with children yy and zz, 2lev(u)=2⋅2max⁡(lev(y),lev(z))≥2lev(y)+2lev(z)≥Σ(y)+Σ(z)=Σ(u)2^{\mathrm{lev}(u)} = 2 \cdot 2^{\max(\mathrm{lev}(y), \mathrm{lev}(z))} \ge 2^{\mathrm{lev}(y)} + 2^{\mathrm{lev}(z)} \ge \Sigma(y) + \Sigma(z) = \Sigma(u). At the root, 2lev≥Σ2^{\mathrm{lev}} \ge \Sigma, so lev≥T(a)\mathrm{lev} \ge T(a). □\square

Lemma 4 (the greedy). Let line L9 start with a queue whose levels are a1,…,ama_1, \ldots, a_m. The last literal has a level of at most T(a)T(a).

Proof. We show that one round of line L9 does not raise TT of the levels in the queue. Let the two lowest levels be x≤yx \le y, and let the AND have level zz. The AND of the AIG page returns either a node of level y+1y + 1, or, by a trivial rule, a literal of level at most yy, so z≤y+1z \le y + 1. Let Σ\Sigma be the sum before the round and Σ′=Σ−2x−2y+2z\Sigma' = \Sigma - 2^x - 2^y + 2^z the sum after it. If z≤yz \le y, then Σ′≤Σ\Sigma' \le \Sigma. If z=y+1z = y + 1 and x=yx = y, then Σ′=Σ\Sigma' = \Sigma. If z=y+1z = y + 1 and x<yx < y, all levels other than xx are at least yy, so Σ−2x\Sigma - 2^x is a multiple of 2y2^y, say k2yk 2^y with k≥1k \ge 1, and Σ′=(k+1)2y\Sigma' = (k + 1) 2^y. Let 2t2^t be the least power of two with 2t≥Σ2^t \ge \Sigma. Then 2t>k2y≥2y2^t > k 2^y \ge 2^y, so 2t2^t is a multiple of 2y2^y and larger than k2yk 2^y, so 2t≥(k+1)2y=Σ′2^t \ge (k + 1) 2^y = \Sigma'. In all cases TT does not grow. At the end the queue holds one literal of some level cc, with T=cT = c, so c≤T(a)c \le T(a). □\square

Lemma 5 (levels). For every AND node v∈Vv \in V, levH(BAL(v))≤levG(v)\mathrm{lev}_H(\mathrm{BAL}(v)) \le \mathrm{lev}_G(v).

Proof. By induction on levG(v)\mathrm{lev}_G(v). Let the leaf edges of the supergate of vv be ℓ1,…,ℓp\ell_1, \ldots, \ell_p with the old levels bj=levG(node(ℓj))b_j = \mathrm{lev}_G(\mathrm{node}(\ell_j)). By Lemma 1 the supergate is a binary tree over these leaves, so by Lemma 3, levG(v)≥T(b)\mathrm{lev}_G(v) \ge T(b). By induction, the literal that line L6 makes from ℓj\ell_j has a level of at most bjb_j, and SS keeps a sub-collection of these literals, one for each distinct value. So the sum ∑x∈S2levH(x)\sum_{x \in S} 2^{\mathrm{lev}_H(x)} is at most ∑j2bj\sum_j 2^{b_j}, and TT of the levels of SS is at most T(b)T(b). If line L7 returns 0 or line L10 returns 1, the level is 0. Otherwise Lemma 4 gives levH(r)≤T(levels of S)≤T(b)≤levG(v)\mathrm{lev}_H(r) \le T(\text{levels of } S) \le T(b) \le \mathrm{lev}_G(v). □\square

Lemma 6 (size). The number of AND nodes of HH is at most ∣V∣|V|.

Proof. Call v∈Vv \in V a root if BAL is called on it. Line L5 enters a node uu only if uu has one fanout and is reached by a plain edge, and BAL is called on a node only as an output node or as a leaf, that is, a node reached by a complemented edge, or with two or more fanouts, or as an output. A node with one fanout is either entered through its one fanin edge, or is a leaf of that edge, not both, and an output counts as a fanout. So each node of VV is a root or an inner node of exactly one supergate, and the supergates of the roots partition VV, with ∑roots(p(v)−1)=∣V∣\sum_{\text{roots}} (p(v) - 1) = |V| by Lemma 1. The memo of line L4 runs the body once per root, and lines L8 to L10 for a root with ∣S∣≤p(v)|S| \le p(v) distinct leaves make at most ∣S∣−1≤p(v)−1|S| - 1 \le p(v) - 1 calls of AND, each of which adds at most one node. Only these calls add nodes to HH. □\square

Theorem. BALANCE returns an AIG HH with the same output functions as GG, with levH\mathrm{lev}_H of each new output at most levG\mathrm{lev}_G of the old one, so no more depth, and with no more AND nodes than the part of GG that the outputs reach.

Proof. Lemma 2 for the functions, with the output phase put back at line L2, Lemma 5 for the levels and Lemma 6 for the size. ■\blacksquare

Complexity

The walks of line L5 touch each AND node of GG once in all, since an inner node of a supergate has one fanout and so belongs to one supergate, and the memo of line L4 runs each supergate once. A supergate with pp leaves costs O(plog⁡p)O(p \log p) for the queue and O(p)O(p) expected time for the hash lookups of AND_H. The sum of pp over all supergates is at most the number of edges, 2N2N, so the time is O(Nlog⁡k)O(N \log k) expected, where kk is the largest supergate. The extra space is the memo, the fanout counts and the queue, O(N)O(N). The recursion of line L6 can be as deep as the AIG, and a long AIG needs an explicit stack.

Properties

What is proved. The functions of the outputs do not change. Every node of HH that replaces a node vv of GG has a level at most the level of vv, so the depth does not grow. The number of AND nodes that the outputs reach does not grow. For each supergate, the tree that line L9 builds has the least level of any tree of two-input ANDs over the same distinct leaves at the same levels.

What is not proved. The depth of HH is not the least depth of an AIG for the same functions. Balancing keeps the supergates of GG, so it cannot move logic across a node with two fanouts or across an inverter, and it never uses the distributive law. A chain of alternating AND and OR gates, a∧(b∨(c∧(d∨e)))a \wedge (b \vee (c \wedge (d \vee e))), has an inverter on every edge of the AIG, so every supergate has two leaves, and balancing does not change it.

What is measured. On 1000 random AIGs with 8 inputs and 60 calls of AND each (seed 1, with each new node taking the last node as a fanin with probability 0.6 and each fanin complemented with probability 0.2), the code of this page lowered the mean depth from 14.7 to 7.2 and the mean number of reached AND nodes from 26.5 to 16.8, and it lowered the depth of 989 of them. Random AIGs have many repeated leaves and long chains, so these numbers show only that the code works. They are not benchmark results.

Variants and improvements

  • Arrival times. In timing-driven balancing the leaves of line L8 are keyed by arrival times from a delay model in place of AIG levels. The same greedy is optimal for any leaf times when each AND adds the same delay.
  • Balancing for area. Some versions keep the shape of a supergate when the depth would not fall, which avoids changing nodes that other passes have tuned.
  • SOP balancing. A later form of balancing in ABC takes a cut of several AND and OR levels, finds a sum of products for it, and builds a balanced AND-OR tree, which can cross the inverters that stop plain balancing.
  • Other operators. The same algorithm balances any associative and commutative operator. For XOR the rules of line L7 change to x⊕x=0x \oplus x = 0, so a leaf that appears twice is dropped in pairs. For the majority-inverter graph the associativity axiom plays the role of line L9.
  • Compilers. Tree height reduction of sums and products in expression trees is the same idea, and parallel prefix circuits solve the harder case where every prefix of a chain is needed.

When to use it

Use balancing as a cheap first pass that removes the depth left by the source of an AIG, such as long chains from the bit-blasting of wide gates, and between passes of AIG rewriting in scripts such as the resyn scripts of ABC. It is fast enough to run many times. When the depth comes from the logic and not from the grouping of AND gates, use restructuring that changes the function of nodes, such as rewriting with a delay cost or SOP balancing.

Pitfalls

  • Going through shared nodes. A node with two fanouts must be a leaf. If the walk of line L5 goes into it, its logic is copied into each supergate that uses it, and the node count grows.
  • Going through inverters. The AND of ¬(x∧y)\neg(x \wedge y) with zz is not x∧y∧zx \wedge y \wedge z. The walk must stop at a complemented edge.
  • Old levels for the leaves. Line L8 must use the levels of the leaves in HH, after line L6. With the levels of GG, the queue joins the wrong pairs above leaves that balancing has already made shallower.
  • Joining in input order. Joining the leaves in a fixed order, such as the order of the walk, gives a tree that is balanced only when all leaves arrive together. The two lowest leaves must be joined first.
  • Expecting a fixed point. A second pass can still lower the depth, since hashing in the first pass can make nodes that a second pass sees as constant or shared.

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.

aig_balancing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aig-balancing/. The authors are listed in prov/AX6R7V.jsonl.

"""AIG balancing: rebuild every multi-input AND tree of an AIG with the least depth.

An AIG uses the literal code of the and-inverter-graph page: a literal is
2 * id + c, node 0 is the constant 0, nodes 1 to n are inputs, and every
later node is an AND of two literals of older nodes. A supergate of a
node v is the tree of AND nodes reached from v through edges that are not
complemented and lead to AND nodes with exactly one fanout. Balancing
rebuilds each supergate over its distinct leaves and always ANDs the two
leaves of lowest level first.
"""

import heapq
from typing import Iterable


class Aig:
    """A small structurally hashed AIG, as on the and-inverter-graph page."""

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

    def is_and(self, v: int) -> bool:
        return v > self.n

    def and_(self, a: int, b: int) -> int:
        if a > b:
            a, b = b, a
        if a == 0 or a == b ^ 1:
            return 0
        if a == 1:
            return b
        if a == b:
            return a
        v = self.table.get((a, b))
        if v is None:
            v = len(self.fanin0)
            self.fanin0.append(a)
            self.fanin1.append(b)
            self.level.append(1 + max(self.level[a >> 1], self.level[b >> 1]))
            self.table[(a, b)] = v
        return 2 * v

    def simulate(self, outputs: Iterable[int]) -> list[int]:
        full = (1 << (1 << self.n)) - 1
        val = [0] * len(self.fanin0)
        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
        for v in range(self.n + 1, len(self.fanin0)):
            a, b = self.fanin0[v], self.fanin1[v]
            val[v] = (val[a >> 1] ^ (full if a & 1 else 0)) & (val[b >> 1] ^ (full if b & 1 else 0))
        return [val[o >> 1] ^ (full if o & 1 else 0) for o in outputs]

    def cone(self, outputs: Iterable[int]) -> set[int]:
        """The AND nodes that the given literals reach."""
        seen: set[int] = set()
        stack = [o >> 1 for o in outputs]
        while stack:
            v = stack.pop()
            if v in seen or not self.is_and(v):
                continue
            seen.add(v)
            stack.append(self.fanin0[v] >> 1)
            stack.append(self.fanin1[v] >> 1)
        return seen

    def depth(self, outputs: Iterable[int]) -> int:
        return max((self.level[o >> 1] for o in outputs), default=0)


def supergate_leaves(g: Aig, v: int, refs: list[int]) -> list[int]:
    """The leaf literals of the supergate of AND node v, with repeats."""
    leaves: list[int] = []
    stack = [g.fanin1[v], g.fanin0[v]]
    while stack:
        lit = stack.pop()
        u = lit >> 1
        if lit & 1 == 0 and g.is_and(u) and refs[u] == 1:
            stack.append(g.fanin1[u])
            stack.append(g.fanin0[u])
        else:
            leaves.append(lit)
    return leaves


def balance(g: Aig, outputs: list[int]) -> tuple[Aig, list[int]]:
    """A new AIG with the same functions, no more AND nodes and no more depth."""
    live = g.cone(outputs)
    refs = [0] * len(g.fanin0)
    for v in live:
        refs[g.fanin0[v] >> 1] += 1
        refs[g.fanin1[v] >> 1] += 1
    for o in outputs:
        refs[o >> 1] += 1
    h = Aig(g.n)  # @line L1
    memo: dict[int, int] = {}

    def bal(v: int) -> int:
        if not g.is_and(v):  # @line L3
            return 2 * v
        if v in memo:  # @line L4
            return memo[v]
        leaves = supergate_leaves(g, v, refs)  # @line L5
        new = {bal(lit >> 1) ^ (lit & 1) for lit in leaves}  # @line L6
        new.discard(1)
        if 0 in new or any(x ^ 1 in new for x in new):  # @line L7
            r = 0
        else:
            heap = [(h.level[x >> 1], x) for x in sorted(new)]  # @line L8
            heapq.heapify(heap)
            while len(heap) > 1:  # @line L9
                _, x = heapq.heappop(heap)
                _, y = heapq.heappop(heap)
                z = h.and_(x, y)
                heapq.heappush(heap, (h.level[z >> 1], z))
            r = heap[0][1] if heap else 1  # @line L10
        memo[v] = r  # @line L11
        return r

    new_outputs = [bal(o >> 1) ^ (o & 1) for o in outputs]  # @line L2
    return h, new_outputs


def min_tree_depth(levels: list[int]) -> int:
    """The least depth of a binary tree of ANDs over leaves with these levels: ceil(log2(sum of 2^level))."""
    s = sum(1 << a for a in levels)
    return (s - 1).bit_length()
test_aig_balancing.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aig-balancing/. The authors are listed in prov/AX6R7V.jsonl.

import heapq
import random
from functools import lru_cache

from aig_balancing import Aig, balance, min_tree_depth, supergate_leaves


def chain(n: int) -> tuple[Aig, int]:
    g = Aig(n)
    x = 2 * n
    for i in range(n - 1, 0, -1):
        x = g.and_(2 * i, x)
    return g, x


def test_chain_example() -> None:
    g, o = chain(5)
    assert g.depth([o]) == 4 and len(g.cone([o])) == 4
    h, (p,) = balance(g, [o])
    assert h.depth([p]) == 3 and len(h.cone([p])) == 4
    assert h.simulate([p]) == g.simulate([o])
    # the pairs of the example: (a, b), (c, d), (e, ab), (cd, abe)
    assert [(h.fanin0[v], h.fanin1[v]) for v in range(6, 10)] == [(2, 4), (6, 8), (10, 12), (14, 16)]


def test_late_leaf_example() -> None:
    # o1 = (a & b) & (c & d) is shared; o2 = e & (f & o1) is a chain over a late leaf
    g = Aig(6)
    s = g.and_(g.and_(2, 4), g.and_(6, 8))
    o2 = g.and_(10, g.and_(12, s))
    refs_ok = g.depth([s, o2]) == 4
    assert refs_ok
    h, outs = balance(g, [s, o2])
    assert h.simulate(outs) == g.simulate([s, o2])
    assert h.depth(outs) == 3
    assert len(h.cone(outs)) == len(g.cone([s, o2])) == 5


def test_duplicate_and_opposite_leaves() -> None:
    g = Aig(3)
    ab = g.and_(2, 4)
    # (a & b) & (a & c): the leaf a appears twice
    o = g.and_(ab, g.and_(2, 6))
    h, (p,) = balance(g, [o])
    assert len(h.cone([p])) == 2 and h.simulate([p]) == g.simulate([o])
    # (a & b) & (!a & c) is 0
    q = g.and_(g.and_(2, 4), g.and_(3, 6))
    h2, (r,) = balance(g, [q])
    assert r == 0


def test_alternating_and_or_chain_is_unchanged() -> None:
    g = Aig(5)
    z = g.and_(8 ^ 1, 10 ^ 1) ^ 1  # d | e
    z = g.and_(6, z)  # c & (d | e)
    z = g.and_(4 ^ 1, z ^ 1) ^ 1  # b | ...
    o = g.and_(2, z)  # a & ...
    h, (p,) = balance(g, [o])
    assert h.depth([p]) == g.depth([o]) == 4
    assert len(h.cone([p])) == 4


@lru_cache(maxsize=None)
def brute_depth(levels: tuple[int, ...]) -> int:
    if len(levels) == 1:
        return levels[0]
    best = None
    k = len(levels)
    for mask in range(1, (1 << k) - 1):
        if mask & 1 == 0:
            continue
        a = tuple(sorted(levels[i] for i in range(k) if mask >> i & 1))
        b = tuple(sorted(levels[i] for i in range(k) if not mask >> i & 1))
        d = 1 + max(brute_depth(a), brute_depth(b))
        best = d if best is None else min(best, d)
    return best


def greedy_depth(levels: list[int]) -> int:
    heap = list(levels)
    heapq.heapify(heap)
    while len(heap) > 1:
        x = heapq.heappop(heap)
        y = heapq.heappop(heap)
        heapq.heappush(heap, 1 + max(x, y))
    return heap[0]


def test_greedy_pairing_is_optimal_against_all_trees() -> None:
    rng = random.Random(5)
    for _ in range(600):
        k = rng.randrange(1, 8)
        levels = tuple(sorted(rng.randrange(0, 4) for _ in range(k)))
        best = brute_depth(levels)
        assert greedy_depth(list(levels)) == best == min_tree_depth(list(levels))


def random_aig(rng: random.Random) -> tuple[Aig, list[int]]:
    n = rng.randrange(2, 7)
    g = Aig(n)
    lits = [2 * i for i in range(1, n + 1)]
    for _ in range(rng.randrange(3, 40)):
        if rng.random() < 0.5 and len(lits) > n:
            a = lits[-1]
        else:
            a = rng.choice(lits)
        b = rng.choice(lits)
        x = g.and_(a ^ (rng.random() < 0.25), b ^ (rng.random() < 0.25))
        if x > 1:
            lits.append(x)
    outs = [rng.choice(lits[n:] or lits) ^ rng.randrange(2) for _ in range(rng.randrange(1, 4))]
    return g, outs


def test_random_aigs_function_size_and_depth() -> None:
    rng = random.Random(99)
    for _ in range(700):
        g, outs = random_aig(rng)
        h, new = balance(g, outs)
        assert h.simulate(new) == g.simulate(outs)
        assert len(h.cone(new)) <= len(g.cone(outs))
        for o, p in zip(outs, new):
            assert h.level[p >> 1] <= g.level[o >> 1]
        # a second pass may find more, never less
        h2, new2 = balance(h, new)
        assert h2.depth(new2) <= h.depth(new)
        assert h2.simulate(new2) == g.simulate(outs)


def test_supergate_stops_at_shared_and_complemented_edges() -> None:
    g = Aig(4)
    ab = g.and_(2, 4)
    cd = g.and_(6, 8)
    top = g.and_(ab, cd ^ 1)
    refs = [0] * len(g.fanin0)
    for v in g.cone([top, ab]):
        refs[g.fanin0[v] >> 1] += 1
        refs[g.fanin1[v] >> 1] += 1
    refs[top >> 1] += 1
    refs[ab >> 1] += 1
    assert sorted(supergate_leaves(g, top >> 1, refs)) == sorted([ab, cd ^ 1])

History

The reduction of tree height for associative operators comes from parallel compilation in the 1960s and 1970s, and Golumbic (1976) proved that joining the two smallest values first gives the least height for a tree with given leaf values, a minimax analogue of Huffman coding. Logic synthesis systems such as SIS used tree height reduction for timing. Mishchenko, Chatterjee and Brayton (2006) paired AIG balancing, which lowers delay with no gain in area, with DAG-aware AIG rewriting, which lowers area with no gain in delay, and the balance command of ABC became a standard step of synthesis scripts.

References

  1. Alan Mishchenko, Satrajit Chatterjee and Robert Brayton, DAG-aware AIG rewriting, a fresh look at combinational logic synthesis, Proceedings of the 43rd Design Automation Conference, 2006, pages 532 to 535, the abstract and the experiments, where AIG balancing for delay is used together with rewriting for area
  2. Martin Charles Golumbic, Combinatorial merging, IEEE Transactions on Computers C-25(11), 1976, pages 1164 to 1167, the merge of the two smallest values with cost max plus one, and its optimality for the least height of a tree with given leaf values
  3. Robert Brayton and Alan Mishchenko, ABC, an academic industrial-strength verification tool, Computer Aided Verification (CAV 2010), Lecture Notes in Computer Science 6174, Springer, 2010, pages 24 to 40, the synthesis commands of ABC on AIGs, among them balance
  4. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 8, Multiple-Level Combinational Logic Optimization (the sections on delay and on restructuring for timing)

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.extra
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