Algorithm Search⌘K

Data structurecore

Fault dictionary

Also called cause-effect diagnosis.

A table of the faulty responses of every modelled fault to the test set, compared with an observed failing response to name the likely faults.

Time
O(F T (L + P)) worst · average · best
Space
O(F T (O / w + 1)) extra
Where
F = the number of faults; L = the number of lines; O = the number of primary outputs; P = the number of gate input pins; T = the number of tests; w = the word size in bits
Properties
deterministiciterative

A fault dictionary stores, for every modeled fault of a circuit, the response that the faulty circuit gives to a fixed test set. When a chip fails on the tester, its observed response is looked up in the table, and the faults stored under that response are the candidates for the defect. The table is built once per design by fault simulation of every fault, so diagnosis of each failing chip is a cheap lookup. The full-response dictionary keeps every output of every test and needs F⋅T⋅OF \cdot T \cdot O bits for FF faults, TT tests and OO outputs. The pass-fail dictionary keeps only which tests fail, F⋅TF \cdot T bits, and tells fewer faults apart.

In plain words

When a chip fails a test, the engineer wants to know where the defect is, so that the chip can be cut open at the right place.

A fault dictionary is prepared before any chip is made. A program breaks the circuit design in one place at a time, runs the tests on the broken design, and writes down how it fails: which tests fail and which outputs are wrong. One line of the table per kind of break.

When a real chip fails, its wrong outputs are looked up in the table. The breaks listed under the same failure are the suspects. A small table that keeps only which tests failed is cheaper to store but often lists more suspects.

The abstract type

The dictionary is built over a fixed circuit CC with OO primary outputs and a fixed test set t0,…,tT−1t_0, \ldots, t_{T-1}. For a fault ff and a test tjt_j, let the error word Rj(f)R_j(f) be the OO-bit word whose bit kk is 1 when output kk of the circuit with ff differs from the good circuit on tjt_j. The full response of ff is R(f)=(R0(f),…,RT−1(f))R(f) = (R_0(f), \ldots, R_{T-1}(f)), and its pass-fail response is P(f)={j:Rj(f)≠0}P(f) = \{ j : R_j(f) \ne 0 \}, the set of failing tests.

The value is a set DD of faults. The operations are:

  • add_fault(f): add ff to DD.
  • observe(z_0, ..., z_(T-1)): turn the output vectors seen on the tester into error words.
  • lookup_full(r): return {f∈D:R(f)=r}\{ f \in D : R(f) = r \}.
  • lookup_pass_fail(r): return {f∈D:P(f)={j:rj≠0}}\{ f \in D : P(f) = \{ j : r_j \ne 0 \} \}.
  • nearest(r): return the faults of DD whose full response is closest to rr in Hamming distance, and the distance.

Representation

Two hash maps. The full map has the key R(f)R(f), a tuple of TT error words, and the value is the list of faults with that response. The pass-fail map has the key P(f)P(f), a TT-bit mask, and the same kind of list. The good output vectors of all tests are stored once. Each fault sits in exactly one list of each map, the one under its own key. That is the invariant.

On disk, the full dictionary is a matrix with one row per fault and T⋅OT \cdot O bits per row, so F⋅T⋅OF \cdot T \cdot O bits, and the pass-fail dictionary has TT bits per row, so F⋅TF \cdot T bits.

Operations

  1. BUILD(C, the tests t_0, ..., t_(T-1))
  2. 1for j ← 0 to T − 1 do G[j] ← the outputs of the good circuit on t_j
  3. ADD-FAULT(f)
  4. 2R ← (R_0, ..., R_(T-1)), where for each test j
  5. 3R_j ← (the outputs of C with f on t_j) XOR G[j]
  6. 4P ← the set of j with R_j ≠ 0
  7. 5append f to FULL[R]
  8. 6append f to PF[P]
  9. LOOKUP(the observed outputs z_0, ..., z_(T-1))
  10. 7r ← (z_0 XOR G[0], ..., z_(T-1) XOR G[T-1])
  11. 8return FULL[r]
  12. 9or, with the pass-fail dictionary, return PF[the set of j with r_j ≠ 0]

Line L1 runs once. Lines L2 to L6 simulate one fault on every test, which is the whole cost of the dictionary. Any fault simulator can do it, for example PPSFP with many tests per word. Lines L7 to L9 are the diagnosis of one chip: one pass over the tester data and one hash probe. A response that matches no key returns the empty list, and then nearest gives the closest stored responses.

