Algorithm Search⌘K

Algorithmcore

PODEM

Also called path-oriented decision making.

Goel's ATPG that decides values on primary inputs only, backtraces each objective to an input and simulates forward, so the search tree has at most 2^(n+1) - 1 nodes.

Time
O(2^n (L + P)) worstO(L + P) best
Space
O(L + n) extra
Where
L = the number of lines; P = the number of gate input pins; n = the number of primary inputs
Properties
completedeterministicexactiterative
Origin
Prabhakar Goel, 1981

PODEM (path-oriented decision making) is an algorithm for automatic test pattern generation. Given a combinational circuit and one single stuck-at fault, it finds an input vector that detects the fault, or proves that no such vector exists. Unlike the D-algorithm, it makes decisions only on the primary inputs. It turns each goal on an internal line into an input value by a backtrace, then finds all consequences by simulation, so it never meets an inconsistent internal value and its search tree has at most 2n+1−12^{n+1} - 1 nodes for nn inputs.

In plain words

You want a fault inside a circuit to show at an output. First the faulty line must get the value opposite to its stuck value. Then the difference must travel through gates to an output.

PODEM only ever sets the circuit inputs. It picks a goal, such as "this line must be 1", and walks back from that line through gates that are still unknown until it reaches an input that is still open. It sets that input to the value that helps the goal, then simulates the good and the faulty circuit to see what is now known.

If a difference reaches an output, it is done. If the fault can no longer show, it flips the last input it chose. When both values of that input fail, it frees the input and goes back one more step.

The problem

The input is a combinational circuit CC with nn primary inputs and LL lines, in topological order, and a fault (ℓ,s)(\ell, s): line ℓ\ell is stuck at s∈{0,1}s \in \{0, 1\}. The lines are the outputs of the primary inputs and gates and the fanout branches. The output is a vector over {0,1,X}\{0, 1, X\} such that every two-valued completion of it detects the fault, or the answer "untestable" if no input vector detects it.

Each line holds a pair (good value, faulty value), each in {0,1,X}\{0, 1, X\}. Roth's five values name these pairs: 0=(0,0)0 = (0, 0), 1=(1,1)1 = (1, 1), D=(1,0)D = (1, 0), D′=(0,1)D' = (0, 1), and X for any pair with an X. The D-frontier is the set of gates whose output has an X and that have an input with D or D'. An X-path is a path of lines that all have an X.

The algorithm

  1. PODEM(C, (ℓ, s))
  2. 1set every primary input to X; stack ← empty
  3. 2loop
  4. 3simulate the good and the faulty circuit with three values
  5. 4if some primary output has D or D' then return the input values
  6. 5if ℓ is not at s in the good circuit and (ℓ has X or some D-frontier gate has an X-path to an output) then
  7. 6(k, v) ← OBJECTIVE()
  8. 7(p, u) ← BACKTRACE(k, v)
  9. 8set input p to u; push (p, u, not flipped)
  10. 9else
  11. 10pop each entry that is flipped and set its input to X
  12. 11if the stack is empty then return "untestable"
  13. 12flip the value of the top entry, set its input to it, and mark it flipped
  14. OBJECTIVE()
  15. 13if the good value of ℓ is X then return (ℓ, ¬s)
  16. 14G ← a gate of the D-frontier with an X-path to an output
  17. 15j ← an input of G with value X
  18. 16return (j, the non-controlling value of G)
  19. BACKTRACE(k, v)
  20. 17while k is not a primary input do
  21. 18j ← an input of k with value X
  22. 19u ← v xor inversion(k)
  23. 20(k, v) ← (j, u)
  24. 21return (k, v)

Here inversion(k) is 1 for NAND, NOR and NOT and 0 for the other gates and for fanout branches. For an XOR gate, line L16 asks for 0 and line L19 passes the wanted value on unchanged. Any choice at lines L14, L15 and L18 is correct. The choice only changes how fast the search ends, and the usual guide is SCOAP: line L18 takes the easiest input when one input value is enough and the hardest input when all inputs need the value.

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.

