Algorithm Search⌘K

Algorithmcore

Parallel-pattern single-fault propagation

Also called PPSFP.

Waicukauski and coauthors' fault simulator that packs many test patterns into a word and propagates one fault at a time only as far as it differs from good values.

Time
O((T / w + 1) (1 + F) (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
John A. Waicukauski, Edward B. Eichelberger, Donato O. Forlenza, Eric Lindbloom, Thomas McCarthy, 1985

Parallel-pattern single-fault propagation, or PPSFP, is a method for fault simulation of combinational circuits. It puts ww input vectors in the ww bits of a machine word and simulates the good circuit once for all of them. Then it takes one single stuck-at fault at a time, sets its line to the stuck value in all ww bits, and evaluates forward only the gates where the faulty word still differs from the good word. The bits where an output differs are the vectors that detect the fault.

In plain words

A computer word holds 64 bits, so it can hold one wire's value for 64 different inputs at once. The simulator first runs the good circuit on 64 inputs together.

Then it takes the breaks one by one. For a break, it changes the broken wire and looks only at the gates just after it. If the gate output is the same as in the good circuit for all 64 inputs, the break is hidden there, and the walk stops on that side. If it differs, the walk goes on to the next gates.

When the walk reaches an output, the bits that differ show which of the 64 inputs find the break. Most breaks die out after a few gates, so most walks are short.

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 TT two-valued input vectors, a flag for fault dropping, and the word size w≥1w \ge 1. 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 reported only at the first vector that detects it.

The vectors must be independent of each other, which holds for a combinational circuit and for a sequential circuit with full scan, where each vector is applied from a scanned-in state.

The algorithm

A block is ww consecutive vectors, and bit ii of every word stands for vector ii of the block. For a word uu, the lowest set bit is the first vector of the block in which uu has a 1.

  1. PPSFP(C, vectors, faults, drop, w)
  2. alive ← faults
  3. 1for each block B of w consecutive vectors do
  4. 2good[k] ← the word of line k in the good circuit on B, for every line k in topological order
  5. 3for each fault f = (ℓ, v) in alive do
  6. 4seen ← PROPAGATE(f): set the word of ℓ to v in every bit, evaluate the lines after ℓ in topological order, and keep a faulty word for a line only where it differs from good; seen is the OR over the primary outputs of faulty word XOR good word
  7. 5if seen = 0 then keep f for the next block
  8. 6else if drop then report f at the vector of the lowest set bit of seen, and do not keep f; else report f at the vector of every set bit of seen, and keep f
  9. 7alive ← the kept faults

Line L4 is a single fault simulation of a whole block. It starts at the fault site, and if the stuck word equals the good word of ℓ\ell, no vector of the block activates the fault and nothing is evaluated. Otherwise it schedules the fanouts of ℓ\ell. When a scheduled line is taken, its gate is evaluated on words: the faulty word for an input that has one, and the good word for the others. If the result equals the good word of the line, the difference has died there, and the fanouts are not scheduled. Taking the scheduled line with the smallest index first is a topological order, as in event-driven logic simulation with zero delay, so each line is evaluated at most once per fault. Line L2 is plain compiled-code logic simulation on words.

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. The four vectors 101, 010, 011, 110 fill one block with w=4w = 4. Each word below lists the bits in vector order, bit 0 on the left.

line aa bb, bgb_g, bhb_h cc gg hh zz
good word 1001 0111 1010 1110 1101 0011

Take b/1. The stuck word 1111 differs from 0111, so bgb_g and bhb_h get 1111. Then g=NAND(1001,1111)=0110g = \mathrm{NAND}(1001, 1111) = 0110, which differs from 1110 in bit 0, and h=NAND(1111,1010)=0101h = \mathrm{NAND}(1111, 1010) = 0101, which differs from 1101 in bit 0. Then z=NAND(0110,0101)=1011z = \mathrm{NAND}(0110, 0101) = 1011 against 0011, so seen = 1000: only vector 101 detects b/1. That walk made 5 gate evaluations. The fault g/0 needs one: gg becomes 0000, and z=NAND(0000,1101)=1111z = \mathrm{NAND}(0000, 1101) = 1111, so seen = 1100. The fault z/0 needs none: zz is an output, and seen = 0011 at once.

fault seen fault seen fault seen fault seen
a/0 0001 bgb_g/0 0001 c/0 0010 h/0 1100
a/1 0100 bgb_g/1 1000 c/1 0100 h/1 0010
b/0 0011 bhb_h/0 0010 g/0 1100 z/0 0011
b/1 1000 bhb_h/1 1000 g/1 0001 z/1 1100

With dropping, each fault is reported at its lowest set bit, which gives the same first vectors as the table on the fault simulation page. The ones in this table are the 21 detections without dropping. The 16 walks make 30 gate evaluations on words, plus 5 for the good circuit. Serial fault simulation of the same four vectors evaluates the 5 lines that are not inputs once per faulty circuit and vector, which is 320 evaluations without dropping.

Correctness

Bitwise operations act on each bit on its own, so the good words of line L2 hold the good value of every line under every vector of the block. For one fault, a line that is never assigned a faulty word has all its inputs at their good words, so its faulty word is the good word, and skipping it loses nothing. A line that is evaluated has all its inputs final, because the lines are taken in increasing index and every input has a smaller index. So when line L4 ends, the faulty word of every line is correct, and bit ii of seen is 1 exactly when some output differs under vector ii. Line L5 keeps exactly the faults that the block does not detect. With dropping, a fault reaches a block only if no earlier block detected it, so the lowest set bit is the first vector that detects it. The full proof gives the details.

Proof: PPSFP 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,…,tTt_1, \ldots, t_T 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.

Fix a block B=(b0,…,bm−1)B = (b_0, \ldots, b_{m-1}) of m≤wm \le w vectors and let M=2m−1M = 2^m - 1. For a word uu, write uiu_i for its bit ii. The words are below 2m2^m, and as on the parallel fault simulation page, a gate evaluated on words with the mask MM gives in each bit i<mi < m the gate applied to the bits ii of its inputs. This is Lemma 1 of that proof, and it holds because AND, OR, XOR and the complement by MM combine equal bit positions only.

Lemma 1 (good words). After line L2, good[k]i=gbi(k)\mathrm{good}[k]_i = g_{b_i}(k) for every line kk and every i<mi < m.

Proof. By induction over kk. A primary input gets bit ii from vector bib_i. A gate line is evaluated on the words of its inputs, which are final and correct by induction, and the gate acts bit by bit. □\square

Now fix a fault f=(ℓ,v)f = (\ell, v) and consider the call of line L4. Define the correct faulty word F[k]F[k] by F[k]i=fbi(k)F[k]_i = f_{b_i}(k) for i<mi < m. The walk keeps a map bad from lines to words. Write cur[k]\mathrm{cur}[k] for bad[k]\mathrm{bad}[k] if kk is in the map, and good[k]\mathrm{good}[k] otherwise.

Lemma 2 (lines before the site). F[k]=good[k]F[k] = \mathrm{good}[k] for every line kk that is not reachable from ℓ\ell, and in particular for every k<ℓk < \ell.

Proof. The value of such a line does not depend on the value of ℓ\ell, since no path leads from ℓ\ell to it, and the fault changes only ℓ\ell. □\square

Lemma 3 (the walk). When the walk ends, cur[k]=F[k]\mathrm{cur}[k] = F[k] for every line kk.

Proof. If the stuck word vMvM (all bits vv) equals good[ℓ]\mathrm{good}[\ell], then gbi(ℓ)=vg_{b_i}(\ell) = v for every ii, so the faulty circuit computes the same value as the good one on every line under every vector of the block. Then F=goodF = \mathrm{good} everywhere, and the walk returns with an empty map. Otherwise bad[ℓ]=vM=F[ℓ]\mathrm{bad}[\ell] = vM = F[\ell].

The walk takes scheduled lines in increasing index, and it schedules only fanouts of a taken line, which have larger indices. So each line is taken at most once, and when line kk is taken, no line with an index below kk is taken later. We show by induction over k>ℓk > \ell, in increasing order, that after all lines up to kk are settled, cur[k]=F[k]\mathrm{cur}[k] = F[k].

If kk is taken, all its inputs jj have j<kj < k and are settled, so cur[j]=F[j]\mathrm{cur}[j] = F[j] by induction (or by Lemma 2, or by the case of ℓ\ell). The walk evaluates the gate of kk on these words, which gives F[k]F[k] bit by bit, since ff does not sit on kk. It stores the word in bad if it differs from good[k]\mathrm{good}[k]. If it equals good[k]\mathrm{good}[k], then cur[k]=good[k]=F[k]\mathrm{cur}[k] = \mathrm{good}[k] = F[k] too.

If kk is not taken, no input of kk was stored in bad, since a stored line schedules all its fanouts, and ℓ\ell is stored. So every input jj of kk has cur[j]=good[j]\mathrm{cur}[j] = \mathrm{good}[j], and by induction F[j]=good[j]F[j] = \mathrm{good}[j]. The gate of kk on the good words gives good[k]\mathrm{good}[k], so F[k]=good[k]=cur[k]F[k] = \mathrm{good}[k] = \mathrm{cur}[k]. □\square

Lemma 4 (seen). The word seen of line L4 has bit ii equal to 1 exactly when bib_i detects ff.

Proof. By Lemma 3, cur[o]⊕good[o]\mathrm{cur}[o] \oplus \mathrm{good}[o] has bit ii equal to fbi(o)⊕gbi(o)f_{b_i}(o) \oplus g_{b_i}(o), and outputs that are not in bad contribute 0, which is right since then cur[o]=good[o]\mathrm{cur}[o] = \mathrm{good}[o]. The OR over the outputs is 1 in bit ii exactly when some output differs under bib_i. □\square

Theorem. PPSFP reports, for each vector tjt_j, exactly the faults that serial fault simulation reports: without dropping, all faults of Φ\Phi that tjt_j detects; with dropping, the faults whose first detecting vector is tjt_j.

Proof. Without dropping, every fault stays alive, and by Lemma 4 each block reports ff at exactly the vectors of the block that detect it. With dropping, we show that a fault is alive at the start of a block exactly when no earlier vector detects it. This holds for the first block. Line L5 keeps ff when seen is 0, that is when no vector of the block detects it, and line L6 removes it otherwise. So the claim carries over to the next block. In a block where ff is alive and seen is not 0, the lowest set bit of seen is the first vector of the block that detects ff, by Lemma 4, and no earlier block detects it. So line L6 reports ff at its first detecting vector, and at no other vector. □\square

Complexity

A block costs O(L+P)O(L + P) word operations for the good circuit. A walk evaluates each line at most once, and a gate with dd inputs costs O(d)O(d) word operations, so a walk costs O(L+P)O(L + P) in the worst case. With a bucket of scheduled lines per level, or a bit per line and a scan in index order, the scheduling adds no more than this. The code of this page uses a binary heap, which adds a factor log⁡L\log L. There are ⌈T/w⌉\lceil T / w \rceil blocks, so the worst case is O((T/w+1)(1+F)(L+P))O((T / w + 1)(1 + F)(L + P)) word operations for FF faults. The extra space is a good word per line, the faulty words of one walk and the fault list, O(L+F)O(L + F).

This worst case is the same as serial fault simulation divided by ww. The gains beyond it are measured, not proved. A walk stops where the difference dies, and most faults are dropped in the first blocks, so the total is often far below the bound. For the c17 benchmark circuit with its 34 faults and all 32 input vectors in one 64-bit block, the code of this page makes 34 walks and 128 gate evaluations on words. 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.
  • Activity-driven. A walk costs only the lines where the fault makes a difference for at least one vector of the block.
  • Combinational only. The bits of a word are different vectors, so they cannot carry a state from one vector to the next. Sequential circuits need full scan or another method.
  • Faults one at a time. The memory holds the good words and one walk, whatever the number of faults. Faults are independent, so the fault list can be split over several processors.
  • Dropping at block size. A fault that is detected in a block is still simulated for all ww vectors of that block. Dropping takes effect from the next block.

Variants and improvements

  • Stem faults and fanout-free regions. Inside a fanout-free region, the vectors that detect a fault follow from those of the root of the region by critical path tracing on words. So only the stems need walks, and the faults inside each region are found by a backward pass. Fault simulators for scan designs often combine PPSFP with this.
  • Transition faults. Waicukauski, Lindbloom, Rosen and Iyengar used PPSFP to simulate transition faults with pairs of vectors: the first vector of a pair sets the initial value, and the second acts as a stuck-at test under the condition that the line changes.
  • Three values. With unknown values, each line holds two words. The walk compares both words with the good ones.
  • Parallel faults and patterns. Parallel fault simulation puts faults in the bits instead. A word can also hold a few faults times a few patterns, which helps when few faults are alive.

When to use it

Use PPSFP to grade large sets of vectors for combinational circuits and full scan designs, and inside the loop of automatic test pattern generation, where each new test is simulated against all faults that are still alive. It also grades the pseudorandom patterns of built-in self-test, where the number of vectors is large and the coverage curve matters. For sequential circuits applied without scan, and for fault models with many logic values and timing, concurrent fault simulation fits better. The result gives the fault coverage of the vectors.

Pitfalls

  • Unused bits in the last block. A last block with fewer than ww vectors must use a mask of that many ones for inverting gates. Otherwise the unused bits of the good and faulty words may differ and report detections at vectors that do not exist.
  • Comparing too early. A walk may stop only where the faulty word equals the good word in every bit. Stopping when one bit agrees loses the vectors that still differ.
  • Wrong order of evaluation. A line evaluated before one of its inputs has its final faulty word uses a stale value. A stack or a plain queue does not give a topological order, so take the scheduled line of smallest index or level.
  • Dropping within a block. Report the lowest set bit as the first detection. Reporting the highest, or the first bit found by a scan from the top, gives a later vector than serial simulation.
  • Faults at the fault site only. A stem fault must start on the stem line and reach every branch. A branch fault must start on its branch. If the stem and its branches share one line, the branch faults are lost.

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)
ppsfp.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ppsfp/. The authors are listed in prov/THPQ1N.jsonl.
"""Parallel-pattern single-fault propagation (PPSFP) of single stuck-at faults.

The vectors are cut into blocks of w. Bit i of a word is vector i of the
block. The good circuit is simulated once per block with bitwise operations.
Then each fault is simulated on its own, against all w vectors at once: its
line gets the constant word of its stuck value, and the difference is pushed
forward in topological order, only through lines where the faulty word
differs from the good word. When no line differs any more, the fault is done
with this block. The bits where a primary output differs are the vectors of
the block that detect the fault.

Python integers have no fixed width. The parameter width plays the part of
the machine word.
"""

from __future__ import annotations

import heapq
from typing import 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 good_words(c: Circuit, block: Sequence[Sequence[int]], mask: int) -> list[int]:
    """The good circuit on a block of vectors: bit i of word[line] is the line under vector i."""
    word = [0] * c.n_lines
    pi = 0
    for line in range(c.n_lines):
        if c.kind[line] == "pi":
            w = 0
            for i, vector in enumerate(block):
                w |= vector[pi] << i
            pi += 1
        else:
            w = eval_word(c.op[line], [word[j] for j in c.fanin[line]], mask)
        word[line] = w
    return word


def propagate(c: Circuit, good: list[int], fault: Fault, mask: int, counter: list[int]) -> int:
    """The mask of vectors of the block on which some primary output differs under the fault."""
    line, v = fault
    start = mask if v else 0
    if start == good[line]:
        return 0  # no vector of the block gives the line the opposite value
    bad = {line: start}
    heap = list(c.fanout[line])
    heapq.heapify(heap)
    queued = set(heap)
    while heap:  # lines in increasing index order, so inputs are final first
        k = heapq.heappop(heap)
        w = eval_word(c.op[k], [bad.get(j, good[j]) for j in c.fanin[k]], mask)
        counter[0] += 1
        if w != good[k]:  # the difference goes on only where it is still alive
            bad[k] = w
            for u in c.fanout[k]:
                if u not in queued:
                    queued.add(u)
                    heapq.heappush(heap, u)
    seen = 0
    for o in c.po:
        if o in bad:
            seen |= bad[o] ^ good[o]
    return seen


def ppsfp(
    c: Circuit,
    vectors: Sequence[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.

    With drop=True a fault is reported only at the first vector that detects
    it and is not simulated in later blocks. Vectors hold 0 and 1 only.
    """
    if width < 1:
        raise ValueError("a block holds at least one vector")
    alive = list(c.faults() if faults is None else faults)
    result: list[set[Fault]] = [set() for _ in vectors]
    counter = [0]
    blocks = fault_runs = 0
    for start in range(0, len(vectors), width):  # @line L1
        block = vectors[start:start + width]
        mask = (1 << len(block)) - 1
        good = good_words(c, block, mask)  # @line L2
        blocks += 1
        still: list[Fault] = []
        for f in alive:  # @line L3
            fault_runs += 1
            seen = propagate(c, good, f, mask, counter)  # @line L4
            if seen == 0:  # @line L5
                still.append(f)
                continue
            if drop:  # @line L6
                first = (seen & -seen).bit_length() - 1
                result[start + first].add(f)
            else:
                for i in range(len(block)):
                    if seen >> i & 1:
                        result[start + i].add(f)
                still.append(f)
        alive = still  # @line L7
    if stats is not None:
        stats.update(blocks=blocks, fault_runs=fault_runs, gate_evals=counter[0])
    return result
test_ppsfp.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ppsfp/. The authors are listed in prov/THPQ1N.jsonl.

import random

import pytest

from gatenet import Circuit, random_circuit
from ppsfp import eval_word, good_words, ppsfp, propagate

# 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 bits(word, n):
    """Bit 0 first, so the string reads in vector order."""
    return "".join(str(word >> i & 1) for i in range(n))


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):
                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([w >> k & 1 for w in words])[0]


def test_page_words_and_masks():
    good = good_words(C3, SEQ, 15)
    assert {C3.name[k]: bits(good[k], 4) for k in range(C3.n_lines)} == {
        "a": "1001", "b": "0111", "b>g": "0111", "b>h": "0111", "c": "1010", "g": "1110", "h": "1101", "z": "0011",
    }
    seen = {}
    evals = {}
    for f in C3.faults():
        counter = [0]
        seen[C3.fault_name(f)] = bits(propagate(C3, good, f, 15, counter), 4)
        evals[C3.fault_name(f)] = counter[0]
    assert seen == {
        "a/0": "0001", "a/1": "0100", "b/0": "0011", "b/1": "1000", "b>g/0": "0001", "b>g/1": "1000",
        "b>h/0": "0010", "b>h/1": "1000", "c/0": "0010", "c/1": "0100", "g/0": "1100", "g/1": "0001",
        "h/0": "1100", "h/1": "0010", "z/0": "0011", "z/1": "1100",
    }
    assert evals["b/0"] == 5 and evals["z/0"] == 0 and sum(evals.values()) == 30


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


def test_page_stats():
    stats = {}
    ppsfp(C3, SEQ, width=4, stats=stats)
    assert stats == {"blocks": 1, "fault_runs": 16, "gate_evals": 30}
    stats = {}
    ppsfp(C3, SEQ, width=1, stats=stats)
    assert stats == {"blocks": 4, "fault_runs": 37, "gate_evals": 39}  # 16 + 10 + 8 + 3 fault runs


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


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


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 ppsfp(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(1, 6)
        for drop in (True, False):
            assert ppsfp(c, vectors, drop=drop, width=width) == serial(c, vectors, drop=drop)


def test_empty_block_size_rejected():
    with pytest.raises(ValueError):
        ppsfp(C3, SEQ, width=0)

History

Waicukauski, Eichelberger, Forlenza, Lindbloom and McCarthy at IBM described the method for structured designs with scan in 1985, in the trade journal VLSI Systems Design and in a paper at the International Test Conference on estimating detection probabilities. The later literature calls it parallel pattern single fault propagation. Waicukauski, Lindbloom, Rosen and Iyengar applied it to transition faults at the International Test Conference of 1986 and in IEEE Design and Test in 1987. The method, often with critical path tracing inside fanout-free regions, became a standard fault simulator for scan-based combinational test.

References

  1. J. A. Waicukauski, E. B. Eichelberger, D. O. Forlenza, E. Lindbloom and T. McCarthy, Fault simulation for structured VLSI, VLSI Systems Design 6(12), 20 to 32, December 1985, the fault simulator for scan designs with many patterns per word and one fault propagated at a time
  2. J. A. Waicukauski, E. B. Eichelberger, D. O. Forlenza, E. Lindbloom and T. McCarthy, A statistical calculation of fault detection probabilities by fast fault simulation, Proceedings of the International Test Conference, 779 to 784, 1985, the same group's fast fault simulator, used to estimate detection probabilities of random patterns
  3. J. A. Waicukauski, E. Lindbloom, B. K. Rosen and V. S. Iyengar, Transition fault simulation, IEEE Design and Test of Computers 4(2), 32 to 38, April 1987, the transition fault model and its simulation by parallel-pattern single-fault propagation
  4. 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 pattern single fault propagation)

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