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
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Robert K. Brayton, Curtis T. McMullen, 1982
Algebraic division, also called weak division, divides a sum of products by another sum of products and returns a quotient and a remainder with . It treats the two expressions as polynomials whose variables are the literals, as in polynomial division, and does not use Boolean rules such as or . The quotient is the largest set of cubes over variables outside such that every product of a cube of and a cube of is a cube of , 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 of an SOP is the set of variables that occur in it. For SOPs and with , the algebraic product is the set of cubes . It has cubes, since disjoint supports make the map one to one.
Input. SOPs and , with .
Output. SOPs and such that
and is as large as possible: every cube with and is in . Then is written , and is an algebraic divisor of when . If as well, is an algebraic factor of .
The equality is an equality of sets of cubes, so it also holds as an equality of Boolean functions.
The algorithm
WEAK-DIVIDE(F, D)- 1
for each cube d_i of D: - 2
V_i ← { c \ d_i : c ∈ F and d_i ⊆ c } ▷ strike d_i out of each cube that contains it - 3
Q ← V_i if i = 1, else Q ∩ V_i ▷ stop early if Q = ∅ - 4
P ← { q ∪ d : q ∈ Q, d ∈ D } ▷ the algebraic product Q D - 5
R ← F \ P; return (Q, R)
Line L2 lists, for one cube of the divisor, every cube such that is a cube of and has no literal of . 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 : such a variable occurs in some , and never holds a literal of it. Line L4 multiplies back, and line L5 keeps the rest of as the remainder.
With and , line L2 gives from the cubes and , and from and . So , the product is , and . The expression of 9 literals becomes with 5 literals.
Example
Divide by .
| step | divisor cube | cubes of F that contain it | list | Q so far |
|---|---|---|---|---|
| L2, L3 | , | |||
| L2, L3 | , | |||
| L4 | ||||
| L5 |
So . The cube is in but not in , because has but no , so cannot be in the quotient.
Algebraic division can miss a divisor that Boolean rules find. equals as a function, since and the Boolean rule removes two cubes. Weak division of by gives from the cube , which is the constant 1, and from , so and . The product is not algebraic, because both factors use .
Correctness
The full proof shows that the cube set of line L3 is exactly the set of all cubes with and for every . A cube of is in every , since . A cube in every has no variable of , by the argument after the pseudocode, and for each . So , 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 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 , is the set of its variables. Fix SOPs and with . Call a cube allowed if and for , and let be the set of allowed cubes. A quotient in the sense of the page is a set of allowed cubes that contains every allowed cube, so is the only quotient, and the remainder is then fixed as .
Lemma 1. If is allowed, then for every .
Proof. The cube is in and contains . Since has no variable of , , so , and line L2 puts in .
Lemma 2. If for every , then is allowed.
Proof. For each there is a cube with and . Then . Let be a variable of , and pick with a literal of in . The cube contains and, being a cube, no other literal of . So has no literal of , and .
Lemma 3. After the loop of lines L1 to L3, . The early stop does not change this.
Proof. Line L3 sets to and then intersects it with each later . If becomes empty, every later intersection is empty too, so stopping returns the same set.
Theorem. WEAK-DIVIDE returns and . These satisfy , and , and they are the unique quotient and remainder.
Proof. By Lemmas 1 to 3, . Every cube of is allowed, so and every product of line L4 lies in . So , and line L5 gives , which is disjoint from and satisfies . A quotient must contain every allowed cube and may contain no other cube, so it equals , and then is fixed.
Complexity
Let have cubes, have cubes, and let there be variables. Line L2 tests cubes for containment and removes from those that contain it, steps, or word operations with cubes as bit vectors. It runs times. The intersections of line L3 take expected time each with a hash table of cubes, since each list has at most cubes. The product of line L4 has cubes, because and the map is one to one. So the time is and the extra space is . This is polynomial in the sizes of and , 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 is one cube , then is the set of cubes of that contain , with removed. This is not the cofactor , which also keeps the cubes of that have no literal of .
- Units. with remainder 0, and with remainder 0.
- Literal count. If , then writing as uses literals in place of , and the saving is , where counts literals.
- Function preserved. 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 for and minimizes with the don't-care set , so that rules such as 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 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 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 and 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 has two cubes with one inside the other, such as and , the algebraic model keeps both, and the quotient depends on that form. Make 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NKSP1R Edit this page History Report an error Markdown