Algorithm Search⌘K

Algorithmadvanced

KISS symbolic minimization

Also called KISS state assignment, symbolic minimization of FSMs.

De Micheli, Brayton and Sangiovanni-Vincentelli's method that minimizes the FSM table with symbolic states, then encodes states to satisfy the face constraints it yields.

Time
O(T + C n 2^(k n)) worst
Space
O(n C + 2^k) extra
Where
C = the number of face constraints; T = the time of the symbolic two-level minimization; k = the code length that is returned; n = the number of states
Properties
deterministicnot exactofflineiterative
Origin
Giovanni De Micheli, Robert K. Brayton, Alberto L. Sangiovanni Vincentelli, 1985

KISS is a method of state assignment for finite state machines whose logic is built as a two-level sum of products, such as a PLA. Its idea is to minimize the logic before the codes exist. The present state is treated as one multiple-valued variable, and the state table is minimized as a multiple-valued function. Each product term of the result covers a group of present states, and if every such group occupies a face of the code cube that holds no other state's code, then the encoded logic needs no more product terms than the symbolic cover. KISS then looks for short codes that meet these face constraints. De Micheli, Brayton and Sangiovanni-Vincentelli published it in 1985. This page proves the bound and shows by exhaustive search that it is only a bound: the codes that KISS returns are not the best codes for the final logic, and on the example of this page the best two-bit code breaks the only face constraint.

In plain words

A controller has a table: in this state, on this input, go to that state and set these outputs. Before choosing bit patterns for the states, KISS simplifies the table with the state names left as names, merging rows where it can: "in state A or state B, on any input, go to C". After that, it chooses bit patterns so that every merged group of states can be named by one pattern with some bits left free, such as "first bit 0", without also naming a state outside the group. Then every merged row of the table becomes one row of the circuit. The catch is that a smaller circuit may exist with codes that break this rule.

The problem

The input is a deterministic finite state machine, given as a table of rows (input cube, present state, next state, outputs), as on the state assignment page. Entries that no row specifies are don't cares. The machine should first be reduced by DFA minimization, or by incompletely specified FSM minimization when it has don't cares. The output is an injective code of kk bits for the nn states. The quantity that matters is the number of product terms, and then of literals, in a minimum two-level cover of the encoded next-state and output functions, where unused codes are don't cares. KISS does not minimize this quantity; it minimizes a bound on it.

Symbolic function. Its variables are the input bits and one variable SS with the nn states as values. Its outputs are one output per state (the next state, one-hot) and the primary outputs. A cube has a set of values for SS, called its group.

Face constraint. For codes enc\mathrm{enc} of kk bits and a group GG, the face of GG is the smallest subcube of {0,1}k\{0, 1\}^k that holds enc(s)\mathrm{enc}(s) for every s∈Gs \in G. The codes meet the face constraint of GG when this face holds no code enc(t)\mathrm{enc}(t) with t∉Gt \notin G.

The algorithm

  1. KISS(M)
  2. 1build the symbolic function of M: the inputs and S as variables, the next state one-hot and the outputs as outputs
  3. 2S_cover ← a minimum multiple-valued cover of it (ESPRESSO-MV in the original, exact here)
  4. 3F ← the groups of the cubes of S_cover with more than one state and fewer than n
  5. 4k ← ⌈log2 n⌉
  6. 5while no injective code of k bits meets every face constraint in F do k ← k + 1
  7. 6enc ← an injective code of k bits that meets every face constraint in F
  8. 7for each cube of S_cover, emit the encoded cube: its input part; the face of its group; as outputs, the next state bits that are 1 in the code of the state it asserts, and the outputs it asserts
  9. 8return enc and the encoded cover, which a two-level minimizer such as Espresso may shrink further

Line L2 is a two-level minimization in the sense of Espresso, run on a function with one multiple-valued input. Line L5 is the face embedding problem. The original KISS solves it with a heuristic that may make kk longer than needed; the reference code here searches all codes of each length by backtracking, so it returns the least kk that meets every constraint, and among those codes the first one in its search order. This exact search fits only small machines. Groups of size 1 and nn give no constraint, since a single code is a face and the whole cube is one.

Example

Take the machine M1M_1 with one input xx, one output zz and four states:

present x=0x = 0 x=1x = 1
s0s_0 s2s_2 / 1 s2s_2 / 0
s1s_1 s2s_2 / 0 s2s_2 / 1
s2s_2 s3s_3 / 0 s1s_1 / 1
s3s_3 s1s_1 / 1 s3s_3 / 0

