Algorithm Search⌘K

Algorithmadvanced

Coudert-Madre image computation

Also called range computation image method, transition function image computation.

Coudert, Berthet and Madre's BDD method that computes the image of a set of states from the next-state functions by recursive splitting and constrain, with no transition relation.

Time
O(2^m m b^2) worst
Space
O(2^m m b^2) extra
Where
b = the largest number of nodes of a BDD in the run; k = the number of primary inputs; m = the number of state bits
Properties
deterministicexactrecursive
Origin
Olivier Coudert, Christian Berthet, Jean Christophe Madre, 1989

Coudert-Madre image computation finds the set of next states of a set of states of a sequential circuit, with BDDs, from the next-state functions δ1,…,δm\delta_1, \ldots, \delta_m alone. It builds no transition relation. It first applies the constrain operator of the generalized cofactor page to each next-state function, with the state set as care set. The image is then the range of the constrained vector of functions, which a recursion computes by splitting on one output bit at a time. This is the transition-function method. The other method uses the transition relation and a relational product, see partitioned transition relation. Both give the same image step of symbolic reachability.

In plain words

A circuit with registers moves from state to state. Given a set of states, you want all states it can reach in one clock tick, for any input. The circuit gives you one formula per register bit: its next value from the present state and the inputs.

First, simplify each formula so that it only has to be right on the given set of states. Done the right way, the simplified formulas together can produce exactly the next states of the set and nothing else. Now ask which bit patterns these formulas can output. Look at the first bit. If it can be 1, find what the other bits can be when it is 1, and the same for 0. Each case is the same question with one bit fewer. Combine the answers.

The problem

The present-state variables are s=(s1,…,sm)s = (s_1, \ldots, s_m), the inputs x=(x1,…,xk)x = (x_1, \ldots, x_k), and the next-state functions δi(s,x)\delta_i(s, x) are BDDs. A set of states SS is a BDD over ss. The task is the BDD over fresh next-state variables y=(y1,…,ym)y = (y_1, \ldots, y_m) of

Img(S)={δ(s,x):S(s)=1, x∈{0,1}k}.\mathrm{Img}(S) = \{\delta(s, x) : S(s) = 1,\ x \in \{0, 1\}^k\}.

With the transition relation T(s,x,y)=⋀i(yi≡δi(s,x))T(s, x, y) = \bigwedge_i (y_i \equiv \delta_i(s, x)), this is Img(S)(y)=∃s,x. S(s)∧T(s,x,y)\mathrm{Img}(S)(y) = \exists s, x.\ S(s) \wedge T(s, x, y). Here "transition" means the next-state functions, not the relation: the method never forms TT.

For a vector g=(g1,…,gr)g = (g_1, \ldots, g_r) of functions, Range(g)\mathrm{Range}(g) is the set of values g(z)g(z) over all points zz. We write f↓cf \downarrow c for constrain, defined on the generalized cofactor page.

The algorithm

  1. IMAGE(δ₁, ..., δₘ, S)
  2. 1if S = 0 then return 0
  3. 2for i ← 1 to m do gᵢ ← δᵢ ↓ S
  4. 3return RANGE(g₁, ..., gₘ; y₁, ..., yₘ)
  5. RANGE(g₁, ..., gᵣ; y₁, ..., yᵣ)
  6. 4if r = 0 then return 1
  7. 5if g₁ = 1 then return y₁ ∧ RANGE(g₂, ..., gᵣ; y₂, ..., yᵣ)
  8. 6if g₁ = 0 then return ¬y₁ ∧ RANGE(g₂, ..., gᵣ; y₂, ..., yᵣ)
  9. 7hi ← RANGE(g₂ ↓ g₁, ..., gᵣ ↓ g₁; y₂, ..., yᵣ)
  10. 8lo ← RANGE(g₂ ↓ ¬g₁, ..., gᵣ ↓ ¬g₁; y₂, ..., yᵣ)
  11. 9return (y₁ ∧ hi) ∨ (¬y₁ ∧ lo)

Line L2 does the main work. Constrain by SS maps every point outside SS to a point inside SS, the same map for all mm functions, so the vector gg takes exactly the values that δ\delta takes on SS. The domain restriction is gone. Often gig_i becomes much smaller than δi\delta_i, or even constant.

