Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 r1,…,rmr_1, \ldots, r_m, where row rir_i is the set of primes that contain the ii-th minterm of the on-set, and a weight w(j)=(1,literals of prime j)w(j) = (1, \text{literals of prime } j) for each of the pp primes. A set SS 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 ff, such a cover is a minimum sum of products of ff. 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

  1. PETRICK(rows) ▷ a product is a set of primes
  2. 1products ← { ∅ } ▷ the empty product is 1
  3. 2for each row r do
  4. 3if r = ∅ then return ∅ ▷ an empty sum is 0: no cover exists
  5. step ← ∅
  6. 4for each product t ∈ products do
  7. 5if t meets r then add t to step ▷ t (t + y) = t
  8. 6else for each prime j ∈ r do add t ∪ {j} to step
  9. 7products ← the sets of step that contain no other set of step
  10. return products
  11. CHEAPEST(products, w)
  12. 8return 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 tt already has a prime of the row, the factor (t+y)(t + y) adds nothing. Line L6 is the distributive law for the other products. Line L7 is absorption between products, X+XY=XX + XY = X, 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 f=∑m(0,1,2,5,6,7)f = \sum m(0, 1, 2, 5, 6, 7) over x1x2x3x_1 x_2 x_3. 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 (A+B)(A+C)(B+D)(C+E)(D+F)(E+F)(A + B)(A + C)(B + D)(C + E)(D + F)(E + F). 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 xˉ1xˉ2+x2xˉ3+x1x3\bar{x}_1 \bar{x}_2 + x_2 \bar{x}_3 + x_1 x_3.

Correctness

The products after row tt are exactly the inclusion-minimal sets of primes that meet the first tt rows. This holds for t=0t = 0, 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 SS for the first tt rows contains a minimal set TT for the first t−1t - 1 rows. If TT meets row tt, line L5 adds TT, and so S=TS = T. If not, SS holds a prime jj of row tt, line L6 adds T∪{j}⊆ST \cup \{j\} \subseteq S, and so S=T∪{j}S = T \cup \{j\}. 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 r1,…,rmr_1, \ldots, r_m, each a set of primes. A set SS of primes is a transversal of rows r1,…,rtr_1, \ldots, r_t when S∩ri≠∅S \cap r_i \ne \emptyset for every i≤ti \le t. It is a minimal transversal when no proper subset of SS is a transversal. Write MtM_t for the set of minimal transversals of the first tt rows. The only transversal of no rows that is minimal is ∅\emptyset, so M0={∅}M_0 = \{\emptyset\}.

Lemma 1 (absorption). Let XX be a finite family of sets. The sets that line L7 keeps are the inclusion-minimal sets of XX, each one time.

Proof. Line L7 goes through the distinct sets of XX in order of size and keeps a set unless it contains a set already kept. If tt is minimal in XX, no other set of XX is a subset of tt, so no kept set is a subset of tt, and tt is kept. If tt is not minimal, some set of XX is a proper subset of tt, and among those there is a minimal one ss of XX. It is smaller than tt, so it comes first and is kept, and then tt is removed. Repeated sets are merged before the pass. □\square

Lemma 2 (invariant). If no row among r1,…,rtr_1, \ldots, r_t is empty, then after the tt-th pass of line L2 the list products is exactly MtM_t.

Proof. By induction on tt. For t=0t = 0, line L1 sets products to {∅}=M0\{\emptyset\} = M_0. Assume products =Mt−1= M_{t-1} before the pass for row r=rtr = r_t.

Every set in step is a transversal of the first tt rows. A set TT that line L5 adds meets the first t−1t - 1 rows by the hypothesis and meets rr by the test. A set T∪{j}T \cup \{j\} that line L6 adds contains TT, which meets the first t−1t - 1 rows, and contains j∈rj \in r.

Every set of MtM_t is in step. Let S∈MtS \in M_t. Then SS is a transversal of the first t−1t - 1 rows, so it contains some T∈Mt−1T \in M_{t-1}. If TT meets rr, then TT is a transversal of the first tt rows with T⊆ST \subseteq S, so T=ST = S by the minimality of SS, and line L5 adds it. If TT does not meet rr, then SS meets rr at some jj, and j∉Tj \notin T. Line L6 adds T∪{j}T \cup \{j\}, which is a transversal of the first tt rows with T∪{j}⊆ST \cup \{j\} \subseteq S, so it is equal to SS.

So Mt⊆stepM_t \subseteq \mathrm{step}, 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 Mt⊆stepM_t \subseteq \mathrm{step}, which contradicts its minimality in step. Conversely, a set of MtM_t is minimal in step, since every set of step is a transversal. So the minimal sets of step are exactly MtM_t, and by Lemma 1 line L7 sets products to MtM_t. □\square

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 ∅\emptyset when it reaches the first empty row. □\square

Theorem. If every row is nonempty, PETRICK returns MmM_m, the set of all irredundant covers, and CHEAPEST returns a cover of least weight. If the rows are the on-set minterms of ff and the columns are all the primes of ff, this cover is a minimum sum of products of ff.

Proof. The first claim is Lemma 2 with t=mt = m. A cover of the table is a transversal of all rows. Let SS be a cover of least weight. Each weight w(j)=(1,ℓj)w(j) = (1, \ell_j) is greater than (0,0)(0, 0), so removing a prime from a cover lowers its weight. If SS were not minimal, a proper subset would be a cover of smaller weight, which is impossible. So S∈MmS \in M_m, and line L8, which takes the least weight over MmM_m, returns a set of the same weight as SS. For the last claim, every set of primes whose union contains the on-set is a cover of ff, 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 ff consists of primes, so its weight is the least weight over the transversals of the table. ■\blacksquare

Termination. The loop of line L2 runs once per row, and each pass works on finite lists.

Complexity

Let TT be the largest number of products after any row. A row turns each product into at most pp sets, so step has at most pTpT sets of at most pp primes each. The absorption of line L7 compares each set of step with the kept sets, in O(p2T2)O(p^2 T^2) time when sets are bit vectors or hash sets of O(p)O(p) words. Over mm rows this is O(mp2T2)O(m p^2 T^2) time and O(pT)O(pT) extra space. In the best case one prime is in every row, T=1T = 1, and the time is O(mp)O(mp).

TT can be exponential. With kk rows that are pairwise disjoint pairs {ai,bi}\{a_i, b_i\}, every choice of one prime from each pair is a minimal cover, so T=2kT = 2^k. The final count is the number of minimal transversals of the rows, and TT can be much larger, since a prefix of the rows can have many more minimal covers than the whole table. If the kk pairs above come first and are followed by the kk rows {a1},…,{ak}\{a_1\}, \ldots, \{a_k\}, the middle list has 2k2^k products and the final list has one. In general T≤2pT \le 2^p, and TT 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 pp 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 X+XY=XX + XY = X removes the larger product XYXY. 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.

petricks_method.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • 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