A minimum symbolic cover has 7 cubes, written as input, group, next state, output:

cube xx group next zz
1 - {s0,s1}\{s_0, s_1\} s2s_2
2 0 {s3}\{s_3\} s1s_1 1
3 1 {s2}\{s_2\} s1s_1 1
4 0 {s2}\{s_2\} s3s_3
5 1 {s3}\{s_3\} s3s_3
6 0 {s0}\{s_0\} s2s_2 1
7 1 {s1}\{s_1\} s2s_2 1

The only face constraint is {s0,s1}\{s_0, s_1\}. Two bits suffice, and the search returns s0=00s_0 = 00, s1=01s_1 = 01, s2=10s_2 = 10, s3=11s_3 = 11, where {s0,s1}\{s_0, s_1\} is the face 0−0{-}. Line L7 turns the 7 symbolic cubes into 7 encoded cubes; cube 1 becomes "x=−x = -, state 0−0{-}, set the high next-state bit". By the theorem below this cover is correct, and an exact two-level minimization of the encoded function under these codes finds nothing smaller: 7 cubes and 19 literals.

Now search every code. Four states in two bits have 24 injective codes, which fall into 12 classes up to swapping the two bits, and the cost is the same within a class. An exact minimization of each class gives:

  • The best class has 4 cubes and 8 literals, with s0=01s_0 = 01, s1=10s_1 = 10, s2=11s_2 = 11, s3=00s_3 = 00. Its cover is xˉqˉ1\bar x \bar q_1, xq1x q_1 (which set the high bit and zz) and qˉ1q0\bar q_1 q_0, q1qˉ0q_1 \bar q_0 (which set both bits), where q1q0q_1 q_0 is the code. These codes break the face constraint: the face of 0101 and 1010 is the whole square.
  • The 8 classes that meet the constraint cost between 5 cubes (9 literals) and 7 cubes (19 literals). The codes that KISS returned are the worst of them.
  • With three bits, the best code needs 3 cubes and 6 literals.

So meeting the face constraints is not needed for small logic, and among the codes that meet them the cost still varies from 5 to 7 cubes. The KISS bound says only that the result is at most 7.

Correctness

The full proof shows:

  • The construction is correct. If enc\mathrm{enc} meets every face constraint of the symbolic cover, the encoded cubes of line L7 implement the machine: at every specified pair of input and state they give the code of the next state and the specified outputs.
  • The bound. Hence the encoded function has a two-level cover with at most as many cubes as the symbolic cover. Cubes whose output part is empty are dropped, so it can be smaller.
  • Termination. Line L5 stops with k≤nk \le n, since the one-hot code of nn bits meets every face constraint.

What is not proved, and is false: that the codes minimize the cubes or literals of the final logic. The example has a code with 4 cubes where KISS gives 7. As a measurement, 100 random machines with 4 states, one input bit, one output bit and every entry specified (seed 1985) were encoded by the reference code and minimized exactly. Of these, 32 needed 3 or more bits to meet all face constraints. On the 99 machines with k≤3k \le 3, the final logic matched the best code of the same length on 41, with 70 extra cubes in total and at most 3 on one machine. These numbers describe this small random sample only.

Proof: Correctness of the KISS constructionfull

We use the notation of the page. The machine has inputs x∈{0,1}mx \in \{0, 1\}^m, states s1,…,sns_1, \ldots, s_n, and a partial function that gives, for some pairs (x,s)(x, s), a next state δ(x,s)\delta(x, s) and an output vector whose entries are 0, 1 or don't care. The symbolic function has the variables xx and SS, and the outputs NtN_t for each state tt and ZjZ_j for each primary output. At a specified pair (x,s)(x, s), NtN_t is 1 if t=δ(x,s)t = \delta(x, s) and 0 otherwise, and ZjZ_j is the specified output or don't care. At an unspecified pair every output is don't care.

A cube cc of the symbolic cover has an input part IcI_c, a group GcG_c of states, and a set of asserted outputs. It contains (x,s)(x, s) when x∈Icx \in I_c and s∈Gcs \in G_c. The cover is correct: at every point and for every output, the output is 1 where the function is 1 and 0 where it is 0, where the value of the cover at a point is 1 if some cube that contains the point asserts the output.

Lemma 1 (what one encoded point sees)

Let enc\mathrm{enc} be injective and meet the face constraint of every group of the cover. For a symbolic cube cc, let c^\hat c be its encoded cube: input part IcI_c and state part face(Gc)\mathrm{face}(G_c). Then for every input xx and state ss, c^\hat c contains (x,enc(s))(x, \mathrm{enc}(s)) if and only if cc contains (x,s)(x, s).

