Algorithm Search⌘K

Algorithmcore

Kernel extraction

Also called common divisor extraction, rectangle covering extraction.

Finds kernels shared by several nodes of a Boolean network as rectangles of a kernel-cube matrix, and makes each one a new node when this saves literals.

Time
O(E P^4 K n) worst
Space
O(P K n) extra
Where
E = the number of extraction steps; K = the largest number of cubes of a kernel; P = the number of cokernel and kernel pairs of all nodes; n = the number of variables
Properties
deterministicnot exactofflinerecursive
Origin
Robert K. Brayton, Curtis T. McMullen, 1982

Kernel extraction is a step of multi-level logic synthesis that finds a sum of cubes used by several nodes of a Boolean network, makes it a new node, and rewrites the other nodes to use it. It looks for these divisors among the algebraic kernels of the nodes, because two expressions share a divisor with two or more cubes only if they share two cubes of some kernels. The kernels of all nodes go into a kernel-cube matrix, and a shared divisor that saves literals is a rectangle of this matrix. The method is a greedy heuristic: each step keeps every function and saves literals, but the result is not proved to be the smallest network.

In plain words

Several formulas of a circuit may hold the same piece, such as c+dc + d, multiplied by different terms. If you compute that piece once as its own signal and let each formula use the signal, you need fewer gate inputs.

To find such pieces, first list for each formula the ways to write part of it as a term times a sum: these sums are its kernels. Then write a table with one row for each term and formula, and one column for each product that occurs in some kernel. A block of rows and columns that is filled in everywhere means that the same sum appears in all these rows. Pull it out if it saves inputs, and repeat until no block saves anything.

The problem

A Boolean network maps each node vv to a sum of products FvF_v over the primary inputs and the other nodes, with no cycle. Its cost is the number of literals, ∑vℓ(Fv)\sum_v \ell(F_v). Given a network, find new nodes x1,x2,…x_1, x_2, \ldots, each a sum of cubes, and algebraic rewrites of the nodes that use them, so that every node keeps its function and the number of literals is small. Kernel extraction uses only algebraic rewrites: FvF_v is changed only by replacing a set of its cubes {c∪k:k∈X}\{c \cup k : k \in X\} by the one cube c∪{x}c \cup \{x\}, where XX is the sum of cubes of a new node xx and cc shares no variable with XX.

Kernel-cube matrix. The rows are the pairs (v,c)(v, c) where cc is a cokernel of FvF_v, and the row holds the kernel Kv,c=Fv/cK_{v,c} = F_v / c. The columns are the distinct cubes that occur in any kernel. The entry at row (v,c)(v, c) and column kk is 1 if k∈Kv,ck \in K_{v,c}, which means that c∪kc \cup k is a cube of FvF_v.

Rectangle and value. A rectangle is a set RR of rows and a set CC of at least two columns with all entries 1. Its value is the number of literals it saves:

value(R,C)=∑(v,q)∈U∣q∣−∑(v,c)∈R(∣c∣+1)−∑k∈C∣k∣,\mathrm{value}(R, C) = \sum_{(v, q) \in U} |q| - \sum_{(v, c) \in R} (|c| + 1) - \sum_{k \in C} |k|,

where U={(v,c∪k):(v,c)∈R,k∈C}U = \{(v, c \cup k) : (v, c) \in R, k \in C\} is the set of covered cubes of the nodes, each counted once. The first sum is the literals removed, the second the new cubes c∪{x}c \cup \{x\}, and the third the new node x=∑k∈Ckx = \sum_{k \in C} k.

The algorithm

  1. KERNELS(g, cok, j) ▷ g = F / cok is cube-free; literals l_0 < l_1 < ... of F
  2. 1for i ← j to the last literal:
  3. 2if fewer than two cubes of g contain l_i then continue
  4. 3C ← the intersection of the cubes of g that contain l_i ▷ the largest such common cube
  5. 4if C holds some l_k with k < i then continue ▷ this kernel is found elsewhere
  6. 5KERNELS(g / C, cok ∪ C, i + 1)
  7. 6output (cok, g)
  8. EXTRACT(N)
  9. 7loop: rows ← the outputs of KERNELS(F_v / c_v, c_v, 0) for every node v, c_v the common cube of F_v
  10. 8(R, C) ← for each seed row, add the row that raises the value most, keeping |C| ≥ 2; take the best
  11. 9if value(R, C) ≤ 0 then return N
  12. 10add a node x with F_x = the sum of the cubes of C
  13. 11for each row (v, c) of R:
  14. 12F_v ← (F_v minus {c ∪ k : k ∈ C}) plus the cube c ∪ {x}