Example

Take the circuit z=a∧bz = a \wedge b, y=b∨cy = b \vee c with the outputs zz and yy. The input bb feeds two gates, so it has a stem bb and two branches, b>zb{>}z and b>yb{>}y. That makes 7 lines and 14 single stuck-at faults. The tests are abc=110,010,100,001abc = 110, 010, 100, 001, and the good outputs zyzy are 11, 01, 00, 01. The table shows the wrong outputs of each fault on each test, with a dash when the test passes.

fault 110 010 100 001 failing tests
aa/0, b>zb{>}z/0, zz/0 zz - - - {0}
aa/1 - zz - - {1}
bb/0 z,yz, y yy - - {0, 1}
b>yb{>}y/0 yy yy - - {0, 1}
bb/1 - - z,yz, y - {2}
b>zb{>}z/1 - - zz - {2}
b>yb{>}y/1, cc/1, yy/1 - - yy - {2}
cc/0 - - - yy {3}
zz/1 - zz zz zz {1, 2, 3}
yy/0 yy yy - yy {0, 1, 3}

The full dictionary has 10 classes and takes 14⋅4⋅2=11214 \cdot 4 \cdot 2 = 112 bits. The pass-fail dictionary has 7 classes and takes 14⋅4=5614 \cdot 4 = 56 bits. It merges bb/0 with b>yb{>}y/0, which fail the same tests on different outputs, and it merges the five faults that fail only test 2.

A chip that shows z=0z = 0 on test 0 and passes the rest has the observed error words (z,−,−,−)(z, -, -, -), and the lookup returns {a/0,b>z/0,z/0}\{a/0, b{>}z/0, z/0\}. No test can split this class: the three faults are equivalent, since each one makes z=0z = 0 always, as on the fault collapsing page. The same holds for {b>y/1,c/1,y/1}\{b{>}y/1, c/1, y/1\}. So here the full dictionary tells apart every pair of faults that any test set could tell apart. A chip with zz wrong on test 0 and yy wrong on test 3 matches no row: no single stuck-at fault explains it. Its nearest rows, at distance 1, are the class of zz/0 and cc/0, which hints at two defects.

Correctness

The claims are proved on the proof page.

  1. Invariant. After any sequence of add_fault calls, every fault of DD is in exactly one list of each map, the list under R(f)R(f) and the list under P(f)P(f).
  2. The true fault is never lost. If a chip behaves exactly like the circuit with a modeled fault f∈Df \in D, then lookup_full returns exactly the faults of DD that no test of the set tells apart from ff, and ff is one of them. lookup_pass_fail returns a superset of it.
  3. Pass-fail is coarser. Each class of the full dictionary lies inside one class of the pass-fail dictionary, so the pass-fail dictionary never has more classes. With TT tests it has at most 2T2^T classes, so it needs T≥log⁡2KT \ge \log_2 K tests to separate KK classes, while a full dictionary can separate up to 2T⋅O2^{T \cdot O}.

The guarantee is for chips whose defect behaves like one modeled fault. A defect outside the model, such as a bridge between two lines or two faults at once, can match no row, or a wrong row.

Proof: A dictionary lookup returns exactly the faults that the tests cannot tell apart from the true onefull

We use the notation of the page. The circuit CC has OO outputs, the tests are t0,…,tT−1t_0, \ldots, t_{T-1}, and G[j]G[j] is the good output vector on tjt_j. For a fault ff, Zj(f)Z_j(f) is the output vector of CC with ff on tjt_j, Rj(f)=Zj(f)⊕G[j]R_j(f) = Z_j(f) \oplus G[j] is its error word, R(f)=(R0(f),…,RT−1(f))R(f) = (R_0(f), \ldots, R_{T-1}(f)), and P(f)={j:Rj(f)≠0}P(f) = \{ j : R_j(f) \ne 0 \}. Simulation is deterministic, so R(f)R(f) and P(f)P(f) depend only on ff.

Lemma 1 (invariant). After any sequence of calls to add_fault, with DD the set of faults added, every f∈Df \in D is in exactly one list of FULL, the one under the key R(f)R(f), and in exactly one list of PF, the one under the key P(f)P(f), and no list holds a fault outside DD.

