Boolean algebra, Boolean functions and circuits
Boolean algebra as an algebraic structure and Boolean functions as objects: canonical forms, functional completeness, circuits and their complexity (Shannon's counting argument), two-level minimization, and reduced ordered binary decision diagrams (ROBDDs), a canonical representation widely used in verification.
After this lesson you can
- Prove Boolean algebra identities from the axioms and relate them to lattices.
- Represent Boolean functions using tables, minterms, circuits, and ROBDDs, and convert between them.
- Prove the functional completeness of {NAND} and the incompleteness of {∧, ∨}.
- Reproduce Shannon's counting argument: almost all functions require exponential-size circuits.
- Minimize functions using Karnaugh maps and Quine–McCluskey.
- Construct ROBDDs and explain their canonicity and sensitivity to variable order.
Before you start
Motivation: the same function, written a thousand ways
Three situations that seem unrelated:
- An access policy. A service grants access to a resource if the user is an administrator, or owns the resource and it is not archived, or owns it and passed a second factor in the last ten minutes. Someone refactors the rule to make it “more readable.” Each atomic condition is a bit, the whole rule is a function of those bits, and the important question is whether the new version grants exactly the same access as the old one. A single differing case is a security flaw or a service outage.
- A circuit. An adder for two 64-bit numbers is a function from 129 input bits to 65 output bits. Hardware design tools rewrite the circuit thousands of times to make it smaller or faster, and after each rewrite one must prove it still computes the specification.
- A binarized neural network. In networks with weights and activations in , each neuron computes the sign of a weighted sum: a Boolean threshold function implemented in hardware with XNOR and a count of ones. The whole network is a Boolean circuit, and verifying a property (for example, changing a few pixels does not change the class) is a question about Boolean functions approached using SAT solvers (Narodytska and coauthors, 2018).
In all three cases we have different expressions and care about the function they represent. A truth table unambiguously decides equality of two functions, but has rows: with 30 conditions that is a billion; with 129 inputs it is absurd. This lesson studies Boolean functions as mathematical objects and answers four questions shaping everything else:
- What algebraic structure do they have? (Boolean algebra, and why it is not the field .)
- What pieces can construct any of them? (Functional completeness: one gate suffices.)
- How much does construction cost? (Circuits and Shannon’s counting argument: almost all are very expensive.)
- Are there compact canonical representations? (Minimal two-level forms and binary decision diagrams.)
Lesson 1 introduced the semantics: valuations, logical equivalence, and normal forms. Here we change viewpoint: formulas become names, and what we study are the functions they name.
Boolean algebra
George Boole proposed in 1854 treating propositions as an algebra with its own laws, and Claude Shannon showed in 1937, in his master’s thesis, that the same algebra describes relay circuits. We use Huntington’s axiomatization (1904).
The examples that matter:
- with ordinary or, and, and negation. This is the two-element Boolean algebra, the only one circuits need.
- , the subsets of a set , with , , complement relative to , , and .
- Boolean functions of variables with pointwise operations: , and similarly for the others. This is the focus of the lesson.
- Divisors of 30 with , , , , and . Check it with : and .
Notice that axioms come in pairs: each becomes its partner by swapping with and with . This gives half the theorems for free.
Proof
Take a derivation of the equality and dualize every step. Each step applied an axiom, and the dual of an axiom is another axiom, so the dualized sequence derives the dual equality.
∎Proof
By duality it suffices to prove one law of each pair. We indicate the axiom at each step.
(1) , using (B3), (B4), (B2), (B4), and (B3).
(2) : (B3) and (B4) to write the 1 on the right, (B2) read backwards, (B1) with (B3), and (B4).
(3) , by (B3), (B2), (2), and (B3).
(4) If and : The third step changes to and the fourth is distributivity (B2) read right to left.
(5) By (B4) and (B1), and : is a complement of and, by (4), the only one, .
(6) By (4), it suffices to show is a complement of . Using associativity (which Huntington derived from (B1) through (B4); many texts include it directly as an axiom), by (B2), (B4), and (2); and .
∎Boolean algebra as a lattice
Define if . By absorption, this is equivalent to , and is a partial order in which is the join of and the meet: a Boolean algebra is a lattice. In , is inclusion; among divisors of 30, divisibility; for functions, means is 1 at every point where is: is exactly .
One direction is what we just saw. For the other, axioms (B1) through (B4) hold by definition, and uniqueness of complements is exactly the proof of (4), which used only distributivity. Distributivity is essential: in lattice from lesson 6, an intermediate element has two distinct complements.
The divisors of 12 form a bounded distributive lattice but not a Boolean algebra: 2 has no complement, because no divisor satisfies and simultaneously. The next theorem gives a faster proof that it cannot be one: it has 6 elements.
Proof
(i) Every lies above some atom: if is not one, something lies strictly between and , and since is finite, descending ends at an atom.
(ii) is the join of the atoms below it. Let ; clearly . If , by (i) there is an atom . Then , hence and ; also , so , impossible. Therefore and , that is, .
(iii) By (ii), is injective. It is surjective: if and is an atom with , then , and since distinct atoms have meet , some is ; thus . It preserves meets because if and only if and . And complements: for an atom, , each parenthesized term is or and they cannot both be , so lies below exactly one of and .
∎For Boolean functions of variables this theorem is an old acquaintance. The atoms are functions equal to 1 at exactly one point: minterms. There are , and the decomposition of into atoms, , is the canonical DNF from lesson 1. The theorem also says how many functions there are: .
It is not the field
has another natural structure: the field of integers modulo 2, with addition (exclusive or, XOR) and multiplication . The two are easy to confuse, and should not be:
In every Boolean algebra, defines, with as product, a Boolean ring: a commutative ring in which for every . The formulas above allow conversion between structures (Stone, 1936), so they are two languages for the same objects. But their laws differ: or distributes over and, while in the ring product distributes over addition and addition distributes over nothing.
The ring language has its own canonical form. Every Boolean function is written uniquely as an XOR sum of monomials without negations, its algebraic normal form or Zhegalkin polynomial: three-bit majority is and is . Uniqueness follows by counting: there are possible monomials, hence polynomials, as many as functions, and existence follows from the formulas above. This is the natural representation when linearity matters: error-correcting codes, cryptography (the algebraic degree of an S-box), and parity, which in the ring is simply .
Boolean functions and the hypercube
The number grows brutally: 4 functions of one variable, 16 of two, 256 of three, 65536 of four, about 4300 million of five, and more than atoms in the observable universe from nine onward. This is the product rule applied to the rows, and we will use it again in Shannon’s argument.
Notation. For long formulas we use engineering notation: is , is , and or is still written . We do not use for or, precisely to avoid confusing it with addition in . Number table rows by the integer formed by the bits, with the first variable as most significant bit: with variables , row is . Thus a function is described by the list of rows where it is 1, such as for majority, or by an -bit integer whose bit is in row .
Proof
Evaluate both sides at a point with : the second term vanishes and the first equals on the remaining coordinates, the value of . The case is symmetric.
∎Applied to all variables one after another, expansion produces canonical DNF. Applied one variable at a time recursively, it produces a decision tree, and by sharing equal subtrees, the binary decision diagrams at the end of the lesson. Notice how simple this is in the table: with the first variable as the high bit, the cofactors of are the table’s upper and lower halves.
Terms as subcubes
is the vertex set of the hypercube : two vertices are adjacent if they differ in one bit, that is, if their Hamming distance is 1. A Boolean function is a two-coloring of the vertices.
A term (a product of literals) with literals fixes coordinates and leaves the other free: the set of vertices where it equals 1 is a subcube of dimension , with vertices. With , term is a vertex, is an edge (joining and ), is a face, and the empty term, , is the entire cube. This is the geometry of minimization: if two adjacent vertices equal 1, the term covering both has one fewer literal because .
A term is an implicant of if , that is, its subcube lies entirely within the ones of . It is a prime implicant if it also fits inside no larger subcube of ones: removing any literal takes it outside . We will return to them during minimization; for now, look at them.
The unfolding explains the Karnaugh map. The four combinations of , traversed in order (Gray code, where consecutive values differ in one bit), form a cycle around a cube face. To place it in a row it must be cut somewhere, and the cut edge, between and , joins the end columns. Thus in a Karnaugh map the first and last columns are neighbors, and with four variables so are the first and last rows: the map is a torus.
Functional completeness
How many gate types are needed to build any function?
is complete: this is exactly what existence of DNF says. De Morgan eliminates one of the two binary operators, , so and are complete too. One connective can suffice.
The idea is to translate , , and into NAND; the complete proof is the first guided exercise at the end. This is why a fabrication technology can use a single cell type: in CMOS, NAND and NOR are the cheapest two-input gates (four transistors versus six for AND), and NAND is often preferred because its series transistors are the faster n-type. Before the exercise, build it yourself.
Some constructions follow from algebra and others do not. NOT is and AND is NOT of NAND: 2 gates. OR follows from De Morgan, : 3. For XOR, direct translation of uses 5, but a 4-gate construction reuses : . The 9-gate full adder also reuses intermediate signals: the NAND of the two inputs serves both the first XOR and the carry. Exhaustive search over all NAND circuits of 8 gates or fewer (more than three million distinct sets of intermediate functions) confirms 8 cannot suffice. Sharing signals distinguishes a circuit from a formula, formalized in the next section.
Why does not suffice
A function is monotone if componentwise implies : raising an input from 0 to 1 never lowers the output. , , majority, and constants are monotone; and are not.
The proof is structural induction on the formula, which you will do in the second guided exercise. The converse also holds: every monotone function can be written without negations as . If , the term for equals 1 at ; and if the term for an with equals 1 at , then , hence . Thus generates exactly the monotone functions. There are 20 of three variables and 168 of four (the Dedekind numbers), versus 256 and 65536 functions in total.
Monotonicity is one of five ways to fall short. Emil Post classified them all in 1941.
The “only if” direction is easy and is used to prove something is not complete: each class is closed under composition (compose two 0-preserving functions and the result preserves 0), so if lies in a class, everything it generates does too, and the class is not everything. The other direction requires constructing and from witnesses and is not proved here.
| Connective | |||||
|---|---|---|---|---|---|
| , | yes | yes | yes | no | no |
| no | no | no | yes | yes | |
| yes | no | no | no | yes | |
| no | yes | no | no | no | |
| majority | yes | yes | yes | yes | no |
| NAND, NOR | no | no | no | no | no |
The last row is the shortest proof that NAND alone is complete. The table also explains curiosities: is not complete (everything it generates preserves 1), but is; is complete (the language of algebraic normal form), and is not, because both are self-dual.
Boolean circuits
A formula is a tree: if a subexpression is used twice, it is written twice. A circuit computes it once and fans out the wire.
Size measures hardware (or sequential work) and depth measures time with unlimited parallelism: gates on the same level work simultaneously. The difference between circuits and formulas can be large. Parity of bits has a circuit of XOR gates in a chain, and over a linear-size circuit (each XOR costs a constant number of gates); but any formula over for parity needs on the order of leaves (Khrapchenko, 1971), because it cannot reuse intermediate XORs.
The adder
Adding two -bit numbers is the canonical example. The full adder adds two bits and a carry :
Chain full adders so each carry feeds the next: this is a ripple-carry adder. With basis it costs gates (two XOR, two AND, and one OR per bit), and with NAND, . Its depth grows linearly: the carry traverses two gates per bit, and the highest sum bit is not ready until carry travels the whole chain.
Depth can be reduced to . For each bit define (the bit generates carry) and (it propagates it). Then , and the operation composing two segments, , is associative. Computing all carries is a prefix problem with an associative operation, solved with a tree of depth and size : the same idea as parallel reduction. This is the carry-lookahead adder in real processors.
Almost all functions are expensive
Every function of variables has some circuit: canonical DNF uses on the order of gates, and recursive Shannon expansion reduces this to . Lupanov (1958) refined the construction to . Can it be much better? For almost all functions, no.
The idea is to compare two numbers: there are functions and far fewer small circuits, and each circuit computes one function. A circuit of gates is described by choosing each gate’s function and two inputs; careful counting gives fewer than descriptions. The step-by-step proof is the third guided exercise. The next cell puts numbers to the bound.
import math
print(f"{'n':>3} {'s = 2^n/(10n)':>14} {'log2 #circuitos':>16} {'log2 #funciones':>16} {'log2 fracción':>14}")
for n in [6, 8, 10, 12, 16, 20]:
s = 2**n // (10 * n)
# cada puerta: 16 funciones y dos entradas entre n + s nodos; y una de las s puertas es la salida
log_circ = math.log2(s) + s * (4 + 2 * math.log2(n + s))
print(f"{n:3d} {s:14d} {log_circ:16.0f} {2**n:16d} {log_circ - 2**n:14.0f}")With , circuits of up to 5242 gates compute at most distinct functions out of : a fraction smaller than . If you choose a 20-variable function at random, with probability practically 1 it has no circuit of fewer than 5242 gates.
Two-level minimization
A sum of products (a DNF) is a two-level circuit: a layer of ANDs and a final OR (with negations at inputs). It was how logic was implemented in programmable logic arrays (PLAs), and remains the starting point of logic synthesis. Its natural cost is the number of terms (AND gates) and total number of literals (wires).
Proof
Each term in a sum of products for is an implicant, because if it equals 1, the sum equals 1. If a term of a minimum sum is not prime, a literal can be removed while it remains an implicant; repeating reaches a prime . Replacing with does not change the function: the new sum is the old one, which is , because ; and it is because all terms are implicants. It reduces literals without increasing terms, contradicting minimality. Finally, an essential prime is the only prime covering a certain minterm, and some term of the sum must cover it.
∎The problem thus splits into two phases: generate all prime implicants and choose the smallest subset covering all ones. Karnaugh maps do both by eye; Quine–McCluskey does them by machine.
Karnaugh maps
A Karnaugh map (Veitch, 1952; Karnaugh, 1953) is a truth table arranged in a grid whose rows and columns follow Gray code, so adjacent cells, including those at opposite edges, are adjacent hypercube vertices. Subcubes then appear as rectangles of or cells, possibly split at edges. To minimize by hand: surround ones with the largest possible rectangles (primes), take required ones first (essentials), and complete with as few as possible.
Don’t-care cells () are inputs that never occur or whose output does not matter: they can join a group to enlarge it, but need not be covered. A real example: if the input is a decimal digit in BCD (4 bits), combinations through never occur.
Quine-McCluskey
Quine (1952) and McCluskey’s (1956) algorithm systematizes the above using one consensus rule: . Represent each term as a string of , , and (free variable), and proceed in rounds:
- Start with minterms (and don’t-cares), grouped by number of ones.
- Combine each pair of terms with dashes in the same positions that differ in one bit: the bit becomes a dash. Only groups with consecutive counts of ones need comparison.
- Terms not combined with anything in a round are prime. Repeat with the new terms until none remain.
- With the cover chart (primes by minterms), take essentials, remove what they cover, and solve the rest: a set-cover problem.
There are not always essentials. Function has eight prime implicants, all with three literals, and each of its ones lies in exactly two: they form a cycle, and there are two minimum covers of 4 terms. In such cases the covering phase is a genuine search.
Why it is hard in general
Both phases explode. The number of prime implicants can be enormous: with a multiple of 3, the function equal to 1 when the input’s number of ones lies between and has a prime for each way to fix variables to 1 and to 0, namely primes, on the order of . Selection is a set-cover problem, NP-hard in general. This is not merely the formulation: deciding whether a function given by its truth table has a DNF with at most terms is NP-complete (Masek, 1979), and when the function is given as a formula the problem is harder still (-complete, Umans 2001).
In practice heuristics are used. Espresso (Brayton, Hachtel, McMullen, and Sangiovanni-Vincentelli, 1984; originating at IBM and expanded at Berkeley) does not generate all primes: it expands cubes, removes redundancies, and iteratively reformulates, often giving nearly minimum solutions for problems with dozens of inputs. For real circuits, two-level minimization falls short because a minimum sum may be exponentially larger than a multilevel circuit (parity needs terms and a linear circuit), and modern tools such as ABC work with AND-inverter graphs rewritten locally.
Binary decision diagrams
Minimum sums are not canonical (the cyclic core has two), and computing them is expensive. Bryant (1986) proposed a representation that is canonical and can also be manipulated.
Apply Shannon expansion recursively in a fixed variable order: the root asks about , its two children about , and so on to the leaves, the table values. This is a complete decision tree with leaves. Now share everything: draw equal subtrees once and remove questions whose answers do not matter.
Proof
It suffices to show that in an ROBDD distinct nodes represent distinct functions: nodes then correspond bijectively to the subfunctions appearing, and the function determines the structure. Suppose otherwise and take distinct nodes with , choosing the pair with as large as possible (terminals count as index ). Thus distinct nodes both below level represent distinct functions. Also and cannot both be terminals, because .
First, every internal node with represents a function depending on . Its children are distinct nodes (elimination) below level , so by choice of pair they represent distinct functions, ; neither depends on because only later variables occur below. Thus there is a point where they differ, and changing only there changes .
Now if (or is terminal), depends on but does not, impossible. If , cofactors agree: , and likewise the high ones. Those nodes lie lower, so by choice of pair they are the same node: and . Then and have the same triple, contrary to the merging rule.
∎The proof says something more concrete: nodes at the level of are the distinct subfunctions obtained by fixing that depend on . ROBDD size counts how much of the past must be remembered to decide the future, and that depends on the order variables arrive. Practical consequences are substantial:
- Equivalence of two functions: compare two pointers, , once constructed.
- Tautology and satisfiability: is a tautology if its root is terminal 1, and satisfiable if it is not 0. Any root-to-1 path gives a satisfying assignment.
- Model counting: the number of assignments making it 1 follows from one traversal, , summing child counts at each node with a factor of 2 per level skipped by an edge.
Operating without tables: apply
Building an ROBDD from the truth table requires rows. What makes ROBDDs useful is that they can be combined directly. If and are nodes and any binary operation (, , …), let be the earlier of their root variables. By Shannon expansion,
and cofactors with respect to are the node’s children if its variable is , or the node itself if it does not depend on . This gives the apply algorithm:
- If and are terminals, return terminal .
- If pair is already memoized, return the stored result.
- Otherwise recursively compute both result cofactors and return , where applies elimination and consults the unique table (merging) before creating a node.
Since each pair of nodes is solved once, the cost is . With apply and individual variables, construct the ROBDD of any formula bottom-up without ever building the table. You will implement it in the coding exercise.
The price: variable order
Proof
By the observation following canonicity, it suffices to count distinct subfunctions depending on the variable at each level.
Interleaved. After fixing , the subfunction is if some pair already equals and otherwise: only one depends on . After also fixing , the result is , , or , and only the last depends on . One node per level: internal nodes plus 2 terminals.
Separated. After fixing with , the subfunction is , and distinct sets give distinct functions (they differ on the of an index where the sets differ). At the level there is one node per : subfunction depends on and differs for each ; these are nodes. At the level there is one per function with : another . Including terminals, .
∎The phenomenon is general. An order is good when interacting variables are close, so little must be remembered between levels. For a comparator or a sum’s carry, interleaving bits of and starting with the most significant gives linear diagrams, while separating them gives exponential diagrams (you will measure this in the second code cell). There are hard limits:
- For some functions no order works: the middle bit of the product of two -bit numbers has exponential ROBDD size under every order (Bryant, 1991). ROBDDs are not a universal solution to equivalence, which remains coNP-complete.
- Finding the optimal order is NP-hard (Bollig and Wegener, 1996). In practice dynamic heuristics such as Rudell’s sifting (1993) move each variable through all positions and leave it where the diagram is smallest.
Even so, ROBDDs enabled industrial-scale formal hardware verification: symbolic model checking by Burch, Clarke, McMillan, and coauthors (1990) represented state sets with ROBDDs and reached systems with more than states. Today SAT solvers have taken much of that ground, but ROBDDs remain natural when solutions must be counted or enumerated, or a compact representation reused many times (product configurators, knowledge compilation for probabilistic inference).
Implementation from scratch
Start with the most direct representation: a function of variables as its truth table, stored as a Boolean array of rows or an -bit integer. With integers, one bitwise operation evaluates a formula on all rows at once; this is Knuth’s trick (TAOCP 7.1.2) for exploring all four-variable functions.
import numpy as np
def variables(n):
"""Tablas de verdad de x1, ..., xn: arrays booleanos de 2^n filas (x1 es el bit alto del número de fila)."""
filas = np.arange(2**n)
return [((filas >> (n - 1 - i)) & 1).astype(bool) for i in range(n)]
def como_entero(tabla):
"""La tabla como entero de 2^n bits: el bit m vale f en la fila m."""
return sum(1 << m for m, v in enumerate(tabla) if v)
a, b, c = variables(3)
maj = (a & b) | (a & c) | (b & c)
print("mayoría, filas 0..7:", maj.astype(int), " entero:", como_entero(maj), "=", bin(como_entero(maj)))
print("mintérminos:", np.flatnonzero(maj).tolist())
# con enteros, una operación bit a bit evalúa la función en las 2^n filas a la vez
A, B, C = (como_entero(v) for v in (a, b, c))
print("A =", bin(A), " B =", bin(B), " C =", bin(C))
print("mayoría con enteros coincide:", ((A & B) | (A & C) | (B & C)) == como_entero(maj))
# expansión de Shannon respecto de x1: las dos mitades de la tabla son los cofactores
print("cofactor a = 0:", maj[:4].astype(int), " (b ∧ c) cofactor a = 1:", maj[4:].astype(int), " (b ∨ c)")
x, y, z = variables(3)
leyes = {
"absorción x ∨ (x ∧ y) = x": (x | (x & y)) == x,
"De Morgan ¬(x ∧ y) = ¬x ∨ ¬y": ~(x & y) == (~x | ~y),
"distributiva x ∨ (y ∧ z) = (x ∨ y) ∧ (x ∨ z)": (x | (y & z)) == ((x | y) & (x | z)),
"anillo x ∨ y = x ⊕ y ⊕ xy": (x | y) == (x ^ y ^ (x & y)),
"¿x ⊕ x = x?": (x ^ x) == x,
}
for nombre, ok in leyes.items():
print(f" {nombre:46s} {bool(ok.all())}")
def anf(tabla):
"""Coeficientes de la forma normal algebraica: transformada de Möbius sobre Z_2, O(n 2^n)."""
c = np.array(tabla, dtype=np.uint8)
paso = 1
while paso < len(c):
for j in range(len(c)):
if j & paso:
c[j] ^= c[j ^ paso]
paso *= 2
return c
def monomios(coef, nombres="abc"):
n = len(nombres)
t = ["".join(nombres[i] for i in range(n) if (m >> (n - 1 - i)) & 1) or "1" for m in np.flatnonzero(coef)]
return " ⊕ ".join(t) or "0"
print("ANF de la mayoría:", monomios(anf(maj)), " ANF de a ∨ b:", monomios(anf(a | b)))
print("número de funciones de n variables:", [2**2**k for k in range(1, 6)])Majority is the integer (read from row 7 to 0). The last law fails, as it should: . The Möbius transform recovers algebraic form : coordinate of the result is the modulo-2 sum of values of on rows whose bits are contained in those of , the inversion of relation .
Now Quine–McCluskey, with each term as a pair (value, mask of free variables): two terms with the same mask combine if their values differ in one position, which moves to the mask.
from itertools import combinations
def cubre(p, m):
v, libres = p
return m & ~libres == v
def primos(unos, indiferentes=()):
"""Implicantes primos como pares (valor, máscara de variables libres), por Quine-McCluskey."""
terminos = {(m, 0) for m in set(unos) | set(indiferentes)}
primos = set()
while terminos:
usados, siguientes = set(), set()
for (v1, l1), (v2, l2) in combinations(terminos, 2):
d = v1 ^ v2
if l1 == l2 and d and d & (d - 1) == 0: # difieren en una sola variable fija
siguientes.add((v1 & ~d, l1 | d))
usados |= {(v1, l1), (v2, l2)}
primos |= terminos - usados
terminos = siguientes
return {p for p in primos if any(cubre(p, m) for m in unos)}
def literales(p, n):
return n - bin(p[1]).count("1")
def texto(p, n, nombres="abcdefghij"):
v, libres = p
s = [nombres[i] + ("" if v >> (n - 1 - i) & 1 else "'") for i in range(n) if not libres >> (n - 1 - i) & 1]
return "".join(s) or "1"
def cobertura_minima(n, unos, P):
"""Primos esenciales y, para el resto, la cobertura con menos términos (y, a igualdad, menos literales)."""
P = sorted(P)
esenciales = {next(p for p in P if cubre(p, m)) for m in unos if sum(cubre(p, m) for p in P) == 1}
resto = [m for m in unos if not any(cubre(p, m) for p in esenciales)]
candidatos = [p for p in P if p not in esenciales]
for k in range(len(candidatos) + 1):
validas = [S for S in combinations(candidatos, k) if all(any(cubre(p, m) for p in S) for m in resto)]
if validas:
mejor = min(validas, key=lambda S: sum(literales(p, n) for p in S))
return sorted(esenciales), sorted(esenciales) + sorted(mejor)
for nombre, unos, ind in [("ejemplo", [0, 1, 2, 5, 8, 9, 10], []),
("BCD primo", [2, 3, 5, 7], range(10, 16)),
("cíclica", [1, 2, 4, 5, 6, 8, 9, 10], [])]:
P = primos(unos, ind)
E, S = cobertura_minima(4, unos, P)
print(f"{nombre:10s} primos: {sorted(texto(p, 4) for p in P)}")
print(f"{'':10s} esenciales: {[texto(p, 4) for p in E]} mínima: {' + '.join(texto(p, 4) for p in S)}")In the output, is . The interactive map’s three functions appear as expected: the example with three essential primes; the prime BCD digit with , where don’t-cares allow four-cell groups; and the cyclic function with no essentials. Exhaustive cover search is feasible only because there are few primes. The next cell measures how many there can be and compares SymPy, whose SOPform implements Quine–McCluskey and whose simplify_logic chooses the shorter form.
import time
from math import factorial
from sympy import symbols, SOPform, POSform, simplify_logic
for n in (3, 6, 9):
banda = [m for m in range(2**n) if n // 3 <= bin(m).count("1") <= 2 * n // 3]
t0 = time.perf_counter()
P = primos(banda)
k = n // 3
print(f"n = {n}: {len(banda)} unos, {len(P)} implicantes primos "
f"(n!/(k!)^3 = {factorial(n) // factorial(k)**3}), {time.perf_counter() - t0:.2f} s")
for n in (30, 60):
k = n // 3
print(f"n = {n}: {factorial(n) // factorial(k)**3:.3e} primos 3^n/n = {3**n / n:.3e}")
a, b, c, d = symbols("a b c d")
print("\nSOPform:", SOPform([a, b, c, d], [0, 1, 2, 5, 8, 9, 10]))
print("POSform:", POSform([a, b, c, d], [0, 1, 2, 5, 8, 9, 10]))
print("BCD primo:", SOPform([a, b, c, d], [2, 3, 5, 7], dontcares=list(range(10, 16))))
e = (a & b) | (~a & c) | (b & c) # el término bc sobra: es el consenso de ab y ¬a c
print("simplify_logic:", simplify_logic(e), " en CNF:", simplify_logic(e, form="cnf"))With there are already 1680 primes and Quine–McCluskey takes appreciable time because it compares pairs of terms in each round; with there would be on the order of . The ratio tends to (Stirling). SymPy agrees with our minimum sum and also gives product-of-sums form . The last example is the consensus theorem: , because is covered by the other two.
The 9-NAND-per-bit adder, simulated on all pairs of 6-bit numbers at once (each signal is an array with one entry per pair):
import numpy as np
class Circuito:
def __init__(self):
self.puertas = 0
def nand(self, x, y):
self.puertas += 1
return ~(x & y)
def sumador_completo(C, a, b, c):
n1 = C.nand(a, b)
x = C.nand(C.nand(a, n1), C.nand(b, n1)) # a ⊕ b con 4 NAND
n5 = C.nand(x, c)
s = C.nand(C.nand(x, n5), C.nand(c, n5)) # x ⊕ c, reutilizando n5
return s, C.nand(n5, n1) # acarreo: ab ∨ c(a ⊕ b)
def sumador(C, A, B):
"""Suma con acarreo en cascada; A y B son listas de bits (arrays), el bit 0 es el menos significativo."""
acarreo = np.zeros_like(A[0])
S = []
for a, b in zip(A, B):
s, acarreo = sumador_completo(C, a, b, acarreo)
S.append(s)
return S + [acarreo]
k = 6
X, Y = (v.ravel() for v in np.meshgrid(np.arange(2**k), np.arange(2**k), indexing="ij"))
bits = lambda v: [(v >> i & 1).astype(bool) for i in range(k)]
C = Circuito()
S = sumador(C, bits(X), bits(Y))
total = sum(s.astype(int) << i for i, s in enumerate(S))
print(f"{k} bits: {C.puertas} puertas NAND; las {X.size} sumas coinciden con X + Y:", np.array_equal(total, X + Y))54 gates for 6 bits, and all 4096 sums correct. The final carry is , which by De Morgan is : the inputs’ NAND, computed for XOR, is reused in the carry.
A minimal ROBDD package
The central piece of an ROBDD package is the unique table: each node is a triple (level, low, high), and mk enforces both reduction rules. To avoid preempting the coding exercise, here we construct diagrams from the truth table using Shannon expansion (the first variable’s cofactors are the two halves of the table). This is exponential in but suffices to check canonicity and measure sizes under different orders.
import numpy as np
class ROBDD:
"""Tabla única de nodos (nivel, bajo, alto). Los nodos 0 y 1 son los terminales."""
def __init__(self, orden):
self.orden = list(orden) # nombres de las variables, de la raíz hacia abajo
self.nodos = [(len(orden), None, None)] * 2
self.unica = {}
def mk(self, i, bajo, alto):
if bajo == alto: # regla de eliminación: el test no sirve
return bajo
clave = (i, bajo, alto)
if clave not in self.unica: # regla de fusión: un solo nodo por terna
self.nodos.append(clave)
self.unica[clave] = len(self.nodos) - 1
return self.unica[clave]
def desde_tabla(self, tabla):
"""ROBDD de la función cuya tabla está en el orden de self.orden (la primera variable es el bit alto)."""
def construir(t, i):
if len(t) == 1:
return int(t[0])
mitad = len(t) // 2 # las dos mitades son los cofactores x_i = 0 y x_i = 1
return self.mk(i, construir(t[:mitad], i + 1), construir(t[mitad:], i + 1))
return construir(np.asarray(tabla, dtype=np.uint8), 0)
def tamano(self, u):
vistos, pila = set(), [u]
while pila:
w = pila.pop()
if w not in vistos:
vistos.add(w)
if w > 1:
pila += self.nodos[w][1:]
return len(vistos)
def modelos(self, u):
"""Número de asignaciones que hacen 1 la función: un recorrido, O(tamaño)."""
memo = {}
def contar(w): # modelos sobre las variables desde el nivel de w
if w < 2:
return w
if w not in memo:
i, b, a = self.nodos[w]
memo[w] = sum(contar(h) * 2 ** (self.nodos[h][0] - i - 1) for h in (b, a))
return memo[w]
return contar(u) * 2 ** self.nodos[u][0]
def tabla(f, orden):
"""Evalúa f(dict nombre -> array) en las 2^n filas, con las variables en el orden dado."""
n = len(orden)
filas = np.arange(2**n)
val = {v: ((filas >> (n - 1 - i)) & 1).astype(bool) for i, v in enumerate(orden)}
return f(val)
# canonicidad: fórmulas distintas, misma función, mismo nodo
B = ROBDD("abc")
f1 = B.desde_tabla(tabla(lambda v: (v["a"] & v["b"]) | (v["a"] & v["c"]) | (v["b"] & v["c"]), B.orden))
f2 = B.desde_tabla(tabla(lambda v: (v["a"] & (v["b"] | v["c"])) | (v["b"] & v["c"]), B.orden))
f3 = B.desde_tabla(tabla(lambda v: ~(~v["a"] & ~v["b"]) & ~(~v["a"] & ~v["c"]) & ~(~v["b"] & ~v["c"]), B.orden))
t = B.desde_tabla(tabla(lambda v: v["a"] | ~v["a"], B.orden))
print("mayoría escrita de tres maneras -> nodos", f1, f2, f3, " tautología -> nodo", t)
print("tamaño de la mayoría:", B.tamano(f1), " modelos:", B.modelos(f1))
def tamano_con_orden(f, orden):
B = ROBDD(orden)
return B.tamano(B.desde_tabla(tabla(f, orden)))
def pares(n): # x1y1 ∨ ... ∨ xnyn
return lambda v: np.logical_or.reduce([v[f"x{i}"] & v[f"y{i}"] for i in range(n)])
def mayor(k): # A > B con A = a_{k-1}...a_0 y B = b_{k-1}...b_0
def f(v):
A = sum(v[f"a{i}"].astype(int) << i for i in range(k))
Bn = sum(v[f"b{i}"].astype(int) << i for i in range(k))
return A > Bn
return f
def acarreo(k): # bit k (el acarreo final) de A + B
def f(v):
A = sum(v[f"a{i}"].astype(int) << i for i in range(k))
Bn = sum(v[f"b{i}"].astype(int) << i for i in range(k))
return ((A + Bn) >> k & 1).astype(bool)
return f
print(f"{'n':>2} | {'pares inter.':>12} {'pares sep.':>10} | {'A>B inter.':>10} {'A>B sep.':>9} | {'acarreo inter.':>14} {'acarreo sep.':>12}")
for n in range(1, 8):
inter = [s for i in range(n) for s in (f"x{i}", f"y{i}")]
sep = [f"x{i}" for i in range(n)] + [f"y{i}" for i in range(n)]
ab_i = [s for i in reversed(range(n)) for s in (f"a{i}", f"b{i}")] # bits más significativos primero
ab_s = [f"a{i}" for i in reversed(range(n))] + [f"b{i}" for i in reversed(range(n))]
print(f"{n:2d} | {tamano_con_orden(pares(n), inter):12d} {tamano_con_orden(pares(n), sep):10d} | "
f"{tamano_con_orden(mayor(n), ab_i):10d} {tamano_con_orden(mayor(n), ab_s):9d} | "
f"{tamano_con_orden(acarreo(n), ab_i):14d} {tamano_con_orden(acarreo(n), ab_s):12d}")The three majority expressions end at the same node and the tautology at terminal 1: comparing functions means comparing integers. The table confirms the theorem ( versus ) and shows the same for the comparator: nodes when interleaving bits from the most significant, versus when separating them. Carry has exactly the same sizes as the comparator, not by chance: equals , the comparator with bits of negated, and negating a variable merely swaps its nodes’ branches.
The professional version
| Tool | What it does | When to use it |
|---|---|---|
sympy.logic (SOPform, POSform, simplify_logic) | exact Quine–McCluskey and simplification | small functions, pure Python |
Espresso (in pyeda or as a binary) | heuristic two-level minimization | dozens of inputs, multiple outputs |
dd (Python, backed by CUDD or Sylvan) | ROBDD with dynamic reordering | equivalence, counting, quantification |
| CUDD (C) | the classic BDD package | verification and synthesis |
| ABC (Berkeley) | multilevel synthesis and verification with AND-inverter graphs | real circuits |
| SAT solvers | equivalence as unsatisfiability of | when the ROBDD explodes |
An example with dd, which is not in the browser (installed with pip install dd):
from dd.autoref import BDD
bdd = BDD()
bdd.declare("x1", "y1", "x2", "y2", "x3", "y3") # el orden de declaración es el orden inicial
f = bdd.add_expr(r"(x1 /\ y1) \/ (x2 /\ y2) \/ (x3 /\ y3)")
g = bdd.add_expr(r"~(~(x1 /\ y1) /\ ~(x2 /\ y2) /\ ~(x3 /\ y3))")
print(f == g, len(f), bdd.count(f, nvars=6)) # mismo nodo; tamaño; número de modelos
bdd.reorder() # sifting de Rudell
For the motivating question (do two versions of an access policy do the same thing?), the industrial recipe is to construct and ask whether it is satisfiable: if so, the solver returns a concrete request on which they differ. To give it to the solver, convert the circuit to CNF without blowing up its size, which is what the next lesson’s Tseitin transformation does.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 5. What strategy do you follow?
Step 1 of 4. Which proof principle do you use?
Step 1 of 4. How many functions must be compared with the circuits?
apply(bdd, op, u, v), returning the ROBDD node for op(f_u, f_v), where op is a two-bit function (for example lambda p, q: p & q). The BDD class already has the unique table: use bdd.mk(i, bajo, alto) to create nodes (it applies both reduction rules), bdd.nivel(u) for the level (terminals 0 and 1 have level nvars), and bdd.nodos[u] for the triple (nivel, bajo, alto). Memoize pairs (u, v) within each call so cost is at most the product of sizes. Tests check canonicity, tautologies and contradictions, reduction of the result, and memoization.class BDD:
"""ROBDD con tabla única. Los nodos 0 y 1 son los terminales (con nivel nvars)."""
def __init__(self, nvars):
self.nvars = nvars
self.nodos = [(nvars, None, None)] * 2
self.unica = {}
def mk(self, i, bajo, alto):
if bajo == alto:
return bajo
clave = (i, bajo, alto)
if clave not in self.unica:
self.nodos.append(clave)
self.unica[clave] = len(self.nodos) - 1
return self.unica[clave]
def var(self, i):
return self.mk(i, 0, 1)
def nivel(self, u):
return self.nodos[u][0]
def apply(bdd, op, u, v):
"""Nodo del ROBDD de op(f_u, f_v)."""
# tu código: caso terminal, memoria de pares (u, v), menor nivel de los dos,
# cofactores de cada uno respecto de ese nivel y bdd.mk con los dos resultados
return 0Summary
- A Boolean algebra is a distributive, bounded, complemented lattice; Huntington’s axioms are self-dual and give half the theorems for free. Finite ones are, up to isomorphism, , with elements. It is not the field : there addition is XOR and .
- There are functions of variables. Shannon expansion, , gives canonical DNF (decomposition into atoms), decision trees, and ROBDDs.
- is complete; is not because it generates only monotone functions. Post’s criterion gives the five possible obstructions.
- A circuit is a DAG of gates; size and depth measure hardware and parallel time. A ripple-carry adder is linear in both; carry-lookahead has logarithmic depth. By counting, almost all functions require on the order of gates, and no explicit one is known to require more than a linear number.
- A minimum sum uses only prime implicants and contains the essentials. Karnaugh (by hand, up to 4 or 5 variables) and Quine–McCluskey (exact) find it, but the general problem is NP-hard.
- An ROBDD is canonical for a fixed order: equivalence is pointer equality, and apply combines diagrams in time proportional to the product of their sizes. The price is variable order, which can take size from linear to exponential.