Algorithm Search⌘K

Algorithmadvanced

SAT sweeping

Also called FRAIG construction, functional reduction.

Finds internal nodes that are equal or complementary by random simulation, proves each candidate pair with SAT, and merges proven pairs, for equivalence checking.

Time
O(N^2 (N W + T)) worst
Space
O(N W) extra
Where
N = the number of AND nodes; T = the cost of one SAT call on a miter; W = the number of simulation patterns at the end
Properties
deterministicexactofflineiterative
Origin
Andreas Kuehlmann, Alan Mishchenko, Satrajit Chatterjee, Roland Jiang, Robert Brayton, 2004

SAT sweeping finds and merges the nodes of an and-inverter graph that compute the same function, or the complement of the same function. It simulates the graph on random input patterns to give each node a signature, and nodes whose signatures agree, after complement, are candidates. Each candidate pair is checked by a SAT solver on the miter of the two nodes, the Tseitin clauses of their cones plus the condition that they differ. If the miter is unsatisfiable, the two nodes are equal and one replaces the other. If it is satisfiable, the model is an input pattern that tells them apart, and it is added to the simulation patterns, which can also split other false candidates. Kuehlmann named the method in 2004, and Mishchenko, Chatterjee, Jiang and Brayton called its result a functionally reduced AIG, or FRAIG, in 2005: no two nodes of a FRAIG compute the same function or complementary functions. Applied to the miter of two circuits, it is the core of combinational equivalence checking in tools such as ABC.

In plain words

A large circuit often computes the same signal in two places. Finding these places makes the circuit smaller, and if two circuits are compared, it splits one hard question into many easy ones.

First, feed the circuit some random inputs and record what each wire does. Two wires that do different things on some input are surely different. Two wires that always did the same thing, or always the opposite, might be equal.

For each such pair, ask a SAT solver for an input that makes them differ. If there is none, they are equal, so keep one and drop the other. If there is one, use it as a new random input, which may also show other pairs to be different.

The problem

The input is an AIG with nn inputs, NN AND nodes in topological order and a list of output literals, in the notation of the AIG page: node 0 is the constant 0, a literal is 2v+c2v + c, and c=1c = 1 complements node vv. The output is an AIG that computes the same output functions and is functionally reduced: no two of its nodes, the constant and the inputs included, compute functions ff and gg with f=gf = g or f=¬gf = \neg g. As a problem this is Boolean equivalence checking for every pair of nodes at once. It is co-NP-hard: a circuit is unsatisfiable exactly when its output node is equal to the constant 0, and a functionally reduced result shows this at once, because the output then is the constant node.

The algorithm

  1. SAT-SWEEP(G, W0)
  2. 1P ← W0 random input patterns; H ← an empty AIG with the inputs of G
  3. 2for each AND node v of G in topological order do
  4. 3w ← the AND in H of the images of the fanins of v, with constant rules and structural hashing
  5. 4if w is an old node of H then image(v) ← w; continue
  6. 5loop
  7. 6s ← the signature of w under P; r ← a node of H other than w with signature s or ¬s
  8. 7if there is no r then image(v) ← w; break
  9. 8if the miter of w and r, or of w and ¬r, is unsatisfiable then
  10. 9image(v) ← r with the phase; point the hash entry of w at it; drop w; break
  11. 10else add the model of the miter to P and simulate H again
  12. 11return the cones in H of the images of the outputs of G

The signature of a node at line L6 is its value on each pattern of PP, a word of bits computed by bit-parallel simulation, as on the page on bit parallelism. To compare up to complement, the signature is complemented when its bit for pattern 0 is 1, so that equal and complementary nodes get the same key. A hash table from keys to nodes finds rr. The phase is the bit of pattern 0 in s⊕sig(r)s \oplus \mathrm{sig}(r). At line L8, the miter is the CNF of the cones of ww and rr by the Tseitin transformation, plus the two clauses (w∨r′)∧(¬w∨¬r′)(w \lor r') \land (\neg w \lor \neg r'), where r′r' is rr with the phase, which say that the two differ. Line L9 points the hash entry of the dropped AND at rr, so that a later AND with the same fanins also gets rr. Line L10 adds one bit to every signature, and the new bit differs between ww and rr, so the loop tries rr at most once.