KERNELS is the recursion of Brayton and McMullen. Line L3 extends the cokernel by the literal lil_i and by every literal that comes with it, so the new quotient is cube-free. Line L4 skips the call when the extended cokernel holds an earlier literal, since that kernel is reached from the earlier literal. Each call outputs its own kernel at line L6, including the node itself, with cokernel 1, when it is cube-free.

EXTRACT computes all rows at line L7 and grows rectangles from each row at line L8: the columns start as the whole kernel of the seed row, and each added row cuts them down to the common cubes. Lines L10 to L12 make the new node and rewrite the rows. The loop runs until the best rectangle found saves nothing.

Example

Take the network y=ac+ad+bc+bd+ey = ac + ad + bc + bd + e and z=cf+df+gz = cf + df + g, with 9 and 5 literals. KERNELS gives these rows.

row cokernel kernel columns
1 yy, aa c+dc + d cc, dd
2 yy, bb c+dc + d cc, dd
3 yy, cc a+ba + b aa, bb
4 yy, dd a+ba + b aa, bb
5 yy, 11 ac+ad+bc+bd+eac + ad + bc + bd + e acac, adad, bcbc, bdbd, ee
6 zz, ff c+dc + d cc, dd
7 zz, 11 cf+df+gcf + df + g cfcf, dfdf, gg

The matrix has 7 rows and 12 columns. The rectangle with rows 1, 2 and 6 and columns cc and dd covers the 6 cubes ac,ad,bc,bd,cf,dfac, ad, bc, bd, cf, df with 12 literals. It adds the cubes axax, bxbx and fxfx with 6 literals and the node x=c+dx = c + d with 2, so its value is 12−6−2=412 - 6 - 2 = 4. This is the best rectangle, and the new network is

x=c+d,y=ax+bx+e,z=fx+g,x = c + d, \qquad y = ax + bx + e, \qquad z = fx + g,

with 10 literals in place of 14. In the next round, yy has the kernel a+ba + b with cokernel xx, but extracting it adds as many literals as it removes, so EXTRACT stops. In the first round, the rectangle with rows 3 and 4 and columns aa and bb has value 8−4−2=28 - 4 - 2 = 2, and a rectangle with one row and the two columns of one kernel, such as row 1 with cc and dd, has value 4−2−2=04 - 2 - 2 = 0.

Correctness

The full proof has two parts. First, KERNELS outputs every pair (cokernel, kernel) of FF exactly once. A cube cc is a cokernel exactly when the cubes of FF that contain cc number at least two and have no other common literal, and the recursion builds each such cube from a unique parent by the test of line L4, as in the enumeration of closed sets. Second, each step of EXTRACT keeps the function of every node and lowers the number of literals by exactly the value of the rectangle. The cubes removed at line L12 are exactly the products c∪kc \cup k, and substituting x=∑k∈Ckx = \sum_{k \in C} k into c∪{x}c \cup \{x\} gives them back. The new node uses only fanins of the rewritten nodes, so the network has no cycle. The number of literals falls by at least 1 at each step, so the loop ends.

Proof: KERNELS lists each kernel pair once, and each extraction keeps the functions and saves its valuefull

Cubes are sets of literals with at most one literal of each variable, and an SOP is a set of cubes. Fix an SOP FF with at least two cubes and the order l0<l1<⋯l_0 < l_1 < \cdots of its literals. For a cube cc let S(c)={x∈F:c⊆x}S(c) = \{x \in F : c \subseteq x\}, and when S(c)≠∅S(c) \neq \emptyset let cl(c)=⋂S(c)\mathrm{cl}(c) = \bigcap S(c). Then c⊆cl(c)c \subseteq \mathrm{cl}(c), cl\mathrm{cl} is monotone, S(cl(c))=S(c)S(\mathrm{cl}(c)) = S(c), so cl(cl(c))=cl(c)\mathrm{cl}(\mathrm{cl}(c)) = \mathrm{cl}(c), and cl(a∪b)=cl(cl(a)∪b)\mathrm{cl}(a \cup b) = \mathrm{cl}(\mathrm{cl}(a) \cup b), because S(a∪b)=S(a)∩S(b)=S(cl(a))∩S(b)S(a \cup b) = S(a) \cap S(b) = S(\mathrm{cl}(a)) \cap S(b). Call cc closed if cl(c)=c\mathrm{cl}(c) = c. Write Pi(c)=c∩{l0,…,li}P_i(c) = c \cap \{l_0, \ldots, l_i\}, with P−1(c)=∅P_{-1}(c) = \emptyset, and c0=cl(∅)c_0 = \mathrm{cl}(\emptyset), the common cube of FF.

