Algorithm Search⌘K

Algorithmcore

Algebraic division

Also called weak division.

Divides one sum of products by another, treating both as polynomials over literals, to get the unique largest quotient and a remainder in time polynomial in the number of cubes.

Time
O(k m n) worst
Space
O(m n) extra
Where
k = the number of cubes of D; m = the number of cubes of F; n = the number of variables
Properties
deterministicexactofflineiterative
Origin
Robert K. Brayton, Curtis T. McMullen, 1982

Algebraic division, also called weak division, divides a sum of products FF by another sum of products DD and returns a quotient QQ and a remainder RR with F=QD+RF = Q D + R. It treats the two expressions as polynomials whose variables are the literals, as in polynomial division, and does not use Boolean rules such as xx=xx x = x or x+xˉ=1x + \bar{x} = 1. The quotient is the largest set of cubes QQ over variables outside DD such that every product of a cube of QQ and a cube of DD is a cube of FF, and it is unique. The algorithm takes time polynomial in the number of cubes, and it is the inner step of factoring, substitution and kernel extraction in multi-level logic synthesis.

In plain words

Write a logic expression as a sum of terms, like a polynomial. To divide it by a smaller expression, ask which terms you can multiply by the divisor and get only terms that are already in the expression. Those terms form the quotient. The terms that are left over form the remainder.

For each term of the divisor, collect what remains of each big term after you strike out that divisor term. A quotient term must appear in every one of these lists, so keep the terms that all lists share.

This division follows only the rules of ordinary algebra. It misses some divisions that need the special rules of logic, but it is fast, its answer is unique, and it is easy to reason about.

The problem

Cubes are sets of literals with at most one literal of each variable, and an SOP is a set of cubes, as on the sum of products page. The support sup(G)\mathrm{sup}(G) of an SOP GG is the set of variables that occur in it. For SOPs AA and BB with sup(A)∩sup(B)=∅\mathrm{sup}(A) \cap \mathrm{sup}(B) = \emptyset, the algebraic product is the set of cubes AB={a∪b:a∈A,b∈B}A B = \{a \cup b : a \in A, b \in B\}. It has ∣A∣⋅∣B∣|A| \cdot |B| cubes, since disjoint supports make the map (a,b)↦a∪b(a, b) \mapsto a \cup b one to one.

Input. SOPs FF and DD, with D≠∅D \neq \emptyset.

Output. SOPs QQ and RR such that

F=QD∪R,QD∩R=∅,sup(Q)∩sup(D)=∅,F = Q D \cup R, \qquad Q D \cap R = \emptyset, \qquad \mathrm{sup}(Q) \cap \mathrm{sup}(D) = \emptyset,

and QQ is as large as possible: every cube qq with sup(q)∩sup(D)=∅\mathrm{sup}(q) \cap \mathrm{sup}(D) = \emptyset and {q}D⊆F\{q\} D \subseteq F is in QQ. Then QQ is written F/DF / D, and DD is an algebraic divisor of FF when Q≠∅Q \neq \emptyset. If R=∅R = \emptyset as well, DD is an algebraic factor of FF.

The equality F=QD∪RF = Q D \cup R is an equality of sets of cubes, so it also holds as an equality of Boolean functions.

The algorithm

  1. WEAK-DIVIDE(F, D)
  2. 1for each cube d_i of D:
  3. 2V_i ← { c \ d_i : c ∈ F and d_i ⊆ c } ▷ strike d_i out of each cube that contains it
  4. 3Q ← V_i if i = 1, else Q ∩ V_i ▷ stop early if Q = ∅
  5. 4P ← { q ∪ d : q ∈ Q, d ∈ D } ▷ the algebraic product Q D
  6. 5R ← F \ P; return (Q, R)

Line L2 lists, for one cube did_i of the divisor, every cube qq such that q∪diq \cup d_i is a cube of FF and qq has no literal of did_i. A cube of the quotient must be in every list, so line L3 intersects them. The intersection also removes every cube with a variable of DD: such a variable occurs in some did_i, and c∖dic \setminus d_i never holds a literal of it. Line L4 multiplies back, and line L5 keeps the rest of FF as the remainder.