Lines L4 to L9 compute a range by output splitting. A constant g1g_1 fixes the first bit, and the rest is the range of the other functions (lines L5 and L6). Otherwise the first bit can be both 1 and 0. The points with g1=1g_1 = 1 give the tails (g2,…,gr)(g_2, \ldots, g_r) on the set g1g_1, which is the range of the vector constrained by g1g_1, by the same property of constrain (line L7), and the same for ¬g1\neg g_1 (line L8). Line L9 joins the two halves with y1y_1 as the top variable.

Example

Take state bits s1,s2,s3s_1, s_2, s_3, one input xx, the order s1,s2,s3,xs_1, s_2, s_3, x, and

δ1=s1⊕x,δ2=s1∧s2,δ3=x∨s2,S=(s1⊕s2)∧¬s3={100,010},\delta_1 = s_1 \oplus x,\qquad \delta_2 = s_1 \wedge s_2,\qquad \delta_3 = x \vee s_2,\qquad S = (s_1 \oplus s_2) \wedge \neg s_3 = \{100, 010\},

where a state is written s1s2s3s_1 s_2 s_3. By enumeration, state 100 goes to 100 (x=0x = 0) and 001 (x=1x = 1), and state 010 goes to 001 (x=0x = 0) and 101 (x=1x = 1). So the image is {100,001,101}\{100, 001, 101\}.

call vector first function action result
IMAGE, L2 (s1⊕x, s1∧s2, x∨s2)↓S(s_1 \oplus x,\ s_1 \wedge s_2,\ x \vee s_2) \downarrow S constrain each by SS g=(s1⊕x, 0, ¬s1∨x)g = (s_1 \oplus x,\ 0,\ \neg s_1 \vee x)
RANGE, depth 1 gg s1⊕xs_1 \oplus x, not constant L7: (0,¬s1∨x)↓g1=(0,¬s1)(0, \neg s_1 \vee x) \downarrow g_1 = (0, \neg s_1); L8: (0,¬s1∨x)↓¬g1=(0,1)(0, \neg s_1 \vee x) \downarrow \neg g_1 = (0, 1) (y1∧hi)∨(¬y1∧lo)(y_1 \wedge \mathrm{hi}) \vee (\neg y_1 \wedge \mathrm{lo})
hi, depth 2 (0,¬s1)(0, \neg s_1) 0 L6 ¬y2∧RANGE(¬s1)\neg y_2 \wedge \mathrm{RANGE}(\neg s_1)
depth 3 (¬s1)(\neg s_1) not constant L7, L8 on empty vectors give 1 and 1 y3∨¬y3=1y_3 \vee \neg y_3 = 1
hi ¬y2\neg y_2
lo, depth 2 (0,1)(0, 1) 0 L6, then L5 ¬y2∧y3\neg y_2 \wedge y_3
result L9 at depth 1 (y1∧¬y2)∨(¬y1∧¬y2∧y3)(y_1 \wedge \neg y_2) \vee (\neg y_1 \wedge \neg y_2 \wedge y_3)

The result is the set {100,101,001}\{100, 101, 001\}, as the enumeration gave. On SS, s1∧s2s_1 \wedge s_2 is 0, so g2=0g_2 = 0, and constrain found that. On SS, s2=¬s1s_2 = \neg s_1, so x∨s2x \vee s_2 became ¬s1∨x\neg s_1 \vee x and s2s_2 and s3s_3 left all three functions. With SS replaced by all 8 states, the image has 6 states: every state except 010 and 110, since y2=1y_2 = 1 needs s1=s2=1s_1 = s_2 = 1, which forces y3=1y_3 = 1.

Correctness

The method is exact. The key fact is the range property of constrain: for c≠0c \ne 0, the vector g↓cg \downarrow c takes exactly the values {g(z):c(z)=1}\{g(z) : c(z) = 1\}. It holds because constrain by cc is composition with one map onto the points of cc that keeps those points fixed, the same map for every function of the vector. The generalized cofactor page proves the composition form. With c=Sc = S this gives Img(S)=Range(δ↓S)\mathrm{Img}(S) = \mathrm{Range}(\delta \downarrow S), and with c=g1c = g_1 and c=¬g1c = \neg g_1 it gives lines L7 and L8. Induction on the number of functions then shows that RANGE returns the range. The full proof is in the correctness proof. The tests also compare each result with the relational product ∃s,x. S∧T\exists s, x.\ S \wedge T and with enumeration of all states and inputs.

