Algorithm Search⌘K

Algorithmadvanced

Concurrent fault simulation

Also called Ulrich-Baker concurrent simulation.

Simulates the good circuit and, at each gate, only the faulty circuits whose values there differ from the good one, as lists updated with each event.

Time
O(T (L + P) (1 + F)) worst
Space
O(L (1 + F)) extra
Where
F = the number of faults; L = the number of lines; P = the number of gate input pins; T = the number of vectors
Properties
deterministicexactiterative
Origin
Ernst G. Ulrich, T. Baker, 1973

Concurrent fault simulation is a method for fault simulation: for each input vector, find which single stuck-at faults it detects. It runs one event-driven simulation of the good circuit. Each line also keeps a list of the faulty circuits whose value on that line differs from the good value, with that value. A faulty circuit is evaluated only at the gates where it differs from the good circuit on an input or where its fault sits, so the many faulty circuits that agree with the good one at a gate cost nothing there.

In plain words

A circuit with one broken wire behaves almost like the good circuit. On most wires, for most input values, the two give the same value. So simulating every broken circuit from scratch repeats the same work again and again.

Concurrent simulation runs the good circuit once. Next to each wire it keeps a short note: "in broken circuit number 7 this wire is 0, not 1". At each gate it looks only at the broken circuits that appear in the notes of the gate inputs, or whose break is at this gate. It computes their output and keeps a note only if the output differs from the good one.

When the notes on an output wire are not empty, those broken circuits are found by this input. They can then be removed.

The problem

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

For a fault ff and a line kk, the faulty value f(k)f(k) is the value of kk in the circuit with fault ff. The fault list of kk is the set of pairs (f,f(k))(f, f(k)) with f(k)f(k) different from the good value of kk.

The algorithm

  1. CONCURRENT-FAULT-SIMULATION(C, vectors, faults, drop)
  2. alive ← faults; every good value is X; every fault list is empty
  3. 1for each vector t do
  4. 2schedule every primary input
  5. 3while a line is scheduled do: take the scheduled line k with the smallest index
  6. 4g ← the value of k in t if k is an input, else the gate of k on the good values of its inputs
  7. 5S ← the alive faults that sit on k or appear in the list of an input of k
  8. 6for each f ∈ S do v ← the stuck value if f sits on k, else the gate of k on the values of f at its inputs
  9. 7if v ≠ g then put (f, v) in the new list of k
  10. 8if g or the new list differs from the stored one then store both and schedule the fanouts of k
  11. 9report the alive faults in the lists of the primary outputs as detected by t
  12. 10if drop then remove them from alive

At line L6, the value of ff at an input jj is the value in the list of jj if ff appears there, and the good value of jj otherwise. Taking the smallest index first is a levelized order for a combinational circuit, so each line is evaluated at most once per vector, after all its inputs. Dropped faults may stay in old lists. Every read keeps only the alive faults, so they cost nothing until the list is next rebuilt.

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 vectors are abc=110abc = 110, then 011. The table shows each line as good value [fault list]. A fault written x/vx/v means line xx stuck at vv, and every value in a list is the complement of the good value, so the list shows only the faults.

line after 110 after 011, without dropping
aa 1 [a/0] 0 [a/1]
bb 1 [b/0] 1 [b/0]
bgb_g 1 [b/0, b_g/0] 1 [b/0, b_g/0]
bhb_h 1 [b/0, b_h/0] 1 [b/0, b_h/0]
cc 0 [c/1] 1 [c/0]
gg 0 [a/0, b/0, b_g/0, g/1] 1 [a/1, g/0]
hh 1 [c/1, h/0] 0 [b/0, b_h/0, c/0, h/1]
zz 1 [a/0, b/0, b_g/0, g/1, z/0] 1 [b/0, b_h/0, c/0, h/1, z/0]

The first vector detects a/0, b/0, bgb_g/0, g/1 and z/0, the list of zz. At gg the list holds the faults of the lists of aa and bgb_g and the fault g/1, and they all differ, because both inputs are at the non-controlling value 1. At hh the fault b/0 is evaluated but not kept: c=0c = 0 already makes h=1h = 1.

For the second vector, the inputs aa and cc change and bb does not. So line L8 schedules gg and hh but not bgb_g and bhb_h, whose values and lists stay as they are, and then zz. The new list of gg loses b/0 and bgb_g/0, because a=0a = 0 now blocks them. The list of zz adds the four faults of hh. With dropping, the second vector reports bhb_h/0, c/0 and h/1, since b/0 and z/0 were dropped after the first vector. The run with dropping makes 14 line evaluations and 22 faulty gate evaluations, where serial simulation of the 16 faulty circuits would evaluate the 5 non-input lines once per circuit and vector.