Example

Take inputs xx and yy and the AIG with t3=x∧¬yt_3 = x \land \neg y, t4=¬x∧yt_4 = \neg x \land y, t5=¬t3∧¬t4t_5 = \neg t_3 \land \neg t_4 (XNOR), t6=x∧yt_6 = x \land y, t7=¬x∧¬yt_7 = \neg x \land \neg y, t8=¬t6∧¬t7t_8 = \neg t_6 \land \neg t_7 (XOR) and o=t9=¬t5∧t8o = t_9 = \neg t_5 \land t_8, whose function is XOR. The code of this page with 4 patterns and seed 3 gets the patterns (x,y)=(1,1),(1,0),(0,0),(0,1)(x, y) = (1, 1), (1, 0), (0, 0), (0, 1) for p0,p1,p2,p3p_0, p_1, p_2, p_3.

node function signature p0p1p2p3p_0 p_1 p_2 p_3 result
xx xx 1100 input
yy yy 1001 input
t3t_3 x∧¬yx \land \neg y 0100 new class
t4t_4 ¬x∧y\neg x \land y 0001 new class
t5t_5 XNOR 1010 new class
t6t_6 x∧yx \land y 1000 new class
t7t_7 ¬x∧¬y\neg x \land \neg y 0010 new class
t8t_8 XOR 0101 candidate ¬t5\neg t_5; SAT says UNSAT; t8→¬t5t_8 \to \neg t_5
t9t_9 ¬t5∧¬t5\neg t_5 \land \neg t_5 the rule a∧a=aa \land a = a gives ¬t5\neg t_5

The signature of t8t_8 is the complement of that of t5t_5, so the pair is a candidate, and the miter is unsatisfiable. The image of t8t_8 is ¬t5\neg t_5. At t9t_9, both fanins become ¬t5\neg t_5, so the AND is not even built. The output is ¬t5\neg t_5, and the cone of the output has the three ANDs t3t_3, t4t_4 and t5t_5. The nodes t6t_6 and t7t_7 stay in HH but leave the result at line L11. One SAT call was made.

With one pattern only, the same run makes 3 SAT calls that find counterexamples before the one UNSAT call, since a single pattern gives many nodes the same key.

Correctness

The full proof shows that the image of every node of GG computes the same function as the node, so the outputs are kept, and that the nodes of HH that stay are pairwise not equal and not complementary. The second fact holds because a node joins HH only when no node has its key, and a node with a different signature is surely different. A dropped node is used by no other node, because it is dropped at once. The loop of lines L5 to L10 ends, because each counterexample separates ww from one more node for good.

Proof: SAT sweeping keeps the output functions and returns a functionally reduced AIGfull

Let GG be an AIG with inputs x1,…,xnx_1, \ldots, x_n, AND nodes in topological order and output literals. For a literal ℓ\ell of GG or of HH, write [ℓ][\ell] for the Boolean function of ℓ\ell over {0,1}n\{0,1\}^n, so [2v+1]=¬[2v][2v + 1] = \neg [2v] and node 0 is the constant 0. Call two functions ff and gg alike if f=gf = g or f=¬gf = \neg g. During the run, a node of HH is live if it is the constant, an input, or an AND node that was not dropped at line L9. Let PP be the current set of patterns, and sig(u)\mathrm{sig}(u) the vector of values of node uu on PP. The key of uu is sig(u)\mathrm{sig}(u), complemented if its bit for pattern 0 is 1.

