Algorithm Search⌘K

Algorithmcore

D-algorithm

Also called Roth D-algorithm.

Roth's ATPG over the five values 0, 1, X, D and D-bar, which drives a D-frontier to an output and justifies internal line values by backtracking search.

Time
O(B^(2L) L (L + P)) worstO(L (L + P)) best
Space
O(L^2) extra
Where
B = the most children of one call, at most max(L, P); L = the number of lines; P = the number of gate input pins
Properties
completedeterministicexactrecursive
Origin
J. Paul Roth, 1966

The D-algorithm is Roth's method of 1966 for automatic test pattern generation. For a combinational circuit and one single stuck-at fault, it computes with five values: 0, 1, X, D for "1 in the good circuit and 0 in the faulty one", and D' (D-bar) for the opposite. It puts D or D' on the fault site, drives it through a gate of the D-frontier toward an output, and then justifies each internal value that is not yet explained by the inputs. It backtracks on a conflict, and it was the first complete method: it finds a test whenever one exists.

In plain words

A fault is seen when the good circuit and the broken circuit give different outputs. The D-algorithm writes down, on each wire, the value in the good circuit and the value in the broken circuit.

It starts at the broken wire and gives it the value opposite to its stuck value. Then it pushes the difference forward, one gate at a time: to let it through a gate, the other inputs of that gate must not block it. Each time it writes a value, it also writes everything that value forces, both forward and backward.

When the difference reaches an output, some wires still hold values that nothing explains yet. The algorithm chooses inputs of their gates to explain them. When two forced values clash, it undoes its last choice and tries another.

The problem

The input is a combinational circuit CC of AND, OR, NAND, NOR, NOT and BUF gates with LL lines in topological order, and a fault (ℓ,s)(\ell, s). The lines are the primary inputs, the gate outputs and the fanout branches. The output is a vector over {0,1,X}\{0, 1, X\} whose two-valued completions all detect the fault, or "untestable". XOR gates are written as AND, OR and NOT first, so that every gate has a controlling value: 0 for AND and NAND, 1 for OR and NOR.

A state gives each line a good entry and a faulty entry, each in {0,1,X}\{0, 1, X\}. The five values are the pairs 0=(0,0)0 = (0, 0), 1=(1,1)1 = (1, 1), D=(1,0)D = (1, 0) and D′=(0,1)D' = (0, 1), and X for the rest. The faulty entry of ℓ\ell is ss and is never derived from the inputs of ℓ\ell.

  • The D-frontier is the set of gates whose output has an X and that have an input with D or D'.
  • The J-frontier is the set of pairs (gate, circuit) where the entry of the gate is known but its known inputs do not imply it.

The algorithm

  1. D-ALGORITHM(C, (ℓ, s))
  2. set every entry to X; faulty entry of ℓ ← s; good entry of ℓ ← ¬s
  3. if D-ALG() then return the good entries of the primary inputs
  4. return "untestable"
  5. D-ALG()
  6. 1apply all implications; if there is a conflict then return false
  7. 2if no primary output has D or D' then
  8. 3if the D-frontier is empty then return false
  9. 4for each gate G of the D-frontier do
  10. 5give each input of G without D or D' the non-controlling value of G in both circuits
  11. 6if there is no conflict and D-ALG() then return true
  12. 7undo the values of this pass
  13. 8return false
  14. 9if the J-frontier is empty then return true
  15. 10(G, m) ← a pair of the J-frontier
  16. 11for each input j of G that is X in circuit m do
  17. 12set j to the controlling value of G in circuit m
  18. 13if D-ALG() then return true
  19. 14undo this pass, and set j to the non-controlling value of G in circuit m
  20. 15return false

The implications of line L1 are the rules that the gates force, in each circuit on its own. Forward, a line whose known inputs fix it gets that value. A primary input other than ℓ\ell has the same entry in both circuits. Backward, the input of a NOT, a BUF or a branch follows from its output. If an AND-type gate has the output that needs all inputs non-controlling, every input gets the non-controlling value. If it has the other output, no input is controlling yet and only one input is X, that input gets the controlling value. Two different values for one entry are a conflict.

Example

The circuit is g=NAND(a,b)g = \mathrm{NAND}(a, b), h=NAND(b,c)h = \mathrm{NAND}(b, c), z=NAND(g,h)z = \mathrm{NAND}(g, h), so z=ab+bcz = ab + bc. The stem bb has the branches bgb_g into gg and bhb_h into hh. The fault is hh stuck at 0, so the start state has h=Dh = D.