Correctness

The good value and the fault list of a line depend only on the good values and the fault lists of its inputs, and on the faults that sit on the line. A fault that sits elsewhere and appears in no input list sees the good values on all inputs, so its value equals the good value and it belongs in no list. So lines L5 to L7 compute the correct list from correct input lists. Because the smallest index is taken first, every input of a line is final before the line is evaluated. A line that is not scheduled had no input change since the last vector, so its old value and list are still correct. By induction over the lines and the vectors, every list is correct after each vector, and line L9 reads exactly the faults whose faulty output differs. Restricting the lists to the alive faults keeps them correct, because each fault's entry is computed from that fault's entries only. The full proof gives the details.

Proof: Concurrent 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 to simulate 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. 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}.

The algorithm stores, for each line kk, a good value good[k]\mathrm{good}[k] and a list lst[k]\mathrm{lst}[k] of pairs (fault, value). Write lst[k]∣A\mathrm{lst}[k]|_A for the pairs whose fault is in the set AA. The correct list of kk for tt and AA is

Et(k,A)={(f,ft(k)):f∈A, ft(k)≠gt(k)}.E_t(k, A) = \{(f, f_t(k)) : f \in A,\ f_t(k) \ne g_t(k)\}.

Lemma 1 (one line is a function of its inputs). Let kk be a line that is not a primary input, and let AA be a set of faults. Then gt(k)g_t(k) and Et(k,A)E_t(k, A) depend only on the pairs (gt(j),Et(j,A))(g_t(j), E_t(j, A)) for the inputs jj of kk, on AA and on the gate of kk. Lines L4 to L7 compute exactly them from these pairs. Moreover Et(k,A′)E_t(k, A') is Et(k,A)∣A′E_t(k, A)|_{A'} for A′⊆AA' \subseteq A.

Proof. The good value is the gate applied to the good input values, which is line L4. For a fault f∈Af \in A, the value of input jj in the faulty circuit is the value of ff in Et(j,A)E_t(j, A) if ff appears there, and gt(j)g_t(j) otherwise. If ff sits on kk, then ft(k)f_t(k) is its stuck value. Otherwise ft(k)f_t(k) is the gate applied to these input values, which is line L6. A fault f∈Af \in A that does not sit on kk and appears in no input list has every input at the good value, so ft(k)=gt(k)f_t(k) = g_t(k), and it does not belong in the list. So the set SS of line L5 holds every fault that can belong, and line L7 keeps exactly those that do. The last claim holds because each fault's entry is computed from that fault's entries only. □\square

Lemma 2 (order of events). During one vector, each line is taken at line L3 at most once, and when line kk is taken, no input of kk is taken later in the same vector.

Proof. Line L3 takes the scheduled line with the smallest index. Line L8 schedules only fanouts of the line just taken, which have larger indices. So after line kk is taken, every line that is scheduled has an index larger than kk, and in particular no input of kk and not kk itself. □\square

Invariant. After vector tit_i is processed, every line kk has good[k]=gti(k)\mathrm{good}[k] = g_{t_i}(k) and lst[k]∣alivei=Eti(k,alivei)\mathrm{lst}[k]|_{\mathrm{alive}_i} = E_{t_i}(k, \mathrm{alive}_i).

Proof. Fix ii, and assume the invariant for i−1i - 1 (for i=1i = 1 there is nothing to assume, since every good value starts at X, which differs from every two-valued value). We show the claim line by line in topological order. Since alivei⊆alivei−1\mathrm{alive}_i \subseteq \mathrm{alive}_{i-1}, Lemma 1 lets us restrict the lists of vector ti−1t_{i-1} to alivei\mathrm{alive}_i and keep them correct for that vector.

A primary input is scheduled at line L2, so it is taken. Line L4 reads its value from tit_i, and its list holds the faults on it whose stuck value differs from that value, which is Eti(k,alivei)E_{t_i}(k, \mathrm{alive}_i). Line L8 stores them if they differ from the old ones, and otherwise the old ones are already equal.

Let kk be a line that is not an input. If kk is taken, then by Lemma 2 its inputs are final for this vector, and correct by induction. Lines L4 to L7 compute gti(k)g_{t_i}(k) and Eti(k,alivei)E_{t_i}(k, \mathrm{alive}_i) by Lemma 1, and line L8 stores them or finds them already stored. If kk is not taken, then no input of kk changed its good value or its restricted list during vector tit_i, since a change schedules kk at line L8. For i=1i = 1 this cannot happen, because every good value changes from X. For i>1i > 1, the inputs of kk hold the same pairs as at the end of vector ti−1t_{i-1}, restricted to alivei\mathrm{alive}_i, and by induction they are correct for both vectors. Then Lemma 1 says that the correct pair of kk is the same for ti−1t_{i-1} and for tit_i, and the stored pair of kk, restricted to alivei\mathrm{alive}_i, is correct for ti−1t_{i-1}. □\square

Theorem. For each vector tit_i, line L9 reports exactly the faults of alivei\mathrm{alive}_i that tit_i detects. So the output is the same as that of serial fault simulation, which simulates each faulty circuit on its own, with or without dropping.

Proof. A fault f∈aliveif \in \mathrm{alive}_i is detected by tit_i exactly when fti(o)≠gti(o)f_{t_i}(o) \ne g_{t_i}(o) for some primary output oo, that is, when ff appears in Eti(o,alivei)E_{t_i}(o, \mathrm{alive}_i), which by the invariant is lst[o]∣alivei\mathrm{lst}[o]|_{\mathrm{alive}_i}. Line L9 reads exactly these faults, and line L10 removes them from the alive set as serial simulation with dropping does. □\square

Complexity

One evaluation of line kk costs O((1+∣S∣)⋅fanin(k))O((1 + |S|) \cdot \mathrm{fanin}(k)) time, up to the cost of the set operations, and ∣S∣|S| is at most the number of alive faults. Each line is evaluated at most once per vector, so a vector costs O((L+P)(1+F))O((L + P)(1 + F)) time in the worst case, where PP is the number of gate input pins and FF the number of faults. This is the same order as serial simulation of every fault. The lists hold at most FF entries per line, so the space is O(L(1+F))O(L (1 + F)).

The gain of the method is in the typical case, and it is measured, not proved. Lists are short when few faulty circuits differ from the good one at a line, and few lines change from one vector to the next. With dropping the lists also shrink as tests are applied. For the c17 benchmark circuit with its 34 faults and all 32 input vectors in counting order, the implementation of this page makes 309 line evaluations and 130 faulty gate evaluations with dropping, and 350 and 816 without. In a shuffled order the counts change, to 384 and 153 with dropping for one fixed shuffle. These are counts on a 6-gate toy circuit, not timings.

Properties

  • Exact. For two-valued vectors on a combinational circuit, the result is the same as serial simulation of each faulty circuit, with or without dropping.
  • Event-driven in two ways. A line is evaluated only if an input changed, and a faulty circuit only where it differs from the good one.
  • Any fault model with local effect. A fault only has to change the value of the gate where it sits. Bridging faults, faults in sequential circuits and faults with more than two logic values fit the same lists.
  • Memory grows with the activity. The lists can be long when many faulty circuits differ on many lines, for example early in a test set before dropping.
  • Deterministic. The output does not depend on the order of the faults.

Variants and improvements

  • Lists per gate. Ulrich and Baker keep, for each good gate, a list of bad gates: copies of the gate with the input and output values of one faulty circuit. This page keeps the output value per line and reads the faulty input values from the input lines, which holds the same information.
  • Sequential circuits and timing. The original method simulated sequential circuits with delays. A faulty circuit then can also differ in the state of a flip-flop, and its entries live in the lists of the state lines. A list entry that converges to the good value is removed, and one that diverges is added.
  • Multiple values. The same scheme simulates faulty circuits with the values 0, 1, X and Z, which is needed for buses and for unknown initial states.
  • Deductive simulation. Armstrong (1972) computes the list of a line from the lists of its inputs with set operations, such as the intersection of the lists of controlling inputs. It needs no faulty gate evaluation but is harder to extend to timing and to more values.
  • Parallel and PPSFP. Parallel fault simulation puts one faulty circuit in each bit of a machine word, as in bit-parallelism. Parallel pattern single fault propagation puts one vector in each bit and is the usual method for combinational circuits and full scan.

When to use it

Use concurrent fault simulation for circuits with state and timing, where faulty circuits diverge and converge again, and for fault models with many logic values. For combinational logic and full scan designs, the bit-parallel pattern methods with fault dropping are often faster and simpler. Fault simulation of either kind runs in the loop of test generation: after each new test from ATPG, it removes all other faults that the test also detects, and it grades the random patterns of built-in self-test.

