Algorithm Search⌘K

Algorithmcore

Deductive fault simulation

Also called Armstrong deductive simulation.

Armstrong's fault simulator that propagates, with the good values, the list of faults that flip each line, computed by set operations at each gate.

Time
O(T (L + P) (1 + F)) worst
Space
O(L (1 + F)) extra
Where
F = the number of faults; L = the number of lines; P = the number of gate input pins; T = the number of vectors
Properties
deterministicexactiterative
Origin
D. B. Armstrong, 1972

Deductive fault simulation is a method for fault simulation that simulates only the good circuit and, for each line, deduces the set of faults that would give the line the opposite value. This set, the fault list of the line, follows from the good values and the fault lists of the gate inputs by unions, intersections and differences. No faulty circuit is ever evaluated. The fault list of a primary output is the set of faults that the vector detects there, for all single stuck-at faults at once, in one pass over the circuit.

In plain words

Run the good circuit on one input. Next to each wire, keep a list of the breaks that would flip that wire.

The list of a gate output comes from the lists of its inputs. Take an AND gate whose inputs are all 1. Then any break that flips any input flips the output, so the output list is all the input lists together. If one input is 0, only a break that flips that input, and does not flip another input to 0, flips the output. If two inputs are 0, a break must flip both of them.

At each wire, add the break of that wire itself that gives the opposite value. The list at an output is the set of breaks this input finds.

The problem

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

For a vector tt, a line kk with good value g(k)g(k) and an alive fault ff, write f(k)f(k) for the value of kk in the circuit with fault ff. The fault list of kk is

Lk={f alive:f(k)≠g(k)}.\mathcal{L}_k = \{f \text{ alive} : f(k) \ne g(k)\}.

Since the values are 0 and 1, a fault in Lk\mathcal{L}_k gives kk the value ¬g(k)\lnot g(k), so the list needs no values, only faults.

The algorithm

For a gate with inputs j1,…,jdj_1, \ldots, j_d, the rule that gives the list of its output from the lists of its inputs depends on the gate type and the good input values. A buffer, an inverter and a fanout branch copy the list of their input. For AND and NAND the controlling value is c=0c = 0, and for OR and NOR it is c=1c = 1. Let SS be the set of inputs at cc. Then

Lgate={⋃jLjif S=∅,⋂j∈SLj∖⋃j∉SLjif S≠∅.\mathcal{L}_{\text{gate}} = \begin{cases} \bigcup_{j} \mathcal{L}_j & \text{if } S = \emptyset, \\ \bigcap_{j \in S} \mathcal{L}_j \setminus \bigcup_{j \notin S} \mathcal{L}_j & \text{if } S \ne \emptyset. \end{cases}

For XOR and XNOR, the output list is the set of faults that appear in an odd number of input lists, the symmetric difference of the lists.

  1. DEDUCTIVE-FAULT-SIMULATION(C, vectors, faults, drop)
  2. alive ← faults
  3. 1for each vector t do
  4. 2simulate the good circuit on t, which gives g(k) for every line k
  5. 3for each line k in topological order do
  6. 4if k is a primary input then 𝓛[k] ← ∅
  7. 5else 𝓛[k] ← the rule of the gate of k on the good values and the lists of its inputs
  8. 6if the fault k stuck at ¬g(k) is alive then add it to 𝓛[k]
  9. 7D ← the union of 𝓛[o] over the primary outputs o; report D as detected by t
  10. 8if drop then alive ← alive ∖ D

Line L6 adds the local fault of the line. The fault kk stuck at g(k)g(k) never enters a list, since it does not change kk under this vector. A stem fault enters the list of the stem and, through the copy rule, the lists of all its branches. A branch fault enters only the list of its branch.

Example

The circuit is g=NAND(a,b)g = \mathrm{NAND}(a, b), h=NAND(b,c)h = \mathrm{NAND}(b, c), z=NAND(g,h)z = \mathrm{NAND}(g, h), so z=ab+bcz = ab + bc. The stem bb has the branches bgb_g into gg and bhb_h into hh, so there are 8 lines and 16 faults. Take the vector abc=111abc = 111, with all 16 faults alive.

line good value how the list is formed fault list
aa 1 input, plus a/0 {a/0}
bb 1 input, plus b/0 {b/0}
bgb_g 1 copy of bb, plus bgb_g/0 {b/0, bgb_g/0}
bhb_h 1 copy of bb, plus bhb_h/0 {b/0, bhb_h/0}
cc 1 input, plus c/0 {c/0}
gg 0 no input at 0: union, plus g/1 {a/0, b/0, bgb_g/0, g/1}
hh 0 no input at 0: union, plus h/1 {b/0, bhb_h/0, c/0, h/1}
zz 1 both inputs at 0: intersection, plus z/0 {b/0, z/0}

The vector detects b/0 and z/0. At zz both inputs are at the controlling value 0, so a fault flips zz only if it flips both gg and hh. Only the stem fault b/0 does that, since it reaches gg through bgb_g and hh through bhb_h. The fault a/0 flips gg alone and leaves h=0h = 0, which keeps z=1z = 1. This is reconvergent fanout, and the intersection handles it with no special case.

For the sequence 101, 010, 011, 110 with dropping, the list of zz is {b/1, bgb_g/1, bhb_h/1, g/0, h/0, z/1}, then {a/1, c/1}, then {b/0, bhb_h/0, c/0, h/1, z/0}, then {a/0, bgb_g/0, g/1}, the first detections in the table of the fault simulation page. The set operations of the run touch 40 list elements in all, against 54 without dropping.

Correctness

The proof is an induction over the lines in topological order. Assume that the list of each input jj of a gate is correct, so that a fault ff that does not sit on the gate output flips exactly the inputs whose lists hold ff. The gate output then flips in exactly the cases that the rule selects. For an AND-type gate with no input at cc, the output flips as soon as one input flips to cc. With inputs at cc, the output flips only if no input is at cc under ff: every input of SS flips, and no other input flips to cc. For XOR, each flipped input flips the output once, so the output flips for an odd number of them. A fault on the gate output sets it to its stuck value and differs exactly when that value is ¬g(k)\lnot g(k), which is line L6. The full proof checks each gate type and the induction.

Proof: The deductive list rules are exact for every gate typefull

Let CC be a combinational circuit with lines 0,…,L−10, \ldots, L - 1 in topological order, so every input of a line has a smaller index. Fix a two-valued vector tt and a set AA of alive single stuck-at faults. Write g(k)g(k) for the value of line kk in the good circuit under tt and f(k)f(k) for its value in the circuit with fault ff. The correct fault list of kk is

Ek={f∈A:f(k)≠g(k)}.E_k = \{f \in A : f(k) \ne g(k)\}.

We show that line L5 and line L6 give L[k]=Ek\mathcal{L}[k] = E_k for every line, and then that line L7 reports the detected faults.

Lemma 1 (where a fault acts). If f=(ℓ,v)f = (\ell, v) and ℓ≠k\ell \ne k, then f(k)f(k) is the gate of kk applied to the values f(j)f(j) of its inputs jj. If ℓ=k\ell = k, then f(k)=vf(k) = v.

Proof. The faulty circuit is the good circuit with the value of ℓ\ell replaced by vv. Every other line computes its gate on its inputs, as in the good circuit. □\square

For a fault ff that does not sit on the gate line kk, let If={j input of k:f(j)≠g(j)}I_f = \{j \text{ input of } k : f(j) \ne g(j)\} be the set of flipped inputs. Under ff, input jj has the value g(j)⊕[j∈If]g(j) \oplus [j \in I_f]. So, by Lemma 1, whether ff flips kk depends only on the gate type, the good input values and the set IfI_f. Each rule below says for which sets IfI_f the output flips.

Lemma 2 (buffer, inverter, branch). For a gate with one input jj, ff flips kk if and only if j∈Ifj \in I_f.

Proof. A buffer and a fanout branch copy their input, and an inverter complements it. Both maps are one to one, so the output changes exactly when the input does. □\square

Lemma 3 (AND, NAND, OR, NOR). Let cc be the controlling value, and let SS be the set of inputs with g(j)=cg(j) = c. If S=∅S = \emptyset, ff flips kk if and only if If≠∅I_f \ne \emptyset. If S≠∅S \ne \emptyset, ff flips kk if and only if S⊆IfS \subseteq I_f and If∩Sˉ=∅I_f \cap \bar{S} = \emptyset, where Sˉ\bar{S} is the set of the other inputs.

Proof. The output of such a gate takes one value, the controlled value, when at least one input is at cc, and the other value when no input is at cc. So it flips exactly when the predicate "some input is at cc" changes. If S=∅S = \emptyset, no input is at cc in the good circuit. Under ff, an input is at cc exactly when it is flipped, so the predicate changes exactly when If≠∅I_f \ne \emptyset. If S≠∅S \ne \emptyset, the predicate is true in the good circuit. Under ff, it is false exactly when every input of SS is flipped, away from cc, and no input of Sˉ\bar{S} is flipped, to cc. □\square

Lemma 4 (XOR, XNOR). ff flips kk if and only if ∣If∣|I_f| is odd.

Proof. XOR is the sum of the inputs modulo 2, and XNOR is its complement. Flipping the inputs in IfI_f adds ∣If∣|I_f| modulo 2 to the sum. □\square

Lemma 5 (set form). Let kk be a gate line, and suppose L[j]=Ej\mathcal{L}[j] = E_j for every input jj of kk. Then the rule of line L5 gives exactly the set of faults f∈Af \in A that do not sit on kk and flip kk.

Proof. A fault ff that does not sit on kk is in L[j]\mathcal{L}[j] exactly when j∈Ifj \in I_f. A fault that sits on kk is in no input list, since it does not change any line with a smaller index, so the rule never puts it in. For one input, the copy rule takes the faults with j∈Ifj \in I_f, which is Lemma 2. For AND-type gates with S=∅S = \emptyset, the union of the input lists is the set of faults with If≠∅I_f \ne \emptyset. With S≠∅S \ne \emptyset, the intersection over SS is the set of faults with S⊆IfS \subseteq I_f, and removing the union over Sˉ\bar{S} keeps those with If∩Sˉ=∅I_f \cap \bar{S} = \emptyset, which is Lemma 3. For XOR and XNOR, the symmetric difference of the lists holds a fault exactly when it lies in an odd number of them, that is when ∣If∣|I_f| is odd, which is Lemma 4. □\square

Lemma 6 (each line). After line kk is processed at lines L4 to L6, L[k]=Ek\mathcal{L}[k] = E_k.

Proof. By induction over kk in topological order. Split EkE_k into the faults that sit on kk and the others. A fault that sits on kk is (k,v)(k, v) for v∈{0,1}v \in \{0, 1\}, and by Lemma 1 it flips kk exactly when v=¬g(k)v = \lnot g(k). Line L6 adds exactly this fault, if it is alive. A fault that sits elsewhere does not change a primary input kk, so EkE_k has no other fault when kk is an input, which is line L4. When kk is a gate line, all inputs are already processed and correct by induction, and Lemma 5 shows that line L5 gives exactly the other faults of EkE_k. □\square

Theorem. For each vector, the algorithm reports exactly the alive faults that the vector detects, so its output is the same as that of serial fault simulation, with or without dropping.

Proof. A fault ff is detected by tt when f(o)≠g(o)f(o) \ne g(o) for some primary output oo, that is, when f∈Eof \in E_o for some oo. By Lemma 6, line L7 computes the union of the sets EoE_o, which is exactly the set of alive faults that tt detects. With dropping, line L8 removes them, as serial simulation does, so by induction over the vectors each vector is simulated against the right set of alive faults. □\square

Complexity

The good simulation costs O(L+P)O(L + P) per vector. The rule of a gate with inputs j1,…,jdj_1, \ldots, j_d costs O(∣Lj1∣+⋯+∣Ljd∣)O(|\mathcal{L}_{j_1}| + \cdots + |\mathcal{L}_{j_d}|) with lists kept sorted by fault number and merged, or the same in expected time with hash sets. A list never holds more than the FF alive faults. A line with fanout feeds several gates, but each gate input pin reads one list, so a vector costs O((L+P)(1+F))O((L + P)(1 + F)) in the worst case, and TT vectors cost O(T(L+P)(1+F))O(T (L + P)(1 + F)). This is the same order as serial fault simulation. The lists of all lines take O(L(1+F))O(L (1 + F)) space; a version that frees the list of a line after its last fanout is read keeps fewer.

The gain is in the typical case and is measured, not proved: most lists are short, since most faults do not reach most lines. For the c17 benchmark circuit with its 34 faults and all 32 input vectors in counting order, the code of this page touches 1408 list elements without dropping and 206 with dropping. These are counts on a 6-gate toy circuit, not benchmark results.

Properties

  • Exact. For two-valued vectors on a combinational circuit, the result is the same as serial fault simulation, with or without dropping. The lists of all lines are exact, not only those of the outputs.
  • One pass per vector. All faults are simulated together, and no faulty gate is evaluated.
  • Memory depends on the vector. The size of a list can change a lot from one vector to the next, so the memory is hard to plan.
  • Two values. The rules need the values 0 and 1. With an unknown value X, a fault can turn a 0 into X, and the lists must carry the faulty value too, which makes the rules much more complex.
  • Deterministic. The detected sets do not depend on the order of the faults.

Variants and improvements

  • Event-driven lists. A line needs a new list only if the good value or the list of an input changed since the last vector. Recomputing only those lines, as in event-driven logic simulation, saves work when vectors differ in few inputs.
  • Bit vectors. For a small fault list, a list is a bit vector of FF bits, and the rules become word-wide AND, OR and XOR. The time is then O(F/w)O(F / w) words per pin, whatever the list sizes.
  • Fanout-free regions. Inside a fanout-free region, the list of each line flows to one gate only. So lists are needed only at the roots of the regions. Inside a region, critical path tracing finds the lines whose flip reaches the root, and a fault on such a line is detected exactly when a flip of the root is detected.
  • Concurrent simulation. Concurrent fault simulation keeps a faulty value per list entry and evaluates the faulty gates. It costs gate evaluations but handles more values, timing and sequential circuits more easily.

When to use it

Use deductive simulation when all faults must be simulated against every vector of a combinational circuit, for example to build a fault dictionary for diagnosis, and when values are two-valued. The lists of all lines give, as a side result, the faults that each vector propagates to each line. For grading large test sets with dropping, the textbooks in the references report PPSFP as faster, and for sequential circuits with unknown initial states, concurrent fault simulation handles the X values that deductive rules do not.

Pitfalls

  • Forgetting the local fault. Line L6 must add the fault of the line itself. Without it, gate output faults never enter any list.
  • Adding both local faults. Only kk stuck at ¬g(k)\lnot g(k) enters the list. The fault kk stuck at g(k)g(k) does not flip kk under this vector.
  • Subtracting only for one controlling input. With two or more inputs at cc, the rule is the intersection of their lists minus the lists of the other inputs. Using the union of the controlling lists reports faults that flip only one of them, which leaves the output at its value.
  • XOR as union. A fault that flips two inputs of an XOR leaves its output unchanged. Use the symmetric difference.
  • Stems without branch lines. If a stem and its branches share one list, the faults on single branches are lost, and the list of the stem gets faults that act on one branch only.

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.

deductive_fault_simulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deductive-fault-simulation/. The authors are listed in prov/WGDS9V.jsonl.
"""Deductive fault simulation (Armstrong 1972) of single stuck-at faults.

For one vector, the good circuit is simulated once. Each line then gets its
fault list: the set of faults under which the line has the opposite of its
good value. The list of a line follows from the good values and the lists of
its inputs by set operations, with no faulty gate evaluation:

- buffer, inverter and fanout branch: the list of the input;
- AND, NAND, OR, NOR with controlling value c: if no input has the value c,
  the union of the input lists; else the intersection of the lists of the
  inputs at c, minus the union of the lists of the other inputs;
- XOR, XNOR: the faults that are in an odd number of input lists;

and then the fault of the line stuck at the opposite of its good value is
added. The list of a primary output is the set of faults that the vector
detects there.
"""

from __future__ import annotations

from typing import Iterable, Optional, Sequence

from gatenet import Circuit, Fault, controlling


def gate_list(op: str, vals: Sequence[int], lists: Sequence[set[Fault]]) -> set[Fault]:
    """The faults that flip the output of one gate, from its good input values and input lists."""
    if op in ("BUF", "NOT"):
        return set(lists[0])
    if op in ("XOR", "XNOR"):
        odd: set[Fault] = set()
        for lst in lists:
            odd ^= lst
        return odd
    c = controlling(op)
    at_c = [lst for v, lst in zip(vals, lists) if v == c]
    if not at_c:  # every input is non-controlling: any flipped input flips the output
        out: set[Fault] = set()
        for lst in lists:
            out |= lst
        return out
    out = set.intersection(*at_c)  # every controlling input must flip
    for v, lst in zip(vals, lists):
        if v != c:
            out -= lst  # and no other input may flip to c
    return out


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

    With drop=True a fault is removed after the first vector that detects it.
    If lists_out is a list, the fault lists of all lines are appended to it
    for each vector. Vectors hold the values 0 and 1 only.
    """
    alive = set(c.faults() if faults is None else faults)
    local: list[list[Fault]] = [[] for _ in range(c.n_lines)]
    for f in alive:
        local[f[0]].append(f)
    result: list[set[Fault]] = []
    elements = 0
    for vector in vectors:  # @line L1
        good = c.simulate(vector)  # @line L2
        lst: list[set[Fault]] = [set() for _ in range(c.n_lines)]
        for line in range(c.n_lines):  # @line L3
            if c.kind[line] == "pi":  # @line L4
                here: set[Fault] = set()
            else:  # @line L5
                ins = c.fanin[line]
                here = gate_list(c.op[line], [good[j] for j in ins], [lst[j] for j in ins])
                elements += sum(len(lst[j]) for j in ins)
            for f in local[line]:  # @line L6
                if f in alive and f[1] != good[line]:
                    here.add(f)
            lst[line] = here
        detected: set[Fault] = set()
        for o in c.po:  # @line L7
            detected |= lst[o]
        result.append(detected)
        if lists_out is not None:
            lists_out.append(lst)
        if drop:  # @line L8
            alive -= detected
    if stats is not None:
        stats.update(list_elements=elements)
    return result
gatenet.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the td1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate-level combinational circuits with single stuck-at faults.

A circuit is built from named primary inputs, gates in topological order and
named primary outputs. Every place where a fault can sit is a *line*:

- one stem line for each primary input and for each gate output;
- when a net feeds two or more sinks (gate input pins or primary outputs), one
  branch line for each sink. A net with one sink has no branch line, and the
  sink reads the stem.

Lines are numbered 0, 1, ... in topological order, so every line comes after
the lines it reads. A single stuck-at fault is a pair (line, value). Values are
0, 1 and X (unknown), with X = 2. Building a circuit and simulating one vector
take O(L + P) time for L lines and P gate input pins.

This module holds the circuit model, plain simulation of the good circuit and
of one faulty circuit, and brute-force detection over all input vectors. It
holds no test generation or fault simulation algorithm.
"""

from __future__ import annotations

import random
from itertools import product
from typing import Optional, Sequence

X = 2
OPS = ("AND", "OR", "NAND", "NOR", "NOT", "BUF", "XOR", "XNOR")
_CONTROL = {"AND": 0, "NAND": 0, "OR": 1, "NOR": 1}
_INVERT = {"AND": 0, "OR": 0, "NAND": 1, "NOR": 1, "NOT": 1, "BUF": 0, "XOR": 0, "XNOR": 1}

Fault = tuple[int, int]


def controlling(op: str) -> Optional[int]:
    """The controlling input value of a gate type, or None (NOT, BUF, XOR, XNOR)."""
    return _CONTROL.get(op)


def inversion(op: str) -> int:
    """1 if the gate type inverts (NAND, NOR, NOT, XNOR), else 0."""
    return _INVERT[op]


def eval_gate(op: str, vals: Sequence[int]) -> int:
    """Three-valued output of a gate for input values in {0, 1, X}."""
    if op in ("XOR", "XNOR"):
        if X in vals:
            return X
        r = 0
        for v in vals:
            r ^= v
        return r ^ _INVERT[op]
    if op in ("NOT", "BUF"):
        v = vals[0]
        return X if v == X else v ^ _INVERT[op]
    c = _CONTROL[op]
    if c in vals:
        r = c
    elif X in vals:
        return X
    else:
        r = 1 - c
    return r ^ _INVERT[op]


class Circuit:
    """A combinational circuit as a DAG of lines (see the module comment)."""

    def __init__(
        self,
        inputs: Sequence[str],
        gates: Sequence[tuple[str, str, Sequence[str]]],
        outputs: Sequence[str],
    ) -> None:
        nets = list(inputs) + [g[0] for g in gates]
        if len(set(nets)) != len(nets):
            raise ValueError("net names must be unique")
        defined = set(inputs)
        sinks: dict[str, list[tuple[str, int, int]]] = {n: [] for n in nets}
        for gi, (name, op, fanin) in enumerate(gates):
            if op not in OPS:
                raise ValueError(f"unknown gate type {op}")
            if (op in ("NOT", "BUF")) != (len(fanin) == 1) or not fanin:
                raise ValueError(f"wrong number of inputs for {name}")
            for pin, src in enumerate(fanin):
                if src not in defined:
                    raise ValueError(f"{src} is used before it is defined")
                sinks[src].append(("gate", gi, pin))
            defined.add(name)
        for k, src in enumerate(outputs):
            if src not in defined:
                raise ValueError(f"unknown output {src}")
            sinks[src].append(("po", k, 0))

        self.name: list[str] = []
        self.kind: list[str] = []
        self.op: list[str] = []
        self.fanin: list[list[int]] = []
        self.index: dict[str, int] = {}
        pin_line: dict[tuple[str, int, int], int] = {}

        def add(name: str, kind: str, op: str, fanin: list[int]) -> int:
            line = len(self.name)
            self.name.append(name)
            self.kind.append(kind)
            self.op.append(op)
            self.fanin.append(fanin)
            self.index[name] = line
            return line

        def add_net(net: str, kind: str, op: str, fanin: list[int]) -> None:
            stem = add(net, kind, op, fanin)
            sk = sinks[net]
            if len(sk) < 2:
                for s in sk:
                    pin_line[s] = stem
                return
            for s in sk:
                if s[0] == "po":
                    label = f"{net}>out{s[1]}" if len(outputs) > 1 else f"{net}>out"
                else:
                    gname = gates[s[1]][0]
                    same = sum(1 for t in sk if t[0] == "gate" and t[1] == s[1])
                    label = f"{net}>{gname}" + (f".{s[2]}" if same > 1 else "")
                pin_line[s] = add(label, "branch", "BUF", [stem])

        self.pi: list[int] = []
        for net in inputs:
            add_net(net, "pi", "PI", [])
            self.pi.append(self.index[net])
        for gi, (name, op, fanin) in enumerate(gates):
            add_net(name, "gate", op, [pin_line[("gate", gi, p)] for p in range(len(fanin))])
        self.po: list[int] = [pin_line[("po", k, 0)] for k in range(len(outputs))]

        self.n_lines = len(self.name)
        self.fanout: list[list[int]] = [[] for _ in range(self.n_lines)]
        for line in range(self.n_lines):
            for j in self.fanin[line]:
                self.fanout[j].append(line)
        self.level = [0] * self.n_lines
        for line in range(self.n_lines):
            if self.fanin[line]:
                self.level[line] = 1 + max(self.level[j] for j in self.fanin[line])

    def line(self, name: str) -> int:
        return self.index[name]

    def faults(self) -> list[Fault]:
        """All 2L single stuck-at faults, in line order."""
        return [(line, v) for line in range(self.n_lines) for v in (0, 1)]

    def fault_name(self, fault: Fault) -> str:
        return f"{self.name[fault[0]]}/{fault[1]}"

    def simulate(self, vector: Sequence[int], fault: Optional[Fault] = None) -> list[int]:
        """Values of all lines for one input vector (entries 0, 1 or X), with an optional fault."""
        vals = [X] * self.n_lines
        k = 0
        for line in range(self.n_lines):
            if self.kind[line] == "pi":
                v = vector[k]
                k += 1
            else:
                v = eval_gate(self.op[line], [vals[j] for j in self.fanin[line]])
            if fault is not None and fault[0] == line:
                v = fault[1]
            vals[line] = v
        return vals

    def outputs(self, vector: Sequence[int], fault: Optional[Fault] = None) -> tuple[int, ...]:
        vals = self.simulate(vector, fault)
        return tuple(vals[o] for o in self.po)

    def detects(self, vector: Sequence[int], fault: Fault) -> bool:
        """True if some output has a known value in both circuits and the values differ."""
        good = self.outputs(vector)
        bad = self.outputs(vector, fault)
        return any(g != X and b != X and g != b for g, b in zip(good, bad))

    def all_vectors(self) -> list[tuple[int, ...]]:
        return list(product((0, 1), repeat=len(self.pi)))

    def detecting_vectors(self, fault: Fault) -> list[tuple[int, ...]]:
        """Brute force: every two-valued input vector that detects the fault."""
        return [v for v in self.all_vectors() if self.detects(v, fault)]

    def detectable(self, fault: Fault) -> bool:
        return any(self.detects(v, fault) for v in self.all_vectors())

    def cone(self, line: int) -> set[int]:
        """The lines reachable from a line, the line included."""
        seen = {line}
        stack = [line]
        while stack:
            u = stack.pop()
            for w in self.fanout[u]:
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
        return seen


def completions(vector: Sequence[int]) -> list[tuple[int, ...]]:
    """All two-valued vectors that agree with a vector that may hold X."""
    choices = [(0, 1) if v == X else (v,) for v in vector]
    return list(product(*choices))


def random_circuit(
    rng: random.Random,
    n_inputs: int,
    n_gates: int,
    ops: Sequence[str] = ("AND", "OR", "NAND", "NOR", "NOT"),
    max_fanin: int = 3,
) -> Circuit:
    """A random circuit. Every net with no sink becomes a primary output."""
    inputs = [f"i{k}" for k in range(n_inputs)]
    nets = list(inputs)
    gates: list[tuple[str, str, list[str]]] = []
    for k in range(n_gates):
        op = rng.choice(list(ops))
        arity = 1 if op in ("NOT", "BUF") else rng.randint(2, max(2, min(max_fanin, len(nets))))
        arity = min(arity, len(nets))
        if op not in ("NOT", "BUF") and arity < 2:
            op, arity = "NOT", 1
        fanin = rng.sample(nets, arity)
        name = f"g{k}"
        gates.append((name, op, fanin))
        nets.append(name)
    used = {src for _, _, fanin in gates for src in fanin}
    outputs = [n for n in nets if n not in used]
    extra = [g[0] for g in gates if g[0] in used]
    if extra and rng.random() < 0.5:
        outputs.append(rng.choice(extra))
    return Circuit(inputs, gates, outputs)
test_deductive_fault_simulation.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deductive-fault-simulation/. The authors are listed in prov/WGDS9V.jsonl.

import random
from itertools import product

from deductive_fault_simulation import deductive_fault_simulation, gate_list
from gatenet import Circuit, random_circuit

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

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

# ISCAS-85 c17: six NAND gates, two outputs, reconvergent fanout at 3, 11 and 16.
C17 = Circuit(
    ["1", "2", "3", "6", "7"],
    [
        ("10", "NAND", ["1", "3"]),
        ("11", "NAND", ["3", "6"]),
        ("16", "NAND", ["2", "11"]),
        ("19", "NAND", ["11", "7"]),
        ("22", "NAND", ["10", "16"]),
        ("23", "NAND", ["16", "19"]),
    ],
    ["22", "23"],
)
C17_COUNTS = [9, 10, 9, 12, 10, 12, 8, 13, 8, 7, 10, 9, 9, 8, 13, 14, 11, 12, 11, 13, 11, 11, 9, 13, 8, 7, 10, 9, 8, 4, 13, 14]

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

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


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


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


def test_gate_rule_against_flipping_inputs():
    # Each input list is a set of abstract faults; a fault flips exactly the inputs whose list holds it.
    rng = random.Random(3)
    for op in OPS:
        for _ in range(200):
            n = 1 if op in ("NOT", "BUF") else rng.randint(2, 4)
            vals = [rng.randint(0, 1) for _ in range(n)]
            lists = [{f for f in range(6) if rng.random() < 0.4} for _ in range(n)]
            c = Circuit([f"x{i}" for i in range(n)], [("y", op, [f"x{i}" for i in range(n)])], ["y"])
            good = c.outputs(vals)[0]
            expect = set()
            for f in range(6):
                flipped = [v ^ (f in lst) for v, lst in zip(vals, lists)]
                if c.outputs(flipped)[0] != good:
                    expect.add(f)
            assert gate_list(op, vals, lists) == expect


def test_page_lists_at_111():
    lists = []
    deductive_fault_simulation(C3, [(1, 1, 1)], drop=False, lists_out=lists)
    got = {C3.name[k]: {C3.fault_name(f) for f in lists[0][k]} for k in range(C3.n_lines)}
    assert got == {
        "a": {"a/0"}, "b": {"b/0"}, "b>g": {"b/0", "b>g/0"}, "b>h": {"b/0", "b>h/0"}, "c": {"c/0"},
        "g": {"a/0", "b/0", "b>g/0", "g/1"}, "h": {"b/0", "b>h/0", "c/0", "h/1"}, "z": {"b/0", "z/0"},
    }


def test_lists_are_exact_on_every_line():
    # The list of each line is exactly the set of faults that flip that line.
    rng = random.Random(11)
    for c in [C3, C17, CONSENSUS] + [random_circuit(rng, 4, 9, ops=OPS) for _ in range(20)]:
        for vector in c.all_vectors():
            lists = []
            deductive_fault_simulation(c, [vector], drop=False, lists_out=lists)
            good = c.simulate(vector)
            for f in c.faults():
                bad = c.simulate(vector, f)
                for k in range(c.n_lines):
                    assert (f in lists[0][k]) == (bad[k] != good[k])


def test_page_example():
    assert names(C3, deductive_fault_simulation(C3, SEQ)) == FIRSTS
    assert names(C3, deductive_fault_simulation(C3, SEQ, drop=False)) == ALL_DETECTED
    stats = {}
    deductive_fault_simulation(C3, SEQ, stats=stats)
    assert stats == {"list_elements": 40}


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


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


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


def test_xor_counts_parity():
    # Two flipped inputs of an XOR cancel: a stem fault that reaches both inputs is not seen.
    c = Circuit(["a"], [("n", "BUF", ["a"]), ("z", "XOR", ["a", "n"])], ["z"])
    for vector in product((0, 1), repeat=1):
        detected = deductive_fault_simulation(c, [vector], drop=False)[0]
        assert {c.fault_name(f) for f in detected} == {c.fault_name(f) for f in c.faults() if c.detects(vector, f)}
        assert c.line("a") not in {f[0] for f in detected}

History

Armstrong published the deductive method in IEEE Transactions on Computers in 1972, as a way to simulate all faults in one pass with set operations instead of one faulty circuit per bit. Ulrich and Baker's concurrent fault simulation of 1973 kept the idea of lists of faults per line but stored faulty values and evaluated faulty gates, which extends to timing and more values. Deductive simulation remained a standard method of the textbooks, and its set rules for gates reappear in critical path tracing, which needs no lists at all inside fanout-free regions.

References

  1. D. B. Armstrong, A deductive method for simulating faults in logic circuits, IEEE Transactions on Computers C-21(5), 464 to 471, 1972, the method, with the fault list of each gate output computed from the good values and the lists of its inputs
  2. Michael L. Bushnell and Vishwani D. Agrawal, Essentials of Electronic Testing for Digital, Memory and Mixed-Signal VLSI Circuits, Kluwer, 2000, the chapter Logic and Fault Simulation (deductive fault simulation and its list rules for each gate type)
  3. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on fault simulation (deductive fault simulation, unknown values and its comparison with concurrent simulation)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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