Algorithm Search⌘K

Algorithmcore

Espresso

Also called Espresso heuristic logic minimizer, Espresso-II.

Brayton and coauthors' heuristic two-level minimizer that loops expand, irredundant cover and reduce on a cover of cubes until the cost stops falling.

Time
O(n^2 c^3 (n^2 (r + c) + 2^n (c + r^2))) worst
Space
O(n^2 (c + r)) extra
Where
c = the number of cubes of F and D; n = the number of variables; r = the largest number of cubes in a complement that the program builds, at most 3^n
Properties
deterministicnot exactofflinerecursive
Origin
Robert K. Brayton, Gary D. Hachtel, Curtis T. McMullen, Alberto L. Sangiovanni Vincentelli, 1984

Espresso is a heuristic for two-level logic minimization. It works on a cover of cubes, a sum of products, and never lists all the prime implicants or minterms. It first computes the off-set RR as the complement of the on-set plus the don't-care set. Then it repeats three steps. EXPAND grows each cube into a prime, as long as it stays away from RR, and lets the grown cubes swallow other cubes. IRREDUNDANT removes cubes that the other cubes and the don't-cares already cover. REDUCE shrinks each cube to the smallest cube that still holds the points only it covers, which gives EXPAND room to grow it in another direction. The loop stops when the cost stops falling. The result is a prime and irredundant cover, a local optimum. It is not always a minimum cover. Brayton, Hachtel, McMullen and Sangiovanni-Vincentelli (1984) built it on the unate recursive paradigm, and it became the standard minimizer for programmable logic arrays.

In plain words

You start with any list of AND terms that gives the right outputs. Make each term as large as it can be without turning on an input that must be 0. Large terms swallow small ones, so throw out the swallowed ones. Then throw out any term whose 1s other terms already give.

Now the list may be stuck. So shrink each term back, as far as it can go without losing a 1 that only it gives. Then grow the terms again. They may grow in new directions and swallow more terms. Repeat while the list gets shorter or cheaper, and stop when a round brings no gain.

The problem

The input is the number of variables nn, a cover FF of the on-set and a cover DD of the don't-care set, both lists of cubes. The output is a cover GG with F⊆G⊆F∪DF \subseteq G \subseteq F \cup D as sets of points, where each cube of GG is a prime implicant of F∪DF \cup D and no cube of GG can be removed. The cost is the number of cubes, then the number of literals. A cube is a string over {0,1,−}\{0, 1, -\}.

The algorithm

  1. ESPRESSO(F, D)
  2. 1R ← COMPLEMENT(F ∪ D) ▷ the off-set
  3. 2F ← EXPAND(F, R)
  4. 3F ← IRREDUNDANT(F, D)
  5. loop
  6. 4before ← cost(F)
  7. 5G ← REDUCE(F, D)
  8. 6G ← IRREDUNDANT(EXPAND(G, R), D)
  9. 7if cost(G) ≥ before then return F
  10. F ← G
  11. EXPAND(F, R)
  12. for each cube c of F, fewest literals first do
  13. 8if c lies in a cube expanded before then skip c
  14. repeat
  15. 9raises ← the cubes made from c by removing one literal that meet no cube of R
  16. 10if raises = ∅ then stop: c is prime
  17. 11c ← the raise that contains the most other cubes of F, ties by the first position
  18. add c to the result
  19. return the result without the cubes that lie in another of its cubes
  20. IRREDUNDANT(F, D)
  21. 12E ← the cubes c of F that do not lie in (F - c) ∪ D ▷ relatively essential
  22. 13P ← the other cubes of F that do not lie in E ∪ D ▷ drop the totally redundant
  23. 14for each c of P, most literals first: if c lies in E ∪ (P - c) ∪ D then remove c from P
  24. return E ∪ P
  25. REDUCE(F, D)
  26. for each cube c of F, fewest literals first do
  27. 15free ← the points of c in no other cube of F and not in D
  28. 16if free = ∅ then remove c
  29. 17else c ← the smallest cube that contains free
  30. return F

COMPLEMENT and the containment tests "lies in" of lines L12 to L14 are the operators of the unate recursive paradigm: a cube cc lies in a cover HH exactly when the cofactor HcH_c is a tautology. Line L15 computes free as the complement of the cofactor of the other cubes and DD by cc.

