Algorithmintro
Petrick's method
Also called Petrick function.
Solves the prime implicant covering table exactly by writing it as a product of sums of primes, expanding to a sum of products and taking the cheapest term.
- Time
- O(m p^2 T^2) worstO(m p) best
- Space
- O(p T) extra
- Where
- T = the largest number of products after a row, at most 2^p; m = the number of rows (on-set minterms); p = the number of primes
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stanley R. Petrick, 1956
Petrick's method solves the prime implicant table of Quine-McCluskey exactly. Give each prime a Boolean variable that is true when the prime is in the cover. A row of the table, one minterm of the on-set, is covered when at least one of its primes is chosen, so it becomes a sum of variables. The table is covered when every row is, so the condition is a product of these sums, the Petrick function. Multiply it out into a sum of products and remove each product that contains another one. Each product that is left is an irredundant cover, and the cheapest one is a minimum cover. The method is simple and exact, but the number of products can grow exponentially, so it suits small tables and the cyclic core that is left after the essential primes are taken.
In plain words
Write a list of choices for each row of the table, such as "prime A or prime B". To cover all rows, you need one choice from every list. Go through the lists one at a time and keep every way of choosing so far. When a way already covers the new row, keep it as it is. When it does not, make one new way for each prime of that row. Throw out a way when a smaller way uses only some of its primes. At the end, each way is a cover that has no extra prime, and you take the cheapest.
The problem
The input is a covering table: rows , where row is the set of primes that contain the -th minterm of the on-set, and a weight for each of the primes. A set of primes is a cover when it meets every row. The output is a cover of least total weight, with weights added coordinatewise and compared lexicographically. When the primes are all the primes of , such a cover is a minimum sum of products of . The problem is the unate case of set cover, and the covers that have no extra prime are the minimal hitting sets of the rows.
The algorithm
PETRICK(rows) ▷ a product is a set of primes- 1
products ← { ∅ } ▷ the empty product is 1 - 2
for each row r do - 3
if r = ∅ then return ∅ ▷ an empty sum is 0: no cover exists step ← ∅- 4
for each product t ∈ products do - 5
if t meets r then add t to step ▷ t (t + y) = t - 6
else for each prime j ∈ r do add t ∪ {j} to step - 7
products ← the sets of step that contain no other set of step return productsCHEAPEST(products, w)- 8
return the product t of least total weight, ties by the sorted list of t
The loop of line L2 multiplies the sums of the rows into the running sum of products, one row at a time. Line L5 is the absorption law: when the product already has a prime of the row, the factor adds nothing. Line L6 is the distributive law for the other products. Line L7 is absorption between products, , and it also removes repeated products. The products that line L7 keeps are the inclusion-minimal sets of primes that cover the rows seen so far. Line L8 picks the cheapest of them. Every weight is positive, so a cheapest cover never has an extra prime, and line L8 never misses it.
Example
Take over . It has six primes and no essential one, so the whole table is a cyclic core:
| prime | cube | minterms |
|---|---|---|
| A | 00- | 0, 1 |
| B | 0-0 | 0, 2 |
| C | -01 | 1, 5 |
| D | -10 | 2, 6 |
| E | 1-1 | 5, 7 |
| F | 11- | 6, 7 |
The Petrick function is . Lines L2 to L7 multiply it out:
| row | sum | size of step | products after L7 |
|---|---|---|---|
| 0 | A + B | 2 | A, B |
| 1 | A + C | 3 | A, BC |
| 2 | B + D | 3 | AB, AD, BC |
| 5 | C + E | 5 | BC, ABE, ACD, ADE |
| 6 | D + F | 6 | ACD, ADE, BCD, BCF, ABEF |
| 7 | E + F | 7 | ADE, BCF, ABEF, ACDF, BCDE |
At row 1, A meets the row and stays, and B becomes BA and BC. Then BA contains A, and line L7 removes it. The five final products are the five irredundant covers. ADE and BCF have three cubes and six literals each, and the other three have four cubes. Line L8 picks ADE by the tie rule, so the result is .
Correctness
The products after row are exactly the inclusion-minimal sets of primes that meet the first rows. This holds for , where the only minimal set is the empty set. Each set that line L5 or line L6 adds meets the new row. Each minimal set for the first rows contains a minimal set for the first rows. If meets row , line L5 adds , and so . If not, holds a prime of row , line L6 adds , and so . Line L7 then keeps exactly the minimal sets of step. Since every weight is positive, a cheapest cover has no extra prime, so it is among the final products. The full proof gives the details.
Proof: Petrick's method lists the irredundant covers and returns a cheapest onefull
Let the rows be , each a set of primes. A set of primes is a transversal of rows when for every . It is a minimal transversal when no proper subset of is a transversal. Write for the set of minimal transversals of the first rows. The only transversal of no rows that is minimal is , so .
Lemma 1 (absorption). Let be a finite family of sets. The sets that line L7 keeps are the inclusion-minimal sets of , each one time.
Proof. Line L7 goes through the distinct sets of in order of size and keeps a set unless it contains a set already kept. If is minimal in , no other set of is a subset of , so no kept set is a subset of , and is kept. If is not minimal, some set of is a proper subset of , and among those there is a minimal one of . It is smaller than , so it comes first and is kept, and then is removed. Repeated sets are merged before the pass.
Lemma 2 (invariant). If no row among is empty, then after the -th pass of line L2 the list products is exactly .
Proof. By induction on . For , line L1 sets products to . Assume products before the pass for row .
Every set in step is a transversal of the first rows. A set that line L5 adds meets the first rows by the hypothesis and meets by the test. A set that line L6 adds contains , which meets the first rows, and contains .
Every set of is in step. Let . Then is a transversal of the first rows, so it contains some . If meets , then is a transversal of the first rows with , so by the minimality of , and line L5 adds it. If does not meet , then meets at some , and . Line L6 adds , which is a transversal of the first rows with , so it is equal to .
So , and every set of step is a transversal. A minimal set of step is then a minimal transversal: if it had a transversal as a proper subset, that subset would contain a set of , which contradicts its minimality in step. Conversely, a set of is minimal in step, since every set of step is a transversal. So the minimal sets of step are exactly , and by Lemma 1 line L7 sets products to .
Lemma 3 (empty row). If some row is empty, no transversal exists, and PETRICK returns the empty list.
Proof. No set meets an empty row. Line L3 returns when it reaches the first empty row.
Theorem. If every row is nonempty, PETRICK returns , the set of all irredundant covers, and CHEAPEST returns a cover of least weight. If the rows are the on-set minterms of and the columns are all the primes of , this cover is a minimum sum of products of .
Proof. The first claim is Lemma 2 with . A cover of the table is a transversal of all rows. Let be a cover of least weight. Each weight is greater than , so removing a prime from a cover lowers its weight. If were not minimal, a proper subset would be a cover of smaller weight, which is impossible. So , and line L8, which takes the least weight over , returns a set of the same weight as . For the last claim, every set of primes whose union contains the on-set is a cover of , since the primes lie inside the on-set together with the don't-care set. By Quine's theorem (see the prime implicant page) some minimum cover of consists of primes, so its weight is the least weight over the transversals of the table.
Termination. The loop of line L2 runs once per row, and each pass works on finite lists.
Complexity
Let be the largest number of products after any row. A row turns each product into at most sets, so step has at most sets of at most primes each. The absorption of line L7 compares each set of step with the kept sets, in time when sets are bit vectors or hash sets of words. Over rows this is time and extra space. In the best case one prime is in every row, , and the time is .
can be exponential. With rows that are pairwise disjoint pairs , every choice of one prime from each pair is a minimal cover, so . The final count is the number of minimal transversals of the rows, and can be much larger, since a prefix of the rows can have many more minimal covers than the whole table. If the pairs above come first and are followed by the rows , the middle list has products and the final list has one. In general , and is at most the product of the row sizes.
Properties
- Exact. It returns a minimum cover for any positive weights.
- Lists all irredundant covers. The final products are all covers with no extra prime, which is useful when a second cost decides among the minimum ones.
- Not output-sensitive. The middle steps can hold far more products than the final answer.
- Simple. It needs only sets and the two laws of absorption, which makes it a good hand method for small cyclic cores.
Variants and improvements
- Reduce first. Take the essential primes and remove the dominated rows and columns before the expansion, as Quine-McCluskey does in phase 2. Only the cyclic core needs Petrick's method.
- Bound the products. Drop a product as soon as its weight is not less than the weight of a known cover. This turns the method into a branch and bound search and loses the list of all irredundant covers.
- Row order. Process rows with few primes first. This keeps the middle steps small in many tables, but it does not change the worst case.
- Implicit products. Store the set of products as a ZDD, where the multiplication and the absorption become set operations on the diagram. This can handle far more products than an explicit list.
- Minimal transversal enumeration. The final list is the set of minimal transversals of the rows. Algorithms for minimal transversal enumeration list them with better bounds on the time per output.
- Binate covering. When a choice of one column forces or forbids others, the condition is no longer a product of positive sums. The binate covering problem handles this case.
When to use it
Use Petrick's method for a small cyclic core, when you want every irredundant cover or a proof by hand that a cover is minimum. For large tables, a branch and bound on the table, or a pseudo-Boolean solver, finds the minimum without the full list. When an exact answer is not needed, a greedy choice or Espresso is much faster.
Pitfalls
- Forgetting absorption. If line L7 keeps every set of step, the list holds every cover, including covers with extra primes, and it can grow by a factor at every row.
- Expanding a covered product. If line L5 is left out, a product that already meets the row is still multiplied by each prime of the row. The result is correct after absorption, but the middle lists are larger.
- Absorbing the wrong product. The law removes the larger product . If line L7 keeps the superset and removes the subset, the result has extra primes and can miss the minimum.
- Rows for don't-cares. The rows of line L2 are the minterms of the on-set only. A row for a don't-care minterm forces the cover to contain it, and the answer can cost more than the minimum.
- Using it on the whole table. Running it before the essential primes are taken makes the lists larger for no gain.
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/petricks-method/. The authors are listed in prov/P7JR23.jsonl.
"""Petrick's method for the prime implicant table.
The table is a list of rows. Row r is the set of the column numbers
(prime implicants) that cover the minterm of row r. A product term of
the Petrick function is a frozenset of column numbers.
"""
from typing import Callable, Iterable
Term = frozenset[int]
def absorb(terms: Iterable[Term]) -> list[Term]:
"""Remove each term that contains another term (X + XY = X)."""
out: list[Term] = []
for t in sorted(set(terms), key=lambda t: (len(t), sorted(t))):
if not any(s <= t for s in out):
out.append(t)
return out
def petrick_products(rows: list[set[int]]) -> list[Term]:
"""Multiply out the product of sums of the rows, with absorption.
The result lists every inclusion-minimal set of columns that meets
every row, each one time.
"""
products: list[Term] = [frozenset()] # @line L1: the empty product is 1
for row in rows: # @line L2
if not row:
return [] # @line L3: an empty sum is 0, so there is no cover
step = []
for t in products: # @line L4
if t & row:
step.append(t) # @line L5: X (X + Y) = X
else:
step.extend(t | {j} for j in row) # @line L6
products = absorb(step) # @line L7
return products
def cheapest(products: list[Term], weight: Callable[[int], tuple[int, int]]) -> Term:
"""The product of least total weight, ties broken by the sorted column list."""
def total(t: Term) -> tuple[int, int]:
a = b = 0
for j in t:
w = weight(j)
a, b = a + w[0], b + w[1]
return a, b
return min(products, key=lambda t: (total(t), sorted(t))) # @line L8
def literals(c: str) -> int:
return sum(ch != "-" for ch in c)
def covers(c: str, m: int) -> bool:
n = len(c)
for i, ch in enumerate(c):
bit = (m >> (n - 1 - i)) & 1
if ch != "-" and int(ch) != bit:
return False
return True
def petricks_method(on: Iterable[int], primes: list[str]) -> list[str]:
"""A minimum cover of the on-set by the given primes, for the cost (cubes, literals)."""
rows = [{j for j, p in enumerate(primes) if covers(p, m)} for m in sorted(set(on))]
products = petrick_products(rows)
if not products:
raise ValueError("the primes do not cover the on-set")
best = cheapest(products, lambda j: (1, literals(primes[j])))
return sorted(primes[j] for j in best)
test_petricks_method.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/petricks-method/. The authors are listed in prov/P7JR23.jsonl.
import itertools
import random
from petricks_method import absorb, cheapest, covers, literals, petrick_products, petricks_method
def brute_minimal_covers(rows: list[set[int]], ncols: int) -> list[frozenset[int]]:
"""Every set of columns that meets every row and has no proper subset that does."""
def ok(s: frozenset[int]) -> bool:
return all(s & r for r in rows)
good = [frozenset(s) for k in range(ncols + 1) for s in itertools.combinations(range(ncols), k) if ok(frozenset(s))]
return sorted((s for s in good if not any(t < s for t in good)), key=lambda s: (len(s), sorted(s)))
def all_cubes(n: int) -> list[str]:
return ["".join(t) for t in itertools.product("01-", repeat=n)]
def primes_of(n: int, allowed: set[int]) -> list[str]:
def inside(c: str) -> bool:
return all(m in allowed for m in range(2 ** n) if covers(c, m))
imps = [c for c in all_cubes(n) if inside(c) and any(covers(c, m) for m in range(2 ** n))]
return sorted(c for c in imps if not any(inside(c[:i] + "-" + c[i + 1:]) for i in range(n) if c[i] != "-"))
def test_cyclic_example() -> None:
# f = sum of m(0, 1, 2, 5, 6, 7): six primes, each minterm in two of them.
primes = ["00-", "0-0", "-01", "-10", "1-1", "11-"]
on = [0, 1, 2, 5, 6, 7]
rows = [{j for j, p in enumerate(primes) if covers(p, m)} for m in on]
products = petrick_products(rows)
assert sorted(sorted(t) for t in products if len(t) == 3) == [[0, 3, 4], [1, 2, 5]]
assert len(products) == 5 # two covers of 3 primes and three of 4 primes
cover = petricks_method(on, primes)
assert cover in (sorted(["00-", "-10", "1-1"]), sorted(["0-0", "-01", "11-"]))
def test_absorb() -> None:
a, b, c = frozenset({1}), frozenset({1, 2}), frozenset({2, 3})
assert absorb([b, a, c, b]) == [a, c]
assert absorb([]) == []
def test_edges() -> None:
assert petrick_products([]) == [frozenset()]
assert petrick_products([set()]) == []
assert petrick_products([{0}, {0, 1}]) == [frozenset({0})]
try:
petricks_method([3], ["00"])
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
def test_products_are_the_minimal_covers() -> None:
rng = random.Random(3)
for _ in range(300):
ncols = rng.randint(1, 8)
rows = [{j for j in range(ncols) if rng.random() < 0.35} for _ in range(rng.randint(1, 7))]
got = sorted(petrick_products(rows), key=lambda s: (len(s), sorted(s)))
assert got == brute_minimal_covers(rows, ncols)
def test_cheapest_against_brute_force() -> None:
rng = random.Random(5)
for _ in range(300):
ncols = rng.randint(1, 8)
rows = [{j for j in range(ncols) if rng.random() < 0.4} | {rng.randrange(ncols)} for _ in range(rng.randint(1, 7))]
w = [(1, rng.randint(1, 4)) for _ in range(ncols)]
best = cheapest(petrick_products(rows), lambda j: w[j])
def total(s: frozenset[int]) -> tuple[int, int]:
return (len(s), sum(w[j][1] for j in s))
every = [frozenset(s) for k in range(ncols + 1) for s in itertools.combinations(range(ncols), k) if all(set(s) & r for r in rows)]
assert total(best) == min(total(s) for s in every)
def test_minimum_sop_on_random_functions() -> None:
rng = random.Random(9)
for n in (2, 3, 4):
for _ in range(40):
on = {m for m in range(2 ** n) if rng.random() < 0.4}
dc = {m for m in range(2 ** n) if m not in on and rng.random() < 0.2}
primes = primes_of(n, on | dc)
cover = petricks_method(on, primes)
got = {m for m in range(2 ** n) if any(covers(c, m) for c in cover)}
assert on <= got <= on | dc
key = (len(cover), sum(literals(c) for c in cover))
best = None
for k in range(len(primes) + 1):
for s in itertools.combinations(primes, k):
if all(any(covers(c, m) for c in s) for m in on):
t = (k, sum(literals(c) for c in s))
best = t if best is None or t < best else best
if best is not None:
break
assert key == best
History
Petrick (1956) gave the method in a report of the Air Force Cambridge Research Center, the same year as McCluskey's tabular method for the primes. The two together became the standard exact procedure taught for two-level minimization: Quine-McCluskey for the primes and the table, and Petrick's method for the cyclic part. The same algebra appears in later work on covering and on the enumeration of minimal transversals of hypergraphs.
References
- A direct determination of the irredundant forms of a Boolean function from the set of prime implicants, the product of sums of the prime implicant table and its expansion into the irredundant forms
- Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 7, Two-Level Combinational Logic Optimization (exact minimization and the covering problem)
- Gary D. Hachtel and Fabio Somenzi, Logic Synthesis and Verification Algorithms, Kluwer, 1996, Chapter 4, Synthesis of Two-Level Circuits (the covering table and its exact solution)
- Olivier Coudert, Two-level logic minimization, an overview, Integration, the VLSI Journal 17(2), 97 to 140, 1994, exact solution of the covering problem and the limits of explicit enumeration
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 P7JR23 Edit this page History Report an error Markdown