Proof: The range of the next-state functions under constrain is the image, and the output-splitting recursion computes the rangefull

Setting. The present-state variables are s=(s1,…,sm)s = (s_1, \ldots, s_m), the inputs are x=(x1,…,xk)x = (x_1, \ldots, x_k), and z=(s,x)z = (s, x) ranges over {0,1}m+k\{0, 1\}^{m + k}. The next-state functions form the vector δ=(δ1,…,δm)\delta = (\delta_1, \ldots, \delta_m), δi:{0,1}m+k→{0,1}\delta_i : \{0, 1\}^{m + k} \to \{0, 1\}. A set of states S⊆{0,1}mS \subseteq \{0, 1\}^m is given by its characteristic function, read as a function of zz that does not depend on xx. The image is

Img(S)={δ(s,x):s∈S, x∈{0,1}k}.\mathrm{Img}(S) = \{\delta(s, x) : s \in S,\ x \in \{0, 1\}^k\}.

For a vector g=(g1,…,gr)g = (g_1, \ldots, g_r) of functions of zz and a function cc, write g(c)={g(z):c(z)=1}g(c) = \{g(z) : c(z) = 1\} and Range(g)=g(1)\mathrm{Range}(g) = g(1). The vector g↓cg \downarrow c is (g1↓c,…,gr↓c)(g_1 \downarrow c, \ldots, g_r \downarrow c), where ↓\downarrow is constrain. A set Y⊆{0,1}rY \subseteq \{0, 1\}^r is identified with its characteristic function over fresh variables y1,…,yry_1, \ldots, y_r. For r=0r = 0, {0,1}0\{0, 1\}^0 has one element, the empty vector, and Range\mathrm{Range} of the empty vector is that one-element set, the constant 1.

Lemma 1 (range under constrain). For c≠0c \ne 0, Range(g↓c)=g(c)\mathrm{Range}(g \downarrow c) = g(c).

Proof. The generalized cofactor proof shows (its Theorem 2) that f↓c=f∘πcf \downarrow c = f \circ \pi_c for every ff, where πc\pi_c is the closest-point map of cc. The map πc\pi_c depends on cc only, so the same map serves every component: (g↓c)(z)=g(πc(z))(g \downarrow c)(z) = g(\pi_c(z)). By its definition, πc(z)\pi_c(z) is a point of cc for every zz, and πc(z)=z\pi_c(z) = z when c(z)=1c(z) = 1, since then zz itself extends every prefix of zz.

(⊆\subseteq) For any zz, (g↓c)(z)=g(πc(z))(g \downarrow c)(z) = g(\pi_c(z)) and c(πc(z))=1c(\pi_c(z)) = 1, so the value is in g(c)g(c).

(⊇\supseteq) For zz with c(z)=1c(z) = 1, g(z)=g(πc(z))=(g↓c)(z)g(z) = g(\pi_c(z)) = (g \downarrow c)(z), which is in Range(g↓c)\mathrm{Range}(g \downarrow c). □\square

Lemma 2 (RANGE). For every vector g=(g1,…,gr)g = (g_1, \ldots, g_r) that does not use the variables yy, RANGE(gg) is the characteristic function of Range(g)\mathrm{Range}(g).

Proof. Induction on rr.

  • Base, r=0r = 0 (line L4). Both sides are the constant 1.
  • Step, g1=1g_1 = 1 (line L5). Every value g(z)g(z) has first bit 1, so Range(g)={(1,w):w∈Range(g2,…,gr)}\mathrm{Range}(g) = \{(1, w) : w \in \mathrm{Range}(g_2, \ldots, g_r)\}. By the induction hypothesis this is y1∧y_1 \wedge RANGE(g2,…,grg_2, \ldots, g_r).
  • Step, g1=0g_1 = 0 (line L6). The same with first bit 0 and ¬y1\neg y_1.
  • Step, g1g_1 not constant (lines L7 to L9). Split by the value of g1g_1:
    Range(g)={(1,w):w∈(g2,…,gr)(g1)}∪{(0,w):w∈(g2,…,gr)(¬g1)}.\mathrm{Range}(g) = \{(1, w) : w \in (g_2, \ldots, g_r)(g_1)\} \cup \{(0, w) : w \in (g_2, \ldots, g_r)(\neg g_1)\}.
    Since g1g_1 is not constant, g1≠0g_1 \ne 0 and ¬g1≠0\neg g_1 \ne 0. By Lemma 1, the first set of tails is Range((g2,…,gr)↓g1)\mathrm{Range}((g_2, \ldots, g_r) \downarrow g_1) and the second is Range((g2,…,gr)↓¬g1)\mathrm{Range}((g_2, \ldots, g_r) \downarrow \neg g_1). Constrain does not add variables that are not in its arguments, so these vectors do not use yy, and the induction hypothesis applies to the calls of lines L7 and L8. Line L9 returns (y1∧hi)∨(¬y1∧lo)(y_1 \wedge \mathrm{hi}) \vee (\neg y_1 \wedge \mathrm{lo}), which is the characteristic function of the union. □\square