Proof. The input parts are equal, so it is enough to show that enc(s)∈face(Gc)\mathrm{enc}(s) \in \mathrm{face}(G_c) exactly when s∈Gcs \in G_c. If s∈Gcs \in G_c, then enc(s)\mathrm{enc}(s) is in the face by its definition. Conversely, suppose enc(s)\mathrm{enc}(s) is in the face. If 1<∣Gc∣<n1 < |G_c| < n, the face constraint of GcG_c says that the face holds no code of a state outside GcG_c, so s∈Gcs \in G_c. If ∣Gc∣=n|G_c| = n, every state is in GcG_c. If Gc={t}G_c = \{t\}, the face is the single point enc(t)\mathrm{enc}(t), so enc(s)=enc(t)\mathrm{enc}(s) = \mathrm{enc}(t), and s=ts = t since enc\mathrm{enc} is injective. □\square

Theorem (the KISS bound)

Under the same assumption, the encoded cubes of line L7, with the cubes whose output part is empty removed, form a correct two-level cover of the encoded function. So the encoded function has a cover with at most as many cubes as the symbolic cover.

Proof. Recall that line L7 gives c^\hat c the next-state bits bb with enc(t)b=1\mathrm{enc}(t)_b = 1 for each state tt that cc asserts, and the primary outputs that cc asserts. Points of the encoded function are (x,y)(x, y) with y∈{0,1}ky \in \{0, 1\}^k. If yy is not a code, or (x,y)=(x,enc(s))(x, y) = (x, \mathrm{enc}(s)) with (x,s)(x, s) unspecified, every output is don't care there and nothing needs checking.

Take a specified pair (x,s)(x, s) with t=δ(x,s)t = \delta(x, s), and let AA be the set of symbolic cubes that contain (x,s)(x, s). By Lemma 1, the encoded cubes that contain (x,enc(s))(x, \mathrm{enc}(s)) are exactly c^\hat c for c∈Ac \in A.

Next-state bits. The symbolic cover is correct, so Nt=1N_t = 1 at (x,s)(x, s) forces some c∈Ac \in A to assert NtN_t, and Nu=0N_u = 0 for u≠tu \ne t forces no c∈Ac \in A to assert NuN_u. So every cube of AA asserts either NtN_t alone among the next-state outputs or none of them. The bits that the cubes c^\hat c, c∈Ac \in A, set are therefore exactly the 1 bits of enc(t)\mathrm{enc}(t), since at least one of them asserts tt. The value of next-state bit bb at (x,enc(s))(x, \mathrm{enc}(s)) is enc(t)b\mathrm{enc}(t)_b.

Primary outputs. c^\hat c asserts ZjZ_j exactly when cc does. So the value of ZjZ_j in the encoded cover at (x,enc(s))(x, \mathrm{enc}(s)) equals its value in the symbolic cover at (x,s)(x, s), which is correct.

Removing a cube that asserts nothing does not change any value. So the cover is correct, and it has at most one cube per symbolic cube. ■\blacksquare

Lemma 2 (termination of line L5)

The one-hot code enc(si)=ei\mathrm{enc}(s_i) = e_i of nn bits meets every face constraint. So line L5 stops with k≤nk \le n.

Proof. The codes eie_i, i∈Gi \in G, agree on every bit outside GG, where they are 0, and differ on each bit of GG when ∣G∣≥2|G| \ge 2. So the face of GG is the set of vectors that are 0 outside GG. A code eje_j with j∉Gj \notin G has a 1 at bit jj, outside GG, so it is not in the face. □\square

The search of line L5 tries every injective code of each length, so it finds a code that meets every constraint at the least such length, and line L6 returns one.

What is not proved

Nothing here says that the codes of line L6 make the final logic small. The theorem is an upper bound, and it holds for every code that meets the constraints. Codes that meet them can differ in cost, and codes that break them can be cheaper; the page gives a machine with both effects, found by exhaustive search over all codes of two bits.

Complexity

The symbolic minimization of line L2 is a two-level minimization, which is hard in general; Espresso-MV runs it as a heuristic, and the reference code runs an exact search that fits only tiny machines. Line L5 tries all injective placements of the nn states on the 2k2^k codes in the worst case, at most 2kn2^{k n} of them for each length, checking CC constraints of up to nn states at each step, which gives the O(Cn2kn)O(C n 2^{k n}) term. Line L7 takes O(kn)O(k n) time per cube. The KISS paper uses a polynomial heuristic for line L5 instead, at the price of codes longer than needed.