With F=ac+ad+bc+bd+eF = ac + ad + bc + bd + e and D=a+bD = a + b, line L2 gives V1={c,d}V_1 = \{c, d\} from the cubes acac and adad, and V2={c,d}V_2 = \{c, d\} from bcbc and bdbd. So Q=c+dQ = c + d, the product is ac+ad+bc+bdac + ad + bc + bd, and R=eR = e. The expression of 9 literals becomes (a+b)(c+d)+e(a + b)(c + d) + e with 5 literals.

Example

Divide F=ac+ad+bc+beF = ac + ad + bc + be by D=a+bD = a + b.

step divisor cube cubes of F that contain it list Q so far
L2, L3 aa acac, adad V1={c,d}V_1 = \{c, d\} {c,d}\{c, d\}
L2, L3 bb bcbc, bebe V2={c,e}V_2 = \{c, e\} {c}\{c\}
L4 P={ac,bc}P = \{ac, bc\} {c}\{c\}
L5 R={ad,be}R = \{ad, be\} {c}\{c\}

So F=(a+b)c+ad+beF = (a + b) c + ad + be. The cube dd is in V1V_1 but not in V2V_2, because FF has adad but no bdbd, so dd cannot be in the quotient.

Algebraic division can miss a divisor that Boolean rules find. F=a+bcF = a + bc equals (a+b)(a+c)(a + b)(a + c) as a function, since (a+b)(a+c)=a+ac+ab+bc(a + b)(a + c) = a + ac + ab + bc and the Boolean rule a+ab=aa + ab = a removes two cubes. Weak division of FF by a+ba + b gives V1={∅}V_1 = \{\emptyset\} from the cube aa, which is the constant 1, and V2={c}V_2 = \{c\} from bcbc, so Q=∅Q = \emptyset and R=FR = F. The product (a+b)(a+c)(a + b)(a + c) is not algebraic, because both factors use aa.

Correctness

The full proof shows that the cube set QQ of line L3 is exactly the set Q\mathcal{Q} of all cubes qq with sup(q)∩sup(D)=∅\mathrm{sup}(q) \cap \mathrm{sup}(D) = \emptyset and q∪d∈Fq \cup d \in F for every d∈Dd \in D. A cube of Q\mathcal{Q} is in every ViV_i, since (q∪di)∖di=q(q \cup d_i) \setminus d_i = q. A cube qq in every ViV_i has no variable of DD, by the argument after the pseudocode, and q∪di∈Fq \cup d_i \in F for each ii. So Q=QQ = \mathcal{Q}, which is the largest set of cubes allowed in a quotient. Any union of allowed cubes is allowed, so this largest set is unique, and with it R=F∖QDR = F \setminus Q D is unique too.

Proof: Weak division returns the unique largest algebraic quotientfull

Cubes are sets of literals with at most one literal of each variable, and an SOP is a set of cubes. For a cube or SOP GG, sup(G)\mathrm{sup}(G) is the set of its variables. Fix SOPs FF and D={d1,…,dk}D = \{d_1, \ldots, d_k\} with k≥1k \ge 1. Call a cube qq allowed if sup(q)∩sup(D)=∅\mathrm{sup}(q) \cap \mathrm{sup}(D) = \emptyset and q∪di∈Fq \cup d_i \in F for i=1,…,ki = 1, \ldots, k, and let Q\mathcal{Q} be the set of allowed cubes. A quotient in the sense of the page is a set QQ of allowed cubes that contains every allowed cube, so Q\mathcal{Q} is the only quotient, and the remainder is then fixed as F∖QDF \setminus \mathcal{Q} D.

Lemma 1. If qq is allowed, then q∈Viq \in V_i for every ii.

Proof. The cube c=q∪dic = q \cup d_i is in FF and contains did_i. Since qq has no variable of did_i, q∩di=∅q \cap d_i = \emptyset, so c∖di=qc \setminus d_i = q, and line L2 puts qq in ViV_i. □\square

Lemma 2. If q∈Viq \in V_i for every ii, then qq is allowed.

Proof. For each ii there is a cube ci∈Fc_i \in F with di⊆cid_i \subseteq c_i and q=ci∖diq = c_i \setminus d_i. Then q∪di=ci∈Fq \cup d_i = c_i \in F. Let xx be a variable of DD, and pick ii with a literal λ\lambda of xx in did_i. The cube cic_i contains λ\lambda and, being a cube, no other literal of xx. So ci∖dic_i \setminus d_i has no literal of xx, and x∉sup(q)x \notin \mathrm{sup}(q). □\square