Theorem (correctness of IMAGE). IMAGE(δ\delta, SS) is the characteristic function of Img(S)\mathrm{Img}(S) over yy.

Proof. If S=0S = 0, the image is empty and line L1 returns 0. Otherwise SS, read as a function of zz, is not 0, and

Img(S)={δ(z):S(z)=1}=δ(S)=Range(δ↓S)\mathrm{Img}(S) = \{\delta(z) : S(z) = 1\} = \delta(S) = \mathrm{Range}(\delta \downarrow S)

by Lemma 1. Line L2 computes δ↓S\delta \downarrow S, and line L3 returns its range by Lemma 2. ■\blacksquare

Remark (the variable order). Lemma 1 holds for every variable order, because the closest-point map is defined for any order. The order changes the BDDs of δ↓S\delta \downarrow S and their sizes, not the result. Also, constrain does not need SS to be independent of xx; for a constraint on states and inputs together, the same proof gives {δ(z):c(z)=1}\{\delta(z) : c(z) = 1\}.

Remark (termination). Each call of RANGE removes one component, so the recursion has depth rr and at most 2r+1−12^{r + 1} - 1 calls.

Complexity

The model is the word RAM, with hashing in expected constant time. Let bb be the largest number of nodes of a BDD in the run. Each call of RANGE removes one function, so the calls form a binary tree of depth at most mm, with at most 2m+1−12^{m + 1} - 1 calls. A call does at most 2(m−1)2(m - 1) constrain operations, each O(b2)O(b^2) with its cache, and a constant number of applies on BDDs over yy, also O(b2)O(b^2). Line L2 adds mm constrain operations. The total is O(2mmb2)O(2^m m b^2) time, and the unique table grows by at most one node per step, which bounds the space the same way.

The 2m2^m factor is real for this simple recursion: a range with many states can need many calls. Practical versions reduce it with a cache of ranges, by splitting on a domain variable in place of an output, and by handling outputs that do not share support separately (see the variants below). Those changes are not in the pseudocode above, and no bound better than the one above is proved here. Against the relational product, the trade is this: the method never builds TT, whose BDD can be much larger than the next-state functions, but it pays for many constrain calls.

Properties

  • Exact for every variable order; the order changes only the sizes.
  • Needs only the BDDs of the next-state functions, not of TT.
  • Works for a care set c(s,x)c(s, x) on states and inputs together, giving {δ(z):c(z)=1}\{\delta(z) : c(z) = 1\}.
  • The recursion depth is mm.

Variants and improvements

  • Input splitting. Split on a variable of ss or xx in place of an output: Img=Range(g∣v=0)∪Range(g∣v=1)\mathrm{Img} = \mathrm{Range}(g|_{v=0}) \cup \mathrm{Range}(g|_{v=1}), with cofactors. This is a Shannon expansion of the domain, not of the range.
  • Range cache. Different branches often meet the same vector after constrain. A table of solved vectors removes repeated calls.
  • Disjoint support. If the functions split into groups with no common variable, the range is the product of the ranges of the groups.
  • Relation-based image. Build TT as a conjunction of parts and quantify ss and xx early. See partitioned transition relation; it is the method of most later model checkers.
  • Preimage. The set of states that reach SS in one step is ∃x. S(δ(s,x))\exists x.\ S(\delta(s, x)), a composition, with no range computation.

When to use it