Pitfalls

  • Forgetting the local fault. A fault on line kk has no entry in the lists of the inputs of kk. Line L5 must add it, or the faults of each gate output never start a list.
  • Keeping equal values. A list entry whose value equals the good value must be removed at line L7. If it stays, the list grows, and line L9 reports it as detected.
  • A wrong order. Evaluating a line before one of its inputs gives a stale value. With unit delays the order is the time of the events, and with zero delay it is the topological order of line L3.
  • Stuck faults on stems and branches. A fault on a stem enters every branch list. A fault on one branch enters only that branch. Merging them loses faults that only one branch detects, such as bhb_h/0 in the example.
  • Comparing lists without the alive filter. Dropped faults left in an old list make it look different from the new one. The comparison of line L8 must use the alive faults only, or every line is rescheduled.

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.

concurrent_fault_simulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/concurrent-fault-simulation/. The authors are listed in prov/NCVK7P.jsonl.
"""Concurrent fault simulation (Ulrich and Baker 1973) of single stuck-at faults.

The good circuit is simulated event by event. Each line also keeps a list of
the faults whose faulty circuit has a different value on that line, with that
value. A faulty circuit is evaluated only at lines where it differs from the
good circuit on an input, or where its fault sits. All other faulty circuits
agree with the good circuit there and cost nothing.

Ulrich and Baker keep the list per gate, with the input and output values of
each faulty copy of the gate. This version keeps the list per line, with the
output value only. The faulty input values are then read from the lists of
the input lines. The information is the same.
"""

from __future__ import annotations

import heapq
from typing import Iterable, Optional, Sequence

from gatenet import X, Circuit, Fault, eval_gate


