Algorithm Search⌘K

Techniqueintro

Karnaugh map

Also called K-map, Veitch diagram.

A grid of the truth table in Gray code order so that adjacent cells differ in one variable, which lets a person read prime implicants as rectangles.

A Karnaugh map draws the truth table of a Boolean function of two to four variables as a grid, with the rows and the columns in Gray code order. In this order, two cells next to each other differ in one variable, also across the edges of the grid, which wrap around. A rectangle of cells with sides 1, 2 or 4 is then exactly the set of points of one cube, so a person can see the implicants of the function as rectangles of 1 cells and the prime implicants as the largest such rectangles. Reading a cover from the map means choosing a few large rectangles that together hold every 1. Cells marked as don't-cares can join a rectangle but need not be covered. Karnaugh (1953) refined the chart of Veitch (1952). The map is a hand method for small functions, and its reading of the cover is not always minimum.

In plain words

Write the outputs of a small function in a square grid. Put the inputs along the sides in a special order, where each step changes one bit, so that cells that touch differ in one input. The left edge also touches the right edge, and the top touches the bottom.

Now draw boxes around the 1s. A box must be a block of 1, 2, 4 or 8 cells, and it can hold cells marked "do not care". Make each box as large as you can. Each box is one AND term, and the inputs that stay the same inside the box are its letters. A bigger box has fewer letters. Pick boxes until every 1 is inside one, and use as few boxes as you can.

When it applies

  • The function has two to four variables. For five or six variables, two or four maps of four variables are laid side by side, and the extra adjacency between maps is hard to see. Beyond six, the map is not used.
  • The goal is a sum of products of few cubes and literals, or a product of sums, which is the same task for the 0 cells.
  • A person does the work, or a program needs a picture of the function for teaching. A program that minimizes should use Quine-McCluskey or Espresso.

The template

The variables are x1,…,xnx_1, \ldots, x_n, and x1x_1 is the high bit of a minterm. For n=4n = 4 the rows are x1x2x_1 x_2 and the columns are x3x4x_3 x_4, both in the order 00, 01, 11, 10. For n=3n = 3 the rows are x1x_1 and the columns are x2x3x_2 x_3. A group is a rectangle of the map, with wrap-around, whose sides are 1, 2 or 4 cells.

  1. READ-MAP(n, on, dc)
  2. 1big ← GROUPS(n, on, dc)
  3. GROUPS:
  4. 2ok ← every group whose cells are all 1 or x
  5. 3return the groups of ok that lie in no larger group of ok and hold a 1
  6. 4for each 1 cell m that lies in exactly one group of big do
  7. 5choose that group ▷ an essential group
  8. 6while some 1 cell is not in a chosen group do
  9. 7choose the group of big with the most uncovered 1 cells, then the larger one
  10. 8mark its cells as covered
  11. return the cube of each chosen group: fix each variable that is constant on the group

Why a group is a cube. An axis of length 4 in Gray order is 00, 01, 11, 10. Its runs of length 2 with wrap-around are 00 01, 01 11, 11 10 and 10 00, and each one fixes one bit and frees the other. The run of length 4 frees both bits. So a run of length 2k2^k on an axis frees kk variables and fixes the rest, and a rectangle of two runs is a cube. Conversely, each cube is the product of one run on each axis. So the groups are exactly the 3n3^n cubes, and line L2 lists the implicants of the function with its don't-cares.

Why the large groups are the primes. A group contains another group exactly when the cube contains the cube. So a group of ok that lies in no larger group of ok is a prime implicant of the function with its don't-cares, and line L3 keeps those that hold at least one 1. A prime made of don't-cares only is not useful in a cover, and line L3 drops it.

Why the essential groups are safe. If a 1 cell lies in one prime only, every cover by primes must take that prime. Lines L4 and L5 take it. By Quine's theorem, some minimum cover is made of primes, so this choice keeps a minimum cover in reach.

Why the last step is a heuristic. After the essential groups, the rest is a set cover problem on the groups of big. Line L7 picks greedily, and the greedy choice can take one group too many. An exact reading must solve this step with Petrick's method or a search.

Cost. A map of 2n2^n cells has 3n3^n groups. For n≤4n \le 4, there are at most 81 groups and 16 cells, so the work is small. The steps of lines L4 to L8 take time polynomial in the number of groups.

Example. Take f=∑m(0,2,8,10)+d(5)f = \sum m(0, 2, 8, 10) + d(5) on four variables. The map, with rows x1x2x_1 x_2 and columns x3x4x_3 x_4, is