Use it when the next-state functions have small BDDs but the transition relation does not, for example circuits with many latches whose next-state logic shares much structure. It also suits sequential equivalence checks of a product machine, where the next-state functions are given by the circuits. For large designs, the partitioned relation with early quantification usually won in later practice, because it can quantify inputs and state bits one group at a time. Symbolic reachability can use either; the choice changes only the cost of the image step.

Pitfalls

  • Restrict in place of constrain at line L2. Restrict also agrees with each function on SS, but it does not use one common map for all functions, so the range of the vector can be too large. With δ=(s1∧s2, s2)\delta = (s_1 \wedge s_2,\ s_2) and S={00,11}S = \{00, 11\}, restrict gives (s1,s2)(s_1, s_2), whose range is all four states, while the image is {00,11}\{00, 11\}. Constrain gives (s1,s1)(s_1, s_1), whose range is right.
  • Constraining by 0. Constrain by the zero function has no meaning. Line L1 handles S=0S = 0, and lines L5 and L6 must come before lines L7 and L8, because a constant g1g_1 makes g1g_1 or ¬g1\neg g_1 zero.
  • Mixing yy with ss. The output variables yy must be fresh. If yiy_i is the same variable as sis_i, line L9 builds a function of the present state mixed with the next state, and the result is wrong. Rename yy to ss only after the image is done.
  • Forgetting the inputs. The image is over all inputs. Constraining by SS alone is right because SS does not depend on xx; a care set that does restrict xx gives the image under those inputs only.

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.

bdd.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the hv1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reduced ordered BDD package with a unique table and an operation cache.

