Algorithm Search⌘K

Algorithmadvanced

Critical path tracing

Also called Abramovici critical path tracing.

Finds the faults a vector detects by tracing back from the outputs through the gate inputs whose flip flips the output, with an explicit check at fanout stems.

Time
O(T (L + P) (1 + S)) worst
Space
O(L) extra
Where
L = the number of lines; P = the number of gate input pins; S = the number of fanout stems; T = the number of vectors
Properties
deterministicexactiterative
Origin
Miron Abramovici, P. R. Menon, D. T. Miller, 1983

Critical path tracing is a method for fault simulation that finds, for one vector, every line whose value change would reach a primary output. Such a line is called critical, and the vector detects it stuck at the opposite of its good value. Inside a fanout-free region the critical lines follow from the good values alone, by a backward trace from the root. At a fanout stem, the trace cannot decide criticality from the branches, so this page checks each stem by an explicit simulation of its flip. The cost per vector depends on the number of stems, not on the number of faults.

In plain words

Run the good circuit on one input. Then ask, for each wire, a simple question: if this wire had the other value, would an output change? If yes, a break that holds the wire at the other value is found by this input.

Start at an output and walk back. A gate input passes a change through when the other inputs let it through. For an AND gate, if all inputs are 1, each input passes a change. If one input is 0, only that input passes a change. If two inputs are 0, no single input does.

Where a wire splits into several wires and the parts meet again later, the walk back cannot tell the answer. There, flip the wire and simulate forward to see.

The problem

The input is a combinational circuit CC with LL lines in topological order, a list of single stuck-at faults, a sequence of two-valued input vectors, and a flag for fault dropping. The lines are the primary inputs, the gate outputs and the fanout branches, and PP is the number of gate input pins. The output is, for each vector, the set of faults that it detects among those still simulated.

For a vector tt, a line kk is critical if changing the value of kk alone from g(k)g(k) to ¬g(k)\lnot g(k) changes some primary output. The fault kk stuck at vv is detected by tt exactly when v=¬g(k)v = \lnot g(k) and kk is critical, since the faulty circuit is the good one with kk forced to vv. So the detected faults follow from the set of critical lines. This set is the set of lines with a nonzero Boolean difference of some output at the vector.

The name has no relation to the critical path of a task graph or the longest path of static timing analysis. Here a critical path is a chain of critical lines from a line to an output.

The algorithm

A gate input is sensitive under tt if flipping it alone flips the gate output. For a gate with controlling value cc (0 for AND and NAND, 1 for OR and NOR), if no input is at cc, all inputs are sensitive. If exactly one input is at cc, only that input is sensitive. If two or more inputs are at cc, no input is sensitive. For a buffer, an inverter, a fanout branch, XOR and XNOR, every input is sensitive.

The lines with exactly one fanout belong to the fanout-free region of that fanout. The other lines are the roots: primary outputs, which have no fanout in the line model, and fanout stems. Each region is a tree that ends at its root. Inside a region, a line is critical exactly when its chain of gate inputs to the root is sensitive at every step and the root is critical. An output root is critical. A stem root is checked by flipping it and simulating forward.

  1. CRITICAL-PATH-TRACING(C, vectors, faults, drop)
  2. alive ← faults
  3. 1for each vector t do
  4. 2simulate the good circuit on t, which gives g(k) for every line k
  5. 3for each root r (a line whose fanout count is not 1) do
  6. 4if r is a primary output then r is critical
  7. 5else if r is a stem then flip r, simulate forward; r is critical if an output changes
  8. 6if r is critical then push r on a stack; while the stack is not empty do pop k
  9. 7mark k critical
  10. 8for each sensitive input j of the gate of k do
  11. 9if j has exactly one fanout then push j
  12. 10D ← {k stuck at ¬g(k) : k critical} ∩ alive; report D as detected by t
  13. 11if drop then alive ← alive ∖ D

Line L9 stops the trace at a stem: a stem is the root of its own region, and line L5 decides it. A line with no fanout that is not an output is never critical. The forward simulation of line L5 needs only the cone of the stem and stops at the first output that changes.

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 roots are zz and bb. All other lines have one fanout and lie in the region of zz.

Take the vector abc=101abc = 101, so g=1g = 1, h=1h = 1 and z=0z = 0. The trace starts at zz. Neither input of zz is at 0, so both gg and hh are sensitive. The gate gg has a=1a = 1 and bg=0b_g = 0, so only bgb_g is sensitive. In the same way only bhb_h is sensitive at hh. The branches lead to the stem bb, where the trace stops. The check of bb flips it to 1, which gives g=0g = 0, h=0h = 0 and z=1z = 1, so bb is critical. The critical lines are bb, bgb_g, bhb_h, gg, hh, zz, and the vector detects b/1, bgb_g/1, bhb_h/1, g/0, h/0 and z/1.

Two vectors show why the stems need a check.

circuit vector critical lines stem branches
z=NAND(NAND(a,b),NAND(b,c))z = \mathrm{NAND}(\mathrm{NAND}(a, b), \mathrm{NAND}(b, c)) 111 bb, zz bb critical no branch critical
z=OR(AND(a,b),AND(¬a,c))z = \mathrm{OR}(\mathrm{AND}(a, b), \mathrm{AND}(\lnot a, c)) 111 apa_p, bb, pp, zz aa not critical apa_p critical

In the first row, both inputs of zz are at 0, so no input of zz is sensitive and the trace marks only zz. But flipping bb flips both gg and hh to 1, and zz changes. The stem is critical through two paths together, while no branch is critical alone. In the second row, p=AND(ap,b)p = \mathrm{AND}(a_p, b) is the only input at 1 of the OR, so the branch apa_p is critical. Flipping the stem aa to 0 gives p=0p = 0 but also q=AND(¬a,c)=1q = \mathrm{AND}(\lnot a, c) = 1, so zz stays 1. The two paths cancel each other. So the criticality of a stem is not a function of the criticality of its branches.

For the sequence 101, 010, 011, 110, the method reports the same first detections as the table of the fault simulation page. It makes 4 stem checks with 19 gate evaluations in them. For the c17 benchmark circuit with all 32 vectors in counting order, the three stems of c17 give 96 checks with 526 gate evaluations, whatever the dropping. These are counts of the code of this page on a 6-gate toy circuit, not benchmark results.

Correctness

Inside a fanout-free region, let ℓ\ell be a line and ℓ=k0,k1,…,km=r\ell = k_0, k_1, \ldots, k_m = r its chain of single fanouts to the root rr. The lines that ℓ\ell can change are the chain and the lines that rr can change. So the side inputs of each gate on the chain keep their good values when ℓ\ell flips, and ℓ\ell flips ki+1k_{i+1} exactly when kik_i is a sensitive input, given that kik_i flips. By induction along the chain, flipping ℓ\ell flips rr exactly when every step is sensitive, and then the circuit sees the same change as when rr flips. So ℓ\ell is critical exactly when the chain is sensitive and rr is critical. This is what lines L6 to L9 compute. An output root is critical by definition, and line L5 decides a stem root by its definition. So every line is marked exactly when it is critical, and line L10 reports exactly the detected faults.

The explicit check is needed. The multiplexer at 110 has the same branch pattern as at 111, apa_p critical and ana_n not, but there the stem aa is critical, since c=0c = 0 keeps qq at 0. So no rule over the branches decides a stem. If the branches of a stem do not reconverge, the stem is critical exactly when some branch is. The full proof gives the induction, the counterexamples and the case with no reconvergence.

Proof: Critical path tracing is exact in fanout-free regions and needs a check at stemsfull

Let CC be a combinational circuit with lines 0,…,L−10, \ldots, L - 1 in topological order, so every input of a line has a smaller index. A primary output line has no fanout in the line model, since a net with an output and another sink gets a branch line for each. Fix a two-valued vector tt with good values g(k)g(k). For a set UU of lines, the UU-flipped circuit is the good circuit with the value of each line of UU replaced by its complement. A line kk is critical if the {k}\{k\}-flipped circuit differs from the good circuit at some primary output.

Lemma 1 (critical lines give the detected faults). The vector tt detects the fault kk stuck at vv if and only if v=¬g(k)v = \lnot g(k) and kk is critical.

Proof. The faulty circuit is the good circuit with kk forced to vv. If v=g(k)v = g(k), it computes the good values on every line. If v=¬g(k)v = \lnot g(k), it is the {k}\{k\}-flipped circuit. □\square

For a gate line kk with input jj, the input jj is sensitive if changing the value of jj alone, with the other inputs at their good values, changes the gate output.

Lemma 2 (sensitive inputs). For AND, NAND, OR and NOR with controlling value cc, all inputs are sensitive if none is at cc, only the input at cc is sensitive if exactly one is, and no input is sensitive if two or more are. For a buffer, an inverter, a fanout branch, XOR and XNOR, all inputs are sensitive.

Proof. An AND-type gate has one output value when some input is at cc and the other when none is. With no input at cc, flipping one input puts it at cc and changes the output. With exactly one input at cc, flipping it leaves no input at cc, while flipping another input leaves the first one at cc. With two or more at cc, flipping one input leaves another at cc. A one-input gate is one to one, and XOR and XNOR change the output whenever one input changes. □\square

Call a line with exactly one fanout a tree line, and a line with no fanout or with two or more fanouts a root. From a tree line ℓ\ell, following the single fanout repeatedly gives a chain ℓ=k0,k1,…,km=r\ell = k_0, k_1, \ldots, k_m = r where k0,…,km−1k_0, \ldots, k_{m-1} are tree lines and rr is a root, with m≥1m \ge 1. The chain is unique, and the lines whose chain ends at rr, with rr itself, form the fanout-free region of rr.

Lemma 3 (the cone of a tree line). Let cone(x)\mathrm{cone}(x) be the set of lines reachable from xx, xx included. Then cone(ℓ)={k0,…,km−1}∪cone(r)\mathrm{cone}(\ell) = \{k_0, \ldots, k_{m-1}\} \cup \mathrm{cone}(r), and no kik_i with i<mi < m lies in cone(r)\mathrm{cone}(r).

Proof. A path from ℓ\ell must leave each kik_i with i<mi < m through its only fanout ki+1k_{i+1}, so it follows the chain until it reaches rr, or it ends earlier. A line kik_i with i<mi < m precedes rr in topological order, so it is not reachable from rr. □\square

Theorem 1 (exact in fanout-free regions). A tree line ℓ\ell with chain k0,…,km=rk_0, \ldots, k_m = r is critical if and only if kik_i is a sensitive input of ki+1k_{i+1} for every i<mi < m and rr is critical.