Lemma 1 (cokernels are closed cubes). F/cF / c is a kernel exactly when ∣S(c)∣≥2|S(c)| \ge 2 and cc is closed.

Proof. F/c={x∖c:x∈S(c)}F / c = \{x \setminus c : x \in S(c)\}, and x↦x∖cx \mapsto x \setminus c is one to one on S(c)S(c), so ∣F/c∣=∣S(c)∣|F / c| = |S(c)|. The common cube of F/cF / c is cl(c)∖c\mathrm{cl}(c) \setminus c. So F/cF / c is cube-free, with two or more cubes and no common literal, exactly when ∣S(c)∣≥2|S(c)| \ge 2 and cl(c)=c\mathrm{cl}(c) = c. □\square

Lemma 2 (what a call holds). Each call KERNELS(g,p,j)(g, p, j) has g=F/pg = F / p, pp closed, ∣S(p)∣≥2|S(p)| \ge 2, and cl(c0∪Pj−1(p))=p\mathrm{cl}(c_0 \cup P_{j-1}(p)) = p.

Proof. The first call has p=c0p = c_0, g=F/c0g = F / c_0 and j=0j = 0, and c0c_0 is closed with S(c0)=FS(c_0) = F. Suppose the claim holds for a call (g,p,j)(g, p, j), and line L5 runs at i≥ji \ge j. The cubes of gg that contain lil_i are x∖px \setminus p for x∈S(p∪{li})x \in S(p \cup \{l_i\}), at least two of them by line L2, and their intersection is C=cl(p∪{li})∖pC = \mathrm{cl}(p \cup \{l_i\}) \setminus p. So the child has c=p∪C=cl(p∪{li})c = p \cup C = \mathrm{cl}(p \cup \{l_i\}), which is closed, ∣S(c)∣≥2|S(c)| \ge 2, and g/C=F/cg / C = F / c. By line L4, CC has no literal of index below ii, so Pi(c)=Pi(p)∪{li}P_i(c) = P_i(p) \cup \{l_i\}. Then cl(c0∪Pi(c))⊇cl(c0∪Pj−1(p)∪{li})=cl(p∪{li})=c\mathrm{cl}(c_0 \cup P_i(c)) \supseteq \mathrm{cl}(c_0 \cup P_{j-1}(p) \cup \{l_i\}) = \mathrm{cl}(p \cup \{l_i\}) = c, and it is at most cl(c)=c\mathrm{cl}(c) = c. So the child call (F/c,c,i+1)(F / c, c, i + 1) satisfies the claim. □\square

For a closed cube c≠c0c \neq c_0, every closed cube contains c0c_0, and we let i(c)i(c) be the least index ii with cl(c0∪Pi(c))=c\mathrm{cl}(c_0 \cup P_i(c)) = c, which exists because cl(c)=c\mathrm{cl}(c) = c, and p(c)=cl(c0∪Pi(c)−1(c))p(c) = \mathrm{cl}(c_0 \cup P_{i(c)-1}(c)). Then p(c)⊆cp(c) \subseteq c and p(c)≠cp(c) \neq c. Also li(c)∈cl_{i(c)} \in c and li(c)∉p(c)l_{i(c)} \notin p(c), since otherwise p(c)⊇c0∪Pi(c)(c)p(c) \supseteq c_0 \cup P_{i(c)}(c) and p(c)=cp(c) = c. Since Pi(c)−1(c)⊆p(c)⊆cP_{i(c)-1}(c) \subseteq p(c) \subseteq c, we get Pi(c)−1(p(c))=Pi(c)−1(c)P_{i(c)-1}(p(c)) = P_{i(c)-1}(c) and cl(p(c)∪{li(c)})=c\mathrm{cl}(p(c) \cup \{l_{i(c)}\}) = c.

Lemma 3 (parent and index). If a call with cokernel qq makes a call with cokernel cc at index i∗i^*, then i∗=i(c)i^* = i(c) and q=p(c)q = p(c).

Proof. Let the call be (F/q,q,j)(F / q, q, j) with j≤i∗j \le i^*. Then c=cl(q∪{li∗})c = \mathrm{cl}(q \cup \{l_{i^*}\}), and c∖qc \setminus q has no literal of index below i∗i^*. By Lemma 2, cl(c0∪Pj−1(q))=q\mathrm{cl}(c_0 \cup P_{j-1}(q)) = q. For k<i∗k < i^*, Pk(c)=Pk(q)P_k(c) = P_k(q), so cl(c0∪Pk(c))⊆q≠c\mathrm{cl}(c_0 \cup P_k(c)) \subseteq q \neq c. The proof of Lemma 2 gives cl(c0∪Pi∗(c))=c\mathrm{cl}(c_0 \cup P_{i^*}(c)) = c. So i∗=i(c)i^* = i(c). Further q=cl(c0∪Pj−1(q))⊆cl(c0∪Pi∗−1(q))⊆cl(q)=qq = \mathrm{cl}(c_0 \cup P_{j-1}(q)) \subseteq \mathrm{cl}(c_0 \cup P_{i^*-1}(q)) \subseteq \mathrm{cl}(q) = q, so q=cl(c0∪Pi∗−1(c))=p(c)q = \mathrm{cl}(c_0 \cup P_{i^*-1}(c)) = p(c). □\square

Lemma 4 (every cokernel once). For each closed cc with ∣S(c)∣≥2|S(c)| \ge 2, exactly one call has cokernel cc.

Proof. For c=c0c = c_0 it is the first call, and no other call has cokernel c0c_0, since a child cokernel contains a literal lil_i that is not in its parent and so is larger than c0c_0. Let c≠c0c \neq c_0, i=i(c)i = i(c) and p=p(c)p = p(c), and use induction on ∣c∣|c|.

Existence. The cube pp is closed with S(p)⊇S(c)S(p) \supseteq S(c) and ∣p∣<∣c∣|p| < |c|, so some call (F/p,p,j)(F / p, p, j) exists. If p=c0p = c_0, then j=0≤ij = 0 \le i. Otherwise this call was made at index i(p)i(p) by Lemma 3, so j=i(p)+1j = i(p) + 1, and i(p)≤i−1i(p) \le i - 1 because cl(c0∪Pi−1(p))=cl(c0∪Pi−1(c))=p\mathrm{cl}(c_0 \cup P_{i-1}(p)) = \mathrm{cl}(c_0 \cup P_{i-1}(c)) = p. So j≤ij \le i. At index ii, line L2 passes since ∣S(p∪{li})∣=∣S(c)∣≥2|S(p \cup \{l_i\})| = |S(c)| \ge 2, and C=c∖pC = c \setminus p has no literal lkl_k with k<ik < i, since such a literal is in Pi−1(c)⊆pP_{i-1}(c) \subseteq p. So line L5 makes a call with cokernel cc.

Uniqueness. By Lemma 3, every call with cokernel cc is made by a call with cokernel pp at index ii. By induction there is one call with cokernel pp, and it makes at most one call at index ii. □\square

Theorem 1. KERNELS(F/c0,c0,0)(F / c_0, c_0, 0) outputs each pair (c,F/c)(c, F / c) with F/cF / c a kernel exactly once.

Proof. Line L6 outputs one pair for each call, and by Lemma 2 its quotient is a kernel by Lemma 1. By Lemmas 1 and 4, each kernel pair has exactly one call. □\square

Theorem 2. Each step of lines L10 to L12 keeps the function of every old node, makes no cycle, and lowers the total number of literals by exactly value(R,C)(R, C). EXTRACT ends.

Proof. Every column k∈Ck \in C lies in the kernel Fv/cF_v / c of each row (v,c)∈R(v, c) \in R, so c∪k∈Fvc \cup k \in F_v and cc shares no variable with kk. For a node vv, let Uv={c∪k:(v,c)∈R,k∈C}U_v = \{c \cup k : (v, c) \in R, k \in C\}, the cubes that line L12 removes from FvF_v, all of them in FvF_v. The new FvF_v is (Fv∖Uv)∪{c∪{x}:(v,c)∈R}(F_v \setminus U_v) \cup \{c \cup \{x\} : (v, c) \in R\}. Substituting Fx=⋁k∈CkF_x = \bigvee_{k \in C} k for xx turns c∧xc \wedge x into ⋁k∈C(c∧k)\bigvee_{k \in C} (c \wedge k), so the new FvF_v has the function ⋁(Fv∖Uv)∨⋁Uv=Fv\bigvee (F_v \setminus U_v) \vee \bigvee U_v = F_v, and every node keeps its function by induction along the network. The variables of FxF_x occur in cubes of every rewritten node, so they are fanins of each of these nodes, and none of them depends on a node that it feeds, so adding the edges from xx makes no cycle. The literals removed are ∑v∑q∈Uv∣q∣\sum_v \sum_{q \in U_v} |q|, the cubes added have ∑(v,c)∈R(∣c∣+1)\sum_{(v, c) \in R} (|c| + 1) literals, since xx is a new variable and the new cubes differ for different rows of one node, and FxF_x has ∑k∈C∣k∣\sum_{k \in C} |k| literals. The change is −value(R,C)-\mathrm{value}(R, C). Line L9 accepts only a positive value, so each step lowers the nonnegative integer literal count by at least 1, and the loop ends. ■\blacksquare

Complexity

The number of kernels can be exponential in the size of a node. A product of kk sums (a1+b1)⋯(ak+bk)(a_1 + b_1) \cdots (a_k + b_k), multiplied out, has 2k2^k cubes, 2k−12^k - 1 distinct kernels and 3k−2k3^k - 2^k pairs of cokernel and kernel, which the test file checks for k≤4k \le 4. KERNELS does O(Lmn)O(L m n) work in each call for LL literals, mm cubes and nn variables, and makes one call for each pair. With PP rows and kernels of at most KK cubes, the greedy search of line L8 starts at PP seeds, adds at most PP rows to each, and tries PP rows at each step, each in O(PKn)O(P K n) time to compute the value. So one step costs O(P4Kn)O(P^4 K n) in the code of this page, and EE steps cost O(EP4Kn)O(E P^4 K n). Tools keep this small by using only kernels of low level or by limiting the matrix, and by updating the matrix after each step in place of building it again.

Properties

What is proved. KERNELS finds every kernel of a node with every cokernel, and by the kernel theorem every multi-cube divisor shared by two nodes is a subset of the cubes of a kernel of each, so no algebraic multi-cube divisor is out of reach of the matrix. Each extraction keeps every function, makes no cycle, and lowers the literal count by exactly the value of the rectangle.

What is not proved. The greedy search of line L8 need not find the rectangle of largest value, and picking the best rectangle at each step need not give the smallest network. The number of rectangles grows exponentially with the number of rows, which is why tools use heuristics. Algebraic rewrites also miss Boolean divisors, such as a+ba + b in a+bc=(a+b)(a+c)a + bc = (a + b)(a + c).

What is measured. On 200 random networks of 4 nodes over 8 inputs, each node a sum of up to two products of a random cube and one of 3 shared random kernels plus one or two random cubes (seed 4), the code of this page lowered the mean literal count from 57.1 to 37.2 in a mean of 2.9 steps. On 2132 smaller networks of this kind (3 nodes over 6 inputs, seed 1, at most 16 rows), the greedy search found a rectangle of the largest value every time. These are toy cases with planted kernels, not benchmark results.

Variants and improvements

  • Cube extraction. A rectangle with one column is a common cube, such as abab in abc+abdabc + abd of one node and abeabe of another. It is found in a cube-literal matrix, where the rows are cubes and the columns literals, and tools run both kinds of extraction.
  • Double-cube and fast extraction. The fast extraction command of SIS uses only divisors with two cubes and cubes with two literals, together with their complements, which are few and can be updated quickly, and gets most of the gain of full kernel extraction in much less time.
  • Level-0 kernels. A kernel that has no kernel other than itself is of level 0. Restricting the matrix to low levels makes it much smaller.
  • Boolean extraction. Divisors found by algebraic means can be checked with don't-cares for a Boolean division, which uses rules that algebraic division ignores.
  • Common subexpressions in compilers. The same idea, with sums and products of numbers in place of cubes, is common subexpression elimination.

When to use it

Use kernel extraction on networks given as sums of products, such as the output of two-level minimization for many outputs, where large shared sums exist. It is the main area step of the classical MIS and SIS scripts. On an and-inverter graph, local rewriting such as AIG rewriting is the usual tool. Use exact methods only for tiny networks.

Pitfalls

  • Counting a covered cube twice. Two entries of one rectangle can name the same cube of a node. The value must count each covered cube once, or it overstates the saving.
  • Single-column rectangles. A rectangle with one column is a cube, not a multi-cube divisor, and needs the cube-literal matrix.
  • Ignoring the cokernel 1 rows. The node itself is a kernel when it is cube-free, and many shared divisors use its cubes. Leaving out these rows misses them.
  • Too many kernels. Products of many sums have exponentially many kernels, so a tool must limit the level or the number of kernels for each node.
  • Stopping rules that allow value 0. Extracting a rectangle of value 0 adds a node and saves nothing, and a loop that accepts it may not end.

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.

kernel_extraction.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-extraction/. The authors are listed in prov/6VFGF9.jsonl.

"""Kernel extraction by rectangles of the kernel-cube matrix.

A literal is 2 * v + c for the variable v and c = 1 for the complement, a
cube is a frozenset of literals, and an SOP is a frozenset of cubes. A
network maps each node variable to its SOP over the primary inputs and the
other node variables, with no cycle.

KERNELS(F) lists the pairs (cokernel, kernel) of F by the recursion of
Brayton and McMullen. EXTRACT builds the kernel-cube matrix of all nodes,
grows a rectangle greedily from each row, and if the best one saves
literals it makes the sum of its column cubes a new node and rewrites the
rows to use it. It repeats until no rectangle found has positive value.
"""

from typing import Optional

Cube = frozenset
Sop = frozenset
Network = dict


def common_cube(f: Sop) -> Cube:
    """The largest cube that divides every cube of f (f must be nonempty)."""
    return frozenset.intersection(*f)


def divide_by_cube(f: Sop, c: Cube) -> Sop:
    """The algebraic quotient f / c."""
    return frozenset(x - c for x in f if c <= x)


def is_cube_free(f: Sop) -> bool:
    """True if f has two or more cubes and no literal common to all of them."""
    return len(f) >= 2 and not common_cube(f)


def literals(f: Sop) -> int:
    return sum(len(c) for c in f)


def kernels(f: Sop) -> list:
    """All pairs (cokernel, kernel) of f, each once."""
    if len(f) < 2:
        return []
    order = sorted({l for c in f for l in c})
    index = {l: i for i, l in enumerate(order)}
    out: list = []

    def rec(g: Sop, cok: Cube, j: int) -> None:
        for i in range(j, len(order)):  # @line L1
            l = order[i]
            s = [x for x in g if l in x]
            if len(s) < 2:  # @line L2
                continue
            c = frozenset.intersection(*s)  # @line L3
            if any(index[k] < i for k in c):  # @line L4
                continue
            rec(divide_by_cube(g, c), cok | c, i + 1)  # @line L5
        out.append((cok, g))  # @line L6

    c0 = common_cube(f)
    rec(divide_by_cube(f, c0), c0, 0)
    return out


def kernel_cube_matrix(net: Network) -> tuple:
    """Rows (node, cokernel, kernel) and the sorted list of distinct kernel cubes."""
    rows = []
    for v in sorted(net):
        for cok, ker in kernels(net[v]):
            rows.append((v, cok, ker))
    cols = sorted({c for _, _, ker in rows for c in ker}, key=lambda c: sorted(c))
    return rows, cols


def value(rows: list, chosen: list, cubes: list) -> int:
    """Literals saved by extracting the rectangle chosen x cubes."""
    covered = {(rows[r][0], rows[r][1] | c) for r in chosen for c in cubes}
    gain = sum(len(x) for _, x in covered)
    cost = sum(len(rows[r][1]) + 1 for r in chosen) + sum(len(c) for c in cubes)
    return gain - cost


def best_rectangle(rows: list) -> tuple:
    """Greedy row growth from every seed row; returns (value, rows, cubes)."""
    best: tuple = (0, [], [])
    for seed in range(len(rows)):
        chosen = [seed]
        cubes = set(rows[seed][2])
        cur = value(rows, chosen, list(cubes))
        while True:
            pick: Optional[tuple] = None
            for s in range(len(rows)):
                if s in chosen:
                    continue
                common = cubes & rows[s][2]
                if len(common) < 2:
                    continue
                val = value(rows, chosen + [s], list(common))
                if val > cur and (pick is None or val > pick[0]):
                    pick = (val, s, common)
            if pick is None:
                break
            cur, s, cubes = pick[0], pick[1], set(pick[2])
            chosen.append(s)
        if cur > best[0]:
            best = (cur, list(chosen), sorted(cubes, key=lambda c: sorted(c)))
    return best


def extract(net: Network, first_new: int) -> tuple:
    """Run extraction to the end. Returns the new network and the list of values."""
    net = dict(net)
    log = []
    x = first_new
    while True:
        rows, _ = kernel_cube_matrix(net)  # @line L7
        val, chosen, cubes = best_rectangle(rows)  # @line L8
        if val <= 0:  # @line L9
            return net, log
        net[x] = frozenset(cubes)  # @line L10
        for r in chosen:  # @line L11
            v, cok, _ = rows[r]
            removed = {cok | c for c in cubes}
            net[v] = (net[v] - removed) | {cok | {2 * x}}  # @line L12
        log.append(val)
        x += 1


def network_literals(net: Network) -> int:
    return sum(literals(f) for f in net.values())


def evaluate(net: Network, point: dict) -> dict:
    """Values of all nodes at a point that maps each primary input to 0 or 1."""
    val = dict(point)

    def get(v: int) -> int:
        if v not in val:
            val[v] = 0
            for c in net[v]:
                if all(get(l >> 1) ^ (l & 1) for l in c):
                    val[v] = 1
                    break
        return val[v]

    for v in net:
        get(v)
    return val
test_kernel_extraction.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-extraction/. The authors are listed in prov/6VFGF9.jsonl.

import itertools
import random

from kernel_extraction import (
    best_rectangle,
    divide_by_cube,
    evaluate,
    extract,
    is_cube_free,
    kernel_cube_matrix,
    kernels,
    network_literals,
    value,
)


def lit(name: str) -> int:
    neg = name.endswith("'")
    return 2 * (ord(name[0]) - ord("a")) + (1 if neg else 0)


def sop(text: str) -> frozenset:
    out = []
    for term in text.replace(" ", "").split("+"):
        lits = []
        i = 0
        while i < len(term):
            j = i + 2 if i + 1 < len(term) and term[i + 1] == "'" else i + 1
            lits.append(lit(term[i:j]))
            i = j
        out.append(frozenset(lits))
    return frozenset(out)


def all_cubes(variables):
    for choice in itertools.product((None, 0, 1), repeat=len(variables)):
        yield frozenset(2 * v + c for v, c in zip(variables, choice) if c is not None)


def brute_kernels(f):
    """Every cube divisor c of f whose quotient is cube-free."""
    variables = sorted({l >> 1 for c in f for l in c})
    return {(c, divide_by_cube(f, c)) for c in all_cubes(variables) if is_cube_free(divide_by_cube(f, c))}


def random_sop(rng, variables, lo, hi, maxlen):
    out = set()
    for _ in range(rng.randrange(lo, hi + 1)):
        k = rng.randrange(1, min(maxlen, len(variables)) + 1)
        out.add(frozenset(2 * v + rng.randrange(2) for v in rng.sample(variables, k)))
    return frozenset(out)


def brute_best_rectangle(rows) -> int:
    best = 0

    def grow(chosen, common, start):
        nonlocal best
        if chosen:
            cols = sorted(common, key=lambda c: sorted(c))
            for k in range(2, len(cols) + 1):
                for sub in itertools.combinations(cols, k):
                    best = max(best, value(rows, chosen, list(sub)))
        for s in range(start, len(rows)):
            nxt = rows[s][2] if not chosen else common & rows[s][2]
            if len(nxt) >= 2:
                grow(chosen + [s], nxt, s + 1)

    grow([], frozenset(), 0)
    return best


def same_network(old, new, inputs) -> bool:
    for bits in itertools.product((0, 1), repeat=len(inputs)):
        point = dict(zip(inputs, bits))
        a, b = evaluate(old, point), evaluate(new, point)
        if any(a[v] != b[v] for v in old):
            return False
    return True


def test_page_example() -> None:
    net = {10: sop("ac + ad + bc + bd + e"), 11: sop("cf + df + g")}
    rows, cols = kernel_cube_matrix(net)
    assert len(rows) == 7 and len(cols) == 12
    val, chosen, cubes = best_rectangle(rows)
    assert val == 4 and cubes == [frozenset([lit("c")]), frozenset([lit("d")])]
    assert sorted((rows[r][0], sorted(rows[r][1])) for r in chosen) == [(10, [0]), (10, [2]), (11, [10])]
    new, log = extract(net, 12)
    assert log == [4] and network_literals(net) == 14 and network_literals(new) == 10
    assert new[12] == sop("c + d")
    assert same_network(net, new, list(range(7)))


def test_kernels_of_products_of_binomials() -> None:
    for k in range(1, 5):
        f = frozenset([frozenset()])
        for i in range(k):
            f = frozenset(c | {l} for c in f for l in (4 * i, 4 * i + 2))
        pairs = kernels(f)
        assert len(pairs) == 3 ** k - 2 ** k
        assert len({ker for _, ker in pairs}) == 2 ** k - 1


def test_kernels_edge_cases() -> None:
    assert kernels(frozenset()) == []
    assert kernels(sop("abc")) == []
    assert kernels(sop("a + b")) == [(frozenset(), sop("a + b"))]
    assert set(kernels(sop("ab + ac"))) == {(frozenset([lit("a")]), sop("b + c"))}


def test_kernels_against_all_cube_divisors() -> None:
    rng = random.Random(5)
    for _ in range(600):
        n = rng.randrange(2, 6)
        f = random_sop(rng, list(range(n)), 1, 6, 3)
        got = kernels(f)
        assert len(got) == len(set(got))
        assert set(got) == brute_kernels(f)


def planted_network(rng, nodes, nv, k):
    """Nodes that are sums of cokernel x kernel products from a shared pool, plus noise."""
    variables = list(range(nv))
    pool = [random_sop(rng, variables, 2, 3, 2) for _ in range(k)]
    net = {}
    for i in range(nodes):
        cubes = set()
        for _ in range(rng.randrange(1, 3)):
            ker = rng.choice(pool)
            kv = {l >> 1 for c in ker for l in c}
            free = [v for v in variables if v not in kv]
            if not free:
                continue
            size = rng.randrange(1, min(2, len(free)) + 1)
            cok = frozenset(2 * v + rng.randrange(2) for v in rng.sample(free, size))
            cubes |= {cok | c for c in ker}
        cubes |= set(random_sop(rng, variables, 1, 2, 3))
        net[100 + i] = frozenset(cubes)
    return net