x1x2\x3x4x_1 x_2 \backslash x_3 x_4 00 01 11 10
00 1 0 0 1
01 0 x 0 0
11 0 0 0 0
10 1 0 0 1

The four 1s are the four corners. The top row and the bottom row are neighbors across the edge, and so are the left and the right columns, so the corners form one group of four cells. It fixes x2=0x_2 = 0 and x4=0x_4 = 0, and the cover is the single cube xˉ2xˉ4\bar{x}_2 \bar{x}_4, the cube -0-0. The don't-care at minterm 5 lies in no group with a 1, so it stays out.

Classic examples

  • Corners and edges. The example above: the wrap-around joins cells that look far apart. Missing the corner group gives two or four cubes in place of one.
  • Seven-segment decoder. Each segment of a BCD to seven-segment decoder is a function of four inputs, where the codes 10 to 15 never occur and are don't-cares. With them, the groups grow, as in ∑m(5,6,7,8,9)+d(10,…,15)\sum m(5, 6, 7, 8, 9) + d(10, \ldots, 15), which becomes x1+x2x4+x2x3x_1 + x_2 x_4 + x_2 x_3.
  • The checkerboard. Parity on four variables has 1 cells where no two touch. Every group has one cell, and the cover needs 8 cubes of 4 literals each, which matches the bound on the sum of products page.
  • A cyclic map. ∑m(1,2,3,4,5,6)\sum m(1, 2, 3, 4, 5, 6) on three variables has six primes and no essential one. The reader must choose, and two of the choices give three cubes, the minimum. This is the cyclic core that Petrick's method solves.
  • Teaching Quine-McCluskey. The prime implicants that Quine-McCluskey lists are the largest groups of the map, and the prime implicant table is the question of which groups to keep.

Variations

  • Product of sums. Group the 0 cells in place of the 1 cells. Each group gives a sum term of the complement, and the product of these sums is a product of sums form of ff.
  • Five and six variables. Use two or four maps of four variables for the values of x1x_1, or of x1x2x_1 x_2. Cells in the same place of neighbor maps are adjacent, so a group can span several maps.
  • Map-entered variables. Write a variable or a small expression in a cell in place of 0 or 1. This folds one more variable into a smaller map, at the cost of a harder reading.
  • Multiple outputs. Draw one map for each output and look for groups that several outputs can share.
  • Hazard covers. For a circuit without static hazards, add a group for every pair of adjacent 1 cells that no single chosen group holds. The cover is then not minimum, but each single input change keeps one cube at 1.

Pitfalls

  • Binary order. If the axis is in the order 00, 01, 10, 11, the cells for 01 and 10 sit side by side but differ in two bits. A group across them, as a reading by line L2 would allow, is not a cube.
  • Groups that are not powers of two. A block of 3 or 6 cells is not a cube. Line L2 allows sides of 1, 2 or 4 only.
  • Forgetting the wrap-around. The edges of the map touch. The corner group of the example and the groups across the left and right edges are easy to miss.
  • Covering the don't-cares. A don't-care can join a group, but it never needs a group of its own. A group of don't-cares only adds a cube for nothing, which line L3 avoids.
  • Trusting the greedy step. Line L7 can take more groups than needed when no group is essential. For ∑m(1,2,4,5,6,8,9,10)\sum m(1, 2, 4, 5, 6, 8, 9, 10) on four variables, all eight groups hold two 1s and no 1 cell is in one group only. The greedy reading takes 5 cubes, but 4 cubes, xˉ2xˉ3x4+xˉ1x3xˉ4+xˉ1x2xˉ3+x1xˉ2xˉ4\bar{x}_2 \bar{x}_3 x_4 + \bar{x}_1 x_3 \bar{x}_4 + \bar{x}_1 x_2 \bar{x}_3 + x_1 \bar{x}_2 \bar{x}_4, cover the function. In our own test of all functions without don't-cares, the reading of the template was a minimum cover for all 256 functions of three variables and missed the minimum for 596 of the 65536 functions of four variables, about 0.9 percent. These counts are measured for this greedy rule only, not for all ways a person can read a map.

Code

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.

karnaugh_map.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/karnaugh-map/. The authors are listed in prov/KAW0FH.jsonl.

"""Karnaugh maps for two to four variables.

The variables are x1..xn, and x1 is the high bit of a minterm. For
n = 2 the rows are x1 and the columns x2; for n = 3 the rows are x1 and
the columns x2 x3; for n = 4 the rows are x1 x2 and the columns x3 x4.
Each axis is in Gray code order, so cells next to each other (with
wrap-around) differ in one variable. A cube is a string over '0', '1'
and '-'.
"""