Properties

  • A proved bound. The number of product terms is at most the size of the symbolic cover, whatever code meets the constraints.
  • Not optimal. Neither the codes nor the code length minimize the final logic. None of KISS, NOVA and MUSTANG is optimal for the final logic: on the example machines of the three pages, an exhaustive search over all codes finds cheaper logic than each of them gives.
  • Code length can grow. Meeting every constraint may need more than ⌈log⁡2n⌉\lceil \log_2 n \rceil bits, and so more flip-flops.
  • Input constraints only. The face constraints come from the present state. The next state is treated as nn separate outputs, and the sharing of next-state bits between cubes is not used.
  • Deterministic. The reference code always returns the same codes.

Variants and improvements

  • NOVA. Villa and Sangiovanni-Vincentelli (1990) fix kk at the least length and meet as many weighted face constraints as they can; see NOVA.
  • Output constraints. Later work on symbolic minimization, described in De Micheli's book (Chapter 9), also extracts constraints from the next-state field, such as dominance constraints between codes, so that cubes can share next-state bits.
  • Multilevel targets. For multilevel logic, MUSTANG chooses codes from attraction weights instead of face constraints.
  • Exact embedding. For small machines the embedding of line L5 can be solved exactly, as in the reference code, which gives the least kk that meets every constraint.

When to use it

Use KISS when the controller is built as a PLA or another two-level form and a guaranteed bound on the number of product terms is wanted. Treat its codes as a good start, not as the best: for small machines, an exhaustive or exact search over codes, as in the example, can find much smaller logic. When the number of flip-flops is fixed, use NOVA, which never makes the code longer.

Pitfalls

  • Reading the title as a promise. The 1985 paper is titled "Optimal state assignment", but the method minimizes the symbolic cover, which only bounds the logic.
  • Unreduced machines. Equivalent states give redundant groups and constraints. Minimize the states first.
  • Long codes. A small machine can need many bits to meet all its face constraints, as the measurements show for a third of random 4-state machines. Each extra bit is a flip-flop and a next-state function.
  • Skipping the final minimization. The encoded cover of line L7 is only an upper bound. Running a two-level minimizer on the encoded function can remove more cubes.
  • Unused codes. When 2k>n2^k > n, the unused codes are don't cares. Forgetting them in the final minimization gives larger logic.

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.

fsmlogic.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the hs3 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small exact two-level logic for finite state machines.

This module holds no state encoder. It gives the encoders and their tests:

- an exact multiple-valued, multiple-output two-level minimizer for tiny
  functions (all cubes, then an exact set cover by branch and bound);
- the symbolic function of a machine (present state as one multiple-valued
  input, next state as one output per state) and the encoded function of a
  machine under given codes;
- a check that a cover implements the machine;
- an exhaustive search for the best codes of a given length.

