Algorithm Search⌘K

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
Properties
completedeterministicexactiterative
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 CC with nn primary inputs and LL lines in topological order, and a fault (ℓ,s)(\ell, s), line ℓ\ell stuck at ss. 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 {0,1,X}\{0, 1, X\} 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 hh is reached form a tree with hh 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 HH.

The algorithm

  1. FAN(C, (ℓ, s))
  2. 1mark the bound lines; H ← the head lines
  3. 2set every line of H to X; stack ← empty
  4. 3loop
  5. 4simulate the good and the faulty circuit with three values from the values on H
  6. 5if some primary output has D or D' then return JUSTIFY()
  7. 6R ← UNIQUE-SENSITIZATION()
  8. 7if ℓ 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
  9. 8O ← {(ℓ, ¬s)} if ℓ has X, plus each (j, v) in R with j at X
  10. 9if 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
  11. 10(h, u) ← MULTIPLE-BACKTRACE(O)
  12. 11set h to u; push (h, u, not flipped)
  13. 12else
  14. 13pop each entry that is flipped and set its line to X
  15. 14if the stack is empty then return "untestable"
  16. 15flip the value of the top entry, set its line to it, and mark it flipped
  17. UNIQUE-SENSITIZATION()
  18. 16if ℓ has X or more than one D-frontier gate has an X-path then return ∅
  19. 17R ← ∅; G ← the D-frontier gate with an X-path
  20. 18for each gate d with a controlling value c that lies on every path from G to a primary output, G included do
  21. 19for each input j of d outside the fanout cone of ℓ do add (j, ¬c) to R
  22. 20return R
  23. MULTIPLE-BACKTRACE(O)
  24. 21n0(k) ← 0 and n1(k) ← 0 for each line k; for each (k, v) in O add 1 to n_v(k)
  25. 22for each line k not in H with n0(k) + n1(k) > 0, in reverse topological order do
  26. 23if k is a fanout stem with n0(k) > 0 and n1(k) > 0 then set the smaller count to 0 (n1 on a tie)
  27. 24for each value v with n_v(k) > 0 do
  28. 25u ← v xor inversion(k)
  29. 26if 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
  30. 27else add n_v(k) to n_u(j) for every input j of k with X
  31. 28return (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)
  32. JUSTIFY()
  33. 29for 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
  34. 30return 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 uu 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 O(L+P)O(L + P) time, where PP is the number of gate input pins. Line L18 needs the gates through which every path from GG to an output passes. These are the post-dominators of GG, 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 RR 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 bb and cc widened into small trees: b=b1b2b = b_1 b_2, c=c1+c2c = c_1 + c_2, na=¬ana = \lnot a, p=abp = ab, q=a‾cq = \overline{a}c, r=bcr = bc and z=p+q+rz = p + q + r. The stems aa, bb and cc fan out, so their branches and everything after them are bound. The head lines are aa, bb and cc, three decision lines for five inputs. The fault rr stuck at 0 is redundant, because bcbc is the consensus of abab and a‾c\overline{a}c. Each pass takes the first candidate on a tie.

pass a b ca\,b\,c values action
1 X X X all X objective (r,1)(r, 1): the AND rr gives a 1-count to bb and to cc; set b=1b = 1
2 X 1 X rr = X objective (r,1)(r, 1); set c=1c = 1
3 X 1 1 r=Dr = D, D-frontier {z}\{z\} the D-frontier gate is the output zz itself, so R={(p,0),(q,0)}R = \{(p, 0), (q, 0)\}. p=0p = 0 gives aa a 0-count and q=0q = 0 gives aa a 1-count through nana; tie, set a=0a = 0
4 0 1 1 q=1q = 1, z=1z = 1 (q,0)(q, 0) fails and the D-frontier is empty: flip aa to 1
5 1 1 1 p=1p = 1, z=1z = 1 (p,0)(p, 0) fails: pop aa, flip cc to 0
6 X 1 0 r=0r = 0 rr is at its stuck value: pop cc, flip bb to 0
7 X 0 X r=0r = 0 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 b1b_1, b2b_2, c1c_1 and aa, then tries both values of aa again after it flips c1c_1 and sets c2c_2, and it needs 13 passes and 6 flips. Its tree enumerates the ways to make b=1b = 1 and c=1c = 1, which FAN never looks at.

Unique sensitization and multiple backtrace. The second circuit is s=e+ks = e + k, g=xsg = x s, w1=e+f‾w_1 = \overline{e + f}, u=gw1u = g w_1, w2=e+h‾w_2 = \overline{e + h} and z=uw2z = u w_2, with inputs in the order x,e,k,f,hx, e, k, f, h. The fault is xx stuck at 0, and xx is a decision line because it is the fault site.

pass x e k f hx\,e\,k\,f\,h values action
1 X X X X X all X objective (x,1)(x, 1); set x=1x = 1
2 1 X X X X x=Dx = D, D-frontier {g}\{g\} every path from gg passes gg, uu and zz: R={(s,1),(w1,1),(w2,1)}R = \{(s, 1), (w_1, 1), (w_2, 1)\}. Counts: ee gets one 1-count from ss and two 0-counts from w1w_1 and w2w_2; set e=0e = 0
3 1 0 X X X ss = X objectives (s,1),(w1,1),(w2,1)(s,1), (w_1,1), (w_2,1); set k=1k = 1
4 1 0 1 X X g=Dg = D set f=0f = 0
5 1 0 1 0 X u=Du = D set h=0h = 0
6 1 0 1 0 0 z=Dz = D return 10100

FAN makes no flip. PODEM first takes the one objective "the X input ss of gg to 1", backtraces through the OR to e=1e = 1, and only then sees that w1=0w_1 = 0 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 RR are necessary: every detecting path leaves the single D-frontier gate GG and passes every gate dd of line L18, and a side input of dd outside the fanout cone of ℓ\ell 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 ∣H∣≤n|H| \le n, 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 CC be a combinational circuit with nn primary inputs and lines in topological order, and let (ℓ,s)(\ell, s) be the fault "line ℓ\ell stuck at ss". The proof follows the proof for PODEM and adds what is new in FAN: the decisions are on head lines, and the required values RR 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 ℓ\ell 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. HH holds the free lines with a bound fanout, and ℓ\ell if ℓ\ell is a primary input. For h∈Hh \in H with h≠ℓh \ne \ell, let F(h)F(h) be the set of lines from which a path of free lines leads to hh.

Lemma 1 (the cones). (a) A free line has no fanout branch among its fanouts unless it is in HH, so every free line outside HH has exactly one fanout or none. (b) The sets F(h)F(h) are disjoint trees, and each one contains a primary input. (c) ∣H∣≤n|H| \le n. (d) Every input of a bound line is bound or in HH.

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 HH. (d) An input of a bound line is bound or free, and a free input with a bound fanout is in HH. (b) A line of HH has no free fanout: with one sink, that sink is the bound fanout, and with more, all fanouts are branches. Take u∈F(h)u \in F(h) with u≠hu \ne h. It is free and not in HH, 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 uu gives the only path of free lines out of uu, and the path stops at the first line of HH. So uu lies in exactly one set F(h)F(h), and inside F(h)F(h) every line except hh has one fanout, which makes F(h)F(h) a tree with root hh. Walking back along inputs from hh inside free lines ends at a primary input, because a free line is never a branch. (c) The sets F(h)F(h) are disjoint and each holds a primary input. If ℓ\ell is a primary input, it is bound, so it lies in no F(h)F(h). So ∣H∣≤n|H| \le n. □\square

Lemma 2 (head lines cut the circuit). Let τ\tau be a two-valued input vector and let AτA_\tau give each line of HH its good value under τ\tau. Then line L4 run on AτA_\tau gives every bound line the same good and faulty values as the simulation of τ\tau. If AA is any partial assignment on HH that AτA_\tau extends, every bound line that is known under AA has the same value under τ\tau.

Proof. Induction over the bound lines in topological order. A line of HH gets its value from AτA_\tau, and its faulty value equals its good value unless it is ℓ\ell: a free line is not reached from ℓ\ell, so the fault does not change it, and for ℓ\ell the faulty value is ss in both computations. A bound line that is not in HH is not a primary input, since the only bound primary input can be ℓ\ell, which is in HH. So it is a gate or a branch, and by Lemma 1(d) its inputs are bound or in HH, where the induction gives the values of τ\tau. The gate rule is the same in both computations, and for ℓ\ell the faulty value is ss in both. For the second claim, three-valued simulation is monotone: a value known under AA stays the same under every assignment that extends AA (the Fact of the PODEM proof), and AτA_\tau extends AA. □\square

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 ℓ\ell and never has an effect, so detection is decided on the bound outputs.

Lemma 3 (justification). For every h∈Hh \in H with h≠ℓh \ne \ell and every value vv, the procedure of line L29 sets primary inputs of F(h)F(h) only, and three-valued simulation then gives hh the value vv, whatever the other inputs are.

Proof. Induction on the tree F(h)F(h) from the leaves. A primary input is set to vv. For NOT and BUF, the input gets the needed value. For a gate with a controlling value cc, when the inputs need the value cc, the first input gets cc, 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. □\square

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 HH its value in the current assignment AA, and ℓ\ell, if it is a primary input in HH, 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 AA, so some primary output has an effect. The Fact of the PODEM proof extends this to every completion. □\square

Lemma 5 (the required values are necessary). Suppose that line L5 did not return under AA, that ℓ\ell is not X, and that the D-frontier gates with an X-path are one gate GG. Let τ\tau be a vector that detects the fault and with AτA_\tau extending AA. Then every pair (j,v)(j, v) in RR has value vv on line jj under τ\tau.

Proof. Take a path ℓ=p0,…,pr=o\ell = p_0, \ldots, p_r = o of lines that differ under τ\tau (Lemma 1 of the PODEM proof). As in Lemma 3 of the PODEM proof, let pip_i be the last line of the path with an effect under AA. Then i<ri < r, and pi+1p_{i+1} is a D-frontier gate and pi+1,…,prp_{i+1}, \ldots, p_r is an X-path. So pi+1=Gp_{i+1} = G, and the rest of the path goes from GG to an output. Every gate dd of line L18 lies on all such paths, so the path enters dd through an input whose values differ under τ\tau, and the output of dd also differs. Let jj be an input of dd outside the fanout cone of ℓ\ell. The fault does not reach jj, so jj has the same value in both circuits. If that value were the controlling value cc of dd, the output of dd would be fixed by jj in both circuits and would not differ. So jj has the value ¬c\lnot c under τ\tau. □\square

Lemma 6 (safe pruning). If the test of line L7 fails for AA, then no vector τ\tau with AτA_\tau extending AA detects the fault.

Proof. There are three cases. If ℓ\ell has the good value ss, the good and the faulty circuit agree everywhere under any such τ\tau, by Lemma 2 and the monotone simulation. If ℓ\ell has the value ¬s\lnot s 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 AA agree with τ\tau by Lemma 2. If some pair (j,v)(j, v) of RR has jj at ¬v\lnot v under AA, then jj has the value ¬v\lnot v under every such τ\tau by Lemma 2, and Lemma 5 says that no such τ\tau detects the fault. (jj is bound or in HH, since it is an input of a bound gate.) □\square

Lemma 7 (the backtrace ends on an open head line). When the test of line L7 holds, line L10 returns a line of HH whose value is X.

Proof. Lines L8 and L9 give a nonempty set OO of lines with an X: the site ℓ\ell, inputs of bound gates, or an input of the D-frontier gate GG, which exists by the test of line L7 as in Lemma 4 of the PODEM proof. All these lines are bound or in HH. 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 HH has an input with an X: a gate whose inputs are all known is known in each circuit, except the faulty value of ℓ\ell, which is ss, and then the X of ℓ\ell 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 HH, and the lines are finite, so some line of HH with an X receives a count, and line L28 returns one. □\square

Lemma 8 (the search tree). The stack holds distinct lines of HH, and the loop of line L3 runs at most 2∣H∣+1−1≤2n+1−12^{|H| + 1} - 1 \le 2^{n+1} - 1 times.

Proof. Line L11 assigns an open line of HH, by Lemma 7, and lines L13 and L15 pop and flip as in PODEM. The choice at lines L8 to L10 depends only on AA. So the passes are a depth-first walk of a binary tree of depth at most ∣H∣|H|, in which each node is entered once, and ∣H∣≤n|H| \le n by Lemma 1(c). □\square

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 τ\tau detects the fault. Follow the nodes of the tree whose assignments AA are extended by AτA_\tau, starting at the root, where all of HH 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 HH, and one of the two children agrees with AτA_\tau. The search enters both children before it leaves the node. At depth ∣H∣|H| the assignment is AτA_\tau, and by Lemma 2 the bound outputs have the values of τ\tau, so line L5 returns there. So FAN returns a vector before the stack can become empty at line L14. □\square

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 O(L(L+P))O(L (L + P)) time by the simple meet-walk used here, and in almost linear time with the Lengauer and Tarjan method. Each pass then costs O(L+P)O(L + P) for the simulation, the D-frontier, the X-paths, the list RR and the backtrace. The tree has at most 2h+1−12^{h+1} - 1 nodes for h=∣H∣h = |H| head lines, so the worst case is O(L(L+P)+2h(L+P))O(L (L + P) + 2^h (L + P)) time. Since h≤nh \le n, 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 O(L+n)O(L + n) 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 RR 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 RR.
  • 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.

fan_algorithm.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example