Lemma 3. After the loop of lines L1 to L3, Q=⋂iViQ = \bigcap_i V_i. The early stop does not change this.

Proof. Line L3 sets QQ to V1V_1 and then intersects it with each later ViV_i. If QQ becomes empty, every later intersection is empty too, so stopping returns the same set. □\square

Theorem. WEAK-DIVIDE returns Q=QQ = \mathcal{Q} and R=F∖QDR = F \setminus \mathcal{Q} D. These satisfy F=QD∪RF = Q D \cup R, QD∩R=∅Q D \cap R = \emptyset and sup(Q)∩sup(D)=∅\mathrm{sup}(Q) \cap \mathrm{sup}(D) = \emptyset, and they are the unique quotient and remainder.

Proof. By Lemmas 1 to 3, Q=⋂iVi=QQ = \bigcap_i V_i = \mathcal{Q}. Every cube of QQ is allowed, so sup(Q)∩sup(D)=∅\mathrm{sup}(Q) \cap \mathrm{sup}(D) = \emptyset and every product q∪dq \cup d of line L4 lies in FF. So P=QD⊆FP = Q D \subseteq F, and line L5 gives R=F∖PR = F \setminus P, which is disjoint from PP and satisfies P∪R=FP \cup R = F. A quotient must contain every allowed cube and may contain no other cube, so it equals Q\mathcal{Q}, and then RR is fixed. ■\blacksquare

Complexity

Let FF have mm cubes, DD have kk cubes, and let there be nn variables. Line L2 tests mm cubes for containment and removes did_i from those that contain it, O(mn)O(m n) steps, or O(mn/w)O(m n / w) word operations with cubes as bit vectors. It runs kk times. The intersections of line L3 take O(mn)O(m n) expected time each with a hash table of cubes, since each list has at most mm cubes. The product of line L4 has ∣Q∣k≤m|Q| k \le m cubes, because QD⊆FQ D \subseteq F and the map is one to one. So the time is O(kmn)O(k m n) and the extra space is O(mn)O(m n). This is polynomial in the sizes of FF and DD, in contrast to Boolean division, which needs a two-level minimization.

Properties

  • Exact for its model. The quotient is the unique largest algebraic quotient, not an approximation.
  • Division by a cube. If DD is one cube dd, then F/dF / d is the set of cubes of FF that contain dd, with dd removed. This is not the cofactor FdF_d, which also keeps the cubes of FF that have no literal of dd.
  • Units. F/1=FF / 1 = F with remainder 0, and F/F=1F / F = 1 with remainder 0.
  • Literal count. If Q≠∅Q \neq \emptyset, then writing FF as QD+RQ D + R uses ℓ(Q)+ℓ(D)+ℓ(R)\ell(Q) + \ell(D) + \ell(R) literals in place of ℓ(F)\ell(F), and the saving is ℓ(QD)−ℓ(Q)−ℓ(D)\ell(Q D) - \ell(Q) - \ell(D), where ℓ\ell counts literals.
  • Function preserved. F=QD+RF = Q D + R holds as cube sets, so the rewrite never changes the function and needs no check by simulation.

Variants and improvements

  • Boolean division. One adds a new variable yy for DD and minimizes FF with the don't-care set y⊕Dy \oplus D, so that rules such as a+ab=aa + ab = a can be used. It finds more divisors, but it costs a two-level minimization, see don't-care condition and observability don't-care.
  • Division by kernels. Kernel extraction divides FF only by its kernels and those of other nodes, since a multi-cube divisor shared by two expressions exists only if they share a kernel.
  • Bit vectors and sorting. An implementation can store each cube as a bit vector of 2n2n bits and sort the lists, so that the intersections of line L3 are merges of sorted lists.
  • Substitution. In a Boolean network, each node is divided by each other node, and a node with a nonempty quotient is rewritten to use the other node as an input.

When to use it

Use weak division inside factoring, substitution and common divisor extraction, where it is called many times on small SOPs and must be fast. Use Boolean division with don't-cares on the few candidates where the algebraic model gives no saving, or in a final pass. Do not use it on expressions where the complement of a variable must be treated as related to the variable, since the algebraic model treats aa and aˉ\bar{a} as two unrelated letters.

