Algorithmcore
FAN
Also called fanout-oriented test generation, Fujiwara-Shimono algorithm.
Fujiwara and Shimono's ATPG that improves PODEM with headlines, backtrace to many objectives at once and unique sensitization, cutting the search a lot.
- Time
- O(L (L + P) + 2^h (L + P)) worstO(L (L + P)) best
- Space
- O(L + n) extra
- Where
- L = the number of lines; P = the number of gate input pins; h = the number of head lines, at most n; n = the number of primary inputs
- Model
- Word RAM
- Properties
- completedeterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hideo Fujiwara, Takeshi Shimono, 1983
FAN is an algorithm for automatic test pattern generation by Fujiwara and Shimono (1983). Like PODEM, it takes a combinational circuit and one single stuck-at fault, and it finds an input vector that detects the fault or proves that none exists. It keeps the PODEM search, a depth-first search over decisions with forward simulation, and makes the search tree smaller and the dead ends easier to see. It decides on head lines, which are the roots of the fanout-free parts of the circuit, instead of on primary inputs. It sends all current goals back at once with counts. And it fixes the values that every path of the fault effect needs before it decides anything else.
In plain words
PODEM sets one circuit input at a time, and it often finds out late that an early choice was wrong. FAN uses three ideas to waste less work.
First, a group of inputs that feeds a tree of gates with no shared signals can give the root of the tree any value, so FAN decides on the root. It works out the inputs only at the end, without any search.
Second, FAN collects all its current goals and walks back from all of them together. Where two goals pull a signal in different directions, it counts the votes and takes the majority.
Third, when the error can only travel through some gates, FAN sets their other inputs to the values that let it through, at once. A wrong earlier choice then shows up immediately.
The problem
The input is a combinational circuit with primary inputs and lines in topological order, and a fault , line stuck at . The lines are the stems of the primary inputs and gates and the fanout branches, as on the PODEM page. The output is a vector over whose every two-valued completion detects the fault, or "untestable" when no vector detects it.
FAN uses Roth's values 0, 1, D, D' and X, the D-frontier and the X-path of the PODEM page. Two new words describe the structure of the circuit.
- A line is bound when it is a fanout branch or is reached from a fanout branch. A line that is not bound is free. On this page, the fault site and every line that it reaches are also bound, so a free line never carries the fault effect.
- A head line is a free line with a bound fanout. The free lines from which a head line is reached form a tree with as root and primary inputs as leaves, and the trees of two head lines share no line. When the fault site is a primary input, it is a decision line too, and the page counts it among the head lines .
The algorithm
FAN(C, (ℓ, s))- 1
mark the bound lines; H ← the head lines - 2
set every line of H to X; stack ← empty - 3
loop - 4
simulate the good and the faulty circuit with three values from the values on H - 5
if some primary output has D or D' then return JUSTIFY() - 6
R ← UNIQUE-SENSITIZATION() - 7
if ℓ is not at s and (ℓ has X or a D-frontier gate has an X-path) and no (j, v) in R has j at ¬v then - 8
O ← {(ℓ, ¬s)} if ℓ has X, plus each (j, v) in R with j at X - 9
if O is empty then O ← {(j, the non-controlling value of G)} for an X input j of a D-frontier gate G with an X-path - 10
(h, u) ← MULTIPLE-BACKTRACE(O) - 11
set h to u; push (h, u, not flipped) - 12
else - 13
pop each entry that is flipped and set its line to X - 14
if the stack is empty then return "untestable" - 15
flip the value of the top entry, set its line to it, and mark it flipped UNIQUE-SENSITIZATION()- 16
if ℓ has X or more than one D-frontier gate has an X-path then return ∅ - 17
R ← ∅; G ← the D-frontier gate with an X-path - 18
for each gate d with a controlling value c that lies on every path from G to a primary output, G included do - 19
for each input j of d outside the fanout cone of ℓ do add (j, ¬c) to R - 20
return R MULTIPLE-BACKTRACE(O)- 21
n0(k) ← 0 and n1(k) ← 0 for each line k; for each (k, v) in O add 1 to n_v(k) - 22
for each line k not in H with n0(k) + n1(k) > 0, in reverse topological order do - 23
if k is a fanout stem with n0(k) > 0 and n1(k) > 0 then set the smaller count to 0 (n1 on a tie) - 24
for each value v with n_v(k) > 0 do - 25
u ← v xor inversion(k) - 26
if u is the controlling value of k then add n_v(k) to n_u(j) for the first input j of k with X - 27
else add n_v(k) to n_u(j) for every input j of k with X - 28
return (h, v): the line h of H with the largest n0(h) + n1(h), and v the value with the larger count (0 on a tie) JUSTIFY()- 29
for each line h of H with a value u, set the inputs of the tree of h by one backtrace so that h gets u - 30
return the primary input values, with X for the inputs that are not set
Here inversion(k) is 1 for NAND, NOR, NOT and XNOR. For XOR and XNOR, line L26 is used with corrected by the parity of the known inputs. In line L29, a gate whose inputs need the controlling value gets it on one input, and otherwise every input of the tree gets a value. Line L1 takes time, where is the number of gate input pins. Line L18 needs the gates through which every path from to an output passes. These are the post-dominators of , and the code builds their dominator tree once, before the loop.
The decisions and the order of the passes are those of PODEM. What changes is the place of the decisions (line L11 sets a head line, not an input), the goals (line L8 can hold many), and the test of line L7, which also fails when a required value of is contradicted. In the original, a fanout stem that gets both counts at line L23 stops the backtrace and becomes a decision of its own, which is justified later. This page keeps the larger count and goes on, so every decision is on a head line. Both forms are complete.
Example
Head lines. The circuit is the consensus circuit of the PODEM page with and widened into small trees: , , , , , and . The stems , and fan out, so their branches and everything after them are bound. The head lines are , and , three decision lines for five inputs. The fault stuck at 0 is redundant, because is the consensus of and . Each pass takes the first candidate on a tie.
| pass | values | action | |
|---|---|---|---|
| 1 | X X X | all X | objective : the AND gives a 1-count to and to ; set |
| 2 | X 1 X | = X | objective ; set |
| 3 | X 1 1 | , D-frontier | the D-frontier gate is the output itself, so . gives a 0-count and gives a 1-count through ; tie, set |
| 4 | 0 1 1 | , | fails and the D-frontier is empty: flip to 1 |
| 5 | 1 1 1 | , | fails: pop , flip to 0 |
| 6 | X 1 0 | is at its stuck value: pop , flip to 0 | |
| 7 | X 0 X | the stack is empty: return "untestable" |
FAN proves the fault redundant in 7 passes and 3 flips. PODEM, with the same first-candidate choices, decides on the five inputs. It sets , , and , then tries both values of again after it flips and sets , and it needs 13 passes and 6 flips. Its tree enumerates the ways to make and , which FAN never looks at.
Unique sensitization and multiple backtrace. The second circuit is , , , , and , with inputs in the order . The fault is stuck at 0, and is a decision line because it is the fault site.
| pass | values | action | |
|---|---|---|---|
| 1 | X X X X X | all X | objective ; set |
| 2 | 1 X X X X | , D-frontier | every path from passes , and : . Counts: gets one 1-count from and two 0-counts from and ; set |
| 3 | 1 0 X X X | = X | objectives ; set |
| 4 | 1 0 1 X X | set | |
| 5 | 1 0 1 0 X | set | |
| 6 | 1 0 1 0 0 | return 10100 |
FAN makes no flip. PODEM first takes the one objective "the X input of to 1", backtraces through the OR to , and only then sees that blocks the path. It needs 7 passes and 1 flip to reach the same vector. Over all 28 faults of this circuit, PODEM makes 13 flips and FAN 9. Over all 36 faults of the first circuit, PODEM makes 24 and FAN 13.
Correctness
FAN returns a test exactly when the fault is detectable. The new part of the proof is that the head lines cut the circuit. Every input of a bound line is bound or a head line, so the good and the faulty values of every bound line depend only on the values of the head lines. Each head line is the root of a tree with its own primary inputs, so any values on the head lines can be justified at the end without a conflict. The values in are necessary: every detecting path leaves the single D-frontier gate and passes every gate of line L18, and a side input of outside the fanout cone of has the same value in both circuits, so it must not be controlling. Hence the test of line L7 fails only at nodes below which no test exists. As in PODEM, each pass assigns a new head line, the tree has depth at most , and the branch that agrees with a test is never pruned. The full proof gives the details.
Proof: FAN returns a test exactly when the fault is detectablefull
Let be a combinational circuit with primary inputs and lines in topological order, and let be the fault "line stuck at ". The proof follows the proof for PODEM and adds what is new in FAN: the decisions are on head lines, and the required values of unique sensitization also prune the search. The words effect, X, completion and detects are used as there. A line has an effect when its good and faulty values are both known and differ, and it has an X when one of the two values is X.
Bound lines and head lines. Line L1 marks a line as bound when it is a fanout branch, the line itself, or a line with a bound input. So the set of bound lines is closed under fanout. A line that is not bound is free. holds the free lines with a bound fanout, and if is a primary input. For with , let be the set of lines from which a path of free lines leads to .
Lemma 1 (the cones). (a) A free line has no fanout branch among its fanouts unless it is in , so every free line outside has exactly one fanout or none. (b) The sets are disjoint trees, and each one contains a primary input. (c) . (d) Every input of a bound line is bound or in .
Proof. (a) If a line has two or more sinks, all of its fanouts are branches, which are bound, so a free line with two or more sinks has a bound fanout and is in . (d) An input of a bound line is bound or free, and a free input with a bound fanout is in . (b) A line of has no free fanout: with one sink, that sink is the bound fanout, and with more, all fanouts are branches. Take with . It is free and not in , since its path of free lines starts with a free fanout. By (a) it has exactly one fanout, and it is free. Following single fanouts from gives the only path of free lines out of , and the path stops at the first line of . So lies in exactly one set , and inside every line except has one fanout, which makes a tree with root . Walking back along inputs from inside free lines ends at a primary input, because a free line is never a branch. (c) The sets are disjoint and each holds a primary input. If is a primary input, it is bound, so it lies in no . So .
Lemma 2 (head lines cut the circuit). Let be a two-valued input vector and let give each line of its good value under . Then line L4 run on gives every bound line the same good and faulty values as the simulation of . If is any partial assignment on that extends, every bound line that is known under has the same value under .
Proof. Induction over the bound lines in topological order. A line of gets its value from , and its faulty value equals its good value unless it is : a free line is not reached from , so the fault does not change it, and for the faulty value is in both computations. A bound line that is not in is not a primary input, since the only bound primary input can be , which is in . So it is a gate or a branch, and by Lemma 1(d) its inputs are bound or in , where the induction gives the values of . The gate rule is the same in both computations, and for the faulty value is in both. For the second claim, three-valued simulation is monotone: a value known under stays the same under every assignment that extends (the Fact of the PODEM proof), and extends .
So the faulty and the good values of every bound line depend only on the values of the head lines. A primary output that is free is not reached from and never has an effect, so detection is decided on the bound outputs.
Lemma 3 (justification). For every with and every value , the procedure of line L29 sets primary inputs of only, and three-valued simulation then gives the value , whatever the other inputs are.
Proof. Induction on the tree from the leaves. A primary input is set to . For NOT and BUF, the input gets the needed value. For a gate with a controlling value , when the inputs need the value , the first input gets , which forces the output. Otherwise every input gets the non-controlling value. For XOR and XNOR, every input gets a value with the right parity. The subtrees of the inputs are disjoint, by Lemma 1(b), so the settings do not overwrite each other, and the trees of two head lines are disjoint too.
Lemma 4 (soundness of line L5). If line L5 returns a vector, every completion of it detects the fault.
Proof. By Lemma 3, simulation of the returned vector gives each line of its value in the current assignment , and , if it is a primary input in , gets its value directly. By Lemma 2 applied to the bound lines, simulation then gives the bound lines at least the values that line L4 gave under , so some primary output has an effect. The Fact of the PODEM proof extends this to every completion.
Lemma 5 (the required values are necessary). Suppose that line L5 did not return under , that is not X, and that the D-frontier gates with an X-path are one gate . Let be a vector that detects the fault and with extending . Then every pair in has value on line under .
Proof. Take a path of lines that differ under (Lemma 1 of the PODEM proof). As in Lemma 3 of the PODEM proof, let be the last line of the path with an effect under . Then , and is a D-frontier gate and is an X-path. So , and the rest of the path goes from to an output. Every gate of line L18 lies on all such paths, so the path enters through an input whose values differ under , and the output of also differs. Let be an input of outside the fanout cone of . The fault does not reach , so has the same value in both circuits. If that value were the controlling value of , the output of would be fixed by in both circuits and would not differ. So has the value under .
Lemma 6 (safe pruning). If the test of line L7 fails for , then no vector with extending detects the fault.
Proof. There are three cases. If has the good value , the good and the faulty circuit agree everywhere under any such , by Lemma 2 and the monotone simulation. If has the value and no D-frontier gate has an X-path, the argument of Lemma 3 of the PODEM proof applies to the bound lines, whose values under agree with by Lemma 2. If some pair of has at under , then has the value under every such by Lemma 2, and Lemma 5 says that no such detects the fault. ( is bound or in , since it is an input of a bound gate.)
Lemma 7 (the backtrace ends on an open head line). When the test of line L7 holds, line L10 returns a line of whose value is X.
Proof. Lines L8 and L9 give a nonempty set of lines with an X: the site , inputs of bound gates, or an input of the D-frontier gate , which exists by the test of line L7 as in Lemma 4 of the PODEM proof. All these lines are bound or in . Lines L21 to L27 pass counts only to inputs with an X, in reverse topological order, so a line is handled after all the lines it feeds have added their counts. A bound line with an X that is not in has an input with an X: a gate whose inputs are all known is known in each circuit, except the faulty value of , which is , and then the X of is in its good value, which comes from its inputs. Line L23 keeps the larger count, so a count that reaches a line is passed on. By Lemma 1(d) the counts stay on bound lines and lines of , and the lines are finite, so some line of with an X receives a count, and line L28 returns one.
Lemma 8 (the search tree). The stack holds distinct lines of , and the loop of line L3 runs at most times.
Proof. Line L11 assigns an open line of , by Lemma 7, and lines L13 and L15 pop and flip as in PODEM. The choice at lines L8 to L10 depends only on . So the passes are a depth-first walk of a binary tree of depth at most , in which each node is entered once, and by Lemma 1(c).
Theorem. FAN stops. It returns a vector exactly when the fault is detectable, and then every completion of the vector detects the fault. It returns "untestable" exactly when the fault is redundant.
Proof. It stops by Lemma 8, and a returned vector is a test by Lemma 4. Suppose that detects the fault. Follow the nodes of the tree whose assignments are extended by , starting at the root, where all of is X. At such a node, line L5 returns, or the test of line L7 holds by Lemma 6. In the second case line L11 assigns one more line of , and one of the two children agrees with . The search enters both children before it leaves the node. At depth the assignment is , and by Lemma 2 the bound outputs have the values of , so line L5 returns there. So FAN returns a vector before the stack can become empty at line L14.
The proof uses no property of the choices at lines L23, L26 and L28, so any tie rule and any guidance by testability measures keeps the result. The choices change only the number of passes.
Complexity
Line L1 and the dominator tree are built once, in time by the simple meet-walk used here, and in almost linear time with the Lengauer and Tarjan method. Each pass then costs for the simulation, the D-frontier, the X-paths, the list and the backtrace. The tree has at most nodes for head lines, so the worst case is time. Since , this bound is never above the bound of PODEM apart from the preprocessing, and it is much lower when the circuit has large fanout-free regions. The extra space is for the values, the counts and the stack.
The bound is exponential, and must be, since the decision problem is NP-complete. That FAN needs fewer passes than PODEM on real circuits is a measured result. Fujiwara and Shimono report it on their test circuits, and later tools such as SOCRATES build on it. On small random circuits the gain is not uniform. In a run over 2000 random circuits with 3 to 6 inputs and 4 to 8 gates of the types AND, OR, NAND, NOR and NOT (86 888 faults), the code of this page made 36 359 flips on the 18 779 redundant faults where PODEM made 38 470, but 3 731 flips on the 68 109 detectable faults where PODEM made 3 606. FAN made fewer flips on 2 521 faults and more on 1 115.
Properties
- Complete. FAN returns a test exactly when one exists, so "untestable" proves that the fault is redundant.
- Smaller tree. The depth of the search is the number of head lines, at most the number of inputs. The inputs inside the tree of a head line are set once, at line L29, without search.
- Same test quality. The returned vector leaves free all inputs that no justification needed, like PODEM, which helps dynamic test compaction.
- Free choices. Any rule for ties at lines L23, L26 and L28 keeps the result correct. Testability measures such as SCOAP are the usual guide.
- Heuristic gain. Head lines and the pruning by never make the bound on the tree larger, but multiple backtrace can pick a different decision than PODEM, so on a single fault FAN can make more flips.
Variants and improvements
- Fanout stems as decisions. In the paper, when the counts at a fanout stem conflict, the stem becomes the final objective, gets the majority value, and is justified later like a line of the D-algorithm. This avoids walking through the stem with a value that half of the goals did not want.
- Immediate implications. The paper also implies values backward. For example, an AND output that must be 1 sets all its inputs to 1 at once. Simulation only goes forward and finds the same conflicts later.
- Learning. SOCRATES (Schulz, Trischler and Sarfert, 1988) adds static learning, which stores indirect implications found before the search, and an improved unique sensitization. Recursive learning by Kunz and Pradhan finds all necessary values with enough depth.
- Dominator-based sensitization. Later systems compute the dominator tree of the circuit once and use it for each fault, as this page does.
- SAT. SAT-based ATPG gives the same problem to a CDCL solver. Its clause learning finds many of the implications that FAN finds with its rules.
When to use it
Use FAN, or a descendant, for test generation on combinational logic or the combinational part of a full scan design, together with a fault simulator that drops the faults each new test also detects. Its rules pay most on circuits with large fanout-free regions and on redundant faults, where the whole tree must be searched. For the hardest faults, tools often switch to SAT-based ATPG after a backtrack limit.
Pitfalls
- The fault inside a fanout-free region. If the fault site lies in the tree of a head line, a decision on the head line also fixes the faulty value. Treat the fault site and its fanout cone as bound, as on this page, or give the head line a value pair.
- Unique sensitization through reconvergence. A side input that the fault reaches by another path can carry the fault effect, and then it need not be non-controlling. Only side inputs outside the fanout cone of the fault site may go into .
- Dominators of the wrong gate. Line L18 needs the gates on every path from the D-frontier gate to any output, not to one output. With two D-frontier gates, nothing is required, since the effect can take either.
- Stopping at a head line that is not free. A line with a bound fanout and a bound input is bound, not a head line. Its value cannot be justified without search.
- Aborted is not redundant. With a backtrack limit, FAN reports some faults as aborted. Only a full search proves redundancy.
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/fan-algorithm/. The authors are listed in prov/DJVVW8.jsonl.
"""FAN (Fujiwara and Shimono 1983): test generation for one single stuck-at fault.
FAN keeps the search of PODEM, a depth-first search with forward simulation,
and adds four rules:
- decisions are made on head lines, not on primary inputs, and a head line is
justified only after a test is found, inside its fanout-free cone;
- multiple backtrace sends all current objectives back at once and counts how
many of them want 0 and 1 at each line;
- unique sensitization finds the gates through which every path from the
single D-frontier gate must pass and requires their side inputs to be
non-controlling;
- these required values prune the search as soon as one of them is
contradicted, before the D-frontier dies.
In the original, a fanout stem that receives both 0 and 1 counts becomes a
decision of its own. Here the stem keeps the larger count and the backtrace
goes on, so every decision is on a head line (see the page).
"""
from __future__ import annotations
from typing import Optional
from td2net 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 bound_and_head_lines(c: Circuit, fault: Fault) -> tuple[list[bool], list[int]]:
"""Bound lines (reached from a fanout branch or from the fault site) and the decision lines.
The decision lines are the head lines, that is the free lines with a bound
fanout, and the fault site when it is a primary input.
"""
site = fault[0]
bound = [False] * c.n_lines
for k in range(c.n_lines): # @line L1
bound[k] = c.kind[k] == "branch" or k == site or any(bound[j] for j in c.fanin[k])
heads = [k for k in range(c.n_lines) if not bound[k] and any(bound[w] for w in c.fanout[k])]
if c.kind[site] == "pi":
heads.append(site)
return bound, sorted(heads)
def imply(c: Circuit, fault: Fault, value: dict[int, int]) -> tuple[list[int], list[int]]:
"""Three-valued simulation of the good and the faulty circuit from the head line values."""
site, s = fault
good = [X] * c.n_lines
bad = [X] * c.n_lines
for k in range(c.n_lines):
if k in value:
g = b = value[k]
elif c.kind[k] == "pi":
g = b = X
else:
ins = c.fanin[k]
g = eval_gate(c.op[k], [good[j] for j in ins])
b = eval_gate(c.op[k], [bad[j] for j in ins])
if k == site:
b = s
good[k], bad[k] = g, b
return good, bad
def d_frontier(c: Circuit, good: list[int], bad: list[int]) -> list[int]:
"""Gate lines with an X 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]) -> list[bool]:
"""For each line with an X: True if a path of lines with an X leads to a primary output."""
is_po = set(c.po)
xp = [False] * c.n_lines
for k in range(c.n_lines - 1, -1, -1):
if X in (good[k], bad[k]):
xp[k] = k in is_po or any(xp[w] for w in c.fanout[k])
return xp
SINK = -1 # the virtual sink that every primary output feeds
def postdominator_tree(c: Circuit) -> list[Optional[int]]:
"""Immediate post-dominator of each line on the way to the outputs.
The value is SINK for a line whose paths to the outputs share no line,
and None for a line with no path to an output. One sweep in reverse
topological order; the meet of two lines walks up the tree, so the
sweep takes O(L (L + P)) time in the worst case.
"""
ipdom: list[Optional[int]] = [None] * c.n_lines
depth = [0] * c.n_lines
is_po = set(c.po)
def meet(u: int, w: int) -> int:
while u != w:
if u == SINK or w == SINK:
return SINK
if depth[u] < depth[w]:
u, w = w, u
u = ipdom[u] # type: ignore[assignment]
return u
for k in range(c.n_lines - 1, -1, -1):
succ = [w for w in c.fanout[k] if ipdom[w] is not None or w in is_po]
if k in is_po:
succ.append(SINK)
if not succ:
continue
m = succ[0]
for w in succ[1:]:
m = meet(m, w)
ipdom[k] = m
depth[k] = 1 if m == SINK else depth[m] + 1
return ipdom
def dominators(ipdom: list[Optional[int]], g: int) -> list[int]:
"""Lines that lie on every path from line g to a primary output, g included."""
if ipdom[g] is None:
return []
out = []
d: Optional[int] = g
while d is not None and d != SINK:
out.append(d)
d = ipdom[d]
return out
def unique_sensitization(
c: Circuit, fault: Fault, good: list[int], front: list[int], fault_cone: set[int],
ipdom: list[Optional[int]],
) -> list[tuple[int, int]]:
"""Values that every test extending the current values must have (lines L16 to L20)."""
site, s = fault
if good[site] == X or len(front) != 1: # @line L16
return []
req = [] # @line L17
for d in dominators(ipdom, front[0]): # @line L18
cv = controlling(c.op[d]) if c.kind[d] == "gate" else None
if cv is None:
continue
for j in c.fanin[d]: # @line L19
if j not in fault_cone:
req.append((j, 1 - cv))
return req # @line L20
def multiple_backtrace(
c: Circuit, good: list[int], bad: list[int], objectives: list[tuple[int, int]], is_head: list[bool]
) -> tuple[int, int]:
"""Send all objectives back at once with counts; return a head line and its value."""
n = [[0] * c.n_lines, [0] * c.n_lines] # @line L21
for k, v in objectives:
n[v][k] += 1
for k in range(c.n_lines - 1, -1, -1): # @line L22
if is_head[k] or n[0][k] + n[1][k] == 0:
continue
if len(c.fanout[k]) > 1 and n[0][k] and n[1][k]: # @line L23: conflict at a fanout stem
n[1 if n[0][k] > n[1][k] else 0][k] = 0
op = c.op[k]
xins = [j for j in c.fanin[k] if X in (good[j], bad[j])]
for v in (0, 1): # @line L24
if not n[v][k]:
continue
u = v ^ inversion(op) # @line L25
cv = controlling(op)
if op in ("XOR", "XNOR"):
parity = 0
for j in c.fanin[k]:
if good[j] != X:
parity ^= good[j]
n[u ^ parity][xins[0]] += n[v][k]
elif cv is not None and u == cv: # @line L26: one input is enough
n[u][xins[0]] += n[v][k]
else: # @line L27: every input is needed
for j in xins:
n[u][j] += n[v][k]
best = max(
(k for k in range(c.n_lines) if is_head[k] and n[0][k] + n[1][k] > 0),
key=lambda k: (n[0][k] + n[1][k], -k),
) # @line L28
return best, 1 if n[1][best] > n[0][best] else 0
def justify_tree(c: Circuit, k: int, v: int, vec: list[int], pi_pos: dict[int, int]) -> None:
"""Set primary inputs of the fanout-free cone of k so that k gets value v."""
if c.kind[k] == "pi":
vec[pi_pos[k]] = v
return
op, ins = c.op[k], c.fanin[k]
u = v ^ inversion(op)
if op in ("XOR", "XNOR"):
for j in ins[:-1]:
justify_tree(c, j, 0, vec, pi_pos)
justify_tree(c, ins[-1], u, vec, pi_pos)
elif controlling(op) is not None and u == controlling(op):
justify_tree(c, ins[0], u, vec, pi_pos)
else:
for j in ins:
justify_tree(c, j, u, vec, pi_pos)
def fan(c: Circuit, fault: Fault, stats: Optional[dict[str, int]] = None) -> Optional[tuple[int, ...]]:
"""Return a test with X for free inputs, or None if the fault is redundant.
The search tree has one level per decision line, at most n levels for n
primary inputs, and each node costs O(L + P) time. The post-dominator
tree for unique sensitization is built once, in O(L (L + P)) time.
"""
site, s = fault
_, heads = bound_and_head_lines(c, fault)
is_head = [False] * c.n_lines
for h in heads:
is_head[h] = True
fault_cone = c.cone(site)
ipdom = postdominator_tree(c)
pi_pos = {line: k for k, line in enumerate(c.pi)}
value: dict[int, int] = {} # @line L2
stack: list[list[int]] = []
steps = backtracks = 0
while True: # @line L3
steps += 1
good, bad = imply(c, fault, value) # @line L4
if any(is_effect(good[o], bad[o]) for o in c.po): # @line L5
vec = [X] * len(c.pi)
for h, u in value.items(): # @line L29
justify_tree(c, h, u, vec, pi_pos)
if stats is not None:
stats.update(steps=steps, backtracks=backtracks)
return tuple(vec) # @line L30
xp = x_paths(c, good, bad)
front = [g for g in d_frontier(c, good, bad) if xp[g]]
req = unique_sensitization(c, fault, good, front, fault_cone, ipdom) # @line L6
ok = good[site] != s and (good[site] == X or bool(front)) # @line L7
ok = ok and all(good[k] in (X, v) for k, v in req)
if ok:
objs = [(site, 1 - s)] if good[site] == X else [] # @line L8
objs += [(k, v) for k, v in req if good[k] == X]
if not objs: # @line L9
gate = front[0]
j = next(j for j in c.fanin[gate] if X in (good[j], bad[j]))
cv = controlling(c.op[gate])
objs = [(j, 0 if cv is None else 1 - cv)]
h, u = multiple_backtrace(c, good, bad, objs, is_head) # @line L10
value[h] = u # @line L11
stack.append([h, u, 0])
else: # @line L12
while stack and stack[-1][2]: # @line L13
del value[stack.pop()[0]]
if not stack: # @line L14
if stats is not None:
stats.update(steps=steps, backtracks=backtracks)
return None
top = stack[-1] # @line L15
top[1], top[2] = 1 - top[1], 1
value[top[0]] = top[1]
backtracks += 1
podem_baseline.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fan-algorithm/. The authors are listed in prov/DJVVW8.jsonl.
"""Plain PODEM (Goel 1981), written only as the baseline for the backtrack counts of FAN.
Decisions are on primary inputs. The objective is to activate the fault, else
to set an X input of the first D-frontier gate with an X-path to its
non-controlling value. The backtrace takes the first input with an X. These
are the same choices that the FAN code makes when it has a free choice, so
the two searches differ only by the FAN rules.
"""
from __future__ import annotations
from typing import Optional
from td2net import X, Circuit, Fault, controlling, 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 with an X 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]) -> list[bool]:
"""For each line with an X: True if a path of lines with an X leads to a primary output."""
is_po = set(c.po)
xp = [False] * c.n_lines
for k in range(c.n_lines - 1, -1, -1):
if X in (good[k], bad[k]):
xp[k] = k in is_po or any(xp[w] for w in c.fanout[k])
return xp
def podem(c: Circuit, fault: Fault, stats: Optional[dict[str, int]] = None) -> Optional[tuple[int, ...]]:
"""Return a test with X for free inputs, or None if the fault is redundant."""
site, s = fault
pi_pos = {line: k for k, line in enumerate(c.pi)}
assign = [X] * len(c.pi)
stack: list[list[int]] = []
steps = backtracks = 0
while True:
steps += 1
good = c.simulate(assign)
bad = c.simulate(assign, fault)
if any(is_effect(good[o], bad[o]) for o in c.po):
if stats is not None:
stats.update(steps=steps, backtracks=backtracks)
return tuple(assign)
xp = x_paths(c, good, bad)
front = [g for g in d_frontier(c, good, bad) if xp[g]]
possible = good[site] != s and (good[site] == X or bool(front))
if possible:
if good[site] == X:
k, v = site, 1 - s
else:
gate = front[0]
k = next(j for j in c.fanin[gate] if X in (good[j], bad[j]))
cv = controlling(c.op[gate])
v = 0 if cv is None else 1 - cv
while c.kind[k] != "pi":
v ^= inversion(c.op[k])
k = next(j for j in c.fanin[k] if X in (good[j], bad[j]))
assign[pi_pos[k]] = v
stack.append([pi_pos[k], v, 0])
else:
while stack and stack[-1][2]:
assign[stack.pop()[0]] = X
if not stack:
if stats is not None:
stats.update(steps=steps, backtracks=backtracks)
return None
top = stack[-1]
top[1], top[2] = 1 - top[1], 1
assign[top[0]] = top[1]
backtracks += 1
td2net.py 239 lines
# SPDX-License-Identifier: MIT
# Shared helper of the td2 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 three-valued simulation of the good
circuit and of one faulty circuit, and brute-force detection over all input
vectors. It holds no test generation, learning, testability or compaction
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_fan_algorithm.py 198 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fan-algorithm/. The authors are listed in prov/DJVVW8.jsonl.
import random
import pytest
from fan_algorithm import (
bound_and_head_lines,
d_frontier,
dominators,
fan,
imply,
postdominator_tree,
unique_sensitization,
x_paths,
)
from podem_baseline import podem
from td2net import X, Circuit, completions, random_circuit
# Unique sensitization and multiple backtrace: the fault x/0 must pass g, u and z.
C1 = Circuit(
["x", "e", "k", "f", "h"],
[
("s", "OR", ["e", "k"]),
("g", "AND", ["x", "s"]),
("w1", "NOR", ["e", "f"]),
("u", "AND", ["g", "w1"]),
("w2", "NOR", ["e", "h"]),
("z", "AND", ["u", "w2"]),
],
["z"],
)
# Head lines: the consensus circuit z = ab + a'c + bc with b and c widened into fanout-free cones.
C2 = Circuit(
["a", "b1", "b2", "c1", "c2"],
[
("b", "AND", ["b1", "b2"]),
("c", "OR", ["c1", "c2"]),
("na", "NOT", ["a"]),
("p", "AND", ["a", "b"]),
("q", "AND", ["na", "c"]),
("r", "AND", ["b", "c"]),
("z", "OR", ["p", "q", "r"]),
],
["z"],
)
def run(c, fault):
sf, sp = {}, {}
t = fan(c, fault, sf)
tp = podem(c, fault, sp)
return t, sf, tp, sp
def test_page_example_unique_sensitization():
t, sf, tp, sp = run(C1, (C1.line("x"), 0))
assert t == (1, 0, 1, 0, 0) and sf == {"steps": 6, "backtracks": 0}
assert tp == (1, 0, 1, 0, 0) and sp == {"steps": 7, "backtracks": 1}
def test_page_example_head_lines():
fault = (C2.line("r"), 0)
_, heads = bound_and_head_lines(C2, fault)
assert [C2.name[h] for h in heads] == ["a", "b", "c"]
t, sf, tp, sp = run(C2, fault)
assert t is None and tp is None and not C2.detectable(fault)
assert sf == {"steps": 7, "backtracks": 3}
assert sp == {"steps": 13, "backtracks": 6}
def test_page_example_totals():
for c, totals in ((C1, (13, 9)), (C2, (24, 13))):
tp = tf = 0
for fault in c.faults():
_, sf, _, sp = run(c, fault)
tp += sp["backtracks"]
tf += sf["backtracks"]
assert (tp, tf) == totals
def test_head_lines_cut_the_bound_lines():
rng = random.Random(7)
for _ in range(60):
c = random_circuit(rng, rng.randint(2, 6), rng.randint(2, 9))
fault = rng.choice(c.faults())
bound, heads = bound_and_head_lines(c, fault)
assert len(heads) <= len(c.pi)
for v in c.all_vectors()[:16]:
good = c.simulate(v)
bad = c.simulate(v, fault)
g2, b2 = imply(c, fault, {h: good[h] for h in heads})
for k in range(c.n_lines):
if bound[k]:
assert (g2[k], b2[k]) == (good[k], bad[k])
def brute_dominators(c, g):
"""Lines d such that no path from g to an output avoids d, by one search per d."""
po = set(c.po)
def reaches(avoid):
if g == avoid:
return False
seen, stack = {g}, [g]
while stack:
u = stack.pop()
if u in po:
return True
for w in c.fanout[u]:
if w != avoid and w not in seen:
seen.add(w)
stack.append(w)
return False
if not reaches(-1):
return []
return [d for d in sorted(c.cone(g)) if not reaches(d)]
def test_dominators_against_path_search():
rng = random.Random(5)
for _ in range(80):
c = random_circuit(rng, rng.randint(2, 6), rng.randint(2, 12))
ipdom = postdominator_tree(c)
for g in range(c.n_lines):
assert sorted(dominators(ipdom, g)) == brute_dominators(c, g)
ipdom = postdominator_tree(C1)
assert [C1.name[d] for d in dominators(ipdom, C1.line("g"))] == ["g", "u", "z"]
def test_unique_sensitization_values_are_necessary():
rng = random.Random(11)
checked = 0
for _ in range(150):
c = random_circuit(rng, rng.randint(3, 6), rng.randint(3, 9))
fault = rng.choice(c.faults())
_, heads = bound_and_head_lines(c, fault)
tests = c.detecting_vectors(fault)
for v in tests[:4]:
good = c.simulate(v)
part = {h: good[h] for h in heads if rng.random() < 0.5}
g, b = imply(c, fault, part)
if any(X not in (g[o], b[o]) and g[o] != b[o] for o in c.po):
continue # FAN returns at line L5 before it looks at R
xp = x_paths(c, g, b)
front = [k for k in d_frontier(c, g, b) if xp[k]]
req = unique_sensitization(c, fault, g, front, c.cone(fault[0]), postdominator_tree(c))
for k, val in req:
checked += 1
assert good[k] == val
assert checked > 50
def check(c, fault):
sf, sp = {}, {}
t = fan(c, fault, sf)
tp = podem(c, fault, sp)
det = c.detectable(fault)
assert (t is not None) == det
assert (tp is not None) == det
_, heads = bound_and_head_lines(c, fault)
assert sf["steps"] <= 2 ** (len(heads) + 1)
assert sp["steps"] <= 2 ** (len(c.pi) + 1)
if t is not None:
assert len(t) == len(c.pi)
assert all(c.detects(v, fault) for v in completions(t))
return sf["backtracks"], sp["backtracks"]
@pytest.mark.parametrize("seed", range(60))
def test_random_circuits_against_exhaustive_search(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, 10), ops=ops)
for fault in c.faults():
check(c, fault)
def test_c17_all_faults():
c = 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"],
)
for fault in c.faults():
assert fan(c, fault) is not None
check(c, fault)
assert X == 2
History
Goel's PODEM of 1981 made decisions only on the primary inputs. Hideo Fujiwara and Takeshi Shimono published FAN in 1983, and the name stands for a fanout-oriented method. They kept the search of PODEM and added head lines, multiple backtrace, unique sensitization and immediate implications, and they reported shorter run times than PODEM on their test circuits. Schulz, Trischler and Sarfert built SOCRATES on FAN in 1988 and added learning. From about 1990, SAT-based engines took over the hardest faults, but the FAN rules stayed in structural test generators.
References
- H. Fujiwara and T. Shimono, On the acceleration of test generation algorithms, IEEE Transactions on Computers C-32(12), 1137 to 1144, 1983, head lines, multiple backtrace, unique sensitization, immediate implications, and the comparison with PODEM
- 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, PODEM, the search that FAN keeps
- M. H. Schulz, E. Trischler and T. M. Sarfert, SOCRATES, a highly efficient automatic test pattern generation system, IEEE Transactions on Computer-Aided Design 7(1), 126 to 137, 1988, the FAN-based system with improved implication, unique sensitization and multiple backtrace
- 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 (FAN)
- 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 (FAN)
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 DJVVW8 Edit this page History Report an error Markdown