A machine is (ni, no, states, rows). A row is (inp, ps, ns, out): inp is a
string over 0, 1 and - of length ni, ps and ns are state names, and out is
a string over 0, 1 and - of length no. Rows of one present state must not
overlap in the input. Input and state pairs that no row covers are don't
cares.
"""

import itertools

# ---------------------------------------------------------------- minimizer


def _minterms(domains):
    return list(itertools.product(*[range(d) for d in domains]))


def _literals(cube, domains):
    return sum(1 for m, d in zip(cube, domains) if m != (1 << d) - 1)


def minimize(domains, on, dc):
    """Exact minimum cover; return a list of (cube, outputs).

    domains[i] is the number of values of variable i (2 for a binary one).
    on[j] and dc[j] are sets of points (tuples) for output j. The cover has
    the least number of cubes, and among those the least number of input
    literals. A cube is a tuple of nonempty value masks.
    """
    nout = len(on)
    points = _minterms(domains)
    npts = len(points)
    index = {p: i for i, p in enumerate(points)}
    # value masks: the points where variable i takes value v, as bit sets
    vmask = [[0] * d for d in domains]
    for p, i in index.items():
        for var, v in enumerate(p):
            vmask[var][v] |= 1 << i
    on_m = [sum(1 << index[p] for p in on[j]) for j in range(nout)]
    ok_m = [on_m[j] | sum(1 << index[p] for p in dc[j]) for j in range(nout)]
    sub = [[sum(vmask[var][v] for v in range(d) if m >> v & 1) for m in range(1 << d)] for var, d in enumerate(domains)]
    full = (1 << npts) - 1
    cands = []
    for cube in itertools.product(*[range(1, 1 << d) for d in domains]):
        pm = full
        for var, m in enumerate(cube):
            pm &= sub[var][m]
        outs = [j for j in range(nout) if pm & ~ok_m[j] == 0]
        cover = 0
        for j in outs:
            cover |= (pm & on_m[j]) << (j * npts)
        if cover:
            cands.append((cube, frozenset(outs), cover, _literals(cube, domains)))
    # Keep only terms that no other term dominates. A cube is dropped at
    # once if adding one value to one variable covers at least as much,
    # since that never adds a literal; the rest are compared in pairs.
    by_cube = {c[0]: c[2] for c in cands}
    pruned = []
    for c in cands:
        cube, cov = c[0], c[2]
        grown = False
        for var, m in enumerate(cube):
            for v in range(domains[var]):
                if not m >> v & 1:
                    bigger = cube[:var] + (m | 1 << v,) + cube[var + 1:]
                    if cov & ~by_cube.get(bigger, 0) == 0:
                        grown = True
                        break
            if grown:
                break
        if not grown:
            pruned.append(c)
    cands = pruned
    cands.sort(key=lambda c: (-bin(c[2]).count("1"), c[3]))
    terms = []
    for c in cands:
        if not any(c[2] & ~t[2] == 0 and t[3] <= c[3] for t in terms):
            terms.append(c)
    need = 0
    for j in range(nout):
        need |= on_m[j] << (j * npts)
    by_elem = {}
    for i, t in enumerate(terms):
        m = t[2]
        while m:
            low = m & -m
            by_elem.setdefault(low, []).append(i)
            m ^= low
    order = sorted(by_elem, key=lambda e: len(by_elem[e]))
    tmask = {e: sum(1 << i for i in by_elem[e]) for e in by_elem}
    best = [None, (len(terms) + 1, 0)]

    def lower_bound(left):
        lb = 0
        used = 0
        for e in order:
            if left & e and not used & tmask[e]:
                lb += 1
                used |= tmask[e]
        return lb

    def search(left, chosen, nlit):
        if not left:
            if (len(chosen), nlit) < best[1]:
                best[0], best[1] = list(chosen), (len(chosen), nlit)
            return
        if (len(chosen) + lower_bound(left), nlit) >= best[1]:
            return
        e = next(e for e in order if left & e)
        for i in sorted(by_elem[e], key=lambda i: (-bin(terms[i][2] & left).count("1"), terms[i][3])):
            chosen.append(i)
            search(left & ~terms[i][2], chosen, nlit + terms[i][3])
            chosen.pop()

    search(need, [], 0)
    return [(terms[i][0], terms[i][1]) for i in best[0]]


def cost(cover, domains):
    """(number of cubes, number of input literals) of a cover."""
    return len(cover), sum(_literals(c, domains) for c, _ in cover)


# ---------------------------------------------------------------- machines


def _bits_match(cube, bits):
    return all(c == "-" or int(c) == b for c, b in zip(cube, bits))


def _lookup(fsm, bits, s):
    ni, no, states, rows = fsm
    for inp, ps, ns, out in rows:
        if ps == s and _bits_match(inp, bits):
            return ns, out
    return None


def symbolic_function(fsm):
    """Domains, on and dc of the symbolic function.

    Variables: the ni inputs, then the present state with len(states)
    values. Outputs: one per next state (one-hot), then the no outputs.
    """
    ni, no, states, rows = fsm
    n = len(states)
    domains = [2] * ni + [n]
    on = [set() for _ in range(n + no)]
    dc = [set() for _ in range(n + no)]
    for p in _minterms(domains):
        hit = _lookup(fsm, p[:ni], states[p[ni]])
        for j in range(n + no):
            if hit is None:
                dc[j].add(p)
            elif j < n:
                if states[j] == hit[0]:
                    on[j].add(p)
            else:
                c = hit[1][j - n]
                if c == "1":
                    on[j].add(p)
                elif c == "-":
                    dc[j].add(p)
    return domains, on, dc


def encoded_function(fsm, codes, k):
    """Domains, on and dc of the machine under codes (state -> int of k bits).

    Variables: the ni inputs, then the k state bits, most significant
    first. Outputs: the k next state bits, then the no outputs. Codes that
    no state uses are don't cares.
    """
    ni, no, states, rows = fsm
    by_code = {codes[s]: s for s in states}
    domains = [2] * (ni + k)
    on = [set() for _ in range(k + no)]
    dc = [set() for _ in range(k + no)]
    for p in _minterms(domains):
        code = int("".join(map(str, p[ni:])), 2) if k else 0
        s = by_code.get(code)
        hit = None if s is None else _lookup(fsm, p[:ni], s)
        for j in range(k + no):
            if hit is None:
                dc[j].add(p)
            elif j < k:
                if codes[hit[0]] >> (k - 1 - j) & 1:
                    on[j].add(p)
            else:
                c = hit[1][j - k]
                if c == "1":
                    on[j].add(p)
                elif c == "-":
                    dc[j].add(p)
    return domains, on, dc


def encoded_cost(fsm, codes, k):
    domains, on, dc = encoded_function(fsm, codes, k)
    return cost(minimize(domains, on, dc), domains)


def implements(fsm, codes, k, cover):
    """Does the two-level cover give the right next state and outputs?

    It checks every input and state pair that some row specifies.
    """
    ni, no, states, rows = fsm
    for s in states:
        for bits in itertools.product((0, 1), repeat=ni):
            hit = _lookup(fsm, bits, s)
            if hit is None:
                continue
            p = tuple(bits) + tuple(codes[s] >> (k - 1 - b) & 1 for b in range(k))
            val = [0] * (k + no)
            for cube, outs in cover:
                if all(m >> v & 1 for m, v in zip(cube, p)):
                    for j in outs:
                        val[j] = 1
            if val[:k] != [codes[hit[0]] >> (k - 1 - b) & 1 for b in range(k)]:
                return False
            for j, c in enumerate(hit[1]):
                if c != "-" and val[k + j] != int(c):
                    return False
    return True


_CODES = {}


def all_codes(n, k):
    """Every injective code of n states in k bits, one per class of bit permutations.

    Permuting the bits of all codes permutes the state variables and the
    next state outputs, so the cost does not change. Complementing a bit
    can change it, so those classes stay apart.
    """
    if (n, k) not in _CODES:
        seen = set()
        keep = []
        perms = list(itertools.permutations(range(k)))
        for codes in itertools.permutations(range(1 << k), n):
            key = min(tuple(sum((c >> perm[b] & 1) << b for b in range(k)) for c in codes) for perm in perms)
            if key not in seen:
                seen.add(key)
                keep.append(codes)
        _CODES[(n, k)] = keep
    return list(_CODES[(n, k)])


def exhaustive_best(fsm, k):
    """Return (best cost, list of cost of every class) over all codes of length k."""
    ni, no, states, rows = fsm
    costs = []
    for codes in all_codes(len(states), k):
        costs.append(encoded_cost(fsm, dict(zip(states, codes)), k))
    return min(costs), costs
kiss_symbolic_minimization.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kiss-symbolic-minimization/. The authors are listed in prov/QRSANA.jsonl.

"""KISS: symbolic minimization, face constraints, and a face embedding.