Proof. By induction on the number of calls. Before any call both maps are empty and DD is empty. Consider a call with a fault ff. If f∈Df \in D already, the call returns at once and nothing changes. Otherwise lines L2 and L3 compute Rj=Zj(f)⊕G[j]=Rj(f)R_j = Z_j(f) \oplus G[j] = R_j(f) for every jj, line L4 computes P={j:Rj≠0}=P(f)P = \{ j : R_j \ne 0 \} = P(f), and lines L5 and L6 append ff to the lists under R(f)R(f) and under P(f)P(f). No other list changes, and ff was in no list before, since by the induction hypothesis the lists hold only faults of DD. So after the call every fault of D∪{f}D \cup \{f\} is in exactly one list of each map, under its own key. ■\blacksquare

Theorem 1 (full lookup). Let a chip give the output vectors z0,…,zT−1z_0, \ldots, z_{T-1}, and let r=(z0⊕G[0],…,zT−1⊕G[T−1])r = (z_0 \oplus G[0], \ldots, z_{T-1} \oplus G[T-1]) as in line L7. Then line L8 returns exactly {g∈D:Zj(g)=zj for all j}\{ g \in D : Z_j(g) = z_j \text{ for all } j \}. In particular, if the chip behaves like the circuit with a fault f∈Df \in D, the answer is {g∈D:Zj(g)=Zj(f) for all j}\{ g \in D : Z_j(g) = Z_j(f) \text{ for all } j \}, and it contains ff.

Proof. By Lemma 1, the list under the key rr is {g∈D:R(g)=r}\{ g \in D : R(g) = r \}, which is empty when the key is absent. For each jj, Rj(g)=rjR_j(g) = r_j means Zj(g)⊕G[j]=zj⊕G[j]Z_j(g) \oplus G[j] = z_j \oplus G[j], and adding G[j]G[j] to both sides gives Zj(g)=zjZ_j(g) = z_j. So R(g)=rR(g) = r exactly when Zj(g)=zjZ_j(g) = z_j for every jj. If the chip behaves like CC with ff, then zj=Zj(f)z_j = Z_j(f), and g=fg = f satisfies the condition. ■\blacksquare

Theorem 2 (pass-fail lookup). Line L9 returns exactly {g∈D:P(g)={j:rj≠0}}\{ g \in D : P(g) = \{ j : r_j \ne 0 \} \}, and this set contains the answer of line L8.

Proof. The first part follows from Lemma 1 as in Theorem 1. If R(g)=rR(g) = r, then Rj(g)≠0R_j(g) \ne 0 exactly when rj≠0r_j \ne 0, so P(g)={j:rj≠0}P(g) = \{ j : r_j \ne 0 \}. So every fault returned by line L8 is also returned by line L9. ■\blacksquare

Corollary 1 (classes). Call two faults of DD full-equivalent when R(f)=R(g)R(f) = R(g), and pass-fail-equivalent when P(f)=P(g)P(f) = P(g). Full-equivalent faults are pass-fail-equivalent, since PP is a function of RR. So each full class lies inside one pass-fail class, and the number of pass-fail classes is at most the number of full classes. Since P(f)P(f) is a subset of {0,…,T−1}\{0, \ldots, T-1\}, there are at most 2T2^T pass-fail classes, and since R(f)R(f) is a string of T⋅OT \cdot O bits, there are at most 2T⋅O2^{T \cdot O} full classes. ■\blacksquare

Theorem 3 (sizes). Stored as a matrix with one row per fault, the full dictionary needs ∣D∣⋅T⋅O|D| \cdot T \cdot O bits and the pass-fail dictionary needs ∣D∣⋅T|D| \cdot T bits. No coding of RR alone can use fewer than ⌈log⁡2K⌉\lceil \log_2 K \rceil bits per fault for KK full classes in the worst case.

Proof. A row of the full dictionary is R(f)R(f), that is TT error words of OO bits each, and a row of the pass-fail dictionary is the indicator of P(f)P(f), that is TT bits. For the lower bound, a code that gives the same string to two faults with different RR cannot return different answers for them, so it needs KK distinct strings, and fewer than ⌈log⁡2K⌉\lceil \log_2 K \rceil bits give fewer than KK strings. ■\blacksquare

Theorem 1 says nothing about chips whose defect is not a fault of DD. For such a chip the lookup may return the empty list, or a list of faults that happen to have the same response.

Complexity