call line what happens state
1 L1 faulty z=NAND(X,0)=1z = \mathrm{NAND}(X, 0) = 1 h=Dh = D, zz = (X, 1)
1 L4, L5 D-frontier {z}\{z\}: set the other input gg to 1, the non-controlling value of NAND g=1g = 1
2 L1 good z=NAND(1,1)=0z = \mathrm{NAND}(1, 1) = 0 z=D′z = D'
2 L10 J-frontier: good h=1h = 1 and g=1g = 1 in both circuits, all with X inputs; take good hh
2 L12 set good bhb_h to 0, the controlling value
3 L1 bh=0b_h = 0 gives b=0b = 0, then bg=0b_g = 0 and g=1g = 1 in both circuits b=bg=bh=0b = b_g = b_h = 0
3 L9 J-frontier empty: return true

The answer is the good input values X0X. Every completion detects the fault, since good zz is 0 and faulty zz is 1 whenever b=0b = 0. The search made 3 calls and no backtrack.

A redundant fault shows the failure case. Take na=NOT(a)na = \mathrm{NOT}(a), p=AND(a,b)p = \mathrm{AND}(a, b), q=AND(na,c)q = \mathrm{AND}(na, c), r=AND(b,c)r = \mathrm{AND}(b, c) and z=OR(p,q,r)z = \mathrm{OR}(p, q, r), with rr stuck at 0. Line L1 of the first call justifies good r=1r = 1 backward, so b=c=1b = c = 1 in both circuits. The D-frontier is {z}\{z\}, and line L5 sets p=q=0p = q = 0, the non-controlling value of OR. In the second call, p=0p = 0 with b=1b = 1 forces a=0a = 0, so na=1na = 1 and q=AND(1,1)=1q = \mathrm{AND}(1, 1) = 1, which conflicts with q=0q = 0. The first call undoes the pass, has no other D-frontier gate, and returns false. So the answer is "untestable" after 2 calls and 1 backtrack.

Correctness

The implications write only values that the gate equations force, so they never remove a test. When line L9 returns true, the implications are at a fixpoint and nothing is left to justify, so every known entry follows from the input entries, whatever values the X inputs take, and an output with D or D' really differs. This is soundness.

For completeness, fix a test τ\tau and keep a state whose known entries all match τ\tau. If no output has D or D' yet, take the first line in topological order that differs under τ\tau but has no D or D' in the state. It is a D-frontier gate, and its other inputs do not differ under τ\tau, so under τ\tau they are all non-controlling, which is what line L5 writes. In justification, line L11 tries the inputs in order, and line L14 writes the non-controlling value on each input that failed. So the pass for the first input that τ\tau sets to the controlling value matches τ\tau. Each call makes at least one more entry known, so the depth is at most 2L2L. The full proof gives the details.

Proof: The D-algorithm finds a test exactly when the fault is detectablefull

Let CC be a combinational circuit of AND, OR, NAND, NOR, NOT and BUF gates and fanout branches, with lines in topological order, and let (ℓ,s)(\ell, s) be the fault "line ℓ\ell stuck at ss". A state gives each line kk two entries, SG(k)S_G(k) for the good circuit and SB(k)S_B(k) for the faulty circuit, each in {0,1,X}\{0, 1, X\}. The entry SB(ℓ)S_B(\ell) is fixed: it is always ss, and no rule reads the inputs of ℓ\ell to change it. A line has an effect in SS when both entries are known and differ.

For a two-valued input vector τ\tau, write gτ(k)g_\tau(k) and bτ(k)b_\tau(k) for the values of line kk in the good and the faulty circuit. The state SS agrees with τ\tau when every known entry is the true value: SG(k)≠XS_G(k) \ne X implies SG(k)=gτ(k)S_G(k) = g_\tau(k), and SB(k)≠XS_B(k) \ne X implies SB(k)=bτ(k)S_B(k) = b_\tau(k). Let cv(G)\mathrm{cv}(G) be the controlling value of GG (0 for AND and NAND, 1 for OR and NOR).

The implications of line L1 are these rules, applied in both circuits until nothing changes. Forward: if the known inputs of a line fix its value, set it. A primary input other than ℓ\ell has the same entry in both circuits. Backward at NOT, BUF and branches: the input follows from the output. Backward at an AND-type gate whose output needs all inputs non-controlling: set them all to 1−cv1 - \mathrm{cv}. Backward at an AND-type gate whose output needs some controlling input, when no input is controlling yet: if exactly one input is X, set it to cv\mathrm{cv}, and if none is X, report a conflict. Setting a known entry to the other value is also a conflict. No rule touches the fixed entry.

Lemma 1 (implications are sound). If SS agrees with a detecting vector τ\tau, then line L1 reports no conflict, and the state after it still agrees with τ\tau.

Proof. Each rule writes a value that the gate equations force from known entries. Since the known entries are the true values under τ\tau, the written value is the true value too, and a conflict, two different true values for one entry, cannot occur. The rule for primary inputs holds because only line ℓ\ell differs between the circuits at the inputs. □\square

Lemma 2 (soundness). If line L9 returns true, then every completion of the good values of the primary inputs is a test.