EXPAND treats the large cubes first, because they are the most likely to swallow others. Line L9 keeps a raise only when it meets no point of RR, so every cube stays inside F∪DF \cup D. Line L11 is a greedy choice of the direction to grow. IRREDUNDANT keeps every cube that alone covers some point, removes the cubes that those cubes and DD cover, and then removes the remaining redundant cubes one at a time, each time testing against what is left. REDUCE works in turn, so a cube that shrinks first leaves more points to the cubes after it. The cube of line L17 is the supercube of free. It can be smaller than cc in many variables at once.

Example

Take the cyclic function f=∑m(1,2,3,4,5,6)f = \sum m(1, 2, 3, 4, 5, 6) over x1x2x3x_1 x_2 x_3 with no don't-cares, given by its six minterms.

step line cover cost
off-set L1 R = 000, 111
expand L2 -01, -10, 0-1, 1-0 (4, 8)
irredundant L3 -01, -10, 0-1, 1-0 (4, 8)
reduce L5 101, 010, 0-1, 1-0
expand and irredundant L6 0-1, 1-0, -01, -10 (4, 8)
stop L7 -01, -10, 0-1, 1-0 (4, 8)

At line L2, the cube 001 can grow to -01 or to 0-1, each of which swallows one more minterm, and the tie goes to the first position. Then 010 grows to -10, 011 to 0-1, and 100 to 1-0, and 101 and 110 lie in cubes grown before. Every cube of the result is needed, so line L3 removes nothing. REDUCE shrinks -01 to 101, since 001 is also in 0-1, and -10 to 010. EXPAND grows them back the same way, and the cost does not fall. The result has 4 cubes, but the minimum, for example xˉ2x3+xˉ1x2+x1xˉ3\bar{x}_2 x_3 + \bar{x}_1 x_2 + x_1 \bar{x}_3, has 3. The cover is prime and irredundant, and still not minimum.

On the BCD function ∑m(5,6,7,8,9)+d(10,…,15)\sum m(5, 6, 7, 8, 9) + d(10, \ldots, 15) over four variables, the off-set is R = 00--, 0100. Line L2 grows the five minterms to -1-1, -11- and 1---, at cost (3, 5). REDUCE shrinks them to 0101, 011- and 100-, line L6 grows them back, and the loop stops with x2x4+x2x3+x1x_2 x_4 + x_2 x_3 + x_1, which is a minimum cover.

Correctness

Three facts hold after each step, and the full proof gives the details. First, the cover GG stays between FF and F∪DF \cup D on the care points: line L9 never lets a cube meet RR, line L8 and the final filter of EXPAND only drop cubes that lie in another cube, lines L12 to L14 only drop a cube that the rest and DD cover, and line L17 keeps every point that only cc covers. Second, the output of EXPAND is prime, because line L10 stops only when no literal can be removed without meeting RR, and the output of IRREDUNDANT is irredundant, because a cube that line L14 keeps was not covered by a larger set of cubes, and removals only make that set smaller. The loop returns the output of an IRREDUNDANT step on the output of an EXPAND step, so the result is prime and irredundant. Third, the loop stops, because the cost is a pair of nonnegative integers that falls strictly at each pass that goes on.

Espresso is not exact. The cyclic example above ends in a cover of 4 cubes when 3 are enough. Prime and irredundant covers can differ in cost, and the loop only moves between them by local steps, so it can stop at a local optimum.

Proof: Espresso returns a prime and irredundant cover and stopsfull

We treat a cube and a cover as sets of points of {0,1}n\{0,1\}^n. Let A=F∪DA = F \cup D be the points of the input on-set and don't-care set, and let C=F∖DC = F \setminus D be the care points of the on-set. A cover GG is valid when C⊆G⊆AC \subseteq G \subseteq A. A cube is an implicant when it lies in AA, and prime when it is an implicant and no implicant contains it as a proper subset. A cover GG is irredundant when no cube g∈Gg \in G lies in (G∖{g})∪D(G \setminus \{g\}) \cup D. We assume that COMPLEMENT and the containment test are correct, as shown on the unate recursive paradigm page. So RR, from line L1, is exactly the set of points outside AA.

Lemma 1 (EXPAND). If every cube of FF is an implicant, then EXPAND(F, R) returns a cover of prime implicants whose union contains the union of FF.

Proof. A cube is an implicant exactly when it meets no cube of RR. Line L9 keeps only raises that meet no cube of RR, so each grown cube is an implicant, and it contains the cube it started from. When line L10 stops, removing any one literal of cc gives a cube that meets RR. Let ee be an implicant that contains cc. Each position where ee has a dash and cc a literal gives a raise of cc inside ee, which would meet no cube of RR. So ee has the same literals as cc, and cc is prime. A cube skipped at line L8 lies in a cube of the result. The final filter removes a cube only when it lies in another cube of the result, and of two equal cubes it removes only one, so the union does not change. □\square

Lemma 2 (IRREDUNDANT). IRREDUNDANT(F, D) returns a subset HH of FF with H∪D=F∪DH \cup D = F \cup D, and HH is irredundant.

Proof. Line L13 removes a cube that lies in E∪DE \cup D, and line L14 removes a cube that lies in what is left and DD. Each removal keeps the union with DD, since the removed cube lies in the union of the rest with DD. For irredundancy, take g∈Eg \in E. It does not lie in (F∖{g})∪D(F \setminus \{g\}) \cup D, and H∖{g}⊆F∖{g}H \setminus \{g\} \subseteq F \setminus \{g\}, so it does not lie in (H∖{g})∪D(H \setminus \{g\}) \cup D. Take gg kept by line L14. When line L14 tested gg, it did not lie in E∪(P∖{g})∪DE \cup (P \setminus \{g\}) \cup D for the PP of that moment. Later steps only remove cubes from PP, so at the end gg still does not lie in (H∖{g})∪D(H \setminus \{g\}) \cup D. □\square

Lemma 3 (REDUCE). If GG is valid, then REDUCE(G, D) returns a valid cover of implicants.

Proof. We show that after each pass of the loop over cubes, G∪DG \cup D is unchanged on CC, that is, C⊆G∪DC \subseteq G \cup D stays true, and every cube is an implicant. Let cc be the current cube and OO the union of the other current cubes. Line L15 sets free to c∖(O∪D)c \setminus (O \cup D). If free is empty, c⊆O∪Dc \subseteq O \cup D, and removing cc at line L16 keeps C⊆G∪DC \subseteq G \cup D. Otherwise line L17 replaces cc by the smallest cube ss that contains free. Since free ⊆c\subseteq c and cc is a cube, s⊆cs \subseteq c, so ss is an implicant. The points of cc outside ss are outside free, so they lie in O∪DO \cup D. So C⊆G∪DC \subseteq G \cup D again. As C∩D=∅C \cap D = \emptyset, this means C⊆GC \subseteq G. □\square

Theorem. ESPRESSO returns a valid cover whose cubes are prime implicants, and the cover is irredundant.

Proof. The cubes of the input FF are implicants, and the input is valid. By Lemma 1, line L2 gives a valid cover of primes. By Lemma 2, line L3 gives an irredundant subset of it that is still valid, since removing cubes that DD and the rest cover keeps every point of CC. Each pass of the loop applies Lemma 3, then Lemma 1 and then Lemma 2, so GG is a valid irredundant cover of primes after line L6. The loop returns FF, which is either the output of line L3 or a GG of an earlier pass, so it has all three properties. ■\blacksquare

Termination. Let F0F_0 be the cover after line L3, with c0c_0 cubes. A pass that does not return sets FF to a cover GG with a strictly smaller cost in the lexicographic order. The costs are pairs (a,b)(a, b) of nonnegative integers with a≤c0a \le c_0 and b≤nab \le n a, so there are at most c0(nc0+1)c_0 (n c_0 + 1) of them, and the loop runs at most that many times. EXPAND stops because each raise removes a literal. The recursions of COMPLEMENT and tautology stop by the argument on the unate recursive paradigm page.

What is not claimed. The result need not be a minimum cover. For f=∑m(1,2,3,4,5,6)f = \sum m(1, 2, 3, 4, 5, 6) the result has four cubes, while a cover of three cubes exists. Every minimum cover can be made prime and irredundant, but not every prime and irredundant cover is minimum.

Complexity