Building takes one simulation of the good circuit per test and one simulation of each fault on each test. With plain simulation of O(L+P)O(L + P) per vector, for LL lines and PP gate input pins, that is O(FT(L+P))O(F T (L + P)) time. Bit-parallel simulators divide this by up to the word size, and fault dropping is not allowed: a dictionary needs the response of a fault to every test, not only to the first test that detects it.

Storage is F⋅T⋅OF \cdot T \cdot O bits for the full dictionary and F⋅TF \cdot T bits for the pass-fail one. For a design with 10610^6 faults, 10410^4 tests and 10410^4 observed scan cells, the full dictionary would need 101410^{14} bits, about 12.5 terabytes, which is why full dictionaries are not stored for large designs.

A lookup reads the TT error words of the chip and makes one hash probe, so O(T)O(T) expected word operations when O≤wO \le w, plus the size of the answer. nearest compares with every row, O(FT)O(F T).

Variants

  • Drop on nn detections. Simulate each fault only until it has been detected nn times. The table is smaller and faster to build, and it keeps the first failing tests, which are what a tester records when it stops after a few failures.
  • Small dictionaries. Pomeranz and Reddy (1992) and Chess and Larrabee (1999) keep only the output bits, or the extra information beyond pass-fail, that are needed to tell the classes apart. Their tables are close to the pass-fail size with close to full resolution.
  • Signature dictionaries. Store the MISR signature of each faulty response instead of the response. This fits BIST, where only signatures are read, but aliasing can merge classes.
  • Matching with a score. Real defects rarely match a row exactly. Score each fault by the number of failing bits it explains, the number it predicts but the chip did not show, and the number it misses, and rank the faults by the score.
  • No dictionary. Effect-cause diagnosis starts from the failing outputs of the chip and simulates only the faults that could reach them, so it needs no table at all.

When to use it

Use a dictionary when many chips of one design must be diagnosed and the design is small enough to store the table, or when only the pass-fail table or a small dictionary is needed. The cost moves from each diagnosis to one large simulation at the start. For large designs, or when the test set changes often, simulate on demand with effect-cause diagnosis, which builds no table but simulates for each chip. To raise the resolution of either method, add tests that tell apart the faults in large classes.

Pitfalls

  • Fault dropping in line L3. A fault simulator used for fault coverage stops simulating a fault once a test detects it. Used to build the table, it leaves the later tests of every fault blank, and two faults that differ only on later tests share a row. Line L3 must simulate every fault on every test, or the table must record which tests were simulated.
  • Exact match only in line L8. Most real defects are not single stuck-at faults, so an exact lookup often returns nothing. Keep nearest or a score as the fallback, and report the distance, since a large distance means the fault model does not fit.
  • The tester stops early. Testers often record only the first few failing cycles. The observed response is then partial, and comparing it with full rows in line L8 treats the missing tests as passes. Compare only the tests that were applied and recorded.
  • Equivalent faults look like a weak test. A class of several faults may be a set of equivalent faults that no test can split. Collapse the fault list first, so that the class size reports real ambiguity.
  • The size grows with three factors. F⋅T⋅OF \cdot T \cdot O grows quickly. Estimate it before choosing the full form.

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.

fault_dictionary.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fault-dictionary/. The authors are listed in prov/4SH7E3.jsonl.
"""Fault dictionaries for single stuck-at faults.

A dictionary is built once from a circuit and a test set t_0, ..., t_(T-1).
For each modeled fault f it stores the response of the faulty circuit, coded
as an error word per test: bit k of R[f][j] is 1 when output k of the faulty
circuit differs from the good circuit on test j.

- The full-response dictionary maps the tuple R[f] to the faults with that
  response. It needs T * O bits per fault for O outputs.
- The pass-fail dictionary maps the set P[f] of failing tests (a T-bit mask)
  to the faults with that set. It needs T bits per fault.

Diagnosis looks up the response observed on the tester. Building costs one
fault simulation per (fault, test) pair; a lookup is one hash probe.
"""

from __future__ import annotations

from typing import Iterable, Optional, Sequence

from td3net import Circuit, Fault


def error_word(good: Sequence[int], seen: Sequence[int]) -> int:
    """Bit k is 1 when output k differs from the good value."""
    w = 0
    for k, (g, s) in enumerate(zip(good, seen)):
        if g != s:
            w |= 1 << k
    return w