Proof. At line L9 the implications are at a fixpoint, some output has an effect and the J-frontier is empty. So for every entry that is known and not fixed, the known inputs of its line fix it: for a gate this is the empty J-frontier together with the forward rule, and for a branch, NOT or BUF the backward rule has made the input known. Let τ\tau be a completion. We show that SS agrees with τ\tau by induction over the lines in topological order. A primary input other than ℓ\ell has equal known entries in both circuits, and τ\tau gives it that value. The fixed entry is the true faulty value ss. Any other known entry is fixed by known inputs, which have their true values by induction, so it is the true value. So the output with an effect differs under τ\tau. □\square

Lemma 3 (propagation is complete). Let SS be a state after line L1 that agrees with a detecting vector τ\tau, with no output with an effect. Then some gate GG of the D-frontier is such that the values of line L5 for GG agree with τ\tau and make at least one new entry known.

Proof. Some output differs under τ\tau and has no effect in SS. Let GG be the first line in topological order that differs under τ\tau and has no effect in SS. Line ℓ\ell has an effect in SS, since both its entries are known from the start, so G≠ℓG \ne \ell. As in the PODEM proof, a line other than ℓ\ell that differs has an input that differs. Every input of GG that differs comes earlier, so it has an effect in SS. If GG were a branch, NOT or BUF, the forward rule would have copied that effect, so GG is an AND-type gate with an X and an input with an effect, a gate of the D-frontier. Take an input jj of GG with no effect in SS. Then jj does not differ under τ\tau, so gτ(j)=bτ(j)g_\tau(j) = b_\tau(j). Since GG differs, one of the two circuits has GG at its value with no controlling input, and in that circuit every input of GG is at 1−cv(G)1 - \mathrm{cv}(G). So gτ(j)=bτ(j)=1−cv(G)g_\tau(j) = b_\tau(j) = 1 - \mathrm{cv}(G), which is the value line L5 writes in both circuits. Last, GG has an X in some circuit, and the forward rule did not fix it, so some input of GG is X in that circuit. That input has no effect, so line L5 makes it known. □\square

Lemma 4 (justification is complete). Let SS be a state after line L1 that agrees with a detecting vector τ\tau, with an output with an effect and a nonempty J-frontier. Let (G,m)(G, m) be the pair chosen at line L10. Then one pass of the loop of lines L11 to L14 calls D-ALG on a state that agrees with τ\tau and has one more known entry.