The bounds below are for the code of this page and use plain lists of cubes. The cost pair falls at each pass, and it is at most (c,nc)(c, nc), so the loop runs O(nc2)O(n c^2) times. One EXPAND tries at most nn raises at each of at most nn rounds per cube, and checks each raise against RR and FF in O(n(r+c))O(n(r + c)) time, which gives O(n3c(r+c))O(n^3 c (r + c)). IRREDUNDANT and REDUCE make O(c)O(c) calls to tautology and complement. Each such call is a recursion of depth at most nn with at most 2n2^n leaves, at O(n(c+r2))O(n(c + r^2)) per node for the cofactors and the containment filter of the merge, so O(2nn(c+r2))O(2^n n (c + r^2)) per call. Together this gives the bound of the front matter. The space is O(n(c+r))O(n(c + r)) per level of the recursion, O(n2(c+r))O(n^2 (c + r)) in all.

These worst cases are far from typical. The off-set alone can have exponentially many cubes, as the complement of x1x2+x3x4+⋯+x2k−1x2kx_1 x_2 + x_3 x_4 + \cdots + x_{2k-1} x_{2k} needs 2k2^k cubes, and tautology is co-NP-complete. On the PLAs of the 1984 book, the recursions stop early, and the book reports run times and results on a set of test PLAs in its Chapter 6 and compares them with other minimizers in Chapter 7.

Properties

  • Heuristic. The result is prime and irredundant, not always minimum.
  • Deterministic. The orders of lines L8, L11, L14 and L15 and their tie rules fix the output.
  • Works on covers. The input and every middle result are lists of cubes, so the time depends on the sizes of FF, DD and RR, not on 2n2^n, except inside the recursions.
  • Uses don't-cares. Cubes grow into DD freely, since only RR limits EXPAND.
  • Measured. In our own tests of the code of this page, which leaves out the ESSENTIAL, LAST_GASP and MAKE_SPARSE steps of the full program, the result was above the minimum for 2 of the 256 functions of three variables and for 3055 of the 65536 functions of four variables (about 4.7 percent), with no don't-cares, compared against Quine-McCluskey on every function. These counts describe this small version only.

Variants and improvements

  • ESSENTIAL. The full program finds the essential primes early, moves them to the don't-care set while the loop runs, and adds them back at the end. This makes the covers in the loop smaller.
  • LAST_GASP. When the loop stops, reduce every cube against the original cover at once, expand the small cubes, and try to replace two or more cubes by one. Its aim is to get out of local optima like the one in the cyclic example.
  • MAKE_SPARSE. After the loop, a last pass lowers the number of connections in the output part of the PLA, with no increase in the number of cubes.
  • Multiple outputs and multiple values. Espresso-MV of Rudell and Sangiovanni-Vincentelli (1987) treats the outputs as one more variable with many values, and so minimizes all outputs of a PLA together.
  • Exact modes. The program also has an exact mode that lists the primes and solves the covering problem, which plays the role of Quine-McCluskey with Petrick's method or a branch and bound.
  • In multi-level synthesis. Multi-level logic synthesis calls Espresso on the function of each node of a network, with don't-cares from the rest of the network.

When to use it

Use Espresso for functions with many inputs and outputs, where listing all minterms or all primes is too expensive, and a cover close to the minimum is enough. For small functions where a proved minimum is needed, use Quine-McCluskey. For hand work on up to four variables, a Karnaugh map is simpler.

Pitfalls

  • The wrong off-set. Line L1 must complement F∪DF \cup D, not FF. With the complement of FF alone, line L9 never lets a cube grow into DD, and the don't-cares are lost.
  • Stopping on strict increase only. Line L7 must stop when the cost is equal too. In the cyclic example the loop returns the same cover at the same cost, and a test of >> in place of ≥\ge loops forever.
  • Reducing all cubes at once. Line L15 must use the cubes as they are after the earlier reductions. If every cube is reduced against the original cover, two equal cubes each find the other, both become empty at line L16, and their points are lost.
  • Removing redundant cubes in one batch. Line L14 must test each cube against the cubes that are still in PP. Two cubes can each be covered by the rest while the rest without both of them is not a cover.
  • Equal cubes in EXPAND. The final filter of EXPAND must keep one of two equal cubes. A test that drops each cube lying in another drops both.
  • Calling the result optimal. The cover is prime and irredundant, and the cyclic example shows that it can have more cubes than the minimum.

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.

espresso.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/espresso/. The authors are listed in prov/70F55E.jsonl.

"""The Espresso loop: expand, irredundant cover and reduce, on covers of cubes.

A cube over n variables is a string over '0', '1' and '-'; a cover is
a list of cubes. F is the on-set cover and D the don't-care cover. This
version has the three main steps and the cost loop. It leaves out the
essential-prime step, LAST_GASP and MAKE_SPARSE of the full program.
"""