from typing import Iterable

GRAY = {1: ["0", "1"], 2: ["00", "01", "11", "10"]}


def split(n: int) -> tuple[int, int]:
    """The number of row variables and of column variables."""
    if n not in (2, 3, 4):
        raise ValueError("this map handles 2 to 4 variables")
    return (1, 1) if n == 2 else (1, 2) if n == 3 else (2, 2)


def cell(n: int, r: int, c: int) -> int:
    """The minterm in row r and column c."""
    a, b = split(n)
    return int(GRAY[a][r] + GRAY[b][c], 2)


def grid(n: int, on: Iterable[int], dc: Iterable[int] = ()) -> list[str]:
    """The map as text rows of '1', '0' and 'x' (don't care)."""
    on, dc = set(on), set(dc)
    a, b = split(n)
    out = []
    for r in range(2 ** a):
        row = ""
        for c in range(2 ** b):
            m = cell(n, r, c)
            row += "1" if m in on else "x" if m in dc else "0"
        out.append(row)
    return out


def intervals(size: int) -> list[list[int]]:
    """The cyclic runs of length 1, 2, 4, ... on an axis of the given size."""
    out = []
    length = 1
    while length < size:
        out += [[(s + t) % size for t in range(length)] for s in range(size)]
        length *= 2
    out.append(list(range(size)))
    return out


def rectangles(n: int) -> list[frozenset[int]]:
    """Every rectangle of the map with sides 1, 2 or 4 cells, with wrap-around, as a set of minterms."""
    a, b = split(n)
    return [frozenset(cell(n, r, c) for r in rs for c in cs) for rs in intervals(2 ** a) for cs in intervals(2 ** b)]


def cube_of(n: int, cells: frozenset[int]) -> str:
    """The cube of a rectangle: a variable is fixed where every cell agrees."""
    out = ""
    for i in range(n):
        bits = {(m >> (n - 1 - i)) & 1 for m in cells}
        out += str(bits.pop()) if len(bits) == 1 else "-"
    return out


def groups(n: int, on: Iterable[int], dc: Iterable[int] = ()) -> list[frozenset[int]]:
    """The largest groups: rectangles inside on | dc, in no larger such rectangle, with a 1 cell."""
    on, dc = set(on), set(dc)
    ok = [g for g in set(rectangles(n)) if g <= on | dc]  # @line L2: legal groups
    big = [g for g in ok if not any(g < h for h in ok)]  # @line L3: keep the maximal ones
    return sorted((g for g in big if g & on), key=lambda g: (-len(g), sorted(g)))


def read_cover(n: int, on: Iterable[int], dc: Iterable[int] = ()) -> list[str]:
    """The cover a person reads from the map: essential groups first, then the largest useful group."""
    on, dc = set(on), set(dc)
    big = groups(n, on, dc)  # @line L1
    chosen: list[frozenset[int]] = []
    for m in sorted(on):  # @line L4: a 1 cell in exactly one largest group
        holders = [g for g in big if m in g]
        if len(holders) == 1 and holders[0] not in chosen:
            chosen.append(holders[0])  # @line L5
    left = on - set().union(*chosen) if chosen else set(on)
    while left:  # @line L6
        g = max(big, key=lambda g: (len(g & left), len(g), [-x for x in sorted(g)]))  # @line L7
        chosen.append(g)
        left -= g  # @line L8
    return sorted(cube_of(n, g) for g in chosen)
test_karnaugh_map.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/karnaugh-map/. The authors are listed in prov/KAW0FH.jsonl.

import itertools
import random

from karnaugh_map import cell, cube_of, grid, groups, read_cover, rectangles