def test_kernel_theorem() -> None:
    rng = random.Random(9)
    meets = 0
    for t in range(400):
        variables = list(range(4))
        if t % 2:
            f = random_sop(rng, variables, 2, 5, 3)
            g = random_sop(rng, variables, 2, 5, 3)
        else:
            f, g = planted_network(rng, 2, 4, 1).values()
        meet = any(len(kf & kg) >= 2 for _, kf in kernels(f) for _, kg in kernels(g))
        subs = set()
        for c in f | g:
            for k in range(len(c) + 1):
                subs.update(frozenset(s) for s in itertools.combinations(sorted(c), k))

        def divides(h, d):
            sd = {l >> 1 for c in d for l in c}
            first = next(iter(d))
            cands = {c - first for c in h if first <= c}
            return any(not {l >> 1 for l in q} & sd and all(q | di in h for di in d) for q in cands)

        share = any(divides(f, frozenset(p)) and divides(g, frozenset(p)) for p in itertools.combinations(sorted(subs, key=sorted), 2))
        assert meet == share
        meets += meet
    assert meets >= 100


def test_greedy_rectangle_against_brute_force() -> None:
    rng = random.Random(21)
    equal = 0
    for t in range(300):
        if t % 2:
            net = {10 + i: random_sop(rng, list(range(5)), 2, 4, 3) for i in range(2)}
        else:
            net = planted_network(rng, 3, 6, 2)
        rows, _ = kernel_cube_matrix(net)
        if len(rows) > 18:
            continue
        val, chosen, cubes = best_rectangle(rows)
        best = brute_best_rectangle(rows)
        assert 0 <= val <= best
        if chosen:
            assert len(cubes) >= 2 and val == value(rows, chosen, cubes)
            assert all(set(cubes) <= rows[r][2] for r in chosen)
        equal += val == best
    assert equal >= 200


def test_extraction_keeps_functions_and_counts_literals() -> None:
    rng = random.Random(33)
    changed = 0
    for t in range(500):
        if t % 2:
            variables = list(range(rng.randrange(3, 7)))
            net = {20 + i: random_sop(rng, variables, 2, 5, 3) for i in range(rng.randrange(1, 4))}
        else:
            variables = list(range(7))
            net = planted_network(rng, 3, 7, 2)
        new, log = extract(net, 300)
        changed += bool(log)
        assert all(v > 0 for v in log)
        assert network_literals(new) == network_literals(net) - sum(log)
        assert len(new) == len(net) + len(log)
        assert same_network(net, new, variables)
    assert changed >= 150

History

Brayton and McMullen (ISCAS 1982) introduced kernels and cokernels, gave the recursion that computes them, and proved that multi-cube common divisors arise from intersections of kernels. MIS (Brayton, Rudell, Sangiovanni-Vincentelli and Wang 1987) extracted common kernels across the nodes of a network. Rudell recast the search as rectangle covering of the kernel-cube matrix, and the survey of Brayton, Hachtel and Sangiovanni-Vincentelli (1990) set out the matrix and the value of a rectangle. SIS added the faster double-cube extraction. Later synthesis moved to AIG rewriting, but algebraic extraction stays in use for sums of products and in teaching.

References

  1. Robert K. Brayton and Curtis T. McMullen, The decomposition and factorization of Boolean expressions, Proceedings of the International Symposium on Circuits and Systems (ISCAS), 1982, pages 49 to 54, kernels, cokernels, the recursive computation of all kernels, and the theorem that common multi-cube divisors come from intersections of kernels
  2. Robert K. Brayton, Richard Rudell, Alberto Sangiovanni-Vincentelli and Albert R. Wang, MIS, a multiple-level logic optimization system, IEEE Transactions on Computer-Aided Design 6(6), 1987, pages 1062 to 1081, the extraction of common kernels across the nodes of a network as a command of MIS
  3. Robert K. Brayton, Gary D. Hachtel and Alberto L. Sangiovanni-Vincentelli, Multilevel logic synthesis, Proceedings of the IEEE 78(2), 1990, pages 264 to 300, the kernel-cube matrix, rectangles and their value in literals, and the extraction of common divisors
  4. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 8, Multiple-Level Combinational Logic Optimization, the sections on kernels and on the extraction of common subexpressions

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