Cube = str
Cover = list[Cube]


# ------------------------------------------------------------ cube operations


def literals(c: Cube) -> int:
    return sum(ch != "-" for ch in c)


def cost(cover: Cover) -> tuple[int, int]:
    return len(cover), sum(literals(c) for c in cover)


def inside(a: Cube, b: Cube) -> bool:
    """True if cube a lies in cube b."""
    return all(y == "-" or x == y for x, y in zip(a, b))


def disjoint(a: Cube, b: Cube) -> bool:
    return any(x != "-" and y != "-" and x != y for x, y in zip(a, b))


def intersect(a: Cube, b: Cube) -> Cube:
    return "".join(y if x == "-" else x for x, y in zip(a, b))


def supercube(cubes: Cover) -> Cube:
    """The smallest cube that contains every cube of the list (the list is not empty)."""
    out = list(cubes[0])
    for c in cubes[1:]:
        for i, ch in enumerate(c):
            if out[i] != ch:
                out[i] = "-"
    return "".join(out)


def cube_cofactor(cover: Cover, d: Cube) -> Cover:
    return ["".join("-" if y != "-" else x for x, y in zip(c, d)) for c in cover if not disjoint(c, d)]


# ------------------------------------------------- unate recursive paradigm


def _cofactor(cover: Cover, i: int, b: str) -> Cover:
    return [c[:i] + "-" + c[i + 1:] for c in cover if c[i] in ("-", b)]


def _split(cover: Cover, n: int) -> int:
    best, key = -1, None
    for i in range(n):
        z = sum(c[i] == "0" for c in cover)
        o = sum(c[i] == "1" for c in cover)
        if z + o:
            k = (z > 0 and o > 0, z + o, -abs(z - o), -i)
            if key is None or k > key:
                best, key = i, k
    return best


def tautology(cover: Cover, n: int) -> bool:
    if not cover:
        return False
    if "-" * n in cover:
        return True
    i = _split(cover, n)
    if not any(c[i] == "0" for c in cover) or not any(c[i] == "1" for c in cover):
        # The most binate variable is unate, so the cover is unate.
        return False
    return tautology(_cofactor(cover, i, "0"), n) and tautology(_cofactor(cover, i, "1"), n)


def covered(cover: Cover, d: Cube) -> bool:
    """True if the cube d lies inside the cover."""
    return tautology(cube_cofactor(cover, d), len(d))


def complement(cover: Cover, n: int) -> Cover:
    if not cover:
        return ["-" * n]
    if "-" * n in cover:
        return []
    if len(cover) == 1:
        c = cover[0]
        return ["-" * i + ("1" if ch == "0" else "0") + "-" * (n - i - 1) for i, ch in enumerate(c) if ch != "-"]
    i = _split(cover, n)
    lo = complement(_cofactor(cover, i, "0"), n)
    hi = complement(_cofactor(cover, i, "1"), n)
    both = set(lo) & set(hi)
    out = sorted(both) + [c[:i] + "0" + c[i + 1:] for c in lo if c not in both]
    out += [c[:i] + "1" + c[i + 1:] for c in hi if c not in both]
    keep = []
    for k, a in enumerate(out):
        if not any(j != k and inside(a, b) and (a != b or j < k) for j, b in enumerate(out)):
            keep.append(a)
    return keep


# ------------------------------------------------------------------- EXPAND


def expand(F: Cover, R: Cover) -> Cover:
    """Make every cube prime, raising literals while the cube stays off R."""
    order = sorted(range(len(F)), key=lambda k: (literals(F[k]), k))  # big cubes first
    out: Cover = []
    for k in order:
        c = F[k]
        if any(inside(c, e) for e in out):  # @line L8: covered by a cube expanded before
            continue
        while True:
            raises = []
            for i, ch in enumerate(c):
                if ch != "-":
                    t = c[:i] + "-" + c[i + 1:]
                    if all(disjoint(t, r) for r in R):  # @line L9: still an implicant
                        gain = sum(inside(F[j], t) for j in order if j != k)
                        raises.append((-gain, i, t))
            if not raises:
                break  # @line L10: no literal can go, so c is prime
            c = min(raises)[2]  # @line L11: the raise that covers the most other cubes
        out.append(c)
    return [c for k, c in enumerate(out) if not any(j != k and inside(c, e) and (c != e or j < k) for j, e in enumerate(out))]