A node is an integer. The terminals are 0 and 1. A variable is a non-negative
integer; a smaller variable is nearer to the root. Every Boolean function has
exactly one node for a fixed order, so two functions are equal if and only if
their nodes are equal. The recursion depth of every operation is at most the
number of variables plus one.
"""

from __future__ import annotations

from typing import Mapping, Optional

TERMINAL_LEVEL = 1 << 30


class BDD:
    """A manager that owns all nodes. Functions of different managers must not be mixed."""

    def __init__(self) -> None:
        self._level: list[int] = [TERMINAL_LEVEL, TERMINAL_LEVEL]
        self._lo: list[int] = [0, 1]
        self._hi: list[int] = [0, 1]
        self._unique: dict[tuple[int, int, int], int] = {}
        self._cache: dict[tuple, int] = {}

    # Structure.

    def level(self, u: int) -> int:
        """The variable of the root of u, or TERMINAL_LEVEL for a terminal."""
        return self._level[u]

    def low(self, u: int) -> int:
        """The child of u for the value 0 of its root variable."""
        return self._lo[u]

    def high(self, u: int) -> int:
        """The child of u for the value 1 of its root variable."""
        return self._hi[u]

    def mk(self, v: int, lo: int, hi: int) -> int:
        """The unique node (v, lo, hi), with the reduction rule lo = hi."""
        if lo == hi:
            return lo
        key = (v, lo, hi)
        u = self._unique.get(key)
        if u is None:
            u = len(self._level)
            self._level.append(v)
            self._lo.append(lo)
            self._hi.append(hi)
            self._unique[key] = u
        return u

    def var(self, v: int) -> int:
        """The function that is the variable v."""
        return self.mk(v, 0, 1)

    def cofactors(self, u: int, v: int) -> tuple[int, int]:
        """The two cofactors of u by v, when v is at or above the root of u."""
        if self._level[u] == v:
            return self._lo[u], self._hi[u]
        return u, u

    # Boolean operations.

    def apply(self, op: str, u: int, w: int) -> int:
        """op(u, w) for op in and, or, xor. Cost O(|u| |w|) with the cache."""
        if op == "and":
            if u == 0 or w == 0:
                return 0
            if u == 1 or u == w:
                return w
            if w == 1:
                return u
        elif op == "or":
            if u == 1 or w == 1:
                return 1
            if u == 0 or u == w:
                return w
            if w == 0:
                return u
        elif op == "xor":
            if u == w:
                return 0
            if u == 0:
                return w
            if w == 0:
                return u
        else:
            raise ValueError(op)
        if u > w:
            u, w = w, u
        key = (op, u, w)
        r = self._cache.get(key)
        if r is None:
            v = min(self._level[u], self._level[w])
            u0, u1 = self.cofactors(u, v)
            w0, w1 = self.cofactors(w, v)
            r = self.mk(v, self.apply(op, u0, w0), self.apply(op, u1, w1))
            self._cache[key] = r
        return r

    def conj(self, u: int, w: int) -> int:
        return self.apply("and", u, w)

    def disj(self, u: int, w: int) -> int:
        return self.apply("or", u, w)

    def xor(self, u: int, w: int) -> int:
        return self.apply("xor", u, w)

    def neg(self, u: int) -> int:
        return self.apply("xor", u, 1)

    def xnor(self, u: int, w: int) -> int:
        return self.neg(self.xor(u, w))

    def ite(self, f: int, g: int, h: int) -> int:
        """If f then g else h."""
        return self.disj(self.conj(f, g), self.conj(self.neg(f), h))

    # Substitution and quantification.

    def restrict(self, u: int, v: int, b: int) -> int:
        """The cofactor of u with variable v fixed to b."""
        if self._level[u] > v:
            return u
        if self._level[u] == v:
            return self._hi[u] if b else self._lo[u]
        key = ("restrict", u, v, b)
        r = self._cache.get(key)
        if r is None:
            r = self.mk(self._level[u], self.restrict(self._lo[u], v, b), self.restrict(self._hi[u], v, b))
            self._cache[key] = r
        return r

    def compose(self, u: int, v: int, g: int) -> int:
        """u with variable v replaced by the function g."""
        return self.ite(g, self.restrict(u, v, 1), self.restrict(u, v, 0))

    def exists(self, u: int, vs: frozenset[int]) -> int:
        """The existential quantification of u over the variables vs."""
        if u <= 1 or not vs:
            return u
        key = ("exists", u, vs)
        r = self._cache.get(key)
        if r is None:
            v = self._level[u]
            lo = self.exists(self._lo[u], vs)
            hi = self.exists(self._hi[u], vs)
            r = self.disj(lo, hi) if v in vs else self.mk(v, lo, hi)
            self._cache[key] = r
        return r

    # Queries.

    def support(self, u: int) -> set[int]:
        """The variables that u depends on."""
        seen: set[int] = set()
        out: set[int] = set()
        stack = [u]
        while stack:
            w = stack.pop()
            if w <= 1 or w in seen:
                continue
            seen.add(w)
            out.add(self._level[w])
            stack.append(self._lo[w])
            stack.append(self._hi[w])
        return out

    def size(self, u: int) -> int:
        """The number of nodes of u, terminals included."""
        seen: set[int] = set()
        stack = [u]
        while stack:
            w = stack.pop()
            if w in seen:
                continue
            seen.add(w)
            if w > 1:
                stack.append(self._lo[w])
                stack.append(self._hi[w])
        return len(seen)

    def sat_one(self, u: int) -> Optional[dict[int, int]]:
        """One assignment to some variables that makes u true, or None if u is 0."""
        if u == 0:
            return None
        point: dict[int, int] = {}
        while u != 1:
            if self._lo[u] != 0:
                point[self._level[u]] = 0
                u = self._lo[u]
            else:
                point[self._level[u]] = 1
                u = self._hi[u]
        return point

    def evaluate(self, u: int, point: Mapping[int, int]) -> int:
        """The value of u at the point; a variable not in the point has the value 0."""
        while u > 1:
            u = self._hi[u] if point.get(self._level[u], 0) else self._lo[u]
        return u
transition_function_image_computation.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transition-function-image-computation/. The authors are listed in prov/H8PR83.jsonl.
"""Image computation from next-state functions (Coudert, Berthet and Madre 1989; Coudert and Madre 1990).