def concurrent_fault_simulation(
    c: Circuit,
    vectors: Iterable[Sequence[int]],
    faults: Optional[Sequence[Fault]] = None,
    drop: bool = True,
    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 removed after the first vector that detects it,
    so it appears in at most one set. Vectors hold the values 0 and 1 only.
    """
    if faults is None:
        faults = c.faults()
    alive = set(faults)
    local: list[list[Fault]] = [[] for _ in range(c.n_lines)]
    for f in faults:
        local[f[0]].append(f)
    good = [X] * c.n_lines
    lists: list[dict[Fault, int]] = [{} for _ in range(c.n_lines)]
    pi_pos = {line: k for k, line in enumerate(c.pi)}
    result: list[set[Fault]] = []
    events = gate_evals = fault_evals = 0

    for vector in vectors:  # @line L1
        queue = list(c.pi)  # @line L2
        heapq.heapify(queue)
        queued = set(queue)
        while queue:  # @line L3
            k = heapq.heappop(queue)
            queued.discard(k)
            events += 1
            ins = c.fanin[k]
            if c.kind[k] == "pi":  # @line L4
                g = vector[pi_pos[k]]
            else:
                g = eval_gate(c.op[k], [good[j] for j in ins])
            gate_evals += 1
            here = {f for f in local[k] if f in alive}  # @line L5
            seen = set(here)
            for j in ins:
                seen.update(f for f in lists[j] if f in alive)
            new: dict[Fault, int] = {}
            for f in seen:  # @line L6
                if f in here:
                    v = f[1]
                else:
                    v = eval_gate(c.op[k], [lists[j].get(f, good[j]) for j in ins])
                    fault_evals += 1
                if v != g:  # @line L7
                    new[f] = v
            old = {f: v for f, v in lists[k].items() if f in alive}
            if g != good[k] or new != old:  # @line L8
                good[k] = g
                lists[k] = new
                for w in c.fanout[k]:
                    if w not in queued:
                        queued.add(w)
                        heapq.heappush(queue, w)
        detected = {f for o in c.po for f in lists[o] if f in alive}  # @line L9
        result.append(detected)
        if drop:  # @line L10
            alive -= detected  # the lists keep dropped faults until they are rebuilt; reads skip them

    if stats is not None:
        stats.update(events=events, gate_evals=gate_evals, fault_evals=fault_evals)
    return result
gatenet.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the tv3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate-level combinational circuits with single stuck-at faults.

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

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

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

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

from __future__ import annotations

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

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

Fault = tuple[int, int]


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


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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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


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

import random

import pytest

from concurrent_fault_simulation import concurrent_fault_simulation
from gatenet import Circuit, random_circuit

# The circuit of the page: z = NAND(NAND(a, b), NAND(b, c)) = ab + bc.
C3 = Circuit(["a", "b", "c"], [("g", "NAND", ["a", "b"]), ("h", "NAND", ["b", "c"]), ("z", "NAND", ["g", "h"])], ["z"])

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


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


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


def test_page_example_two_vectors():
    vectors = [(1, 1, 0), (0, 1, 1)]
    stats = {}
    got = concurrent_fault_simulation(C3, vectors, stats=stats)
    assert got == serial(C3, vectors)
    assert names(C3, got[0]) == ["a/0", "b/0", "b>g/0", "g/1", "z/0"]
    assert names(C3, got[1]) == ["b>h/0", "c/0", "h/1"]
    assert stats == {"events": 14, "gate_evals": 14, "fault_evals": 22}
    kept = concurrent_fault_simulation(C3, vectors, drop=False)
    assert names(C3, kept[1]) == ["b/0", "b>h/0", "c/0", "h/1", "z/0"]


@pytest.mark.parametrize("drop", [True, False])
def test_c17_exhaustive_vectors(drop):
    vectors = C17.all_vectors()
    rng = random.Random(1)
    rng.shuffle(vectors)
    assert concurrent_fault_simulation(C17, vectors, drop=drop) == serial(C17, vectors, drop=drop)
    total = set().union(*concurrent_fault_simulation(C17, vectors))
    assert len(total) == 34


def test_c17_counts_of_the_page():
    counts = []
    for drop in (True, False):
        stats = {}
        concurrent_fault_simulation(C17, C17.all_vectors(), drop=drop, stats=stats)
        counts.append((stats["events"], stats["fault_evals"]))
    assert counts == [(309, 130), (350, 816)]
    vectors = C17.all_vectors()
    random.Random(1).shuffle(vectors)
    stats = {}
    concurrent_fault_simulation(C17, vectors, stats=stats)
    assert (stats["events"], stats["fault_evals"]) == (384, 153)


def test_fault_subset():
    faults = [(C3.line("h"), 0), (C3.line("b"), 1)]
    vectors = C3.all_vectors()
    assert concurrent_fault_simulation(C3, vectors, faults=faults) == serial(C3, vectors, faults=faults)


def test_repeated_vector_causes_no_events():
    stats = {}
    concurrent_fault_simulation(C17, [(0, 1, 0, 1, 1)] * 3, drop=False, stats=stats)
    one = {}
    concurrent_fault_simulation(C17, [(0, 1, 0, 1, 1)], drop=False, stats=one)
    assert stats["fault_evals"] == one["fault_evals"]
    assert stats["events"] == one["events"] + 2 * len(C17.pi)


@pytest.mark.parametrize("seed", range(60))
def test_random_circuits_against_serial(seed):
    rng = random.Random(seed)
    ops = ("AND", "OR", "NAND", "NOR", "NOT", "XOR", "XNOR", "BUF")
    c = random_circuit(rng, rng.randint(2, 8), rng.randint(2, 14), ops=ops)
    vectors = [tuple(rng.randint(0, 1) for _ in c.pi) for _ in range(rng.randint(1, 12))]
    drop = seed % 2 == 0
    assert concurrent_fault_simulation(c, vectors, drop=drop) == serial(c, vectors, drop=drop)

History

Fault simulation in the 1960s simulated each faulty circuit on its own, or one faulty circuit per bit of a machine word. Armstrong (1972) gave deductive simulation, which computes fault lists by set operations. Ulrich and Baker presented concurrent simulation at the Design Automation Workshop of 1973, and in IEEE Computer in 1974, as a method for simulating many nearly identical networks at once. It became a common method in fault simulators for sequential circuits.

References

  1. E. G. Ulrich and T. Baker, The concurrent simulation of nearly identical digital networks, Proceedings of the 10th Design Automation Workshop, 145 to 150, 1973, the method, with one list of bad gates per good gate and evaluation only where a bad gate differs
  2. E. G. Ulrich and T. Baker, Concurrent simulation of nearly identical digital networks, IEEE Computer 7(4), 39 to 44, April 1974, the journal version of the method
  3. D. B. Armstrong, A deductive method for simulating faults in logic circuits, IEEE Transactions on Computers C-21(5), 464 to 471, 1972, deductive fault simulation with fault lists computed by set operations, the method that concurrent simulation is compared with
  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 (serial, parallel, deductive and concurrent fault simulation)

About this page

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

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