# -------------------------------------------------------------- IRREDUNDANT


def irredundant(F: Cover, D: Cover) -> Cover:
    """Drop cubes until no cube lies in the union of the others and D."""
    essential = [c for k, c in enumerate(F) if not covered(F[:k] + F[k + 1:] + D, c)]  # @line L12
    rest = [c for c in F if c not in essential and not covered(essential + D, c)]  # @line L13
    keep = list(rest)
    for c in sorted(rest, key=lambda c: (-literals(c), c)):  # @line L14: small cubes first
        others = [e for e in keep if e != c]
        if covered(essential + others + D, c):
            keep = others
    return essential + keep


# ------------------------------------------------------------------- REDUCE


def reduce(F: Cover, D: Cover, n: int) -> Cover:
    """Shrink each cube, in turn, to the smallest cube that still covers its own part."""
    F = list(F)
    order = sorted(range(len(F)), key=lambda k: (literals(F[k]), k))
    gone = set()
    for k in order:
        c = F[k]
        others = [F[j] for j in range(len(F)) if j != k and j not in gone] + D
        free = complement(cube_cofactor(others, c), n)  # @line L15: points of c no other cube covers
        if not free:
            gone.add(k)  # @line L16
            continue
        F[k] = intersect(c, supercube(free))  # @line L17
    return [F[k] for k in range(len(F)) if k not in gone]


# --------------------------------------------------------------------- loop


def espresso(n: int, F: Cover, D: Cover = ()) -> Cover:
    """A prime and irredundant cover G with F <= G <= F + D, by the Espresso loop."""
    F, D = list(F), list(D)
    if not F:
        return []
    R = complement(F + D, n)  # @line L1: the off-set
    F = expand(F, R)  # @line L2
    F = irredundant(F, D)  # @line L3
    while True:
        before = cost(F)  # @line L4
        G = reduce(F, D, n)  # @line L5
        G = expand(G, R)  # @line L6
        G = irredundant(G, D)
        if cost(G) >= before:  # @line L7: stop when the cost does not fall
            return sorted(F)
        F = G
test_espresso.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/espresso/. The authors are listed in prov/70F55E.jsonl.

import itertools
import random

from espresso import complement, cost, covered, espresso, expand, irredundant, reduce, tautology


def cells(c: str) -> set[int]:
    n = len(c)
    return {m for m in range(2 ** n) if all(ch == "-" or int(ch) == (m >> (n - 1 - i)) & 1 for i, ch in enumerate(c))}


def points(cover: list[str], n: int) -> set[int]:
    out: set[int] = set()
    for c in cover:
        out |= cells(c)
    return out


def minterms(n: int, ms: set[int]) -> list[str]:
    return [format(m, "b").zfill(n) for m in sorted(ms)]


def brute_min_cost(n: int, on: set[int], dc: set[int]) -> tuple[int, int]:
    if not on:
        return (0, 0)
    allowed = on | dc
    imps = [c for c in ("".join(t) for t in itertools.product("01-", repeat=n)) if cells(c) <= allowed]
    primes = [c for c in imps if not any(cells(c) < cells(d) for d in imps)]
    masks = [sum(1 << m for m in cells(p)) for p in primes]
    lits = [sum(ch != "-" for ch in p) for p in primes]
    target = sum(1 << m for m in on)
    for k in range(1, len(primes) + 1):
        best = None
        for s in itertools.combinations(range(len(primes)), k):
            got = 0
            for j in s:
                got |= masks[j]
            if got & target == target:
                t = sum(lits[j] for j in s)
                best = t if best is None or t < best else best
        if best is not None:
            return (k, best)
    raise AssertionError("no cover")


def check(n: int, on: set[int], dc: set[int], G: list[str]) -> None:
    """G is correct on the care set, every cube is prime, and no cube is redundant."""
    allowed = on | dc
    assert on <= points(G, n) <= allowed
    for c in G:
        for i, ch in enumerate(c):
            if ch != "-":
                assert not cells(c[:i] + "-" + c[i + 1:]) <= allowed, (G, c)
        rest = [e for e in G if e != c]
        assert not (cells(c) & on) <= points(rest, n), (G, c)