The image of a set S of states under next-state functions delta_1..delta_m is
the range of the vector (delta_1 constrain S, ..., delta_m constrain S). The
range is computed by splitting on one output at a time. No transition relation
is built.
"""

from __future__ import annotations

from bdd import BDD


def constrain(bdd: BDD, f: int, c: int) -> int:
    """The generalized cofactor f constrain c of Coudert and Madre, for c != 0.

    It agrees with f where c is 1. Cost O(|f| |c|) calls with a cache.
    """
    if c == 0:
        raise ValueError("constrain by the zero function")
    cache: dict[tuple[int, int], int] = {}

    def go(f: int, c: int) -> int:
        if c == 1 or f <= 1:
            return f
        if f == c:
            return 1
        key = (f, c)
        r = cache.get(key)
        if r is None:
            v = min(bdd.level(f), bdd.level(c))
            f0, f1 = bdd.cofactors(f, v)
            c0, c1 = bdd.cofactors(c, v)
            if c0 == 0:
                r = go(f1, c1)
            elif c1 == 0:
                r = go(f0, c0)
            else:
                r = bdd.mk(v, go(f0, c0), go(f1, c1))
            cache[key] = r
        return r

    return go(f, c)


def range_of(bdd: BDD, g: list[int], y: list[int]) -> int:
    """The set {g(z) : z any point}, as a BDD over the variables y (one per function).

    Precondition: the variables y do not occur in g. Cost: at most 2^len(g) - 1 calls,
    each with up to len(g) constrain operations.
    """
    if not g:  # @line L4
        return 1
    head, rest = g[0], g[1:]
    yi = bdd.var(y[0])
    if head == 1:  # @line L5
        return bdd.conj(yi, range_of(bdd, rest, y[1:]))
    if head == 0:  # @line L6
        return bdd.conj(bdd.neg(yi), range_of(bdd, rest, y[1:]))
    hi = range_of(bdd, [constrain(bdd, h, head) for h in rest], y[1:])  # @line L7
    lo = range_of(bdd, [constrain(bdd, h, bdd.neg(head)) for h in rest], y[1:])  # @line L8
    return bdd.disj(bdd.conj(yi, hi), bdd.conj(bdd.neg(yi), lo))  # @line L9


def image(bdd: BDD, delta: list[int], states: int, y: list[int]) -> int:
    """The image {delta(s, x) : states(s) = 1, x any input} as a BDD over the next-state variables y.

    Precondition: delta[i] is the next-state function of state bit i over the present-state
    and input variables; states is a BDD over the present-state variables; y are fresh
    variables, one per state bit. Cost: len(delta) constrain operations plus range_of.
    """
    if states == 0:  # @line L1
        return 0
    g = [constrain(bdd, d, states) for d in delta]  # @line L2
    return range_of(bdd, g, y)  # @line L3
test_transition_function_image_computation.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transition-function-image-computation/. The authors are listed in prov/H8PR83.jsonl.

import random

import pytest

from bdd import BDD
from transition_function_image_computation import constrain, image, range_of


def from_table(bdd: BDD, table: list[int], vars_: list[int]) -> int:
    """The BDD of the function whose value at index sum(b_j 2^j) is table[index], for b_j the value of vars_[j]."""
    f = 0
    for idx, bit in enumerate(table):
        if bit:
            term = 1
            for j, v in enumerate(vars_):
                lit = bdd.var(v) if (idx >> j) & 1 else bdd.neg(bdd.var(v))
                term = bdd.conj(term, lit)
            f = bdd.disj(f, term)
    return f


def states_of(bdd: BDD, f: int, vars_: list[int]) -> set[int]:
    """Oracle helper: the set of codes sum(b_j 2^j) of the points where f is 1."""
    out = set()
    for code in range(1 << len(vars_)):
        if bdd.evaluate(f, {v: (code >> j) & 1 for j, v in enumerate(vars_)}):
            out.add(code)
    return out


def explicit_image(tables: list[list[int]], n: int, k: int, s: set[int]) -> set[int]:
    """Oracle: apply the next-state tables to every state of s and every input."""
    out = set()
    for st in s:
        for x in range(1 << k):
            idx = st | (x << n)
            out.add(sum(tables[i][idx] << i for i in range(n)))
    return out


def page_example():
    """State bits s1 s2 s3 (variables 0, 1, 2), input x (variable 3), next-state variables 4, 5, 6."""
    bdd = BDD()
    s1, s2, s3, x = (bdd.var(i) for i in range(4))
    delta = [bdd.xor(s1, x), bdd.conj(s1, s2), bdd.disj(x, s2)]
    states = bdd.conj(bdd.xor(s1, s2), bdd.neg(s3))  # {100, 010} as s1 s2 s3
    return bdd, delta, states


def test_page_example():
    bdd, delta, states = page_example()
    s1, x = bdd.var(0), bdd.var(3)
    g = [constrain(bdd, d, states) for d in delta]
    assert g == [bdd.xor(s1, x), 0, bdd.disj(bdd.neg(s1), x)]
    assert [constrain(bdd, h, g[0]) for h in g[1:]] == [0, bdd.neg(s1)]
    assert [constrain(bdd, h, bdd.neg(g[0])) for h in g[1:]] == [0, 1]
    img = image(bdd, delta, states, [4, 5, 6])
    # Codes are s1 + 2 s2 + 4 s3; the image is {100, 001, 101} as s1 s2 s3.
    assert states_of(bdd, img, [4, 5, 6]) == {0b001, 0b100, 0b101}
    assert img == bdd.disj(bdd.conj(bdd.var(4), bdd.neg(bdd.var(5))), bdd.conj(bdd.neg(bdd.var(5)), bdd.var(6)))


def test_empty_and_full_state_sets():
    bdd, delta, _ = page_example()
    assert image(bdd, delta, 0, [4, 5, 6]) == 0
    full = states_of(bdd, image(bdd, delta, 1, [4, 5, 6]), [4, 5, 6])
    tables = [[bdd.evaluate(d, {j: (i >> j) & 1 for j in range(4)}) for i in range(16)] for d in delta]
    assert full == explicit_image(tables, 3, 1, set(range(8)))
    assert len(full) == 6


def test_constant_functions_and_constrain_by_zero():
    bdd = BDD()
    assert range_of(bdd, [], []) == 1
    r = range_of(bdd, [1, 0], [5, 6])
    assert states_of(bdd, r, [5, 6]) == {0b01}
    with pytest.raises(ValueError):
        constrain(bdd, bdd.var(0), 0)


def test_random_against_explicit_image_and_relational_product():
    rng = random.Random(1990)
    for case in range(600):
        n = rng.randint(1, 4)
        k = rng.randint(0, 2)
        order = list(range(2 * n + k))
        rng.shuffle(order)
        svars, xvars, yvars = order[:n], order[n : n + k], order[n + k :]
        bdd = BDD()
        rows = 1 << (n + k)
        tables = [[rng.randrange(2) for _ in range(rows)] for _ in range(n)]
        if case % 5 == 0:
            tables[0] = [tables[-1][r] for r in range(rows)]
        delta = [from_table(bdd, t, svars + xvars) for t in tables]
        s_codes = [c for c in range(1 << n) if rng.random() < 0.4]
        s_table = [1 if c in s_codes else 0 for c in range(1 << n)]
        states = from_table(bdd, s_table, svars)
        img = image(bdd, delta, states, yvars)
        expect = explicit_image(tables, n, k, set(s_codes))
        assert states_of(bdd, img, yvars) == expect
        assert bdd.support(img) <= set(yvars)
        rel = 1
        for d, y in zip(delta, yvars):
            rel = bdd.conj(rel, bdd.xnor(bdd.var(y), d))
        assert img == bdd.exists(bdd.conj(states, rel), frozenset(svars + xvars))

History

Coudert, Berthet and Madre (1989) verified synchronous machines by symbolic execution and introduced constrain to compute the image as a range. Coudert and Madre (ICCAD 1990) put the operations on sets of states and of transitions into one framework and added restrict. Touati, Savoj, Lin, Brayton and Sangiovanni-Vincentelli (ICCAD 1990) compared the transition-function method with the transition-relation method and gave the image property of the generalized cofactor. Later work, from Burch, Clarke and Long (1991) on, mostly used partitioned relations, but range computation stayed in use for product machines and for synthesis.

References

  1. O. Coudert, C. Berthet and J. C. Madre, Verification of synchronous sequential machines based on symbolic execution, LNCS 407, Springer, 1989, the image of a set of states as the range of the next-state functions constrained by the set, and the recursive range computation
  2. O. Coudert and J. C. Madre, A unified framework for the formal verification of sequential circuits, ICCAD 1990, 126 to 129, sets of states and of transitions handled with the same image operators, and the restrict operator
  3. H. J. Touati, H. Savoj, B. Lin, R. K. Brayton and A. Sangiovanni-Vincentelli, Implicit state enumeration of finite state machines using BDDs, ICCAD 1990, the comparison of image computation from the transition relation and from the transition functions, and the image property of the generalized cofactor
  4. A. Kuehlmann and C. A. J. van Eijk, Combinational and sequential equivalence checking, in S. Hassoun and T. Sasao (editors), Logic Synthesis and Verification, Kluwer, 2002, 343 to 372, the section on sequential equivalence by state traversal of the product machine

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