Proof. The entry of GG in circuit mm is known but not fixed by the known inputs. If this value needed all inputs at 1−cv1 - \mathrm{cv}, the backward rule would have set them, and the forward rule would fix the output. So it needs some input at cv\mathrm{cv}, no known input has cv\mathrm{cv}, and at least two inputs are X, or the backward rule would have acted. Let j1,…,jtj_1, \ldots, j_t be these X inputs in the order of line L11. Under τ\tau some jij_i is at cv\mathrm{cv} in circuit mm; take the first such ii. For i′<ii' < i, the input ji′j_{i'} is at 1−cv1 - \mathrm{cv} under τ\tau, and this is the value that line L14 writes after the pass for ji′j_{i'} fails. So the state of pass ii is SS with j1,…,ji−1j_1, \ldots, j_{i-1} at 1−cv1 - \mathrm{cv} and jij_i at cv\mathrm{cv}, which agrees with τ\tau. □\square

Theorem. D-ALG stops, with recursion depth at most 2L2L. The D-algorithm returns a vector exactly when the fault is detectable, and every completion of the returned vector is a test.

Proof. Each recursive call of line L6 or line L13 gets a state with at least one more known entry than the state after line L1 of its parent. Line L1 never makes an entry unknown. There are 2L2L entries, so the depth is at most 2L2L, and each call has finitely many children, so the search stops.

If the result is a vector, then line L9 returned true somewhere, the true value passed up to the top, and Lemma 2 applies to the good values of the inputs at that moment, which are the returned values.

Now let τ\tau detect the fault. Then gτ(ℓ)=¬sg_\tau(\ell) = \lnot s, since otherwise the two circuits agree on every line. So the first state, with SG(ℓ)=¬sS_G(\ell) = \lnot s, SB(ℓ)=sS_B(\ell) = s and X elsewhere, agrees with τ\tau. We show by induction on the number of unknown entries that a call on a state that agrees with τ\tau returns true. By Lemma 1, line L1 finds no conflict and keeps agreement. If no output has an effect, Lemma 3 gives a gate of the D-frontier whose child state agrees with τ\tau, and this child returns true by induction. The loop of line L4 restores the state at line L7 after each gate, so it reaches that gate with the same state unless it returns true earlier. If an output has an effect and the J-frontier is empty, line L9 returns true. Otherwise Lemma 4 gives a pass whose child agrees with τ\tau and returns true by induction, and the loop reaches it unless it returns true earlier. So the top call returns true. □\square

Complexity

Line L1 makes passes over all lines until nothing changes. One pass costs O(L+P)O(L + P), where PP is the number of gate input pins, and each pass but the last makes a new entry known, so line L1 costs O(L(L+P))O(L (L + P)). The recursion has depth at most 2L2L, and a call has at most BB children, where BB is bounded by the size of the D-frontier or the fanin of the gate at line L10. So the worst case is O(B2LL(L+P))O(B^{2L} L (L + P)) time. It is exponential in the number of lines, not in the number of inputs as for PODEM. The problem is NP-complete, so no polynomial bound is expected. Each level of the recursion keeps a copy of the 2L2L entries, which is O(L2)O(L^2) extra space.

Properties

  • Complete. For a combinational circuit, the D-algorithm returns a test exactly when the fault is detectable. "Untestable" proves that the fault is redundant.
  • Decisions on internal lines. Lines L5 and L12 set values inside the circuit. This finds tests with few decisions when the paths are clear, but a bad choice may show as a conflict only much later, after many more decisions.
  • Tests with X. The result leaves free inputs at X, which helps test compaction.
  • Deterministic. The order of the D-frontier at line L4 and the choice at line L10 fix the result.
  • No XOR. The rules need a controlling value, so XOR and XNOR gates are expanded first, or need their own D-cubes.

Variants and improvements

  • Roth's cube form. Roth wrote each gate as a singular cover of cubes over its inputs and output, and the propagation through a gate as a propagation D-cube. The fault is a primitive D-cube of failure. A step of the algorithm is the D-intersection of the current test cube with a cube of a gate. The two-circuit form of this page holds the same information in pairs of three-valued entries.
  • D-drive with many paths. Line L5 drives the effect through one gate at a time. Some faults need the effect on several reconvergent paths at once. The algorithm still finds them, because a later pass adds the second path while the first is still open.
  • Better implication. Static learning finds implications such as "a=1a = 1 forces b=0b = 0" before the search, and recursive learning finds them during the search. Both cut the number of conflicts.
  • PODEM and FAN. PODEM makes decisions only on primary inputs, and FAN adds rules on head lines and fanout stems. Both are on the PODEM page.
  • SAT. SAT-based ATPG writes the same constraints as clauses. The implication step of line L1 then becomes unit propagation.

When to use it

Use the D-algorithm to learn and to reason about test generation: its five values, its two frontiers and its implications are the vocabulary of the field, and later algorithms reuse them. For tools, PODEM or FAN, with a SAT engine for the hard faults, is the usual choice, because the D-algorithm can make many conflicting decisions on circuits with much reconvergent fanout.

Pitfalls

  • Deriving the faulty value of the site. The faulty entry of ℓ\ell is ss. If the implications compute it from the inputs of ℓ\ell, they find a false conflict and report a detectable fault as untestable.
  • Too strong a propagation. Line L5 must not write the non-controlling value on an input that already has D or D'. Such an input carries the effect, and forcing it to one value is a conflict that hides a test.
  • Forgetting the second value in justification. After the pass for an input fails, line L14 sets that input to the non-controlling value. This is safe, because every test that the failed pass did not cover has that value there. Without it the search is still complete, but the later passes cannot use the value in their implications and repeat work.
  • Mixing the two circuits. Justification is done per circuit. A good value of 1 on an AND gate needs all its good inputs at 1, but says nothing about its faulty inputs.
  • Reconvergent fanout. An effect that reaches a gate on two paths as D and D' cancels. The implications see it, but only after the values on both paths are known, which is often deep in the search.

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.

d_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/d-algorithm/. The authors are listed in prov/C6DBQN.jsonl.
"""The D-algorithm (Roth 1966) for one single stuck-at fault.

Each line holds a pair (good value, faulty value), each in {0, 1, X}. Roth's
five values are 0 = (0, 0), 1 = (1, 1), D = (1, 0), D' = (0, 1) and X. The
search assigns values to internal lines, not only to primary inputs. It
propagates the fault effect through the D-frontier, then justifies the values
of the J-frontier, and backtracks on a conflict.

The gate types are AND, OR, NAND, NOR, NOT and BUF. Rewrite XOR and XNOR into
these types first.
"""

from __future__ import annotations

from typing import Optional

from gatenet import X, Circuit, Fault, controlling, eval_gate, inversion

GOOD, BAD = 0, 1


class _State:
    """Values of all lines in the good (val[0]) and the faulty (val[1]) circuit."""

    def __init__(self, c: Circuit, fault: Fault) -> None:
        self.c = c
        self.site, self.s = fault
        self.val = [[X] * c.n_lines, [X] * c.n_lines]

    def copy(self) -> list[list[int]]:
        return [self.val[0][:], self.val[1][:]]

    def restore(self, saved: list[list[int]]) -> None:
        self.val = [saved[0][:], saved[1][:]]

    def set(self, m: int, k: int, v: int) -> Optional[bool]:
        """Assign v to line k in circuit m. True if new, False if already so, None on a conflict."""
        cur = self.val[m][k]
        if cur == X:
            self.val[m][k] = v
            return True
        return False if cur == v else None

    def fixed(self, m: int, k: int) -> bool:
        """The faulty value of the fault site does not depend on the inputs of the site."""
        return m == BAD and k == self.site


def _imply_line(st: _State, k: int) -> Optional[bool]:
    """Apply the forward and the backward rules at line k. Returns None on a conflict."""
    c, val = st.c, st.val
    changed = False

    def put(m: int, j: int, v: int) -> bool:
        nonlocal changed
        r = st.set(m, j, v)
        if r is None:
            return False
        changed = changed or r
        return True

    if c.kind[k] == "pi":
        if k != st.site:  # a primary input has the same value in both circuits
            for m in (GOOD, BAD):
                if val[m][k] != X and not put(1 - m, k, val[m][k]):
                    return None
        return changed
    for m in (GOOD, BAD):
        if st.fixed(m, k):
            continue
        ins = c.fanin[k]
        out = eval_gate(c.op[k], [val[m][j] for j in ins])
        if out != X and not put(m, k, out):  # forward
            return None
        w = val[m][k]
        if w == X:
            continue
        op = c.op[k]
        u = w ^ inversion(op)  # the value of the gate before its inversion
        if op in ("NOT", "BUF"):
            if not put(m, ins[0], u):
                return None
            continue
        cv = controlling(op)
        if u == 1 - cv:  # the output is not forced: every input is non-controlling
            for j in ins:
                if not put(m, j, 1 - cv):
                    return None
        else:  # some input must be controlling; if only one can be, it is
            if cv in [val[m][j] for j in ins]:
                continue
            free = [j for j in ins if val[m][j] == X]
            if not free:
                return None
            if len(free) == 1 and not put(m, free[0], cv):
                return None
    return changed


def imply_and_check(st: _State) -> bool:
    """Apply all implications until nothing changes. False on a conflict."""
    while True:
        changed = False
        for k in range(st.c.n_lines):
            r = _imply_line(st, k)
            if r is None:
                return False
            changed = changed or r
        if not changed:
            return True


def _effect(st: _State, k: int) -> bool:
    g, b = st.val[GOOD][k], st.val[BAD][k]
    return g != X and b != X and g != b


def d_frontier(st: _State) -> list[int]:
    """Gate lines that are not fully known and have an input with D or D'."""
    c, val = st.c, st.val
    return [
        k for k in range(c.n_lines)
        if c.kind[k] == "gate" and X in (val[GOOD][k], val[BAD][k])
        and any(_effect(st, j) for j in c.fanin[k])
    ]


def j_frontier(st: _State) -> list[tuple[int, int]]:
    """Pairs (gate line, circuit) whose value is known but not implied by the inputs."""
    c, val = st.c, st.val
    out = []
    for k in range(c.n_lines - 1, -1, -1):
        if c.kind[k] != "gate":
            continue
        for m in (GOOD, BAD):
            if not st.fixed(m, k) and val[m][k] != X and eval_gate(c.op[k], [val[m][j] for j in c.fanin[k]]) == X:
                out.append((k, m))
    return out


def _d_alg(st: _State, stats: dict[str, int]) -> bool:
    stats["calls"] += 1
    if not imply_and_check(st):  # @line L1
        return False
    c = st.c
    if not any(_effect(st, o) for o in c.po):  # @line L2
        frontier = d_frontier(st)
        if not frontier:  # @line L3
            return False
        for gate in frontier:  # @line L4
            cv = controlling(c.op[gate])
            if cv is None:
                continue
            saved = st.copy()
            ok = True
            for j in c.fanin[gate]:  # @line L5
                if not _effect(st, j):  # every input without D or D' gets the non-controlling value
                    for m in (GOOD, BAD):
                        if st.set(m, j, 1 - cv) is None:
                            ok = False
            if ok and _d_alg(st, stats):  # @line L6
                return True
            st.restore(saved)  # @line L7
            stats["backtracks"] += 1
        return False  # @line L8
    jf = j_frontier(st)
    if not jf:  # @line L9
        return True
    gate, m = jf[0]  # @line L10
    cv = controlling(c.op[gate])
    for j in [j for j in c.fanin[gate] if st.val[m][j] == X]:  # @line L11
        saved = st.copy()
        st.val[m][j] = cv  # @line L12
        if _d_alg(st, stats):  # @line L13
            return True
        st.restore(saved)  # @line L14
        st.val[m][j] = 1 - cv  # every test below this node has the other value on j
        stats["backtracks"] += 1
    return False  # @line L15


def d_algorithm(c: Circuit, fault: Fault, stats: Optional[dict[str, int]] = None) -> Optional[tuple[int, ...]]:
    """Return a test for the fault, with X for free inputs, or None if the fault is undetectable.

    Every completion of the X entries detects the fault. The search depth is at
    most 2L, since each call fixes at least one more of the 2L values.
    """
    for op in c.op:
        if op in ("XOR", "XNOR"):
            raise ValueError("rewrite XOR and XNOR into AND, OR and NOT first")
    st = _State(c, fault)
    site, s = fault
    st.val[BAD][site] = s  # the faulty circuit has the stuck value at the site
    st.val[GOOD][site] = 1 - s  # activate the fault: D or D' at the site
    counts = {"calls": 0, "backtracks": 0}
    ok = _d_alg(st, counts)
    if stats is not None:
        stats.update(counts)
    if not ok:
        return None
    return tuple(st.val[GOOD][p] for p in c.pi)
gatenet.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the tv3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate-level combinational circuits with single stuck-at faults.

A circuit is built from named primary inputs, gates in topological order and
named primary outputs. Every place where a fault can sit is a *line*:

- one stem line for each primary input and for each gate output;
- when a net feeds two or more sinks (gate input pins or primary outputs), one
  branch line for each sink. A net with one sink has no branch line, and the
  sink reads the stem.

Lines are numbered 0, 1, ... in topological order, so every line comes after
the lines it reads. A single stuck-at fault is a pair (line, value). Values are
0, 1 and X (unknown), with X = 2. Building a circuit and simulating one vector
take O(L + P) time for L lines and P gate input pins.

This module holds the circuit model, plain simulation of the good circuit and
of one faulty circuit, and brute-force detection over all input vectors. It
holds no test generation or fault simulation algorithm.
"""

from __future__ import annotations

import random
from itertools import product
from typing import Optional, Sequence

X = 2
OPS = ("AND", "OR", "NAND", "NOR", "NOT", "BUF", "XOR", "XNOR")
_CONTROL = {"AND": 0, "NAND": 0, "OR": 1, "NOR": 1}
_INVERT = {"AND": 0, "OR": 0, "NAND": 1, "NOR": 1, "NOT": 1, "BUF": 0, "XOR": 0, "XNOR": 1}

Fault = tuple[int, int]


def controlling(op: str) -> Optional[int]:
    """The controlling input value of a gate type, or None (NOT, BUF, XOR, XNOR)."""
    return _CONTROL.get(op)


def inversion(op: str) -> int:
    """1 if the gate type inverts (NAND, NOR, NOT, XNOR), else 0."""
    return _INVERT[op]


def eval_gate(op: str, vals: Sequence[int]) -> int:
    """Three-valued output of a gate for input values in {0, 1, X}."""
    if op in ("XOR", "XNOR"):
        if X in vals:
            return X
        r = 0
        for v in vals:
            r ^= v
        return r ^ _INVERT[op]
    if op in ("NOT", "BUF"):
        v = vals[0]
        return X if v == X else v ^ _INVERT[op]
    c = _CONTROL[op]
    if c in vals:
        r = c
    elif X in vals:
        return X
    else:
        r = 1 - c
    return r ^ _INVERT[op]


class Circuit:
    """A combinational circuit as a DAG of lines (see the module comment)."""

    def __init__(
        self,
        inputs: Sequence[str],
        gates: Sequence[tuple[str, str, Sequence[str]]],
        outputs: Sequence[str],
    ) -> None:
        nets = list(inputs) + [g[0] for g in gates]
        if len(set(nets)) != len(nets):
            raise ValueError("net names must be unique")
        defined = set(inputs)
        sinks: dict[str, list[tuple[str, int, int]]] = {n: [] for n in nets}
        for gi, (name, op, fanin) in enumerate(gates):
            if op not in OPS:
                raise ValueError(f"unknown gate type {op}")
            if (op in ("NOT", "BUF")) != (len(fanin) == 1) or not fanin:
                raise ValueError(f"wrong number of inputs for {name}")
            for pin, src in enumerate(fanin):
                if src not in defined:
                    raise ValueError(f"{src} is used before it is defined")
                sinks[src].append(("gate", gi, pin))
            defined.add(name)
        for k, src in enumerate(outputs):
            if src not in defined:
                raise ValueError(f"unknown output {src}")
            sinks[src].append(("po", k, 0))

        self.name: list[str] = []
        self.kind: list[str] = []
        self.op: list[str] = []
        self.fanin: list[list[int]] = []
        self.index: dict[str, int] = {}
        pin_line: dict[tuple[str, int, int], int] = {}

        def add(name: str, kind: str, op: str, fanin: list[int]) -> int:
            line = len(self.name)
            self.name.append(name)
            self.kind.append(kind)
            self.op.append(op)
            self.fanin.append(fanin)
            self.index[name] = line
            return line

        def add_net(net: str, kind: str, op: str, fanin: list[int]) -> None:
            stem = add(net, kind, op, fanin)
            sk = sinks[net]
            if len(sk) < 2:
                for s in sk:
                    pin_line[s] = stem
                return
            for s in sk:
                if s[0] == "po":
                    label = f"{net}>out{s[1]}" if len(outputs) > 1 else f"{net}>out"
                else:
                    gname = gates[s[1]][0]
                    same = sum(1 for t in sk if t[0] == "gate" and t[1] == s[1])
                    label = f"{net}>{gname}" + (f".{s[2]}" if same > 1 else "")
                pin_line[s] = add(label, "branch", "BUF", [stem])

        self.pi: list[int] = []
        for net in inputs:
            add_net(net, "pi", "PI", [])
            self.pi.append(self.index[net])
        for gi, (name, op, fanin) in enumerate(gates):
            add_net(name, "gate", op, [pin_line[("gate", gi, p)] for p in range(len(fanin))])
        self.po: list[int] = [pin_line[("po", k, 0)] for k in range(len(outputs))]

        self.n_lines = len(self.name)
        self.fanout: list[list[int]] = [[] for _ in range(self.n_lines)]
        for line in range(self.n_lines):
            for j in self.fanin[line]:
                self.fanout[j].append(line)
        self.level = [0] * self.n_lines
        for line in range(self.n_lines):
            if self.fanin[line]:
                self.level[line] = 1 + max(self.level[j] for j in self.fanin[line])

    def line(self, name: str) -> int:
        return self.index[name]

    def faults(self) -> list[Fault]:
        """All 2L single stuck-at faults, in line order."""
        return [(line, v) for line in range(self.n_lines) for v in (0, 1)]

    def fault_name(self, fault: Fault) -> str:
        return f"{self.name[fault[0]]}/{fault[1]}"

    def simulate(self, vector: Sequence[int], fault: Optional[Fault] = None) -> list[int]:
        """Values of all lines for one input vector (entries 0, 1 or X), with an optional fault."""
        vals = [X] * self.n_lines
        k = 0
        for line in range(self.n_lines):
            if self.kind[line] == "pi":
                v = vector[k]
                k += 1
            else:
                v = eval_gate(self.op[line], [vals[j] for j in self.fanin[line]])
            if fault is not None and fault[0] == line:
                v = fault[1]
            vals[line] = v
        return vals

    def outputs(self, vector: Sequence[int], fault: Optional[Fault] = None) -> tuple[int, ...]:
        vals = self.simulate(vector, fault)
        return tuple(vals[o] for o in self.po)

    def detects(self, vector: Sequence[int], fault: Fault) -> bool:
        """True if some output has a known value in both circuits and the values differ."""
        good = self.outputs(vector)
        bad = self.outputs(vector, fault)
        return any(g != X and b != X and g != b for g, b in zip(good, bad))

    def all_vectors(self) -> list[tuple[int, ...]]:
        return list(product((0, 1), repeat=len(self.pi)))

    def detecting_vectors(self, fault: Fault) -> list[tuple[int, ...]]:
        """Brute force: every two-valued input vector that detects the fault."""
        return [v for v in self.all_vectors() if self.detects(v, fault)]

    def detectable(self, fault: Fault) -> bool:
        return any(self.detects(v, fault) for v in self.all_vectors())

    def cone(self, line: int) -> set[int]:
        """The lines reachable from a line, the line included."""
        seen = {line}
        stack = [line]
        while stack:
            u = stack.pop()
            for w in self.fanout[u]:
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
        return seen


def completions(vector: Sequence[int]) -> list[tuple[int, ...]]:
    """All two-valued vectors that agree with a vector that may hold X."""
    choices = [(0, 1) if v == X else (v,) for v in vector]
    return list(product(*choices))


def random_circuit(
    rng: random.Random,
    n_inputs: int,
    n_gates: int,
    ops: Sequence[str] = ("AND", "OR", "NAND", "NOR", "NOT"),
    max_fanin: int = 3,
) -> Circuit:
    """A random circuit. Every net with no sink becomes a primary output."""
    inputs = [f"i{k}" for k in range(n_inputs)]
    nets = list(inputs)
    gates: list[tuple[str, str, list[str]]] = []
    for k in range(n_gates):
        op = rng.choice(list(ops))
        arity = 1 if op in ("NOT", "BUF") else rng.randint(2, max(2, min(max_fanin, len(nets))))
        arity = min(arity, len(nets))
        if op not in ("NOT", "BUF") and arity < 2:
            op, arity = "NOT", 1
        fanin = rng.sample(nets, arity)
        name = f"g{k}"
        gates.append((name, op, fanin))
        nets.append(name)
    used = {src for _, _, fanin in gates for src in fanin}
    outputs = [n for n in nets if n not in used]
    extra = [g[0] for g in gates if g[0] in used]
    if extra and rng.random() < 0.5:
        outputs.append(rng.choice(extra))
    return Circuit(inputs, gates, outputs)
test_d_algorithm.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/d-algorithm/. The authors are listed in prov/C6DBQN.jsonl.

import random

import pytest

from d_algorithm import d_algorithm
from gatenet import X, Circuit, completions, random_circuit

# The circuit of the page: z = NAND(NAND(a, b), NAND(b, c)) = ab + bc.
C3 = Circuit(["a", "b", "c"], [("g", "NAND", ["a", "b"]), ("h", "NAND", ["b", "c"]), ("z", "NAND", ["g", "h"])], ["z"])

C17 = Circuit(
    ["1", "2", "3", "6", "7"],
    [
        ("10", "NAND", ["1", "3"]),
        ("11", "NAND", ["3", "6"]),
        ("16", "NAND", ["2", "11"]),
        ("19", "NAND", ["11", "7"]),
        ("22", "NAND", ["10", "16"]),
        ("23", "NAND", ["16", "19"]),
    ],
    ["22", "23"],
)

# z = ab + a'c + bc. The term bc is the consensus of the other two, so its AND gate is redundant.
CONSENSUS = Circuit(
    ["a", "b", "c"],
    [
        ("na", "NOT", ["a"]),
        ("p", "AND", ["a", "b"]),
        ("q", "AND", ["na", "c"]),
        ("r", "AND", ["b", "c"]),
        ("z", "OR", ["p", "q", "r"]),
    ],
    ["z"],
)


def check_against_brute_force(c, fault):
    stats = {}
    t = d_algorithm(c, fault, stats=stats)
    if t is None:
        assert not c.detectable(fault)
    else:
        assert len(t) == len(c.pi)
        assert all(c.detects(v, fault) for v in completions(t))


def test_page_example_h_stuck_at_0():
    fault = (C3.line("h"), 0)
    t = d_algorithm(C3, fault)
    assert t is not None
    assert set(completions(t)) <= set(C3.detecting_vectors(fault))


def test_page_example_traces():
    stats = {}
    assert d_algorithm(C3, (C3.line("h"), 0), stats=stats) == (X, 0, X)
    assert stats == {"calls": 3, "backtracks": 0}
    stats = {}
    assert d_algorithm(CONSENSUS, (CONSENSUS.line("r"), 0), stats=stats) is None
    assert stats == {"calls": 2, "backtracks": 1}


def test_c3_all_faults():
    for fault in C3.faults():
        check_against_brute_force(C3, fault)


def test_c17_all_faults():
    for fault in C17.faults():
        assert d_algorithm(C17, fault) is not None
        check_against_brute_force(C17, fault)


def test_redundant_fault_has_no_test():
    fault = (CONSENSUS.line("r"), 0)
    assert not CONSENSUS.detectable(fault)
    assert d_algorithm(CONSENSUS, fault) is None
    for f in CONSENSUS.faults():
        check_against_brute_force(CONSENSUS, f)


def test_xor_is_rejected():
    c = Circuit(["a", "b"], [("z", "XOR", ["a", "b"])], ["z"])
    with pytest.raises(ValueError):
        d_algorithm(c, (c.line("z"), 0))


@pytest.mark.parametrize("seed", range(60))
def test_random_circuits_against_brute_force(seed):
    rng = random.Random(seed)
    c = random_circuit(rng, rng.randint(2, 7), rng.randint(2, 10), ops=("AND", "OR", "NAND", "NOR", "NOT", "BUF"))
    for fault in c.faults():
        check_against_brute_force(c, fault)

History

Roth published the D-calculus and the D-algorithm in 1966, while at IBM, and with Bouricius and Schneider gave programmed versions in 1967. It was the first test generation method that is proved to find a test for every detectable single stuck-at fault in a combinational circuit, and its terms (D, D', D-frontier, justification and implication) became the standard ones. Goel's PODEM of 1981 moved the decisions to the primary inputs, and the NP-completeness results of Ibarra and Sahni (1975) and Fujiwara and Toida (1982) showed that no method is expected to avoid exponential cases.

References

  1. J. P. Roth, Diagnosis of automata failures, a calculus and a method, IBM Journal of Research and Development 10(4), 278 to 291, 1966, the D-calculus, the singular cover and the D-cubes, D-intersection, and the D-algorithm with its D-drive and consistency steps
  2. Michael L. Bushnell and Vishwani D. Agrawal, Essentials of Electronic Testing for Digital, Memory and Mixed-Signal VLSI Circuits, Kluwer, 2000, the chapter Combinational Circuit Test Generation (Roth's five values, the D-frontier, the J-frontier and the D-algorithm)
  3. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on test generation for combinational circuits (the D-algorithm, implication and the two frontiers)

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.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example