pass inputs abcabc values line action
1 XXX all X L13 objective (h,1)(h, 1); backtrace: hh is a NAND, so bh=0b_h = 0, then b=0b = 0
2 X0X b=bg=bh=0b = b_g = b_h = 0, g=1g = 1, h=Dh = D, z=D′z = D' L4 return X0X

Every completion of X0X, that is 000, 001, 100 and 101, detects hh stuck at 0, and so does 010, which PODEM did not need.

A second circuit shows a backtrack. It is 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), so z=ab+aˉc+bcz = ab + \bar{a}c + bc. The fault is aa stuck at 0, and the choices take the first candidate each time.

pass inputs abcabc values action
1 XXX all X objective (a,1)(a, 1), which is an input: set a=1a = 1
2 1XX a=Da = D, na=D′na = D', D-frontier {p,q}\{p, q\} objective: the input bb of pp to 1; set b=1b = 1
3 11X p=Dp = D, D-frontier {q,z}\{q, z\} objective: the input cc of qq to 1; set c=1c = 1
4 111 p=Dp = D, q=D′q = D', r=1r = 1, z=1z = 1 no D-frontier is left: flip cc to 0
5 110 p=Dp = D, q=0q = 0, r=0r = 0, z=Dz = D return 110

Pass 3 chose a gate on the wrong side of the reconvergent fanout of aa: through qq, the effect arrives at zz with the opposite sign. Simulation finds this at once, and one flip repairs it.

On the same circuit the fault rr stuck at 0 is redundant, because bcbc is the consensus of abab and aˉc\bar{a}c. PODEM makes 7 passes and 3 flips: it sets b=1b = 1 and c=1c = 1, so r=Dr = D, and then any value of aa makes pp or qq equal to 1, which blocks zz. With c=0c = 0 or b=0b = 0, the line rr is at its stuck value. The stack becomes empty, and PODEM answers "untestable".

Correctness

Three facts make PODEM correct. First, three-valued simulation never claims a value that some completion contradicts, so the vector returned by line L4 is a test whatever values the X inputs take. Second, the test of line L5 fails only when no completion of the current inputs is a test. If the site is at its stuck value, the two circuits agree on every line. Otherwise, any test has a path of differing lines from ℓ\ell to an output, and the first line on it after the last line with D or D' is a D-frontier gate with an X-path. Third, lines L6 and L7 always find an unassigned input, so each pass goes one level deeper in a binary tree of depth at most nn. The search walks this tree depth first and prunes only subtrees with no test. If a test exists, the branch that agrees with it is never pruned, and PODEM returns before the stack is empty. The full proof gives the details.

Proof: PODEM returns a test exactly when the fault is detectablefull

Let CC be a combinational circuit with nn primary inputs and lines in topological order, and let (ℓ,s)(\ell, s) be the fault "line ℓ\ell stuck at ss". An assignment AA gives each primary input a value in {0,1,X}\{0, 1, X\}. Line L3 computes, for each line kk, a good value gA(k)g_A(k) and a faulty value bA(k)b_A(k) by three-valued simulation. In the faulty circuit, line ℓ\ell has the value ss whatever its inputs are. A line has an effect under AA when gA(k)g_A(k) and bA(k)b_A(k) are both in {0,1}\{0, 1\} and differ, that is, when it carries D or D'. A line has an X when gA(k)=Xg_A(k) = X or bA(k)=Xb_A(k) = X. A completion of AA is an assignment with values in {0,1}\{0, 1\} only that agrees with AA wherever AA is not X. A two-valued vector τ\tau detects the fault when some primary output has gτ(o)≠bτ(o)g_\tau(o) \ne b_\tau(o).

Fact (three-valued simulation). The three-valued rules for AND, OR, NAND, NOR, NOT, BUF, XOR and XNOR give X exactly when the output is not fixed by the inputs that are not X. So if A′A' is a completion of AA and gA(k)≠Xg_A(k) \ne X, then gA′(k)=gA(k)g_{A'}(k) = g_A(k), and the same holds for bb. On two-valued inputs the rules give the true values.

Proof. Induction over the lines in topological order, with the gate rules checked one by one. □\square