def cube_cells(c: str) -> frozenset[int]:
    n = len(c)
    return frozenset(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 all_cubes(n: int) -> list[str]:
    return ["".join(t) for t in itertools.product("01-", repeat=n)]


def brute_primes(n: int, on: set[int], dc: set[int]) -> set[frozenset[int]]:
    imps = [cube_cells(c) for c in all_cubes(n) if cube_cells(c) <= on | dc]
    return {g for g in imps if not any(g < h for h in imps) and g & on}


def brute_min_cost(n: int, on: set[int], dc: set[int]) -> tuple[int, int]:
    primes = sorted(brute_primes(n, on, dc), key=sorted)
    lits = [sum(ch != "-" for ch in cube_of(n, g)) for g in primes]
    for k in range(len(primes) + 1):
        costs = [sum(lits[j] for j in s) for s in itertools.combinations(range(len(primes)), k)
                 if on <= set().union(*(primes[j] for j in s))]
        if costs:
            return (k, min(costs))
    raise AssertionError("no cover")


def cost(cover: list[str]) -> tuple[int, int]:
    return len(cover), sum(ch != "-" for c in cover for ch in c)


def test_layout_is_gray() -> None:
    for n in (2, 3, 4):
        rows, cols = (2, 2) if n == 2 else (2, 4) if n == 3 else (4, 4)
        seen = {cell(n, r, c) for r in range(rows) for c in range(cols)}
        assert seen == set(range(2 ** n))
        for r in range(rows):
            for c in range(cols):
                for r2, c2 in (((r + 1) % rows, c), (r, (c + 1) % cols)):
                    if (r2, c2) != (r, c):
                        assert bin(cell(n, r, c) ^ cell(n, r2, c2)).count("1") == 1


def test_grid_text() -> None:
    assert grid(4, {0, 2, 8, 10}, {5}) == ["1001", "0x00", "0000", "1001"]


def test_rectangles_are_the_cubes() -> None:
    for n in (2, 3, 4):
        rects = rectangles(n)
        assert len(set(rects)) == 3 ** n
        assert {cube_of(n, g) for g in rects} == set(all_cubes(n))
        for g in rects:
            assert cube_cells(cube_of(n, g)) == g


def test_corners_are_one_group() -> None:
    # The four corners of a 4-variable map form x2' x4'.
    assert read_cover(4, {0, 2, 8, 10}) == ["-0-0"]


def test_groups_are_the_primes() -> None:
    rng = random.Random(31)
    for n in (2, 3, 4):
        for _ in range(150):
            on = {m for m in range(2 ** n) if rng.random() < 0.45}
            dc = {m for m in range(2 ** n) if m not in on and rng.random() < 0.2}
            assert set(groups(n, on, dc)) == brute_primes(n, on, dc)


def test_reading_is_a_valid_cover() -> None:
    rng = random.Random(32)
    for n in (2, 3, 4):
        for _ in range(150):
            on = {m for m in range(2 ** n) if rng.random() < 0.45}
            dc = {m for m in range(2 ** n) if m not in on and rng.random() < 0.2}
            cover = read_cover(n, on, dc)
            got = set().union(*(cube_cells(c) for c in cover)) if cover else set()
            assert on <= got <= on | dc
            assert cost(cover) >= brute_min_cost(n, on, dc)


def test_reading_is_minimum_on_all_three_variable_functions() -> None:
    # On three variables the reading is minimum for every function; on four it can fail.
    for bits in range(2 ** 8):
        on = {m for m in range(8) if bits >> m & 1}
        assert cost(read_cover(3, on)) == brute_min_cost(3, on, set())

Exercises

  1. Show that a rectangle of a four-variable map with wrap-around is a cube if and only if each of its sides has 1, 2 or 4 cells.
  2. Draw the map of ∑m(0,1,2,5,6,7)\sum m(0, 1, 2, 5, 6, 7) on three variables, list its primes, and find both minimum covers.
  3. Find the minimum sum of products of ∑m(0,2,3,4,5,7)+d(1,6)\sum m(0, 2, 3, 4, 5, 7) + d(1, 6) on three variables, and say which don't-cares the cover uses.
  4. Read a minimum product of sums of ∑m(1,3,5,7,9,11,12,13)\sum m(1, 3, 5, 7, 9, 11, 12, 13) on four variables from its 0 cells.
  5. Prove that the number of groups of an nn-variable map is 3n3^n.

References

  1. M. Karnaugh, The map method for synthesis of combinational logic circuits, Transactions of the AIEE, Part I, 72(5), 593 to 599, 1953, the map with its rows and columns in reflected binary order, and the reading of products as groups of adjacent cells
  2. E. W. Veitch, A chart method for simplifying truth functions, Proceedings of the 1952 ACM national meeting (Pittsburgh), 127 to 133, 1952, the earlier chart of the truth table that the map refines
  3. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 7, Two-Level Combinational Logic Optimization (the map view of implicants and primes)
  4. Gary D. Hachtel and Fabio Somenzi, Logic Synthesis and Verification Algorithms, Kluwer, 1996, Chapter 4, Synthesis of Two-Level Circuits (maps as a picture of the Boolean cube)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises