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.
- Solves
- Fault simulation
- 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
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with 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 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 , a line is critical if changing the value of alone from to changes some primary output. The fault stuck at is detected by exactly when and is critical, since the faulty circuit is the good one with forced to . 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 if flipping it alone flips the gate output. For a gate with controlling value (0 for AND and NAND, 1 for OR and NOR), if no input is at , all inputs are sensitive. If exactly one input is at , only that input is sensitive. If two or more inputs are at , 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.
CRITICAL-PATH-TRACING(C, vectors, faults, drop)alive ← faults- 1
for each vector t do - 2
simulate the good circuit on t, which gives g(k) for every line k - 3
for each root r (a line whose fanout count is not 1) do - 4
if r is a primary output then r is critical - 5
else if r is a stem then flip r, simulate forward; r is critical if an output changes - 6
if r is critical then push r on a stack; while the stack is not empty do pop k - 7
mark k critical - 8
for each sensitive input j of the gate of k do - 9
if j has exactly one fanout then push j - 10
D ← {k stuck at ¬g(k) : k critical} ∩ alive; report D as detected by t - 11
if 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 , , , so . The stem has the branches into and into . The roots are and . All other lines have one fanout and lie in the region of .
Take the vector , so , and . The trace starts at . Neither input of is at 0, so both and are sensitive. The gate has and , so only is sensitive. In the same way only is sensitive at . The branches lead to the stem , where the trace stops. The check of flips it to 1, which gives , and , so is critical. The critical lines are , , , , , , and the vector detects b/1, /1, /1, g/0, h/0 and z/1.
Two vectors show why the stems need a check.
| circuit | vector | critical lines | stem | branches |
|---|---|---|---|---|
| 111 | , | critical | no branch critical | |
| 111 | , , , | not critical | critical |
In the first row, both inputs of are at 0, so no input of is sensitive and the trace marks only . But flipping flips both and to 1, and changes. The stem is critical through two paths together, while no branch is critical alone. In the second row, is the only input at 1 of the OR, so the branch is critical. Flipping the stem to 0 gives but also , so 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 be a line and its chain of single fanouts to the root . The lines that can change are the chain and the lines that can change. So the side inputs of each gate on the chain keep their good values when flips, and flips exactly when is a sensitive input, given that flips. By induction along the chain, flipping flips exactly when every step is sensitive, and then the circuit sees the same change as when flips. So is critical exactly when the chain is sensitive and 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, critical and not, but there the stem is critical, since keeps 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 be a combinational circuit with lines 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 with good values . For a set of lines, the -flipped circuit is the good circuit with the value of each line of replaced by its complement. A line is critical if the -flipped circuit differs from the good circuit at some primary output.
Lemma 1 (critical lines give the detected faults). The vector detects the fault stuck at if and only if and is critical.
Proof. The faulty circuit is the good circuit with forced to . If , it computes the good values on every line. If , it is the -flipped circuit.
For a gate line with input , the input is sensitive if changing the value of 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 , all inputs are sensitive if none is at , only the input at 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 and the other when none is. With no input at , flipping one input puts it at and changes the output. With exactly one input at , flipping it leaves no input at , while flipping another input leaves the first one at . With two or more at , flipping one input leaves another at . A one-input gate is one to one, and XOR and XNOR change the output whenever one input changes.
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 , following the single fanout repeatedly gives a chain where are tree lines and is a root, with . The chain is unique, and the lines whose chain ends at , with itself, form the fanout-free region of .
Lemma 3 (the cone of a tree line). Let be the set of lines reachable from , included. Then , and no with lies in .
Proof. A path from must leave each with through its only fanout , so it follows the chain until it reaches , or it ends earlier. A line with precedes in topological order, so it is not reachable from .
Theorem 1 (exact in fanout-free regions). A tree line with chain is critical if and only if is a sensitive input of for every and is critical.
Proof. In the -flipped circuit, only the lines of can differ from the good values, by induction in topological order. For , let be an input of other than , a side input. Then precedes , and is or precedes it, so precedes and is not in . Also is not a chain line with , since the only fanout of is . By Lemma 3, , so every side input keeps its good value.
Assume that every step is sensitive. By induction over , flips: flips, and if flips while the side inputs of keep their good values, then flips because is sensitive. So flips. A line of has each input in or outside , by Lemma 3, and the second kind keeps its good value. So, by induction in topological order, the values in , and at the outputs, are those of the -flipped circuit, and is critical exactly when is.
Assume that some step is not sensitive, and let be the first such step. Then flip, and keeps its good value, since its side inputs keep theirs and is not sensitive. The only fanout of with is the chain line , and the only fanout of is . So no line outside 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 , and no output changes.
Corollary (the trace). Lines L6 to L9 mark, for a critical root , exactly the lines of the region of 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.
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 , , , , where and are the branches of the stem . The good values are and . Flipping alone gives with , so : is not critical, and in the same way is not critical. Flipping flips both branches, so and : the stem is critical.
Second, the multiplexer , , , , where and are the branches of the stem , at the vector . The good values are , , and . Flipping alone gives with , so : the branch is critical. Flipping alone gives and with , so : the branch is not critical. Flipping gives , and , so : the stem is not critical.
Third, the same multiplexer at the vector . The good values are , , and . Flipping alone gives , so is critical. Flipping alone gives but since , so is not critical. Flipping gives and , so : the stem is critical.
The second and third cases have the same branch pattern, critical and not, and opposite answers for the stem. So the criticality of a stem is not a function of the criticality of its branches.
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 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 -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.
Complexity
The good simulation costs . Every line other than a root lies in exactly one region, and the trace visits it at most once, with work to find its sensitive inputs, so all traces cost . Each of the stem checks simulates forward in the cone of the stem, at most , plus a log factor for the priority queue of the code. A vector costs , and vectors cost . The extra space is for the good values, the marks and one stem check.
The bound does not depend on the number of faults , which is about . Serial simulation costs , 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 , a dominator of the stem, then the stem is critical exactly when its flip reaches and is critical. So the forward simulation can stop at .
- Bit-parallel tracing. The good values of 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 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.
# 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KS79ZE Edit this page History Report an error Markdown