Algorithm Search⌘K

Algorithmcore

Parallel fault simulation

Also called Seshu parallel fault simulation, bit-parallel fault simulation.

Simulates the good circuit and w - 1 faulty circuits at once by packing them into the bits of a machine word and evaluating gates with bitwise operations.

Time
O(T (F / (w - 1) + 1) (L + P)) worst
Space
O(L + 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; w = the word size in bits
Properties
deterministicexactiterative
Origin
Sundaram Seshu, 1965

Parallel fault simulation is a method for fault simulation that puts the good circuit and w−1w - 1 faulty circuits, each with one single stuck-at fault, in the ww bits of a machine word. Each gate is evaluated once per word with bitwise operations, so one pass over the circuit simulates w−1w - 1 faults and the good circuit together. Two masks per line put each fault into its own bit. The method gives exactly the answer of serial fault simulation, with about w−1w - 1 times fewer gate evaluations.

In plain words

A computer adds or compares 64 bits in one step. Each bit can hold the value of a wire in a different copy of the circuit. Copy 0 is the good circuit. Copies 1 to 63 each have one wire that is broken.

So the simulator walks through the gates once, as for one circuit, but each step computes the gate in all 64 copies at the same time. Where a copy has its broken wire, a mask forces that bit to the stuck value. At the outputs, each copy is compared with copy 0. A copy that differs shows a break that this input finds.

If there are more broken copies than bits, the simulator does more walks, one group of 63 at a time.

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, a flag for fault dropping, and the word size w≥2w \ge 2. The lines are the primary inputs, the gate outputs and the fanout branches, as in the stuck-at fault model, 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.

This is the problem of the fault simulation page, for combinational circuits. A sequential circuit with full scan gives this problem too.

The algorithm

A group GG holds at most w−1w - 1 alive faults. The fault in position ii of the group uses bit ii of every word, for 1≤i≤∣G∣1 \le i \le |G|, and bit 0 holds the good circuit. For a line kk, the mask clear[k]\mathrm{clear}[k] has bit ii set when fault ii is kk stuck at 0, and set[k]\mathrm{set}[k] has bit ii set when fault ii is kk stuck at 1. A line can have both of its faults in one group, in two different bits.

  1. PARALLEL-FAULT-SIMULATION(C, vectors, faults, drop, w)
  2. alive ← faults
  3. 1for each vector t do
  4. 2for each group G of at most w − 1 faults of alive do
  5. 3build clear[k] and set[k] for every line k from the faults of G
  6. 4for each line k in topological order do
  7. 5if k is a primary input then W ← all ones if t gives k the value 1, else all zeros
  8. 6else W ← the gate of k applied bitwise to the words of the inputs of k
  9. 7word[k] ← (W AND NOT clear[k]) OR set[k]
  10. 8diff ← OR over the primary outputs o of (word[o] XOR bit 0 of word[o] copied into every bit)
  11. 9report the fault of each set bit i ≥ 1 of diff as detected by t
  12. 10if drop then remove the detected faults from alive

Line L7 is the fault insertion. AND with the complement of the clear mask forces the bits of the stuck-at-0 faults on kk to 0, and OR with the set mask forces the bits of the stuck-at-1 faults to 1. The other bits keep the value that the gate computed. The inverting gates NOT, NAND, NOR and XNOR complement with a word of ∣G∣+1|G| + 1 ones, so that unused high bits stay 0. A fanout branch is a buffer of its stem, so a fault on the stem reaches every branch, and a fault on one branch changes only the bit in that branch.

Every line is evaluated in every pass, whatever its value, as in compiled-code logic simulation. There is no event queue.

Example

The circuit is g=NAND(a,b)g = \mathrm{NAND}(a, b), h=NAND(b,c)h = \mathrm{NAND}(b, c), z=NAND(g,h)z = \mathrm{NAND}(g, h), so z=ab+bcz = ab + bc. The stem bb has the branches bgb_g into gg and bhb_h into hh. The 8 lines in topological order are a,b,bg,bh,c,g,h,za, b, b_g, b_h, c, g, h, z, and there are 16 faults. The code names a branch b>g.

Take w=8w = 8 and the vector abc=101abc = 101. The first group holds the first 7 faults in line order: bit 1 is a/0, bit 2 a/1, bit 3 b/0, bit 4 b/1, bit 5 bgb_g/0, bit 6 bgb_g/1 and bit 7 bhb_h/0. The table writes each word with bit 0 on the left.

line WW from line L5 or L6 clear set word after L7
aa 11111111 01000000 00100000 10111111
bb 00000000 00010000 00001000 00001000
bgb_g 00001000 00000100 00000010 00001010
bhb_h 00001000 00000001 00000000 00001000
cc 11111111 00000000 00000000 11111111
gg 11110101 00000000 00000000 11110101
hh 11110111 00000000 00000000 11110111
zz 00001010 00000000 00000000 00001010

Bit 0 of zz is 0, the good output. Bits 4 and 6 are 1, so line L9 reports b/1 and bgb_g/1. Bit 1, the fault a/0, gives a=0a = 0 and g=1g = 1, which is the good value of gg, so the fault does not reach zz. Bit 7, the fault bhb_h/0, does nothing at all, since bhb_h is already 0. The second and third groups hold the other 9 faults and report bhb_h/1, g/0, h/0 and z/1, so vector 101 detects 6 faults.

With dropping and w=8w = 8, the four vectors 101, 010, 011, 110 see 16, 10, 8 and 3 alive faults, so they take 3, 2, 2 and 1 passes. That is 8 passes of 8 line evaluations, 64 word evaluations in all. Serial fault simulation with dropping simulates 16 + 10 + 8 + 3 = 37 faulty circuits of 8 lines, which is 296 line evaluations. Without dropping, parallel simulation needs 12 passes. With w=64w = 64 all 16 faults fit in one group, and each vector takes one pass. The detected sets are those of the table on the fault simulation page.

Correctness

Bitwise operations act on each bit on its own: bit ii of u&vu \mathbin{\&} v depends only on bit ii of uu and of vv. So the pass of lines L4 to L7 is ∣G∣+1|G| + 1 independent simulations, one per bit, that share their instructions. In bit 0 no mask has a set bit, so it is the good circuit. In bit i≥1i \ge 1 the masks change only the line of fault ii, and only to its stuck value, which is the faulty circuit of fault ii. Lines are taken in topological order, so every input word is final before it is read. Line L8 sets bit ii of diff exactly when some output differs between the good circuit and faulty circuit ii, which is the definition of detection. The groups cover the alive faults, so line L9 reports exactly the alive faults that tt detects, and line L10 drops them as serial simulation does. The full proof writes this as an induction over the lines.

Proof: Parallel fault simulation reports the same faults as serial simulationfull

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. Let Φ\Phi be the list of single stuck-at faults and t1,t2,…t_1, t_2, \ldots the two-valued vectors. For a vector tt, write gt(k)g_t(k) for the value of line kk in the good circuit and ft(k)f_t(k) for its value in the circuit with fault ff. A fault ff is detected by tt when ft(o)≠gt(o)f_t(o) \ne g_t(o) for some primary output oo. Let alivei\mathrm{alive}_i be the set of faults alive while vector tit_i is simulated: Φ\Phi for i=1i = 1, and with dropping, Φ\Phi minus the faults reported for t1,…,ti−1t_1, \ldots, t_{i-1}.

Fix a vector tt and a group G=(f1,…,fm)G = (f_1, \ldots, f_m) with m≤w−1m \le w - 1, and let M=2m+1−1M = 2^{m+1} - 1 be the word of m+1m + 1 ones. For a word uu, write uiu_i for its bit ii. Define the reference value of bit ii of line kk as

ri(k)=gt(k) if i=0,ri(k)=(fi)t(k) if 1≤i≤m.r_i(k) = g_t(k) \text{ if } i = 0, \qquad r_i(k) = (f_i)_t(k) \text{ if } 1 \le i \le m.

Lemma 1 (bitwise gates). Let op\mathrm{op} be a gate type and u1,…,udu^1, \ldots, u^d words below 2m+12^{m+1}. The word WW that line L6 computes satisfies W<2m+1W < 2^{m+1} and Wi=op(ui1,…,uid)W_i = \mathrm{op}(u^1_i, \ldots, u^d_i) for 0≤i≤m0 \le i \le m.

Proof. AND starts from MM and takes the AND of the inputs, OR and XOR start from 0, and BUF copies its input. In each case bit ii of the result is the AND, OR, XOR or copy of the bits ii of the inputs, since these operations combine equal bit positions only, and no bit above mm is set. The inverting types then XOR with MM, which complements bits 00 to mm and leaves the higher bits 0. □\square

Lemma 2 (insertion). For 0≤i≤m0 \le i \le m, bit ii of clear[k]\mathrm{clear}[k] is 1 exactly when i≥1i \ge 1 and fi=(k,0)f_i = (k, 0), and bit ii of set[k]\mathrm{set}[k] is 1 exactly when i≥1i \ge 1 and fi=(k,1)f_i = (k, 1). So bit ii of (W&¬clear[k])∣set[k](W \mathbin{\&} \lnot \mathrm{clear}[k]) \mid \mathrm{set}[k] is the stuck value vv if fi=(k,v)f_i = (k, v), and WiW_i otherwise.

Proof. Line L3 sets bit ii of clear[k]\mathrm{clear}[k] for fi=(k,0)f_i = (k, 0) and of set[k]\mathrm{set}[k] for fi=(k,1)f_i = (k, 1), and nothing else. A fault has one line and one value, so at most one of the two masks has bit ii set. If clear[k]\mathrm{clear}[k] has it, the AND makes the bit 0 and the OR leaves it. If set[k]\mathrm{set}[k] has it, the OR makes it 1. If neither has it, both operations leave WiW_i. □\square

Invariant. After line L7 has processed line kk in the pass for tt and GG, bit ii of word[k]\mathrm{word}[k] is ri(k)r_i(k) for every 0≤i≤m0 \le i \le m, and word[k]<2m+1\mathrm{word}[k] < 2^{m+1}.

Proof. By induction over kk in topological order. If kk is a primary input, line L5 gives the word MM or 0, so every bit is t(k)=gt(k)t(k) = g_t(k). If kk is not a primary input, every input jj of kk has j<kj < k and is already processed, so by induction and Lemma 1, WiW_i is the gate of kk applied to the values ri(j)r_i(j) of its inputs. In the circuit of bit ii, that is the value of kk before any fault on kk acts. Lemma 2 then replaces bit ii by the stuck value exactly when fif_i sits on kk. The value of kk in the good circuit is the gate on the good inputs, and in the circuit with fault fif_i it is the stuck value if fif_i sits on kk and the gate on the faulty inputs otherwise. These are exactly the cases above, so bit ii of word[k]\mathrm{word}[k] is ri(k)r_i(k). Neither mask has a bit above mm, so the word stays below 2m+12^{m+1}. □\square

Lemma 3 (comparison). For 1≤i≤m1 \le i \le m, bit ii of the word diff of line L8 is 1 exactly when tt detects fif_i.

Proof. For an output oo, the word "bit 0 of word[o]\mathrm{word}[o] copied into every bit" has every bit equal to gt(o)g_t(o), by the invariant. So bit ii of word[o]\mathrm{word}[o] XOR this word is (fi)t(o)⊕gt(o)(f_i)_t(o) \oplus g_t(o), which is 1 exactly when oo differs under fif_i. The OR over the outputs is 1 exactly when some output differs. □\square

Theorem. For each vector tit_i, the algorithm reports exactly the faults of alivei\mathrm{alive}_i that tit_i detects. So its output is the same as that of serial fault simulation, with or without dropping.

Proof. Line L2 cuts alivei\mathrm{alive}_i into groups, and each alive fault is in exactly one of them. By Lemma 3, line L9 reports a fault of a group exactly when tit_i detects it. So the union over the groups is the set of faults of alivei\mathrm{alive}_i that tit_i detects. With dropping, line L10 removes exactly these faults, so the alive set of the next vector is alivei+1\mathrm{alive}_{i+1}. Without dropping, the alive set stays Φ\Phi, and alivei+1=Φ\mathrm{alive}_{i+1} = \Phi too. By induction over ii, every vector is simulated against the right alive set. □\square

The count of passes is ⌈∣alivei∣/(w−1)⌉\lceil |\mathrm{alive}_i| / (w - 1) \rceil for vector tit_i, and each pass processes each line once, which gives the bound of the complexity section.

Complexity

A pass evaluates each line once. A gate with dd inputs costs O(d)O(d) word operations, so a pass costs O(L+P)O(L + P) word operations, plus O(L+w)O(L + w) to build and clear the masks. A vector with AA alive faults takes ⌈A/(w−1)⌉\lceil A / (w - 1) \rceil passes. Over TT vectors and FF faults, the worst case is O(T(F/(w−1)+1)(L+P))O(T (F / (w - 1) + 1)(L + P)) word operations, against O(TF(L+P))O(T F (L + P)) for serial simulation. The extra space is one word and two masks per line, and the fault list, so O(L+F)O(L + F) words.

This bound is a count of word operations in the word RAM, and the factor w−1w - 1 is proved for that count. The time on a real machine is measured, not proved. For the c17 benchmark circuit with 17 lines, its 34 faults and all 32 input vectors in counting order, the code of this page with w=64w = 64 makes 32 passes and 544 line evaluations without dropping, and 21 passes and 357 line evaluations with dropping, since every fault is dropped after the 21st vector. 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.
  • Compiled, not event-driven. Every line is evaluated in every pass, even where no faulty circuit differs from the good one. The cost of a pass does not depend on the activity.
  • Speed-up at most w−1w - 1. The gain over serial simulation comes only from the word width. Dropping helps less than in other methods: when the alive faults fall below w−1w - 1, a pass still costs a full walk over the circuit.
  • Sequential circuits. Each bit can carry its own state from vector to vector, so the method also simulates sequential circuits, where the vectors must be applied in order.
  • Deterministic. The detected sets do not depend on the order of the faults or on ww. Only the number of passes does.

Variants and improvements

  • Three values. With the values 0, 1 and X, each line holds two words, for example one word for "the value can be 1" and one for "the value can be 0". Each gate then costs a few more word operations, as in ternary simulation.
  • Event-driven passes. A pass can skip a line whose input words did not change since the last pass, as in event-driven logic simulation. For a group of faults that are far apart, few lines change.
  • Fault grouping. Faults that sit close together are often detected by the same vectors. If one group holds them, the group can empty as a whole when they are dropped, and the event-driven variant has fewer lines to change.
  • Patterns in the bits. PPSFP puts ww vectors, not w−1w - 1 faults, in a word, and follows one fault at a time only as far as its effect goes. The textbooks in the references report it as the faster method for combinational circuits with dropping.
  • Wider words. Vector registers and graphics processors give words of hundreds of bits. The algorithm does not change, and only ww grows.

When to use it

Use parallel fault simulation when the circuit is small or when the vectors of a sequential circuit must be applied in order, so that patterns cannot share a word. It is also a simple reference that is easy to get right: the masks are the only part that differs from a compiled-code logic simulator. For combinational circuits and full scan designs, PPSFP, often with critical path tracing inside fanout-free regions, does less work. For sequential circuits with timing, concurrent fault simulation evaluates a faulty circuit only where it differs. In all cases fault collapsing first reduces the fault list, and the result gives the fault coverage of the vectors.

Pitfalls

  • Bit 0 is the good circuit. A group has room for w−1w - 1 faults, not ww. Line L8 compares each bit with a copy of bit 0, not with bit 0 alone.
  • Unused bits. An inverting gate must complement with a mask of ∣G∣+1|G| + 1 ones. With a full-width complement, a short last group gets 1s in its unused bits, and these can look like detected faults if line L9 does not stop at ∣G∣|G|.
  • Insertion after evaluation. The masks act on the word that the gate computed, at line L7. Inserting them on the input words of the next gate instead puts a stem fault on one branch only.
  • Stem and branch. A fault on a stem must be inserted on the stem line, and a fault on a branch on that branch line. If the branch lines are not built, the branch faults cannot be simulated.
  • Dropping changes the groups. After line L10, the faults of the next vector are cut into new groups. The bit of a fault is different from vector to vector, so the report must map bits back to faults through the current group.

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.

gatenet.pyI0RawGitHub
# 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)
parallel_fault_simulation.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-fault-simulation/. The authors are listed in prov/S63TGE.jsonl.
"""Parallel fault simulation of single stuck-at faults (one fault per bit).

Each line holds a word of w bits. Bit 0 is the good circuit and bits 1 to
w - 1 are faulty circuits, one fault each. A gate is evaluated once per word
with bitwise operations, so one pass over the circuit simulates w - 1 faulty
circuits and the good one. A fault is put in its own bit by two masks on its
line: a clear mask for stuck-at 0 and a set mask for stuck-at 1. The faults
are cut into groups of w - 1, and each vector takes one pass per group.

Python integers have no fixed width. The parameter width plays the part of
the machine word, so that the number of passes is the one a real word gives.
"""

from __future__ import annotations

from typing import Iterable, Optional, Sequence

from gatenet import Circuit, Fault


def eval_word(op: str, words: Sequence[int], mask: int) -> int:
    """One gate on words: bit k of the result is the gate on bit k of each input."""
    if op in ("BUF", "NOT"):
        r = words[0]
    elif op in ("AND", "NAND"):
        r = mask
        for w in words:
            r &= w
    elif op in ("OR", "NOR"):
        r = 0
        for w in words:
            r |= w
    else:  # XOR, XNOR
        r = 0
        for w in words:
            r ^= w
    if op in ("NOT", "NAND", "NOR", "XNOR"):
        r ^= mask
    return r


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

    width is the word size w >= 2: bit 0 is the good circuit, so a pass holds
    w - 1 faults. With drop=True a fault is removed after the first vector that
    detects it. Vectors hold the values 0 and 1 only.
    """
    if width < 2:
        raise ValueError("the word needs a bit for the good circuit and one for a fault")
    alive = list(c.faults() if faults is None else faults)
    result: list[set[Fault]] = []
    passes = word_evals = 0
    for vector in vectors:  # @line L1
        detected: set[Fault] = set()
        for start in range(0, len(alive), width - 1):  # @line L2
            group = alive[start:start + width - 1]
            mask = (1 << (len(group) + 1)) - 1
            clear = [0] * c.n_lines  # @line L3
            setm = [0] * c.n_lines
            for k, (line, v) in enumerate(group, 1):
                if v == 0:
                    clear[line] |= 1 << k
                else:
                    setm[line] |= 1 << k
            word = [0] * c.n_lines
            pi = 0
            for line in range(c.n_lines):  # @line L4
                if c.kind[line] == "pi":  # @line L5
                    w = mask if vector[pi] else 0
                    pi += 1
                else:  # @line L6
                    w = eval_word(c.op[line], [word[j] for j in c.fanin[line]], mask)
                word[line] = (w & ~clear[line]) | setm[line]  # @line L7
            diff = 0
            for o in c.po:  # @line L8
                good = mask if word[o] & 1 else 0
                diff |= word[o] ^ good
            for k in range(1, len(group) + 1):  # @line L9
                if diff >> k & 1:
                    detected.add(group[k - 1])
            passes += 1
            word_evals += c.n_lines
        result.append(detected)
        if drop:  # @line L10
            alive = [f for f in alive if f not in detected]
    if stats is not None:
        stats.update(passes=passes, word_evals=word_evals)
    return result
test_parallel_fault_simulation.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parallel-fault-simulation/. The authors are listed in prov/S63TGE.jsonl.

import random

import pytest

from gatenet import Circuit, random_circuit
from parallel_fault_simulation import eval_word, parallel_fault_simulation

# 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_eval_word_matches_gates_bit_by_bit():
    rng = random.Random(1)
    mask = (1 << 8) - 1
    for op in OPS:
        for _ in range(50):
            n = 1 if op in ("NOT", "BUF") else rng.randint(2, 4)
            words = [rng.getrandbits(8) for _ in range(n)]
            out = eval_word(op, words, mask)
            for k in range(8):
                bits = [w >> k & 1 for w in words]
                c = Circuit([f"x{i}" for i in range(n)], [("y", op, [f"x{i}" for i in range(n)])], ["y"])
                assert out >> k & 1 == c.outputs(bits)[0]


@pytest.mark.parametrize("width", [2, 3, 8, 17, 64])
def test_page_example(width):
    assert names(C3, parallel_fault_simulation(C3, SEQ, width=width)) == FIRSTS
    assert names(C3, parallel_fault_simulation(C3, SEQ, drop=False, width=width)) == ALL_DETECTED


def test_page_pass_counts():
    stats = {}
    parallel_fault_simulation(C3, SEQ, width=8, stats=stats)
    assert stats == {"passes": 8, "word_evals": 64}  # 16, 10, 8 and 3 faults alive: 3 + 2 + 2 + 1 passes
    stats = {}
    parallel_fault_simulation(C3, SEQ, width=8, drop=False, stats=stats)
    assert stats["passes"] == 12
    stats = {}
    parallel_fault_simulation(C3, SEQ, width=64, stats=stats)
    assert stats["passes"] == 4


def test_c17_all_vectors():
    vectors = C17.all_vectors()
    result = parallel_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 parallel_fault_simulation(C17, vectors, width=5) == serial(C17, vectors)


def test_redundant_faults_by_exhaustive_patterns():
    detected = set().union(*parallel_fault_simulation(CONSENSUS, CONSENSUS.all_vectors(), width=4))
    undetected = {CONSENSUS.fault_name(f) for f in CONSENSUS.faults() if f not in detected}
    assert undetected == REDUNDANT
    # Exhaustive patterns: an undetected fault here is redundant.
    for f in CONSENSUS.faults():
        if CONSENSUS.fault_name(f) in REDUNDANT:
            assert not CONSENSUS.detectable(f)


def test_fault_subset_and_order():
    rng = random.Random(5)
    faults = C17.faults()
    rng.shuffle(faults)
    faults = faults[:13]
    vectors = [tuple(rng.randint(0, 1) for _ in range(5)) for _ in range(9)]
    assert parallel_fault_simulation(C17, vectors, faults=faults, width=4) == serial(C17, vectors, faults=faults)


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))]
        width = rng.randint(2, 9)
        for drop in (True, False):
            assert parallel_fault_simulation(c, vectors, drop=drop, width=width) == serial(c, vectors, drop=drop)


def test_width_must_hold_good_and_one_fault():
    with pytest.raises(ValueError):
        parallel_fault_simulation(C3, SEQ, width=1)

History

Seshu's diagnosis programs of the early 1960s at the University of Illinois simulated faulty machines to build tests and diagnosis data, and the 1965 paper on an improved diagnosis program is the work that textbooks cite for parallel fault simulation. The method was a standard way to simulate faults in the 1960s and 1970s, beside serial simulation. Armstrong (1972) gave deductive fault simulation, Ulrich and Baker (1973) gave concurrent fault simulation, and Waicukauski and coauthors (1985) turned the word around, with patterns in the bits, in PPSFP.

References

  1. S. Seshu, On an improved diagnosis program, IEEE Transactions on Electronic Computers EC-14(1), 76 to 79, February 1965, the diagnosis program that simulates faulty machines, which later textbooks cite as the origin of parallel fault simulation
  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 (parallel fault simulation, with one faulty circuit per bit and masks that insert the faults)
  3. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on fault simulation (parallel fault simulation, fault insertion by masks, and three-valued words)

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