Lemma 1 (keys). If [u][u] and [u′][u'] are alike, then uu and u′u' have the same key for every PP. If uu and u′u' have the same key, then sig(u)=sig(u′)\mathrm{sig}(u) = \mathrm{sig}(u') or sig(u)=¬sig(u′)\mathrm{sig}(u) = \neg\mathrm{sig}(u'), and the phase bit bb of line L6, the bit for pattern 0 of sig(u)⊕sig(u′)\mathrm{sig}(u) \oplus \mathrm{sig}(u'), gives sig(u)=sig(u′)⊕b\mathrm{sig}(u) = \mathrm{sig}(u') \oplus b on every pattern.

Proof. If [u]=[u′][u] = [u'], the signatures are equal. If [u]=¬[u′][u] = \neg[u'], they are complements, and exactly one of them has bit 1 for pattern 0, so after the normalization both keys are the same. Conversely, the key determines the signature up to complement. If the keys agree, the signatures agree or are complements; in the first case the bit for pattern 0 of the XOR is 0, in the second it is 1. □\square

Lemma 2 (the miter). For live nodes ww and rr and a bit bb, the miter CNF of line L8 is satisfiable if and only if [2w]≠[2r+b][2w] \ne [2r + b]. A model restricted to the input variables is a pattern on which the two literals differ.

Proof. The Tseitin clauses of an AND node vv with fanins a,ba, b say v↔(a∧b)v \leftrightarrow (a \land b), and the unit clause of the constant fixes it to 0. Every assignment to the inputs extends to exactly one assignment of the cone variables that meets these clauses, the values computed by the gates. The two last clauses say that the values of ww and rr with the phase differ. So a model is an input vector, with its gate values, on which the two literals differ, and such a vector gives a model. Inputs outside both cones do not change either value, so any value for them works. □\square

Invariant. After each step of the outer loop, for every node vv of GG that is done:

  • (I1) image(v)\mathrm{image}(v) is a literal of a live node of HH, and [image(v)]=[2v][\mathrm{image}(v)] = [2v];
  • (I2) the live nodes of HH are pairwise not alike;
  • (I3) every fanin of a live AND node of HH is a literal of a live node, and every entry of the structural hash table points at a literal of a live node with the function of the AND of the entry's fanins;
  • (I4) the table of keys used at line L6 maps each key to a live node with that key, and its keys are exactly the keys of the live nodes under the current PP.

The table of keys keeps one node per key. Two live nodes can share a key, for example two inputs that the starting patterns do not tell apart, and then only one of them is in the table. The proof does not need the keys to be different.

Base. Before line L2, HH has the constant and the inputs, with image(xi)=2i\mathrm{image}(x_i) = 2i and image(0)=0\mathrm{image}(0) = 0. These functions are pairwise not alike, since xix_i is not constant and xix_i is neither xjx_j nor ¬xj\neg x_j for i≠ji \ne j. The structural hash table is empty, and the table of keys is built from all of these nodes.

Step. Let vv be the next AND node of GG, with fanin literals aa and bb. By (I1) the images a′a' and b′b' of the fanins, with their complement bits, are literals of live nodes with [a′]=[a][a'] = [a] and [b′]=[b][b'] = [b]. Line L3 applies three rules. If a′=0a' = 0 or a′=¬b′a' = \neg b', the AND is the constant 0. If a′=1a' = 1 or a′=b′a' = b', the AND is the other fanin. If the pair is in the hash table, the AND is the stored literal, which by (I3) is live and has the function [a′]∧[b′][a'] \land [b']. In each of these cases line L4 sets an image with [image(v)]=[a]∧[b]=[2v][\mathrm{image}(v)] = [a] \land [b] = [2v], and HH does not change, so (I1) to (I3) hold.

Otherwise line L3 makes a new AND node ww with fanins a′,b′a', b', which are live, and [2w]=[2v][2w] = [2v]. During the loop of lines L5 to L10, the live nodes other than ww are those of before the step, and (I4) holds for them: the code rebuilds the table of keys from them, without ww, each time PP changes. At line L6, rr is the node that the table gives for the key of ww.

If there is no such rr (line L7), then by (I4) no live node other than ww has the key of ww, and by Lemma 1 no live node is alike to ww. So (I2) holds with ww added, and image(v)=2w\mathrm{image}(v) = 2w gives (I1). The new hash entry points at ww, so (I3) holds. The key of ww goes into the table, so (I4) holds.

If the miter is unsatisfiable (lines L8 and L9), then [2w]=[2r+b][2w] = [2r + b] with the phase bb of Lemma 1, by Lemma 2. The image of vv is 2r+b2r + b, a literal of a live node with [2r+b]=[2v][2r + b] = [2v], so (I1) holds. The node ww is dropped, and the live nodes are those of before, so (I2) and (I4) hold. No live node has ww as a fanin, since ww was made in this step and nothing was built after it. The hash entry of the fanins of ww now points at 2r+b2r + b, which has the function of the AND of those fanins, so (I3) holds.

If the miter is satisfiable (line L10), the model gives a pattern pp with [2w](p)≠[2r+b](p)[2w](p) \ne [2r + b](p). Add it to PP. On the old patterns, sig(w)=sig(r)⊕b\mathrm{sig}(w) = \mathrm{sig}(r) \oplus b, and on pp this fails, so under the new PP the signatures of ww and rr are neither equal nor complements, and their keys differ. The loop goes back to line L6.

The loop ends. Two nodes with different keys under PP have different keys under every larger set of patterns, since the signature on more patterns extends the signature on fewer, and pattern 0, which fixes the phase, stays the same. So the node rr of a pass through line L10 never again has the key of ww, and it is never again returned at line L6 in this step. There are finitely many live nodes, so after at most that many passes the loop leaves through line L7 or line L9. This gives the bound on SAT calls of the page.

Theorem. SAT-SWEEP returns an AIG whose outputs compute the output functions of GG, and no two of its nodes are alike.

Proof. After the last step, (I1) holds for every node of GG, so the image of each output literal of GG, with its complement bit, has the function of that output. Line L11 copies the cones of these literals. By (I3), the cones contain only live nodes, and the copy rebuilds each AND from the copies of its fanins, so each copied node keeps its function, and the outputs keep theirs.

Each copied node is the copy of a different live node, and by (I2) the live nodes are pairwise not alike, so neither are the copies. The constant and the inputs are live nodes too, so no AND node of the result is constant, equal to an input, or equal to the complement of an input. If the copy step meets a pair of fanins that is already in its table, or a constant rule, the result would be a node alike to an existing one, which (I2) rules out, so each live node of the cones gives exactly one node of the result. ■\blacksquare

Remark. If a new node ww is alike to a live node uu that is hidden in the table of keys behind another node u2u_2 with the same key, line L6 returns u2u_2, the miter is satisfiable, and the counterexample separates ww from u2u_2. Since ww and uu are alike, it separates uu from u2u_2 too, and the rebuilt table no longer has u2u_2 under the key of ww. The loop does not end at line L7 while uu has the key of ww, which by Lemma 1 is always, so it ends at line L9 with a node alike to ww.

Complexity

One simulation of HH costs O(NW)O(N W) bit operations, or O(NW/w)O(N W / w) word operations with machine words of ww bits. For a new node, each SAT call at line L8 either merges it or separates it from one node, so there are at most N+n+1N + n + 1 calls for that node and O(N2)O(N^2) calls in all, in the worst case. Each call costs TT, the cost of the SAT solver on a miter of at most NN AND nodes, which is exponential in the number of inputs of the cones in the worst case, since the problem is co-NP-hard. This gives O(N2(NW+T))O(N^2 (N W + T)). In practice most candidates are true, few calls return SAT, and the simulation is redone only for the new bit. The signatures take O(NW)O(N W) bits.

Properties

What is proved. The result computes the same output functions as GG. It is functionally reduced: no two of its nodes are equal or complementary, and no node is equal to a constant or to an input or its complement. Each merge is backed by an UNSAT answer of the solver, and each split by a counterexample that can be checked by simulation. Each AND node of the result was built for a different AND node of GG, so the result has at most NN AND nodes.

What is not proved. A FRAIG is not a smallest AIG for its functions, and it depends on the order of the nodes. The number of SAT calls depends on the patterns, and with too few patterns it can be large. When a solver has a limit on its effort, as real tools set, an undecided pair is left unmerged, and the result is then not functionally reduced.

What is measured. On the test set of this page, 150 random AIGs with at most 8 inputs and 25 ANDs (seed 2) and 1, 4 or 16 starting patterns, the sweep made 389 SAT calls that found a counterexample and 207 that proved a merge. This is a small test run, not a benchmark result.

Variants and improvements

  • Incremental SAT. Real implementations keep one solver for the whole sweep, add the clauses of each node once, and ask each miter under assumptions, as in incremental SAT with a CDCL solver.
  • Effort limits. A limit on the number of conflicts per call stops hard pairs from blocking the sweep. The pairs that fail are left alone or tried again later with a larger limit.
  • Better patterns. Tools simulate many words of patterns at once, and they also add patterns near each counterexample, so that one model splits more classes.
  • Equivalence checking. For two circuits, sweep the miter of their outputs. If the circuits are equal, the sweep reduces every output of the miter to the constant 0. Mishchenko, Chatterjee, Brayton and Eén (2006) improved this flow.
  • Choices instead of merges. Keep the proved equal nodes as a class of choices instead of dropping them. A mapper such as priority cuts can then pick the best structure.
  • Sequential sweeping. Signal correspondence finds nodes equal in all reachable states with simulation and induction, the sequential form of the same idea.

When to use it

Use SAT sweeping to check two combinational circuits for equality after synthesis, to shrink an AIG before bounded model checking or other SAT queries, and to find structural choices for mapping. For a single pair of small functions, a BDD or one SAT call on the outputs may be simpler. Note that equivalence checking of transition systems up to bisimulation is a different problem.

Pitfalls

  • Comparing only equal signatures. Normalize the phase, for example by pattern 0, or complementary nodes are never found.
  • Keeping the dropped node in the hash table. A later AND with the same fanins must get the kept node, not a new copy of the dropped one.
  • Merging on simulation alone. Equal signatures are only a hint. Without the SAT proof, a merge can change the function.
  • Dropping a node that is used. Decide on a node as soon as it is built, before any other node reads it. A node that is merged later must have its fanouts moved first.
  • Missing the constants. Put the constant node and the inputs in the table of keys, so that a node that is always 0 or equal to an input is found.

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.

sat_sweeping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-sweeping/. The authors are listed in prov/D7SVKR.jsonl.

"""SAT sweeping: build a functionally reduced AIG (a FRAIG).

An AIG has node 0 (the constant 0), inputs 1..n and AND nodes after
them. A literal is 2 v + c: node v, complemented when c = 1. The input
AIG is given as `n` and a list `ands` of fanin literal pairs; node
n + 1 + i has the fanins ands[i]. Outputs are literals.

The sweep copies the AIG in topological order into a new AIG. Each new
AND node gets a simulation signature over a set of input patterns. Two
nodes whose signatures are equal, or equal after complement, are
candidates. A candidate pair is checked with SAT on the miter of the two
cones. When the miter is unsatisfiable the new node is replaced by the
old one (with the phase); when it is satisfiable the counterexample is
added to the patterns, which splits the pair. At the end no two nodes of
the result compute the same function or its complement.
"""

import random
from typing import List, Optional, Sequence, Tuple


# ---------------------------------------------------------------- SAT
def dpll(clauses: Sequence[Sequence[int]], n_vars: int) -> Optional[List[int]]:
    """A small DPLL solver. Return a model as a list of 0/1 for vars 1..n, or None."""
    assign: dict = {}

    def value(lit):
        v = assign.get(abs(lit))
        return None if v is None else (v if lit > 0 else 1 - v)

    def propagate(trail):
        changed = True
        while changed:
            changed = False
            for cl in clauses:
                free, sat = None, False
                n_free = 0
                for lit in cl:
                    val = value(lit)
                    if val == 1:
                        sat = True
                        break
                    if val is None:
                        n_free += 1
                        free = lit
                if sat:
                    continue
                if n_free == 0:
                    return False
                if n_free == 1:
                    assign[abs(free)] = 1 if free > 0 else 0
                    trail.append(abs(free))
                    changed = True
        return True

    def solve():
        trail: list = []
        if not propagate(trail):
            for v in trail:
                del assign[v]
            return False
        var = next((v for v in range(1, n_vars + 1) if v not in assign), None)
        if var is None:
            return True
        for b in (1, 0):
            assign[var] = b
            if solve():
                return True
            del assign[var]
        for v in trail:
            del assign[v]
        return False

    if not solve():
        return None
    return [assign.get(v, 0) for v in range(1, n_vars + 1)]


# ---------------------------------------------------------------- AIG
class Aig:
    def __init__(self, n: int) -> None:
        self.n = n
        self.fanins: List[Tuple[int, int]] = [(0, 0)] * (n + 1)  # const and inputs
        self.table: dict = {}

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

    def add_and(self, a: int, b: int) -> int:
        """AND with constant rules and structural hashing; returns a literal."""
        if a > b:
            a, b = b, a
        if a == 0 or a == (b ^ 1):
            return 0
        if a == 1 or a == b:
            return b
        if (a, b) in self.table:
            return self.table[(a, b)]
        self.fanins.append((a, b))
        lit = 2 * (len(self.fanins) - 1)
        self.table[(a, b)] = lit
        return lit


def simulate(aig: Aig, patterns: Sequence[int], width: int) -> list:
    """Bit-parallel simulation: sig[v] holds the value of node v in each pattern."""
    mask = (1 << width) - 1
    sig = [0] + list(patterns)
    for v in range(aig.n + 1, len(aig.fanins)):
        a, b = aig.fanins[v]
        x = sig[a >> 1] ^ (mask if a & 1 else 0)
        y = sig[b >> 1] ^ (mask if b & 1 else 0)
        sig.append(x & y)
    return sig


def miter_cnf(aig: Aig, p: int, q: int):
    """CNF that is satisfiable iff literals p and q differ on some input."""
    seen, stack = set(), [p >> 1, q >> 1]
    while stack:
        v = stack.pop()
        if v not in seen:
            seen.add(v)
            if aig.is_and(v):
                stack.extend(lit >> 1 for lit in aig.fanins[v])
    var = {v: i + 1 for i, v in enumerate(sorted(seen))}

    def lit(x):
        return -var[x >> 1] if x & 1 else var[x >> 1]

    clauses = []
    if 0 in var:
        clauses.append([-var[0]])
    for v in sorted(seen):
        if aig.is_and(v):  # Tseitin: v <-> a and b
            a, b = aig.fanins[v]
            clauses += [[-var[v], lit(a)], [-var[v], lit(b)], [var[v], -lit(a), -lit(b)]]
    clauses += [[lit(p), lit(q)], [-lit(p), -lit(q)]]  # p != q
    return clauses, var


def sat_sweep(n: int, ands: Sequence[Tuple[int, int]], outputs: Sequence[int],
              n_patterns: int = 16, seed: int = 1):
    """Return (fraig, output literals, stats). stats counts SAT calls by result."""
    for i, (a, b) in enumerate(ands):
        if max(a, b) >> 1 >= n + 1 + i:
            raise ValueError("fanins must come before the node")
    rng = random.Random(seed)
    width = n_patterns
    pats = [rng.getrandbits(width) for _ in range(n)]  # @line L1: pats[i] belongs to input i + 1
    new = Aig(n)
    old_to_new = list(range(0, 2 * (n + 1), 2))  # node v of the input -> literal
    stats = {"sat": 0, "unsat": 0}

    def key_of(s):  # the phase is fixed by pattern 0: the key has bit 0 clear
        return s ^ ((1 << width) - 1) if s & 1 else s

    dead: set = set()

    def classes(sig, skip):
        return {key_of(sig[u]): u for u in range(len(new.fanins)) if u not in dead and u != skip}

    sig = simulate(new, pats, width)
    reps = classes(sig, None)
    for a, b in ands:  # @line L2
        fa = old_to_new[a >> 1] ^ (a & 1)
        fb = old_to_new[b >> 1] ^ (b & 1)
        size = len(new.fanins)
        lit = new.add_and(fa, fb)  # @line L3
        if len(new.fanins) == size:  # @line L4: a constant rule or the hash table answered
            old_to_new.append(lit)
            continue
        w = lit >> 1
        sig = simulate(new, pats, width)
        while True:  # @line L5
            r = reps.get(key_of(sig[w]))  # @line L6
            if r is None:  # @line L7: no candidate, w is a new class
                reps[key_of(sig[w])] = w
                old_to_new.append(lit)
                break
            phase = (sig[w] ^ sig[r]) & 1
            clauses, var = miter_cnf(new, 2 * w, 2 * r + phase)
            model = dpll(clauses, len(var))  # @line L8
            if model is None:  # @line L9: proved equal, use r and drop w
                stats["unsat"] += 1
                dead.add(w)
                new.table[new.fanins[w]] = 2 * r + phase
                old_to_new.append(2 * r + phase)
                break
            stats["sat"] += 1  # @line L10: the counterexample becomes a new pattern
            for i_in in range(1, n + 1):
                bit = model[var[i_in] - 1] if i_in in var else 0
                pats[i_in - 1] |= bit << width
            width += 1
            sig = simulate(new, pats, width)
            reps = classes(sig, w)
    outs = [old_to_new[o >> 1] ^ (o & 1) for o in outputs]
    res, res_outs = compact(new, outs)  # @line L11
    return res, res_outs, stats


def compact(aig: Aig, outs: Sequence[int]):
    """Copy the cones of the outputs into a fresh AIG; return (aig, outputs)."""
    res = Aig(aig.n)
    m = {v: 2 * v for v in range(aig.n + 1)}

    def copy(v):
        if v not in m:
            a, b = aig.fanins[v]
            m[v] = res.add_and(copy(a >> 1) ^ (a & 1), copy(b >> 1) ^ (b & 1))
        return m[v]

    return res, [copy(o >> 1) ^ (o & 1) for o in outs]
test_sat_sweeping.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-sweeping/. The authors are listed in prov/D7SVKR.jsonl.

import random
from itertools import product

from sat_sweeping import Aig, dpll, sat_sweep

# The example of the page, n = 2 (x = 1, y = 2):
#   3 = x & !y, 4 = !x & y, 5 = !3 & !4 (XNOR), 6 = x & y, 7 = !x & !y,
#   8 = !6 & !7 (XOR), 9 = !5 & 8, output 9 (XOR and XOR = XOR).
EXAMPLE_ANDS = [(2, 5), (3, 4), (7, 9), (2, 4), (3, 5), (13, 15), (11, 16)]
EXAMPLE_OUT = [18]


def tables(n, fanins, total) -> list:
    """Truth table of every node as an integer; input 1 is the high bit."""
    full = (1 << (1 << n)) - 1
    t = [0]
    for i in range(1, n + 1):
        t.append(sum(1 << m for m in range(1 << n) if (m >> (n - i)) & 1))
    for v in range(n + 1, total):
        a, b = fanins[v]
        x = t[a >> 1] ^ (full if a & 1 else 0)
        y = t[b >> 1] ^ (full if b & 1 else 0)
        t.append(x & y)
    return t


def lit_table(t, lit, n) -> int:
    full = (1 << (1 << n)) - 1
    return t[lit >> 1] ^ (full if lit & 1 else 0)


def input_tables(n, ands, outs) -> list:
    fanins = [(0, 0)] * (n + 1) + list(ands)
    t = tables(n, fanins, len(fanins))
    return [lit_table(t, o, n) for o in outs]


def random_aig(rng, n, n_and, window):
    """A random AIG with copies of its own logic, so that sweeping has work."""
    ands = []
    for i in range(n_and):
        v = n + 1 + i
        lo = max(1, v - window)
        a, b = rng.randrange(lo, v), rng.randrange(lo, v)
        ands.append((2 * a + rng.randint(0, 1), 2 * b + rng.randint(0, 1)))
    # rebuild a few nodes in another form: a & b = !( !a | !b ) = !(!(!(!a & !b)))
    for _ in range(rng.randint(0, 4)):
        v = rng.randrange(n + 1, n + 1 + len(ands))
        a, b = ands[v - n - 1]
        base = n + 1 + len(ands)
        ands.append((a ^ 1, a ^ 1))            # base     = !a  (as !a & !a)
        ands.append((b ^ 1, b ^ 1))            # base + 1 = !b
        ands.append((2 * base + 1, 2 * (base + 1) + 1))  # base + 2 = a & b
    top = n + len(ands)
    outs = [2 * top + rng.randint(0, 1)] + [2 * rng.randrange(1, top + 1) + rng.randint(0, 1)
                                            for _ in range(2)]
    return ands, outs


def test_dpll_against_brute_force() -> None:
    rng = random.Random(1)
    for _ in range(300):
        nv = rng.randint(1, 9)
        cls = [[rng.choice([1, -1]) * rng.randint(1, nv) for _ in range(rng.randint(1, 3))]
               for _ in range(rng.randint(1, 5 * nv))]
        brute = any(all(any((x[abs(l) - 1] == 1) == (l > 0) for l in c) for c in cls)
                    for x in product((0, 1), repeat=nv))
        model = dpll(cls, nv)
        assert (model is not None) == brute
        if model is not None:
            assert all(any((model[abs(l) - 1] == 1) == (l > 0) for l in c) for c in cls)


def test_example() -> None:
    res, outs, stats = sat_sweep(2, EXAMPLE_ANDS, EXAMPLE_OUT, n_patterns=4, seed=3)
    assert len(res.fanins) - 3 == 3  # x & !y, !x & y and one XOR node
    t = tables(2, res.fanins, len(res.fanins))
    assert lit_table(t, outs[0], 2) == 0b0110
    assert stats["unsat"] >= 1


def check_reduced(res, outs, n) -> None:
    t = tables(n, res.fanins, len(res.fanins))
    full = (1 << (1 << n)) - 1
    seen = {}
    for v in range(len(res.fanins)):
        key = min(t[v], t[v] ^ full)
        assert key not in seen, (v, seen[key])  # no two nodes equal up to complement
        seen[key] = v


def test_function_kept_and_result_reduced() -> None:
    rng = random.Random(2)
    for trial in range(150):
        n = rng.randint(1, 8)
        ands, outs = random_aig(rng, n, rng.randint(1, 25), 6)
        res, res_outs, _ = sat_sweep(n, ands, outs, n_patterns=rng.choice([1, 4, 16]),
                                     seed=trial)
        t = tables(n, res.fanins, len(res.fanins))
        assert [lit_table(t, o, n) for o in res_outs] == input_tables(n, ands, outs)
        check_reduced(res, res_outs, n)
        assert len(res.fanins) - n - 1 <= len(ands)


def test_constant_node_is_found() -> None:
    # 3 = x & y, 4 = x & !y, 5 = 3 & 4 is the constant 0 but not by a local rule
    res, outs, stats = sat_sweep(2, [(2, 4), (2, 5), (6, 8)], [10], n_patterns=2, seed=0)
    assert outs == [0]
    assert len(res.fanins) == 3


def test_add_and_rules() -> None:
    g = Aig(2)
    assert g.add_and(2, 3) == 0 and g.add_and(2, 1) == 2 and g.add_and(4, 4) == 4
    a = g.add_and(2, 4)
    assert g.add_and(4, 2) == a and len(g.fanins) == 4

History

Brand (1993) used internal equivalences found by test generation to check large synthesized designs. Kuehlmann and Krohm (1997) combined structural hashing with BDD and SAT checks of internal points for equivalence checking, which led to the AIG based checkers. In 2004 Kuehlmann named SAT sweeping and used it to simplify the transition relation of bounded property checking. In 2005 Mishchenko, Chatterjee, Jiang and Brayton defined functionally reduced AIGs and built them by simulation and SAT, and the ABC system uses them for equivalence checking, for choices in mapping and as a basic step of synthesis.

References

  1. Dynamic transition relation simplification for bounded property checking, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design (ICCAD 2004), pages 50 to 57; SAT sweeping of the AIG of the unrolled transition relation
  2. FRAIGs: a unifying representation for logic synthesis and verification, the definition of a functionally reduced AIG and its construction by simulation and SAT (general locator)
  3. Improvements to combinational equivalence checking, SAT sweeping of a miter for combinational equivalence checking, with counterexample simulation and resource limits (general locator, not checked)

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