class FaultDictionary:
    """Full-response and pass-fail dictionaries over one test set."""

    def __init__(self, circuit: Circuit, tests: Sequence[Sequence[int]]) -> None:
        """Precondition: every test is a 0/1 vector over the primary inputs. Cost O(T (L + P))."""
        self.circuit = circuit
        self.tests = [tuple(t) for t in tests]
        self.n_outputs = len(circuit.po)
        self.good = [circuit.outputs(t) for t in self.tests]  # @line L1
        self.response: dict[Fault, tuple[int, ...]] = {}
        self.full: dict[tuple[int, ...], list[Fault]] = {}
        self.pass_fail: dict[int, list[Fault]] = {}

    def add_fault(self, fault: Fault) -> None:
        """Simulate one fault on every test and file it in both dictionaries. O(T (L + P))."""
        if fault in self.response:
            return
        r = tuple(  # @line L2
            error_word(g, self.circuit.outputs(t, fault))  # @line L3
            for t, g in zip(self.tests, self.good)
        )
        p = 0  # @line L4
        for j, w in enumerate(r):
            if w:
                p |= 1 << j
        self.response[fault] = r
        self.full.setdefault(r, []).append(fault)  # @line L5
        self.pass_fail.setdefault(p, []).append(fault)  # @line L6

    def build(self, faults: Optional[Iterable[Fault]] = None) -> "FaultDictionary":
        """Add every fault of the list, by default all 2L single stuck-at faults."""
        for f in self.circuit.faults() if faults is None else faults:
            self.add_fault(f)
        return self

    def observe(self, responses: Sequence[Sequence[int]]) -> tuple[int, ...]:
        """Turn the output vectors seen on the tester (one per test) into error words."""
        if len(responses) != len(self.tests):
            raise ValueError("one response per test")
        return tuple(error_word(g, s) for g, s in zip(self.good, responses))  # @line L7

    def lookup_full(self, observed: tuple[int, ...]) -> list[Fault]:
        """Faults whose full response equals the observed error words. One hash probe."""
        return list(self.full.get(tuple(observed), []))  # @line L8

    def lookup_pass_fail(self, observed: tuple[int, ...]) -> list[Fault]:
        """Faults that fail on exactly the tests that failed on the tester."""
        p = 0
        for j, w in enumerate(observed):
            if w:
                p |= 1 << j
        return list(self.pass_fail.get(p, []))  # @line L9

    def nearest(self, observed: tuple[int, ...]) -> tuple[int, list[Fault]]:
        """Faults whose response is closest in Hamming distance to the observed one. O(|F| T)."""
        best, out = None, []
        for f, r in self.response.items():
            d = sum(bin(a ^ b).count("1") for a, b in zip(r, observed))
            if best is None or d < best:
                best, out = d, [f]
            elif d == best:
                out.append(f)
        return (0 if best is None else best), out

    def size_bits_full(self) -> int:
        return len(self.response) * len(self.tests) * self.n_outputs

    def size_bits_pass_fail(self) -> int:
        return len(self.response) * len(self.tests)

    def classes_full(self) -> int:
        return len(self.full)

    def classes_pass_fail(self) -> int:
        return len(self.pass_fail)

    def check_invariant(self) -> bool:
        """Every fault sits in exactly one class of each dictionary, under the key of its response."""
        n = len(self.response)
        if sum(map(len, self.full.values())) != n or sum(map(len, self.pass_fail.values())) != n:
            return False
        for key, fs in self.full.items():
            if not fs or any(self.response[f] != key for f in fs):
                return False
        for key, fs in self.pass_fail.items():
            for f in fs:
                if sum(1 << j for j, w in enumerate(self.response[f]) if w) != key:
                    return False
        return True