Pitfalls

  • Shared variables. The quotient must not use a variable of the divisor. Code that intersects the lists without the support argument, or that multiplies back with Boolean rules, can produce a product that is not algebraic.
  • Redundant cubes in F. If FF has two cubes with one inside the other, such as aa and abab, the algebraic model keeps both, and the quotient depends on that form. Make FF free of single-cube containment first.
  • Division by the constant 0. The empty divisor has no quotient. Line L1 then has nothing to intersect, and code must reject it.
  • Mixing up quotient and cofactor. Dividing by a single literal is not the cofactor, as the Properties list shows.

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.

algebraic_division.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algebraic-division/. The authors are listed in prov/NKSP1R.jsonl.

"""Weak (algebraic) division of a sum of products by another one.

A literal is the integer 2 * v + c for the variable v and c = 1 for the
complement. A cube is a frozenset of literals with at most one literal of
each variable, and a sum of products (SOP) is a frozenset of cubes. The
empty cube is the constant 1 and the empty SOP is the constant 0.

WEAK_DIVIDE(F, D) returns the quotient Q and the remainder R with
F = Q D + R as sets of cubes, where Q D is the algebraic product (the
supports of Q and D are disjoint) and Q is the largest such set of cubes.
"""

Cube = frozenset
Sop = frozenset


def parse(text: str) -> Sop:
    """Parse a string such as "ab'c + d" over the letters a to z."""
    cubes = []
    for term in text.replace(" ", "").split("+"):
        if term == "":
            continue
        lits = set()
        if term != "1":
            i = 0
            while i < len(term):
                v = ord(term[i]) - ord("a")
                c = 1 if i + 1 < len(term) and term[i + 1] == "'" else 0
                lits.add(2 * v + c)
                i += 1 + c
        cubes.append(frozenset(lits))
    return frozenset(cubes)


def show(f: Sop) -> str:
    """The SOP as a string, cubes and literals in sorted order."""
    if not f:
        return "0"

    def cube(c: Cube) -> str:
        if not c:
            return "1"
        return "".join(chr(ord("a") + (l >> 1)) + ("'" if l & 1 else "") for l in sorted(c))

    return " + ".join(sorted(cube(c) for c in f))


def support(f: Sop) -> set:
    """The variables that occur in f."""
    return {l >> 1 for c in f for l in c}


def literals(f: Sop) -> int:
    """The number of literals of f."""
    return sum(len(c) for c in f)


def weak_divide(f: Sop, d: Sop) -> tuple:
    """Return (Q, R) with f = Q d + R, Q d algebraic and Q as large as possible."""
    if not d:
        raise ZeroDivisionError("division by the constant 0")
    q = None
    for di in d:  # @line L1
        vi = {c - di for c in f if di <= c}  # @line L2
        q = vi if q is None else q & vi  # @line L3
        if not q:
            break
    qd = {qc | dc for qc in q for dc in d}  # @line L4
    r = f - qd  # @line L5
    return frozenset(q), frozenset(r)


def algebraic_product(q: Sop, d: Sop) -> Sop:
    """The product of two SOPs with disjoint supports, as a set of cubes."""
    if support(q) & support(d):
        raise ValueError("the supports are not disjoint")
    return frozenset(a | b for a in q for b in d)


def evaluate(f: Sop, point: dict) -> int:
    """The value of f at a point that maps each variable to 0 or 1."""
    for c in f:
        if all(point[l >> 1] ^ (l & 1) for l in c):
            return 1
    return 0
test_algebraic_division.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algebraic-division/. The authors are listed in prov/NKSP1R.jsonl.

import itertools
import random

import pytest

from algebraic_division import (
    algebraic_product,
    evaluate,
    literals,
    parse,
    show,
    support,
    weak_divide,
)


def brute_quotient(f, d):
    """Every cube q over the variables of f outside sup(d) with q x d inside f."""
    sd = support(d)
    free = sorted(support(f) - sd)
    q = set()
    for choice in itertools.product((None, 0, 1), repeat=len(free)):
        cube = frozenset(2 * v + c for v, c in zip(free, choice) if c is not None)
        if all(cube | di in f for di in d):
            q.add(cube)
    return frozenset(q)