def test_bcd_digit_at_least_five() -> None:
    # Inputs a b c d hold a BCD digit; codes 10 to 15 never occur.
    on, dc = {5, 6, 7, 8, 9}, set(range(10, 16))
    G = espresso(4, minterms(4, on), minterms(4, dc))
    assert sorted(G) == ["-1-1", "-11-", "1---"]
    assert cost(G) == (3, 5)


def test_cyclic_function() -> None:
    on = {0, 1, 2, 5, 6, 7}
    G = espresso(3, minterms(3, on))
    check(3, on, set(), G)
    assert len(G) in (3, 4)


def test_steps() -> None:
    F = ["000", "001", "011"]
    R = complement(F, 3)
    assert points(R, 3) == {2, 4, 5, 6, 7}
    E = expand(F, R)
    assert sorted(E) == ["0-1", "00-"]
    assert irredundant(["00-", "0-1", "001"], []) == ["00-", "0-1"]
    # The first cube in the order shrinks to its own part; the second keeps 001 then.
    assert sorted(reduce(["00-", "0-1"], [], 3)) == ["0-1", "000"]


def test_tautology_and_containment() -> None:
    assert tautology(["1-", "0-"], 2)
    assert not tautology(["1-", "-1"], 2)
    assert covered(["1-", "-1"], "11")
    assert not covered(["1-", "-1"], "0-")


def test_edges() -> None:
    assert espresso(3, []) == []
    assert espresso(3, minterms(3, set(range(8)))) == ["---"]
    assert espresso(2, ["00"], ["01", "10", "11"]) == ["--"]
    odd = {m for m in range(16) if bin(m).count("1") % 2}
    assert cost(espresso(4, minterms(4, odd))) == (8, 32)


def test_all_three_variable_functions() -> None:
    for bits in range(2 ** 8):
        on = {m for m in range(8) if bits >> m & 1}
        G = espresso(3, minterms(3, on))
        check(3, on, set(), G)
        assert cost(G) >= brute_min_cost(3, on, set())


def test_random_with_dont_cares() -> None:
    rng = random.Random(41)
    for n, trials in ((3, 150), (4, 60), (5, 25)):
        for _ in range(trials):
            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}
            G = espresso(n, minterms(n, on), minterms(n, dc))
            check(n, on, dc, G)
            if n <= 4:
                assert cost(G) >= brute_min_cost(n, on, dc)


def test_input_given_as_cubes() -> None:
    # The same function given as a cover of overlapping cubes gives a correct answer.
    F = ["1-0-", "11--", "-1-1", "0101"]
    G = espresso(4, F)
    assert points(G, 4) == points(F, 4)
    check(4, points(F, 4), set(), G)

History

Brayton, Hachtel, McMullen and Sangiovanni-Vincentelli described Espresso-II in their 1984 book, from work at IBM and at the University of California, Berkeley. The book takes ideas from earlier heuristic minimizers, compares Espresso with MINI, POP and PRESTO, and builds all its operators on the unate recursive paradigm. Rudell and Sangiovanni-Vincentelli (1987) gave Espresso-MV for multiple-valued variables. The Berkeley program espresso became the standard two-level minimizer and is still used as a step of multi-level synthesis.

References

  1. Robert K. Brayton, Gary D. Hachtel, Curtis T. McMullen and Alberto L. Sangiovanni-Vincentelli, Logic Minimization Algorithms for VLSI Synthesis, Kluwer, 1984, Chapter 4 (Sections 4.1 Complementation, 4.2 Tautology and 4.3 Expand, and the later sections on the other steps of the loop), Chapter 6 (experimental results on a set of test PLAs) and Chapter 7 (comparisons with MINI, POP and PRESTO)
  2. Richard L. Rudell and Alberto L. Sangiovanni-Vincentelli, Multiple-valued minimization for PLA optimization, IEEE Transactions on Computer-Aided Design 6(5), 1987, Espresso-MV, the loop for multiple-valued variables
  3. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 7, Two-Level Combinational Logic Optimization (heuristic minimization, the expand, reduce and irredundant operators)
  4. Gary D. Hachtel and Fabio Somenzi, Logic Synthesis and Verification Algorithms, Kluwer, 1996, Chapter 5, Heuristic Minimization of Two-Level Circuits
  5. Olivier Coudert, Two-level logic minimization, an overview, Integration, the VLSI Journal 17(2), 97 to 140, 1994, heuristic minimization and the place of Espresso among the exact and heuristic methods

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example