td3net.py 166 lines
# SPDX-License-Identifier: MIT
# Shared helper of the td3 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate-level combinational circuits with single stuck-at faults (two values).

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.

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). 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 and plain simulation of the good circuit
and of one faulty circuit. It holds no diagnosis algorithm.
"""

from __future__ import annotations

import random
from typing import Optional, Sequence

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

Fault = tuple[int, int]


def eval_gate(op: str, vals: Sequence[int]) -> int:
    """Two-valued output of a gate."""
    if op in ("AND", "NAND"):
        r = int(all(vals))
    elif op in ("OR", "NOR"):
        r = int(any(vals))
    elif op in ("XOR", "XNOR"):
        r = 0
        for v in vals:
            r ^= v
    else:
        r = vals[0]
    return r ^ int(op in ("NAND", "NOR", "XNOR", "NOT"))


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]}"
                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)

    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, with an optional stuck-at fault."""
        vals = [0] * 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 random_circuit(rng: random.Random, n_inputs: int, n_gates: int, max_fanin: int = 3) -> Circuit:
    """A random circuit of AND, OR, NAND, NOR, XOR and NOT gates. Every net with no sink is an output."""
    ops = ("AND", "OR", "NAND", "NOR", "XOR", "NOT")
    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(ops)
        if op == "NOT" or len(nets) < 2:
            op, fanin = "NOT", [rng.choice(nets)]
        else:
            fanin = rng.sample(nets, rng.randint(2, min(max_fanin, len(nets))))
        gates.append((f"g{k}", op, fanin))
        nets.append(f"g{k}")
    used = {src for _, _, fanin in gates for src in fanin}
    outputs = [n for n in nets if n not in used]
    inner = [g[0] for g in gates if g[0] in used]
    if inner and rng.random() < 0.5:
        outputs.append(rng.choice(inner))
    return Circuit(inputs, gates, outputs)
test_fault_dictionary.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fault-dictionary/. The authors are listed in prov/4SH7E3.jsonl.

import random

import pytest

from fault_dictionary import FaultDictionary
from td3net import Circuit, random_circuit


def page_circuit() -> Circuit:
    # z = a AND b, y = b OR c; b feeds both gates, so it has two branch lines.
    return Circuit(["a", "b", "c"], [("z", "AND", ["a", "b"]), ("y", "OR", ["b", "c"])], ["z", "y"])


PAGE_TESTS = [(1, 1, 0), (0, 1, 0), (1, 0, 0), (0, 0, 1)]


def names(c, faults):
    return sorted(c.fault_name(f) for f in faults)


def test_page_example():
    c = page_circuit()
    d = FaultDictionary(c, PAGE_TESTS).build()
    assert d.check_invariant()
    assert d.size_bits_full() == 14 * 4 * 2 == 112
    assert d.size_bits_pass_fail() == 14 * 4 == 56
    assert d.classes_full() == 10
    assert d.classes_pass_fail() == 7
    # The tester sees z = 0 on test 0 and nothing else: an equivalence class of three faults.
    seen = [(0, 1), (0, 1), (0, 0), (0, 1)]
    assert names(c, d.lookup_full(d.observe(seen))) == ["a/0", "b>z/0", "z/0"]
    # b/0 and b>y/0 fail the same tests but on different outputs.
    obs = d.response[(c.index["b"], 0)]
    assert names(c, d.lookup_full(obs)) == ["b/0"]
    assert names(c, d.lookup_pass_fail(obs)) == ["b/0", "b>y/0"]
    # Only test 2 fails: five faults in the pass-fail dictionary, split three ways by the full one.
    obs = d.response[(c.index["c"], 1)]
    assert names(c, d.lookup_pass_fail(obs)) == ["b/1", "b>y/1", "b>z/1", "c/1", "y/1"]
    assert names(c, d.lookup_full(obs)) == ["b>y/1", "c/1", "y/1"]


def test_unknown_response_and_nearest():
    c = page_circuit()
    d = FaultDictionary(c, PAGE_TESTS).build()
    # z fails on test 0 and y fails on test 3: no single stuck-at fault does this.
    obs = (1, 0, 0, 2)
    assert d.lookup_full(obs) == []
    dist, near = d.nearest(obs)
    assert dist == 1
    assert names(c, near) == ["a/0", "b>z/0", "c/0", "z/0"]


def test_edge_cases():
    c = page_circuit()
    d = FaultDictionary(c, []).build()
    assert d.classes_full() == 1 and d.size_bits_full() == 0
    assert len(d.lookup_full(())) == 14
    d = FaultDictionary(c, PAGE_TESTS)
    assert d.lookup_full((0, 0, 0, 0)) == [] and d.nearest((0, 0, 0, 0)) == (0, [])
    d.add_fault((0, 0))
    d.add_fault((0, 0))
    assert d.check_invariant() and len(d.response) == 1
    with pytest.raises(ValueError):
        d.observe([(0, 0)])


def brute_candidates(c, tests, raw, true_fault):
    """Every fault whose output vectors equal those of the true fault, by plain simulation."""
    return {g for g in c.faults() if raw[g] == raw[true_fault]}