The machine format and the exact minimizer come from fsmlogic. The
embedding step here is an exact search for the shortest codes that meet
every face constraint, which fits only small machines; De Micheli, Brayton
and Sangiovanni-Vincentelli used a heuristic for it.
"""

from fsmlogic import minimize, symbolic_function


def symbolic_cover(fsm):
    """A minimum symbolic cover: (input mask tuple, state group, next states, outputs)."""
    ni, no, states, rows = fsm
    n = len(states)
    domains, on, dc = symbolic_function(fsm)  # @line L1
    cover = []
    for cube, outs in minimize(domains, on, dc):  # @line L2
        group = frozenset(states[v] for v in range(n) if cube[ni] >> v & 1)
        nexts = frozenset(states[j] for j in outs if j < n)
        outputs = frozenset(j - n for j in outs if j >= n)
        cover.append((cube[:ni], group, nexts, outputs))
    return cover


def face_constraints(cover, states):
    """The groups of present states with more than one and fewer than all states."""
    seen = []
    for _, group, _, _ in cover:
        if 1 < len(group) < len(states) and group not in seen:  # @line L3
            seen.append(group)
    return seen


def face(codes, group, k):
    """(fixed mask, fixed value) of the least cube that holds the codes of group."""
    vals = [codes[s] for s in group]
    full = (1 << k) - 1
    agree = full
    for v in vals[1:]:
        agree &= ~(v ^ vals[0]) & full
    return agree, vals[0] & agree


def satisfies(codes, group, k, states):
    mask, val = face(codes, group, k)
    return all(codes[t] & mask != val for t in states if t not in group)


def embed(states, constraints, k):
    """Injective codes of k bits that meet every constraint, or None.

    Backtracking over the states in order. A partial assignment fails as
    soon as the face of the placed members of a group holds the code of a
    placed state outside the group; faces only grow, so this is safe.
    """
    n = len(states)
    codes = {}
    used = set()

    def ok():
        for g in constraints:
            placed = [s for s in g if s in codes]
            if len(placed) < 2:
                continue
            mask, val = face(codes, placed, k)
            if any(codes[t] & mask == val for t in codes if t not in g):
                return False
        return True

    def place(i):
        if i == n:
            return True
        for c in range(1 << k):
            if c in used:
                continue
            codes[states[i]] = c
            used.add(c)
            if ok() and place(i + 1):
                return True
            used.discard(c)
            del codes[states[i]]
        return False

    return dict(codes) if place(0) else None


def kiss_encode(fsm):
    """Return (k, codes, symbolic cover, constraints) with the least k that meets all."""
    ni, no, states, rows = fsm
    cover = symbolic_cover(fsm)
    cons = face_constraints(cover, states)
    k = max(1, (len(states) - 1).bit_length())  # @line L4
    while True:
        codes = embed(states, cons, k)  # @line L5 L6
        if codes is not None:
            return k, codes, cover, cons  # @line L8
        k += 1


def encoded_cover(fsm, codes, k, cover):
    """Map each symbolic cube to one encoded cube (the KISS construction).

    The state part is the face of the group; the output part sets the bits
    of the code of the next state and the outputs. A cube whose output part
    is empty is dropped. Variables and outputs follow fsmlogic.
    """
    ni, no, states, rows = fsm
    result = []
    for inp, group, nexts, outputs in cover:  # @line L7
        mask, val = face(codes, group, k)
        state_part = []
        for b in range(k - 1, -1, -1):
            if mask >> b & 1:
                state_part.append(2 if val >> b & 1 else 1)
            else:
                state_part.append(3)
        outs = set(k + j for j in outputs)
        for s in nexts:
            outs.update(k - 1 - b for b in range(k) if codes[s] >> b & 1)
        if outs:
            result.append((tuple(inp) + tuple(state_part), frozenset(outs)))
    return result
test_kiss_symbolic_minimization.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kiss-symbolic-minimization/. The authors are listed in prov/QRSANA.jsonl.

import itertools
import random

from fsmlogic import all_codes, cost, encoded_cost, encoded_function, exhaustive_best, implements, minimize
from kiss_symbolic_minimization import embed, encoded_cover, face_constraints, kiss_encode, satisfies, symbolic_cover

# The machine of the page: one input, one output, four states.
M1 = (1, 1, ["s0", "s1", "s2", "s3"], [
    ("0", "s0", "s2", "1"), ("1", "s0", "s2", "0"),
    ("0", "s1", "s2", "0"), ("1", "s1", "s2", "1"),
    ("0", "s2", "s3", "0"), ("1", "s2", "s1", "1"),
    ("0", "s3", "s1", "1"), ("1", "s3", "s3", "0"),
])


def random_fsm(rng: random.Random, n, ni, no):
    states = [f"s{i}" for i in range(n)]
    rows = []
    for s in states:
        for x in range(1 << ni):
            rows.append((format(x, f"0{ni}b"), s, rng.choice(states), "".join(rng.choice("01") for _ in range(no))))
    return (ni, no, states, rows)


def brute_min_cubes(domains, on, dc):
    """Least number of cubes, by trying all sets of cubes of growing size."""
    nout = len(on)
    allowed = [on[j] | dc[j] for j in range(nout)]
    terms = []
    for cube in itertools.product(*[range(1, 1 << d) for d in domains]):
        pts = list(itertools.product(*[[v for v in range(d) if cube[i] >> v & 1] for i, d in enumerate(domains)]))
        outs = [j for j in range(nout) if all(p in allowed[j] for p in pts)]
        terms.append(frozenset((p, j) for j in outs for p in pts if p in on[j]))
    terms = sorted({t for t in terms if t}, key=len, reverse=True)
    need = frozenset((p, j) for j in range(nout) for p in on[j])
    for size in range(len(need) + 1):
        for combo in itertools.combinations(terms, size):
            if need <= frozenset().union(*combo):
                return size


def test_minimizer_against_brute_force():
    rng = random.Random(5)
    for _ in range(30):
        domains = rng.choice([[2, 2, 2], [2, 3], [4]])
        pts = list(itertools.product(*[range(d) for d in domains]))
        on, dc = [], []
        for _ in range(2):
            on.append({p for p in pts if rng.random() < 0.4})
            dc.append({p for p in pts if p not in on[-1] and rng.random() < 0.2})
        cover = minimize(domains, on, dc)
        assert len(cover) == brute_min_cubes(domains, on, dc)
        for j in range(2):
            got = {p for p in pts if any(j in outs and all(c[i] >> p[i] & 1 for i in range(len(p))) for c, outs in cover)}
            assert on[j] <= got <= on[j] | dc[j]


def test_page_example():
    cover = symbolic_cover(M1)
    assert len(cover) == 7
    assert face_constraints(cover, M1[2]) == [frozenset({"s0", "s1"})]
    k, codes, _, _ = kiss_encode(M1)
    assert (k, codes) == (2, {"s0": 0, "s1": 1, "s2": 2, "s3": 3})
    enc = encoded_cover(M1, codes, k, cover)
    assert len(enc) == 7 and implements(M1, codes, k, enc)
    assert encoded_cost(M1, codes, k) == (7, 19)
    best, costs = exhaustive_best(M1, 2)
    assert best == (4, 8) and len(costs) == 12
    sat = [encoded_cost(M1, dict(zip(M1[2], cs)), 2) for cs in all_codes(4, 2)
           if satisfies(dict(zip(M1[2], cs)), frozenset({"s0", "s1"}), 2, M1[2])]
    assert len(sat) == 8 and min(sat) == (5, 9) and max(sat) == (7, 19)
    assert exhaustive_best(M1, 3)[0] == (3, 6)


def test_random_machines():
    rng = random.Random(1985)
    hits = excess = worst = longer = compared = 0
    for _ in range(100):
        fsm = random_fsm(rng, 4, 1, 1)
        states = fsm[2]
        cover = symbolic_cover(fsm)
        cons = face_constraints(cover, states)
        k, codes, _, _ = kiss_encode(fsm)
        # k is the least length that meets every face constraint
        if k > 2:
            longer += 1
            assert embed(states, cons, k - 1) is None
            assert not any(all(satisfies(dict(zip(states, cs)), g, k - 1, states) for g in cons)
                           for cs in all_codes(4, k - 1))
        assert all(satisfies(codes, g, k, states) for g in cons)
        # the KISS construction: one encoded cube per symbolic cube at most
        enc = encoded_cover(fsm, codes, k, cover)
        assert len(enc) <= len(cover) and implements(fsm, codes, k, enc)
        domains, on, dc = encoded_function(fsm, codes, k)
        exact = minimize(domains, on, dc)
        assert implements(fsm, codes, k, exact)
        assert len(exact) <= len(enc)
        # every 2-bit code that meets all constraints obeys the same bound
        for cs in all_codes(4, 2):
            cd = dict(zip(states, cs))
            if all(satisfies(cd, g, 2, states) for g in cons):
                assert encoded_cost(fsm, cd, 2)[0] <= len(cover)
        # measured gap to the best code of the same length (up to 3 bits)
        if k > 3:
            continue
        compared += 1
        best = exhaustive_best(fsm, k)[0][0]
        got = cost(exact, domains)[0]
        assert got >= best
        hits += got == best
        excess += got - best
        worst = max(worst, got - best)
    assert (longer, compared, hits, excess, worst) == MEASURED


# 100 machines: 32 need 3 or more bits, 99 need at most 3; KISS meets the
# best code of its own length on 41 of those 99, with 70 extra cubes in
# total and at most 3 extra cubes on one machine.
MEASURED = (32, 99, 41, 70, 3)

History

De Micheli, Brayton and Sangiovanni-Vincentelli (1985) introduced symbolic minimization and face constraints, with the bound on product terms and a heuristic embedding. Rudell and Sangiovanni-Vincentelli (1987) built ESPRESSO-MV, the multiple-valued minimizer that such methods use. Villa and Sangiovanni-Vincentelli (1990) gave NOVA, which keeps the code length fixed and meets constraints selectively. De Micheli's 1994 textbook presents these methods together with the output constraints of later work.

References

  1. Giovanni De Micheli, Robert K. Brayton and Alberto L. Sangiovanni-Vincentelli, Optimal state assignment for finite state machines, IEEE Transactions on Computer-Aided Design CAD-4(3), 269 to 285, 1985, symbolic minimization of the state table, the face constraints, the bound on the number of product terms, and the heuristic embedding of the constraints
  2. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 9 (state encoding for two-level circuits, symbolic minimization, input and output encoding constraints)
  3. Richard L. Rudell and Alberto L. Sangiovanni-Vincentelli, Multiple-valued minimization for PLA optimization, IEEE Transactions on Computer-Aided Design 6(5), 727 to 750, 1987, ESPRESSO-MV, the multiple-valued two-level minimizer used for symbolic minimization

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