Lemma 1 (paths of differences). Let τ\tau be a two-valued vector that detects the fault at output oo. Then there are lines ℓ=p0,p1,…,pr=o\ell = p_0, p_1, \ldots, p_r = o, each pi+1p_{i+1} a fanout of pip_i, with gτ(pi)≠bτ(pi)g_\tau(p_i) \ne b_\tau(p_i) for every ii.

Proof. A primary input other than ℓ\ell has the same value in both circuits. A line k≠ℓk \ne \ell that is not a primary input has the same gate in both circuits, so if all its inputs agree, then kk agrees. So every line k≠ℓk \ne \ell with gτ(k)≠bτ(k)g_\tau(k) \ne b_\tau(k) has an input with the same property. Start at oo and step to such an input until the walk reaches ℓ\ell. The walk stops, because the lines are in topological order, and it can stop only at ℓ\ell. Reverse it. □\square

Lemma 2 (soundness of line L4). If line L4 returns AA, then every completion of AA detects the fault.

Proof. Some output oo has an effect under AA. By the Fact, every completion A′A' has gA′(o)=gA(o)≠bA(o)=bA′(o)g_{A'}(o) = g_A(o) \ne b_A(o) = b_{A'}(o). □\square

Lemma 3 (safe pruning at line L5). If the test of line L5 fails for AA, then no completion of AA detects the fault.

Proof. The test fails in two cases.

Case 1: gA(ℓ)=sg_A(\ell) = s. By the Fact, every completion τ\tau has gτ(ℓ)=s=bτ(ℓ)g_\tau(\ell) = s = b_\tau(\ell). Then the two circuits have the same value on every line, by induction in topological order, and τ\tau detects nothing.

Case 2: gA(ℓ)=¬sg_A(\ell) = \lnot s, and no gate of the D-frontier has an X-path, that is, a path of lines that all have an X, from the gate to a primary output. Suppose that a completion τ\tau detects the fault at oo, and take the path p0,…,prp_0, \ldots, p_r of Lemma 1. Line p0=ℓp_0 = \ell has an effect under AA. Line oo has none, since line L4 did not return. Let jj be the largest index such that pjp_j has an effect under AA, so j<rj < r. For i>ji > j, line pip_i differs under τ\tau, so by the Fact it cannot have two equal known values under AA, and it has no effect. So pip_i has an X. Line pj+1p_{j+1} is not a fanout branch: a branch copies its stem in both circuits, and pj+1≠ℓp_{j+1} \ne \ell, so it would have the effect of pjp_j. So pj+1p_{j+1} is a gate with an X and an input with an effect, which is a gate of the D-frontier, and pj+1,…,prp_{j+1}, \ldots, p_r is an X-path from it to an output. This contradicts the case. □\square

Lemma 4 (the objective and the backtrace are defined). When the test of line L5 holds and line L4 did not return, line L6 returns a line with an X, and line L7 returns a primary input whose value in AA is X.

Proof. If gA(ℓ)=Xg_A(\ell) = X, line L13 returns ℓ\ell, which has an X. Otherwise, case 2 of Lemma 3 does not hold, so some D-frontier gate GG has an X-path. A gate with an X has an input with an X, because a gate whose inputs are all known in a circuit is known in that circuit, except for the faulty value of ℓ\ell, which is always ss. So line L15 finds an input jj with an X. The same argument shows that the loop of lines L17 to L20 always finds an input with an X at line L18, and that it moves to an earlier line each time, so it stops at a primary input pp that has an X. Since bA(p)=sb_A(p) = s when p=ℓp = \ell, the X of pp is its good value, and the good value of a primary input is its value in AA. □\square

Lemma 5 (the search tree). The stack holds entries for distinct primary inputs, and the values of AA are X exactly at the inputs without an entry. Each pass of the loop of line L2 visits a different node of a binary tree of depth at most nn, so the loop runs at most 2n+1−12^{n+1} - 1 times.

Proof. Line L8 assigns an input with value X, by Lemma 4, and pushes it. Lines L10 and L12 pop entries and reset their inputs to X, or flip the top entry. So the stack is a path from the root of a tree whose nodes are the stacks, and each entry adds one input, which bounds the depth by nn. The choice at lines L6 and L7 depends only on AA, which the stack fixes, so each node has at most the two children "first value" and "flipped value". Line L12 moves from the first child of a node to the second, and line L10 leaves a node only after both of its children are done. This is a depth-first walk in which each node is entered once. A binary tree of depth nn has at most 2n+1−12^{n+1} - 1 nodes. □\square

Theorem. PODEM stops. It returns an assignment exactly when the fault is detectable, and then every completion of the assignment detects the fault. It returns "untestable" exactly when the fault is redundant.

Proof. It stops by Lemma 5. A returned assignment is a test by Lemma 2, and then the fault is detectable. Now suppose that a two-valued vector τ\tau detects the fault, and follow the nodes of the tree whose assignments agree with τ\tau, starting at the root, where every input is X. At such a node, either line L4 returns, or the test of line L5 holds by Lemma 3, since τ\tau is a completion. In the second case lines L6 to L8 assign one more input, and one of the two children agrees with τ\tau. The search enters both children before it leaves the node, so it reaches that child unless it returns first. The depth is at most nn, and at depth nn the assignment is τ\tau, where line L4 returns. So PODEM returns an assignment before the stack can become empty at line L11. □\square

Complexity

Each node of the search tree costs two simulations, the D-frontier, one sweep of the lines in reverse order to mark the X-paths, and a backtrace of at most LL steps, so O(L+P)O(L + P) time, where PP is the number of gate input pins. The tree has at most 2n+1−12^{n+1} - 1 nodes, so the worst case is O(2n(L+P))O(2^n (L + P)) time. This is exponential, and no polynomial bound is expected, because the problem is NP-complete. The best case is one simulation, when the first backtrace already gives a test. The extra space is the stack of at most nn entries and the values of the lines, O(L+n)O(L + n).

The D-algorithm branches on internal lines, so the depth of its search tree is bounded by the number of line values, 2L2L, and not by nn. Goel's argument for PODEM was this smaller space and the absence of conflicts on internal lines. How much faster PODEM runs is a measured result on benchmark circuits, not a theorem.

Properties

  • Complete. For a combinational circuit, PODEM returns a test exactly when the fault is detectable, so "untestable" is a proof of redundancy.
  • Decisions on inputs only. Every value on an internal line comes from simulation, so internal lines never hold values that conflict with each other.
  • Tests with X. The returned vector can leave inputs at X. These free inputs help test compaction, where one vector is made to detect several faults.
  • Deterministic. The choice rules of lines L14, L15 and L18 fix the output.
  • Combinational only. For a sequential circuit, PODEM needs scan design, or a time frame expansion that unrolls the circuit.

Variants and improvements

  • SCOAP guidance. Pick the D-frontier gate with the best observability, and backtrace through the input that is easiest or hardest to control, as on the SCOAP page. This changes the order of the search, not its result.
  • FAN. Fujiwara and Shimono (1983) keep decisions on a small set of lines but add four rules. Head lines are lines that no fanout reaches from behind, and backtrace stops at them, because a head line can always be justified later. Multiple backtrace sends several objectives back at once and counts how many want 0 or 1 at each fanout stem. Unique sensitization sets the side inputs of gates through which every path from the D-frontier must pass. Immediate implications fix forced values before the next decision.
  • Learning. Later systems such as SOCRATES (Schulz, Trischler and Sarfert, 1988) find implications in a preprocessing pass, for example that a=1a = 1 forces b=0b = 0 through reconvergent fanout, and add them to simulation.
  • SAT solvers. SAT-based ATPG gives the same problem to a CDCL solver, which learns clauses from conflicts. PODEM is close to DPLL with decisions on the input variables only.
  • Sequential circuits. Unroll the circuit over several clock cycles and run PODEM on the unrolled copy, or use full scan so that every flip-flop becomes an input and an output.

When to use it

Use PODEM, or one of its descendants such as FAN, for test generation on combinational logic or on the combinational part of a full scan design. It is a standard choice in teaching and a common base in tools, with a fault simulator that removes the faults each new test also detects. For faults that it aborts after a backtrack limit, often redundant ones, a SAT-based engine is the usual second step, since it proves redundancy better.

Pitfalls

  • A wrong X-path check. Line L5 must look for a path of X lines from a D-frontier gate to an output. Without it, the search goes deep below a dead node and finds the dead end only at the leaves.
  • Stopping at the first D-frontier gate. A gate of the D-frontier can be blocked while another one is still open. The X-path check must look at all of them, or the search prunes a node that still has a test.
  • Forgetting the inversion. Line L19 must flip the wanted value at each inverting gate. A backtrace that ignores it still terminates but sets inputs to the wrong values and needs many more flips.
  • Treating "untestable" as a bug. A redundant fault has no test. PODEM proves this only by exhausting the tree, so tools stop at a backtrack limit and report the fault as aborted, which is not the same as redundant.
  • Fanout branches. Faults on a stem and on its branches are different faults. A circuit model without branch lines cannot target a branch fault.

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.

gatenet.pyI0RawGitHub
# 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)
podem.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/podem/. The authors are listed in prov/FHMN9N.jsonl.
"""PODEM (Goel 1981): test generation for one single stuck-at fault by search over primary inputs.

The value of a line is the pair (good value, faulty value), each in {0, 1, X}.
The five values of Roth are 0 = (0, 0), 1 = (1, 1), D = (1, 0), D' = (0, 1),
and X for every pair with an X in it.
"""

from __future__ import annotations

from typing import Optional

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


def is_effect(g: int, b: int) -> bool:
    """True for D or D': both values known and different."""
    return g != X and b != X and g != b


def d_frontier(c: Circuit, good: list[int], bad: list[int]) -> list[int]:
    """Gate lines whose value is X and that have an input with D or D'."""
    return [
        k
        for k in range(c.n_lines)
        if c.kind[k] == "gate"
        and X in (good[k], bad[k])
        and any(is_effect(good[j], bad[j]) for j in c.fanin[k])
    ]


def x_paths(c: Circuit, good: list[int], bad: list[int], is_po: list[bool]) -> list[bool]:
    """For each line with value X: True if a path of lines with value X leads from it to a primary output.

    One sweep in reverse topological order, O(L + P) time.
    """
    xp = [False] * c.n_lines
    for k in range(c.n_lines - 1, -1, -1):
        if X in (good[k], bad[k]):
            xp[k] = is_po[k] or any(xp[w] for w in c.fanout[k])
    return xp


def controllability(c: Circuit) -> tuple[list[int], list[int]]:
    """SCOAP combinational controllabilities CC0 and CC1 of every line (Goldstein 1979)."""
    cc0 = [0] * c.n_lines
    cc1 = [0] * c.n_lines
    for k in range(c.n_lines):
        op, ins = c.op[k], c.fanin[k]
        if c.kind[k] == "pi":
            cc0[k], cc1[k] = 1, 1
        elif c.kind[k] == "branch":
            cc0[k], cc1[k] = cc0[ins[0]], cc1[ins[0]]
        elif op in ("NOT", "BUF"):
            a0, a1 = cc0[ins[0]] + 1, cc1[ins[0]] + 1
            cc0[k], cc1[k] = (a1, a0) if op == "NOT" else (a0, a1)
        elif op in ("XOR", "XNOR"):
            e0, e1 = cc0[ins[0]], cc1[ins[0]]  # cost of even and odd parity so far
            for j in ins[1:]:
                e0, e1 = min(e0 + cc0[j], e1 + cc1[j]), min(e0 + cc1[j], e1 + cc0[j])
            cc0[k], cc1[k] = (e0 + 1, e1 + 1) if op == "XOR" else (e1 + 1, e0 + 1)
        else:
            cv = controlling(op)
            one = min((cc0, cc1)[cv][j] for j in ins) + 1  # one input at the controlling value
            alls = sum((cc0, cc1)[1 - cv][j] for j in ins) + 1  # all inputs non-controlling
            out_c = cv ^ inversion(op)  # output value forced by a controlling input
            if out_c == 0:
                cc0[k], cc1[k] = one, alls
            else:
                cc1[k], cc0[k] = one, alls
    return cc0, cc1


def objective(c: Circuit, good: list[int], bad: list[int], fault: Fault, is_po: list[bool]) -> tuple[int, int]:
    """The next goal (line, value): activate the fault, else advance the D-frontier."""
    site, s = fault
    if good[site] == X:  # @line L13
        return site, 1 - s
    xp = x_paths(c, good, bad, is_po)
    for gate in d_frontier(c, good, bad):  # @line L14
        if xp[gate]:
            for j in c.fanin[gate]:  # @line L15
                if X in (good[j], bad[j]):
                    cv = controlling(c.op[gate])
                    return j, 0 if cv is None else 1 - cv  # @line L16
    raise AssertionError("objective called when no test is possible")


def backtrace(
    c: Circuit, good: list[int], bad: list[int], k: int, v: int,
    cc: Optional[tuple[list[int], list[int]]] = None,
) -> tuple[int, int]:
    """Walk from an objective back to an unassigned primary input along lines with value X."""
    while c.kind[k] != "pi":  # @line L17
        op = c.op[k]
        cand = [j for j in c.fanin[k] if X in (good[j], bad[j])]  # @line L18
        u = v ^ inversion(op)  # @line L19: the value wanted at the inputs of k
        if cc is None or len(cand) == 1:
            j = cand[0]
        elif controlling(op) is not None and u == controlling(op):
            j = min(cand, key=lambda t: cc[u][t])  # one input is enough: take the easiest
        else:
            j = max(cand, key=lambda t: cc[u][t])  # all inputs are needed: take the hardest
        k, v = j, u  # @line L20
    return k, v  # @line L21


def test_possible(c: Circuit, good: list[int], bad: list[int], fault: Fault, is_po: list[bool]) -> bool:
    """False only if no completion of the current input values can detect the fault."""
    site, s = fault
    if good[site] == s:
        return False
    if good[site] == X:
        return True
    xp = x_paths(c, good, bad, is_po)
    return any(xp[g] for g in d_frontier(c, good, bad))


def podem(
    c: Circuit,
    fault: Fault,
    guided: bool = False,
    stats: Optional[dict[str, int]] = None,
) -> Optional[tuple[int, ...]]:
    """Return a test for the fault, with X for inputs that may take any value, or None.

    None means that the fault is undetectable (redundant). With guided=True the
    backtrace picks inputs by SCOAP controllability. The search visits at most
    2^(n+1) - 1 nodes for n primary inputs, and each node costs O(L + P) time.
    """
    pi_pos = {line: k for k, line in enumerate(c.pi)}
    is_po = [False] * c.n_lines
    for o in c.po:
        is_po[o] = True
    cc = controllability(c) if guided else None
    assign = [X] * len(c.pi)  # @line L1
    stack: list[list[int]] = []  # entries [input position, value, 1 if both values were tried]
    steps = backtracks = 0
    while True:  # @line L2
        steps += 1
        good = c.simulate(assign)  # @line L3
        bad = c.simulate(assign, fault)
        if any(is_effect(good[o], bad[o]) for o in c.po):  # @line L4
            if stats is not None:
                stats.update(steps=steps, backtracks=backtracks)
            return tuple(assign)
        if test_possible(c, good, bad, fault, is_po):  # @line L5
            k, v = objective(c, good, bad, fault, is_po)  # @line L6
            p, u = backtrace(c, good, bad, k, v, cc)  # @line L7
            assign[pi_pos[p]] = u  # @line L8
            stack.append([pi_pos[p], u, 0])
        else:  # @line L9
            while stack and stack[-1][2]:  # @line L10
                assign[stack.pop()[0]] = X
            if not stack:  # @line L11
                if stats is not None:
                    stats.update(steps=steps, backtracks=backtracks)
                return None
            top = stack[-1]  # @line L12
            top[1], top[2] = 1 - top[1], 1
            assign[top[0]] = top[1]
            backtracks += 1
test_podem.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/podem/. The authors are listed in prov/FHMN9N.jsonl.

import random

import pytest

from gatenet import X, Circuit, completions, random_circuit
from podem import backtrace, controllability, podem

# 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, guided):
    stats = {}
    t = podem(c, fault, guided=guided, stats=stats)
    assert stats["steps"] <= 2 ** (len(c.pi) + 1)
    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 = podem(C3, fault)
    assert t is not None
    assert all(C3.detects(v, fault) for v in completions(t))
    assert set(completions(t)) <= set(C3.detecting_vectors(fault))
    assert sorted(C3.detecting_vectors(fault)) == [(0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 0, 0), (1, 0, 1)]


def test_page_example_traces():
    stats = {}
    assert podem(C3, (C3.line("h"), 0), stats=stats) == (X, 0, X)
    assert stats == {"steps": 2, "backtracks": 0}
    stats = {}
    assert podem(CONSENSUS, (CONSENSUS.line("a"), 0), stats=stats) == (1, 1, 0)
    assert stats == {"steps": 5, "backtracks": 1}
    stats = {}
    assert podem(CONSENSUS, (CONSENSUS.line("r"), 0), stats=stats) is None
    assert stats == {"steps": 7, "backtracks": 3}


@pytest.mark.parametrize("guided", [False, True])
def test_c3_all_faults(guided):
    for fault in C3.faults():
        check_against_brute_force(C3, fault, guided)


@pytest.mark.parametrize("guided", [False, True])
def test_c17_all_faults(guided):
    assert C17.n_lines == 17
    for fault in C17.faults():
        assert podem(C17, fault, guided=guided) is not None
        check_against_brute_force(C17, fault, guided)


def test_redundant_fault_has_no_test():
    fault = (CONSENSUS.line("r"), 0)
    assert not CONSENSUS.detectable(fault)
    assert podem(CONSENSUS, fault) is None
    assert podem(CONSENSUS, fault, guided=True) is None


def test_scoap_values_of_page_example():
    cc0, cc1 = controllability(C3)
    by_name = {C3.name[k]: (cc0[k], cc1[k]) for k in range(C3.n_lines)}
    assert by_name["a"] == (1, 1)
    assert by_name["g"] == (3, 2)
    assert by_name["z"] == (5, 4)


def test_backtrace_ends_at_unassigned_input():
    good = C17.simulate([X] * 5)
    for k in range(C17.n_lines):
        for v in (0, 1):
            p, u = backtrace(C17, good, good, k, v)
            assert C17.kind[p] == "pi" and u in (0, 1)


@pytest.mark.parametrize("seed", range(40))
def test_random_circuits_against_brute_force(seed):
    rng = random.Random(seed)
    ops = ("AND", "OR", "NAND", "NOR", "NOT", "XOR", "XNOR", "BUF") if seed % 2 else ("AND", "OR", "NAND", "NOR", "NOT")
    c = random_circuit(rng, rng.randint(2, 7), rng.randint(2, 9), ops=ops)
    for fault in c.faults():
        check_against_brute_force(c, fault, guided=bool(seed % 3 == 0))

History

Roth's D-algorithm of 1966 assigned values to internal lines and spent much time on conflicts between them. Goel (1981), at IBM, noticed that the values of all lines follow from the inputs, and called his method an implicit enumeration of the input space. He showed that it worked on error correction and translation circuits, which have much reconvergent XOR logic and were hard for the D-algorithm. Fujiwara and Shimono (1983) improved it to FAN. The search over inputs with forward simulation stayed the core of structural test generation, and SAT-based engines took over the hard faults from about 1990.

References

  1. P. Goel, An implicit enumeration algorithm to generate tests for combinational logic circuits, IEEE Transactions on Computers C-30(3), 215 to 222, March 1981, the algorithm with decisions on primary inputs, the objective, the backtrace and the X-path check
  2. H. Fujiwara and T. Shimono, On the acceleration of test generation algorithms, IEEE Transactions on Computers C-32(12), 1137 to 1144, 1983, FAN, with head lines, multiple backtrace, unique sensitization and immediate implications
  3. 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 (PODEM, its backtrace and FAN)
  4. 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 (PODEM and FAN)

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