def test_against_exhaustive_fault_simulation():
    rng = random.Random(31)
    cases = 0
    total_full = total_pf = 0
    for _ in range(80):
        ni = rng.randint(2, 6)
        c = random_circuit(rng, ni, rng.randint(1, 12))
        tests = [tuple(rng.randint(0, 1) for _ in range(ni)) for _ in range(rng.randint(1, 10))]
        d = FaultDictionary(c, tests).build()
        assert d.check_invariant()
        assert d.size_bits_full() == len(c.faults()) * len(tests) * len(c.po)
        assert d.size_bits_pass_fail() == len(c.faults()) * len(tests)
        assert d.classes_pass_fail() <= d.classes_full()
        raw = {g: tuple(c.outputs(t, g) for t in tests) for g in c.faults()}
        for f in c.faults():
            seen = [c.outputs(t, f) for t in tests]  # the tester data of a chip with fault f
            obs = d.observe(seen)
            full = set(d.lookup_full(obs))
            pf = set(d.lookup_pass_fail(obs))
            assert f in full
            assert full == brute_candidates(c, tests, raw, f)
            assert full <= pf
            assert d.nearest(obs) == (0, d.lookup_full(obs))
            cases += 1
            total_full += len(full)
            total_pf += len(pf)
    assert cases >= 500
    assert total_full <= total_pf


def test_random_operation_sequences_against_model():
    # Faults added in random order, with repeats; after each step every lookup agrees with a plain dict.
    rng = random.Random(21)
    for _ in range(40):
        ni = rng.randint(2, 5)
        c = random_circuit(rng, ni, rng.randint(1, 8))
        tests = [tuple(rng.randint(0, 1) for _ in range(ni)) for _ in range(rng.randint(1, 6))]
        good = [c.outputs(t) for t in tests]
        d = FaultDictionary(c, tests)
        model = {}
        for _ in range(30):
            f = rng.choice(c.faults())
            d.add_fault(f)
            model[f] = tuple(sum(1 << k for k, (a, b) in enumerate(zip(g, c.outputs(t, f))) if a != b) for t, g in zip(tests, good))
            assert d.check_invariant()
            probe = model[rng.choice(list(model))]
            assert sorted(d.lookup_full(probe)) == sorted(g for g, r in model.items() if r == probe)
            fails = [bool(w) for w in probe]
            assert sorted(d.lookup_pass_fail(probe)) == sorted(g for g, r in model.items() if [bool(w) for w in r] == fails)
        assert d.size_bits_full() == len(model) * len(tests) * len(c.po)


def test_noisy_observation_nearest_contains_true_fault_within_distance():
    # One flipped tester bit: the true fault is at distance 1, so the nearest distance is at most 1.
    rng = random.Random(12)
    for _ in range(100):
        ni = rng.randint(2, 5)
        c = random_circuit(rng, ni, rng.randint(2, 8))
        tests = [tuple(rng.randint(0, 1) for _ in range(ni)) for _ in range(rng.randint(2, 6))]
        d = FaultDictionary(c, tests).build()
        f = rng.choice(c.faults())
        obs = list(d.response[f])
        j = rng.randrange(len(tests))
        obs[j] ^= 1 << rng.randrange(len(c.po))
        dist, near = d.nearest(tuple(obs))
        assert dist <= 1
        if dist == 1:
            assert f in near

History

Fault dictionaries are the first form of logic diagnosis described in the test books: simulate every fault ahead of time and look up the failing response, starting from the causes rather than from the effects. The growth of F⋅T⋅OF \cdot T \cdot O with design size led to the pass-fail form and to the small dictionaries of Pomeranz and Reddy (1992) and of Chess and Larrabee (1999), and to the dictionary-free effect-cause methods that start from the observed failures.

References

  1. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on logic-level diagnosis (fault dictionaries, their size, and matching an observed response)
  2. I. Pomeranz and S. M. Reddy, On the generation of small dictionaries for fault location, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design, 272 to 279, 1992, dictionaries that keep only the output values needed to tell the faults apart
  3. B. Chess and T. Larrabee, Creating small fault dictionaries, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 18(3), 346 to 356, 1999, the sizes of full-response and pass-fail dictionaries, and smaller dictionaries with almost the full resolution
  4. Laung-Terng Wang, Cheng-Wen Wu and Xiaoqing Wen, VLSI Test Principles and Architectures, Morgan Kaufmann, 2006, the chapter on logic diagnosis (diagnosis with dictionaries and by effect-cause analysis)

Where this leads

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.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4SH7E3/text.yaml