Proof. In the {ℓ}\{\ell\}-flipped circuit, only the lines of cone(ℓ)\mathrm{cone}(\ell) can differ from the good values, by induction in topological order. For i<mi < m, let jj be an input of ki+1k_{i+1} other than kik_i, a side input. Then jj precedes ki+1k_{i+1}, and ki+1k_{i+1} is rr or precedes it, so jj precedes rr and is not in cone(r)\mathrm{cone}(r). Also jj is not a chain line ki′k_{i'} with i′≠ii' \ne i, since the only fanout of ki′k_{i'} is ki′+1≠ki+1k_{i'+1} \ne k_{i+1}. By Lemma 3, j∉cone(ℓ)j \notin \mathrm{cone}(\ell), so every side input keeps its good value.

Assume that every step is sensitive. By induction over ii, kik_i flips: k0=ℓk_0 = \ell flips, and if kik_i flips while the side inputs of ki+1k_{i+1} keep their good values, then ki+1k_{i+1} flips because kik_i is sensitive. So rr flips. A line of cone(r)\mathrm{cone}(r) has each input in cone(r)\mathrm{cone}(r) or outside cone(ℓ)\mathrm{cone}(\ell), by Lemma 3, and the second kind keeps its good value. So, by induction in topological order, the values in cone(r)\mathrm{cone}(r), and at the outputs, are those of the {r}\{r\}-flipped circuit, and ℓ\ell is critical exactly when rr is.

Assume that some step is not sensitive, and let ii be the first such step. Then k0,…,kik_0, \ldots, k_i flip, and ki+1k_{i+1} keeps its good value, since its side inputs keep theirs and kik_i is not sensitive. The only fanout of ki′k_{i'} with i′<ii' < i is the chain line ki′+1k_{i'+1}, and the only fanout of kik_i is ki+1k_{i+1}. So no line outside {k0,…,ki}\{k_0, \ldots, k_i\} has a flipped input, and by induction in topological order no such line changes. A primary output has no fanout, so it is not one of the tree lines k0,…,kik_0, \ldots, k_i, and no output changes. □\square

Corollary (the trace). Lines L6 to L9 mark, for a critical root rr, exactly the lines of the region of rr whose chain is sensitive at every step, and they mark nothing for a root that is not critical. With line L4, which marks every primary output, and line L5, which decides each stem by its definition, every line is marked exactly when it is critical. A root with no fanout that is not a primary output has an empty effect on the outputs and is not critical. With Lemma 1, line L10 reports exactly the detected alive faults, and line L11 drops them as serial simulation does. □\square

Theorem 2 (stems need a check). There is no rule that decides whether a stem is critical from whether its branches are critical.

Proof. We give three cases. The first shows that "some branch is critical" is not necessary, and the other two show that no function of the branch pattern works.

First, at the vector abc=111abc = 111, g=NAND(a,bg)g = \mathrm{NAND}(a, b_g), h=NAND(bh,c)h = \mathrm{NAND}(b_h, c), z=NAND(g,h)z = \mathrm{NAND}(g, h), where bgb_g and bhb_h are the branches of the stem bb. The good values are g=h=0g = h = 0 and z=1z = 1. Flipping bgb_g alone gives g=1g = 1 with h=0h = 0, so z=1z = 1: bgb_g is not critical, and in the same way bhb_h is not critical. Flipping bb flips both branches, so g=h=1g = h = 1 and z=0z = 0: the stem is critical.

Second, the multiplexer p=AND(ap,b)p = \mathrm{AND}(a_p, b), n=NOT(an)n = \mathrm{NOT}(a_n), q=AND(n,c)q = \mathrm{AND}(n, c), z=OR(p,q)z = \mathrm{OR}(p, q), where apa_p and ana_n are the branches of the stem aa, at the vector abc=111abc = 111. The good values are p=1p = 1, n=0n = 0, q=0q = 0 and z=1z = 1. Flipping apa_p alone gives p=0p = 0 with q=0q = 0, so z=0z = 0: the branch apa_p is critical. Flipping ana_n alone gives n=1n = 1 and q=1q = 1 with p=1p = 1, so z=1z = 1: the branch ana_n is not critical. Flipping aa gives p=0p = 0, n=1n = 1 and q=1q = 1, so z=1z = 1: the stem is not critical.

Third, the same multiplexer at the vector abc=110abc = 110. The good values are p=1p = 1, n=0n = 0, q=0q = 0 and z=1z = 1. Flipping apa_p alone gives z=0z = 0, so apa_p is critical. Flipping ana_n alone gives n=1n = 1 but q=0q = 0 since c=0c = 0, so ana_n is not critical. Flipping aa gives p=0p = 0 and q=0q = 0, so z=0z = 0: the stem is critical.

The second and third cases have the same branch pattern, apa_p critical and ana_n not, and opposite answers for the stem. So the criticality of a stem is not a function of the criticality of its branches. □\square

Theorem 3 (stems with no reconvergence). If the cones of the branches of a stem are pairwise disjoint, the stem is critical if and only if some branch is critical.

Proof. Flipping the stem flips all its branches. Since the cones are disjoint, each line of the cone of a branch bb has all its inputs either in that cone or outside the cone of the stem, so its value in the stem-flipped circuit equals its value in the {b}\{b\}-flipped circuit, by induction in topological order. Each output lies in at most one branch cone, so an output changes when the stem flips exactly when it changes when that branch flips. □\square

Complexity

The good simulation costs O(L+P)O(L + P). Every line other than a root lies in exactly one region, and the trace visits it at most once, with O(fanin)O(\text{fanin}) work to find its sensitive inputs, so all traces cost O(L+P)O(L + P). Each of the SS stem checks simulates forward in the cone of the stem, at most O(L+P)O(L + P), plus a log factor for the priority queue of the code. A vector costs O((L+P)(1+S))O((L + P)(1 + S)), and TT vectors cost O(T(L+P)(1+S))O(T (L + P)(1 + S)). The extra space is O(L)O(L) for the good values, the marks and one stem check.

The bound does not depend on the number of faults FF, which is about 2L2L. Serial simulation costs O(T(L+P)F)O(T (L + P) F), so the gain is large when stems are few compared to lines. When stems are many, the checks dominate, and fault dropping does not reduce them, since a stem must be decided for the lines of its region even when its own faults are dropped. Only the lines of its own region need the answer for a stem, so a stem whose region holds no alive fault can be skipped. The code of this page does not do that.

Properties

  • Exact, with explicit stem checks. With line L5 as written, the result equals serial fault simulation for two-valued vectors on a combinational circuit, with or without dropping. The original method decided stems by rules on the traces and was approximate in some cases of reconvergence.
  • Fault-free trace. Inside regions, no faulty circuit and no fault list is formed. The trace uses only the good values.
  • Independent of the fault list. The critical lines are the same for all alive faults. Dropping changes only the report at line L10.
  • Detects only. The method gives the lines that a single flip makes visible. It does not give the faulty output values, which a fault dictionary needs.
  • Two values. Sensitivity needs known values on the side inputs. With an unknown value X, a side input may or may not block, and the trace is no longer exact.

Variants and improvements

  • Stem regions. Maamari and Rajski bound, for each reconvergent stem, the region outside of which its flip need not be simulated, and simulate the stem flip only inside it. Stems whose branches do not reconverge need no simulation at all: such a stem is critical exactly when some branch is.
  • Dominators. If every path from a stem to the outputs passes through one line dd, a dominator of the stem, then the stem is critical exactly when its flip reaches dd and dd is critical. So the forward simulation can stop at dd.
  • Bit-parallel tracing. The good values of ww vectors fit in one word as in PPSFP, and the sensitivity of each input becomes a word, so the trace and the stem checks run for ww vectors at once.
  • Mixed with other simulators. Combining critical path tracing inside regions with deductive or parallel simulation of the stems is a common split: the regions hold most lines, and the stems are few.

When to use it

Use critical path tracing to grade a large set of two-valued vectors on a combinational circuit, or the combinational part of a full-scan design, when most faults are not on reconvergent stems. It is well suited to random or pseudo-random patterns, where fault dropping helps little at first and the cost per vector should not grow with the number of faults. For circuits with many reconvergent stems, PPSFP or the stem-region variant is often faster. For sequential circuits with unknown states, use concurrent fault simulation.

Pitfalls

  • Inferring stems from branches. Marking a stem critical when one branch is critical, or not critical when no branch is, gives wrong answers. The table of the example has a case of each kind.
  • Tracing through a stem. If the trace passes a stem as if it had one fanout, it uses only one branch and misses the effect of the others. The trace must stop at line L9 and leave the stem to line L5.
  • Treating two controlling inputs as sensitive. With two or more inputs at the controlling value, no single input is sensitive, although a pair of them is. A stem that feeds both of them is decided by its check.
  • XOR as AND. Every input of an XOR is sensitive, whatever the values.
  • Reporting both faults of a line. A critical line gives only the fault at the opposite of its good value.

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.

critical_path_tracing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/critical-path-tracing/. The authors are listed in prov/KS79ZE.jsonl.
"""Critical path tracing (Abramovici, Menon and Miller 1984) for single stuck-at faults.

A line is critical under a vector when flipping its value flips some primary
output. Then the vector detects the line stuck at the opposite of its good
value, and no other fault of the line. The circuit splits into fanout-free
regions: each region is a tree whose root is a line with no fanout or with
two or more, and whose other lines each have exactly one fanout. Inside a
region, criticality is found by a backward trace from the root through the
sensitive gate inputs, with no fault simulation. A gate input is sensitive
when flipping it alone flips the gate output. A root with two or more
fanouts is a reconvergent stem in general: its criticality is checked here by
flipping it and propagating the change forward to the outputs.
"""

from __future__ import annotations

import heapq
from typing import Iterable, Optional, Sequence

from gatenet import Circuit, Fault, controlling, eval_gate


def sensitive_inputs(op: str, vals: Sequence[int]) -> list[int]:
    """Positions of the gate inputs whose flip alone flips the output, for good values vals."""
    c = controlling(op)
    if c is None:  # BUF, NOT, XOR, XNOR: every input is sensitive
        return list(range(len(vals)))
    at_c = [i for i, v in enumerate(vals) if v == c]
    if not at_c:
        return list(range(len(vals)))
    if len(at_c) == 1:
        return at_c
    return []


def stem_is_critical(c: Circuit, good: list[int], stem: int, po: set[int], counter: list[int]) -> bool:
    """Flip the stem and propagate the change forward. True if some primary output changes."""
    bad = {stem: 1 - good[stem]}
    heap = list(c.fanout[stem])
    heapq.heapify(heap)
    queued = set(heap)
    while heap:
        k = heapq.heappop(heap)
        v = eval_gate(c.op[k], [bad.get(j, good[j]) for j in c.fanin[k]])
        counter[0] += 1
        if v != good[k]:
            if k in po:
                return True
            bad[k] = v
            for u in c.fanout[k]:
                if u not in queued:
                    queued.add(u)
                    heapq.heappush(heap, u)
    return False


def critical_lines(c: Circuit, vector: Sequence[int], counter: Optional[list[int]] = None) -> list[bool]:
    """crit[line] is True when flipping the line flips some primary output under the vector."""
    if counter is None:
        counter = [0, 0]
    good = c.simulate(vector)  # @line L2
    po = set(c.po)
    crit = [False] * c.n_lines
    for root in range(c.n_lines):  # @line L3
        if len(c.fanout[root]) == 1:
            continue  # not a root: the line belongs to the region of its only fanout
        if root in po:  # @line L4
            ok = True
        elif len(c.fanout[root]) >= 2:  # @line L5
            counter[1] += 1
            ok = stem_is_critical(c, good, root, po, counter)
        else:
            ok = False  # a line that feeds nothing and is not an output
        if not ok:
            continue
        stack = [root]  # @line L6
        while stack:
            k = stack.pop()
            crit[k] = True  # @line L7
            if c.kind[k] == "pi":
                continue
            ins = c.fanin[k]
            for pos in sensitive_inputs(c.op[k], [good[j] for j in ins]):  # @line L8
                j = ins[pos]
                if len(c.fanout[j]) == 1:  # @line L9
                    stack.append(j)
    return crit


def critical_path_tracing(
    c: Circuit,
    vectors: Iterable[Sequence[int]],
    faults: Optional[Sequence[Fault]] = None,
    drop: bool = True,
    stats: Optional[dict[str, int]] = None,
) -> list[set[Fault]]:
    """For each vector, the set of faults it detects among the faults still listed.

    With drop=True a fault is removed after the first vector that detects it.
    Vectors hold the values 0 and 1 only.
    """
    alive = set(c.faults() if faults is None else faults)
    result: list[set[Fault]] = []
    counter = [0, 0]  # gate evaluations in stem checks, number of stem checks
    for vector in vectors:  # @line L1
        crit = critical_lines(c, vector, counter)
        good = c.simulate(vector)
        detected = {(k, 1 - good[k]) for k in range(c.n_lines) if crit[k]} & alive  # @line L10
        result.append(detected)
        if drop:  # @line L11
            alive -= detected
    if stats is not None:
        stats.update(stem_gate_evals=counter[0], stem_checks=counter[1])
    return result
gatenet.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the td1 eda 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_critical_path_tracing.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/critical-path-tracing/. The authors are listed in prov/KS79ZE.jsonl.

import random

from critical_path_tracing import critical_lines, critical_path_tracing, sensitive_inputs
from gatenet import Circuit, random_circuit

# The circuits below are the same in the tests of the four td1 fault simulators
# (parallel, PPSFP, deductive, critical path tracing), with the same expected sets,
# so the four methods are checked to report the same detected faults.

# The circuit of the page: z = NAND(NAND(a, b), NAND(b, c)) = ab + bc, with fanout at b.
C3 = Circuit(["a", "b", "c"], [("g", "NAND", ["a", "b"]), ("h", "NAND", ["b", "c"]), ("z", "NAND", ["g", "h"])], ["z"])
SEQ = [(1, 0, 1), (0, 1, 0), (0, 1, 1), (1, 1, 0)]
FIRSTS = [
    {"b/1", "b>g/1", "b>h/1", "g/0", "h/0", "z/1"},
    {"a/1", "c/1"},
    {"b/0", "b>h/0", "c/0", "h/1", "z/0"},
    {"a/0", "b>g/0", "g/1"},
]
ALL_DETECTED = [
    {"b/1", "b>g/1", "b>h/1", "g/0", "h/0", "z/1"},
    {"a/1", "c/1", "g/0", "h/0", "z/1"},
    {"b/0", "b>h/0", "c/0", "h/1", "z/0"},
    {"a/0", "b/0", "b>g/0", "g/1", "z/0"},
]

# ISCAS-85 c17: six NAND gates, two outputs, reconvergent fanout at 3, 11 and 16.
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"],
)
C17_COUNTS = [9, 10, 9, 12, 10, 12, 8, 13, 8, 7, 10, 9, 9, 8, 13, 14, 11, 12, 11, 13, 11, 11, 9, 13, 8, 7, 10, 9, 8, 4, 13, 14]

# z = ab + a'c + bc: the consensus term bc is redundant, so r/0 and the faults that only kill r are undetectable.
CONSENSUS = Circuit(
    ["a", "b", "c"],
    [("p", "AND", ["a", "b"]), ("na", "NOT", ["a"]), ("q", "AND", ["na", "c"]), ("r", "AND", ["b", "c"]), ("z", "OR", ["p", "q", "r"])],
    ["z"],
)
REDUNDANT = {"r/0", "b>r/0", "c>r/0"}

# A 2-to-1 multiplexer z = ab + a'c: under 111 the branch a>p is critical, but the stem a is not.
MUX = Circuit(["a", "b", "c"], [("p", "AND", ["a", "b"]), ("na", "NOT", ["a"]), ("q", "AND", ["na", "c"]), ("z", "OR", ["p", "q"])], ["z"])

OPS = ("AND", "OR", "NAND", "NOR", "NOT", "BUF", "XOR", "XNOR")


def serial(c, vectors, faults=None, drop=True):
    """Reference method: inject each fault on its own and simulate every vector."""
    alive = list(c.faults() if faults is None else faults)
    result = []
    for vector in vectors:
        detected = {f for f in alive if c.detects(vector, f)}
        result.append(detected)
        if drop:
            alive = [f for f in alive if f not in detected]
    return result


def names(c, sets):
    return [{c.fault_name(f) for f in s} for s in sets]


def flip_critical(c, vector):
    """Brute force: line k is critical when the fault k stuck at the opposite of its good value is detected."""
    good = c.simulate(vector)
    return [c.detects(vector, (k, 1 - good[k])) for k in range(c.n_lines)]


def crit_names(c, vector):
    crit = critical_lines(c, vector)
    return {c.name[k] for k in range(c.n_lines) if crit[k]}


def test_sensitive_inputs():
    assert sensitive_inputs("NAND", [1, 1]) == [0, 1]
    assert sensitive_inputs("NAND", [1, 0]) == [1]
    assert sensitive_inputs("NAND", [0, 0]) == []
    assert sensitive_inputs("NOR", [0, 1, 0]) == [1]
    assert sensitive_inputs("XOR", [1, 0, 1]) == [0, 1, 2]


def test_page_trace():
    assert crit_names(C3, (1, 0, 1)) == {"b", "b>g", "b>h", "g", "h", "z"}
    assert crit_names(C3, (0, 1, 0)) == {"a", "c", "g", "h", "z"}


def test_stem_critical_with_no_critical_branch():
    # Under 111 both branches of b are masked alone, but flipping b flips both g and h, and z.
    assert crit_names(C3, (1, 1, 1)) == {"b", "z"}
    assert flip_critical(C3, (1, 1, 1)) == critical_lines(C3, (1, 1, 1))


def test_critical_branch_with_stem_not_critical():
    assert crit_names(MUX, (1, 1, 1)) == {"a>p", "b", "p", "z"}
    assert flip_critical(MUX, (1, 1, 1)) == critical_lines(MUX, (1, 1, 1))


def test_critical_lines_against_brute_force():
    rng = random.Random(9)
    circuits = [C3, C17, CONSENSUS, MUX] + [random_circuit(rng, 4, 10, ops=OPS) for _ in range(25)]
    for c in circuits:
        for vector in c.all_vectors():
            assert critical_lines(c, vector) == flip_critical(c, vector)


def test_page_example():
    assert names(C3, critical_path_tracing(C3, SEQ)) == FIRSTS
    assert names(C3, critical_path_tracing(C3, SEQ, drop=False)) == ALL_DETECTED
    stats = {}
    critical_path_tracing(C3, SEQ, stats=stats)
    assert stats == {"stem_gate_evals": 19, "stem_checks": 4}


def test_c17_all_vectors():
    vectors = C17.all_vectors()
    result = critical_path_tracing(C17, vectors, drop=False)
    assert result == serial(C17, vectors, drop=False)
    assert [len(s) for s in result] == C17_COUNTS
    rng = random.Random(17)
    rng.shuffle(vectors)
    assert critical_path_tracing(C17, vectors) == serial(C17, vectors)


def test_redundant_faults_by_exhaustive_patterns():
    detected = set().union(*critical_path_tracing(CONSENSUS, CONSENSUS.all_vectors()))
    undetected = {CONSENSUS.fault_name(f) for f in CONSENSUS.faults() if f not in detected}
    assert undetected == REDUNDANT


def test_random_circuits_against_serial():
    rng = random.Random(2024)
    for _ in range(120):
        c = random_circuit(rng, rng.randint(2, 6), rng.randint(3, 14), ops=OPS)
        vectors = [tuple(rng.randint(0, 1) for _ in c.pi) for _ in range(rng.randint(1, 10))]
        for drop in (True, False):
            assert critical_path_tracing(c, vectors, drop=drop) == serial(c, vectors, drop=drop)

History

Abramovici, Menon and Miller presented critical path tracing at the Design Automation Conference in 1983 and in the first issue of IEEE Design and Test of Computers in 1984, as an alternative to fault simulation that does not handle faults one by one. Their stem analysis used rules over the traces, which are approximate in some cases of reconvergent fanout. Later work made the method exact by simulating the stems explicitly, and Maamari and Rajski in 1990 bounded the part of the circuit that each stem check must simulate. The trace inside fanout-free regions became a standard part of fast fault simulators for combinational and full-scan circuits.

References

  1. M. Abramovici, P. R. Menon and D. T. Miller, Critical path tracing, an alternative to fault simulation, IEEE Design and Test of Computers 1(1), 83 to 93, February 1984, the method, with sensitive inputs, the backward trace inside fanout-free regions and the rules for stems
  2. M. Abramovici, P. R. Menon and D. T. Miller, Critical path tracing, an alternative to fault simulation, Proceedings of the 20th Design Automation Conference, 214 to 220, 1983, the conference version of the method
  3. F. Maamari and J. Rajski, A method of fault simulation based on stem regions, IEEE Transactions on Computer-Aided Design 9(2), 212 to 220, 1990, exact stem analysis by explicit simulation of the stems, limited to the stem region of each stem
  4. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on fault simulation (critical path tracing, fanout-free regions and stem analysis)

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