def same_function(f, g, variables) -> bool:
    for bits in itertools.product((0, 1), repeat=len(variables)):
        point = dict(zip(variables, bits))
        if evaluate(f, point) != evaluate(g, point):
            return False
    return True


def test_page_example() -> None:
    f = parse("ac + ad + bc + bd + e")
    q, r = weak_divide(f, parse("a + b"))
    assert show(q) == "c + d" and show(r) == "e"
    assert (literals(f), literals(q) + 2 + literals(r)) == (9, 5)


def test_partial_quotient() -> None:
    q, r = weak_divide(parse("ac + ad + bc + be"), parse("a + b"))
    assert show(q) == "c" and show(r) == "ad + be"


def test_boolean_divisor_not_found() -> None:
    # a + bc = (a + b)(a + c) as functions, but the algebraic quotient is empty
    f = parse("a + bc")
    q, r = weak_divide(f, parse("a + b"))
    assert q == frozenset() and r == f
    g = parse("a + b")
    h = parse("a + c")
    prod = frozenset(x | y for x in g for y in h)
    assert same_function(prod, f, [0, 1, 2])


def test_edge_cases() -> None:
    f = parse("ab + c")
    assert weak_divide(f, parse("1")) == (f, frozenset())
    assert weak_divide(f, f) == (frozenset([frozenset()]), frozenset())
    assert weak_divide(frozenset(), parse("a")) == (frozenset(), frozenset())
    assert weak_divide(f, parse("d")) == (frozenset(), f)
    q, r = weak_divide(parse("ab + a'c"), parse("a"))
    assert show(q) == "b" and show(r) == "a'c"
    with pytest.raises(ZeroDivisionError):
        weak_divide(f, frozenset())


def random_cube(rng, variables):
    k = rng.randrange(0, len(variables) + 1)
    return frozenset(2 * v + rng.randrange(2) for v in rng.sample(variables, k))


def test_random_against_brute_force() -> None:
    rng = random.Random(7)
    nonempty = 0
    for _ in range(800):
        n = rng.randrange(2, 7)
        variables = list(range(n))
        rng.shuffle(variables)
        cut = rng.randrange(1, n)
        dv, qv = variables[:cut], variables[cut:]
        d = frozenset(random_cube(rng, dv) for _ in range(rng.randrange(1, 4)))
        planted = frozenset(random_cube(rng, qv) for _ in range(rng.randrange(0, 4)))
        noise = frozenset(random_cube(rng, list(range(n))) for _ in range(rng.randrange(0, 5)))
        f = algebraic_product(planted, d) | noise
        q, r = weak_divide(f, d)
        assert q == brute_quotient(f, d)
        assert planted <= q
        assert not support(q) & support(d)
        qd = algebraic_product(q, d)
        assert qd | r == f and not qd & r
        assert same_function(f, qd | r, list(range(n)))
        nonempty += bool(q)
    assert nonempty > 400


def test_random_divisors_with_shared_variables() -> None:
    rng = random.Random(11)
    for _ in range(600):
        n = rng.randrange(1, 6)
        variables = list(range(n))
        f = frozenset(random_cube(rng, variables) for _ in range(rng.randrange(0, 7)))
        d = frozenset(random_cube(rng, variables) for _ in range(rng.randrange(1, 3)))
        q, r = weak_divide(f, d)
        assert q == brute_quotient(f, d)
        assert algebraic_product(q, d) | r == f

History

Brayton and McMullen (ISCAS 1982) set up the algebraic model of multi-level logic, with expressions as polynomials over literals, defined the algebraic product and quotient, gave the weak division algorithm, and defined kernels as the divisors to try. The MIS system of Brayton, Rudell, Sangiovanni-Vincentelli and Wang (1987) used weak division in its factoring, substitution and extraction commands, and SIS (Sentovich et al. 1992) kept it. The textbooks of De Micheli (1994) and Hachtel and Somenzi (1996) present it as the basic step of algebraic synthesis.

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, the algebraic product, the quotient and remainder of algebraic division, and the weak division algorithm
  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 use of weak division in the factoring, substitution and extraction commands of MIS
  3. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 8, Multiple-Level Combinational Logic Optimization, the section on the algebraic model and algebraic division
  4. Gary D. Hachtel and Fabio Somenzi, Logic Synthesis and Verification Algorithms, Kluwer, 1996, the chapters on multi-level logic synthesis (a general locator)

Where this leads

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