Algorithm Search⌘K

Techniquecore

Time-frame expansion

Also called iterative logic array model, sequential circuit unrolling.

Unrolls a sequential circuit into copies of its combinational logic, one per clock cycle, so combinational ATPG can find test sequences.

Time-frame expansion turns test generation for a sequential circuit into test generation for a combinational one. A synchronous sequential circuit is a block of combinational logic and a set of flip-flops, and in each clock cycle the logic computes the outputs and the next state from the inputs and the present state. To look at kk clock cycles at once, make kk copies of the combinational logic, one per cycle, and wire the next-state outputs of each copy to the present-state inputs of the next one. The result is a combinational circuit, an iterative logic array, and a combinational test generator such as the D-algorithm, PODEM or SAT-based ATPG can search it. A test for the array is a sequence of kk input vectors that detects the fault. This page proves that the method is exact for a given number of frames, that a bound on the number of frames makes it complete, and that the number of frames needed can grow exponentially with the number of flip-flops.

In plain words

A circuit with memory gives different answers to the same input, depending on what it has stored. So a test is not one input but a list of inputs, given one per clock tick, starting from a known reset.

The trick is to draw the circuit once for each clock tick and connect the drawings in a row: what one tick stores is what the next tick reads. The row has no memory any more. It is just a big circuit with the inputs of every tick at once, so the usual tools for circuits without memory can find a test in it. If no test fits in a row of a given length, make the row longer and try again. The bad news is that some faults need a very long row.

When it applies

  • The circuit is synchronous: one clock, and mm flip-flops that all load their next state at each clock edge. Its combinational part CC has the primary inputs and the present-state lines q1,…,qmq_1, \ldots, q_m as inputs, and the primary outputs and the next-state lines d1,…,dmd_1, \ldots, d_m as outputs. As a machine it is a Mealy machine with 2m2^m states.
  • The circuit starts in a known reset state, the same in the good and the faulty machine. (Without one, see Variations.)
  • The flip-flops are not in a scan chain, or only some of them are. With full scan design, every flip-flop is a primary input and output of test mode, and combinational test generation on CC is enough.
  • The fault is permanent, such as a single stuck-at fault on a line of CC as in the stuck-at fault model. It is then present in every clock cycle.

The template

An iterative logic array is a combinational circuit made of identical cells in a row. Cell tt has its own inputs and outputs, and it also passes some signals to cell t+1t + 1, which reads them as inputs. A ripple-carry adder is one, with the carry as the signal passed on. Time-frame expansion builds an iterative logic array whose cell is CC, whose passed signals are the state lines, and whose cell tt stands for clock cycle tt, also called time frame tt.

  1. TIME-FRAME-EXPANSION(C, reset state s0, fault f, k_max)
  2. 1for k ← 1 to k_max
  3. 2A ← k copies C1, …, Ck of the combinational logic C
  4. 3connect the next-state outputs of Ct to the present-state inputs of Ct+1
  5. 4fix the present-state inputs of C1 to s0
  6. 5put the fault f in every copy
  7. 6T ← a complete combinational test generator on A, with the primary outputs of all copies as outputs
  8. 7if T is a test then return the primary input vectors of C1, …, Ck in T
  9. 8return no test of at most k_max vectors

The holes are the combinational test generator at line L6 and the logic values it uses. Two-valued or three-valued values, with one copy of the array for the good machine and one for the faulty one, are enough for an exact method. A test generator that works on one array with D-style values needs the nine values of Muth: pairs (good value, faulty value) in which each part is 0, 1 or X, because the fault effect can enter a frame through the state lines and through the fault site at the same time.

Why it is exact for kk frames. For every sequence of input vectors v1,…,vkv_1, \ldots, v_k, simulating the array with vtv_t on the primary inputs of CtC_t gives, in copy tt, the outputs and next state of cycle tt of the sequential machine. This holds for the good machine and, with the fault in every copy, for the faulty one. The proof is by induction on tt. In cycle 1 the machine is in s0s_0, and copy 1 reads s0s_0 by line L4. If copy tt has the state of cycle tt, it computes the same function as the machine in that cycle, so its next-state outputs are the state of cycle t+1t + 1, which copy t+1t + 1 reads by line L3. So the array has a test exactly when some sequence of kk vectors makes some output of some cycle differ. A sequence of j<kj < k vectors that detects the fault still detects it after any k−jk - j more vectors, because later inputs do not change earlier outputs. So the kk-frame array has a test exactly when some sequence of at most kk vectors detects the fault, and the loop at line L1 returns a shortest test sequence. If the search at line L6 uses X values, a test it reports is still a test of every completion, because three-valued simulation is monotone, as on the ternary simulation page.

Why 4m4^m frames are enough. Look at the pair (good state, faulty state) at the start of each cycle. From the pair and the input vector, the outputs of both machines and the next pair follow. Take a shortest test v1,…,vTv_1, \ldots, v_T, which detects the fault only in cycle TT. If the pairs at the start of cycles i<j≤Ti < j \le T were equal, dropping vi,…,vj−1v_i, \ldots, v_{j-1} would give a shorter sequence that reaches the same pair at the start of cycle ii and then sees the same inputs, so it would also detect the fault, which is a contradiction. So the TT pairs are all different, and TT is at most the number of pairs reachable from (s0,s0)(s_0, s_0), which is at most 2m⋅2m=4m2^m \cdot 2^m = 4^m. With kmax⁡≥4mk_{\max} \ge 4^m, the answer "no test" at line L8 is a proof that no input sequence from reset detects the fault. The bound counts all pairs. In practice tools use far smaller limits, and their "no test" then says nothing about longer sequences.

Why the number of frames can be exponential. Take an mm-bit counter with an enable input ee: in each cycle it adds ee to its count, with the next-state logic d0=q0⊕ed_0 = q_0 \oplus e, c1=ec_1 = e AND q0q_0, di=qi⊕cid_i = q_i \oplus c_i, ci+1=cic_{i+1} = c_i AND qiq_i, and the output z=qm−1⋯q0z = q_{m-1} \cdots q_0. The reset state is 0. The fault zz stuck-at 0 (for m≥2m \ge 2, zz feeds only the output) leaves the state alone, and the faulty zz is always 0. The good zz is 1 only when the count is 2m−12^m - 1. The count grows by at most 1 per cycle, so in cycle tt it is at most t−1t - 1, and zz can first be 1 in cycle 2m2^m, after 2m−12^m - 1 cycles with e=1e = 1. So every test needs at least 2m2^m vectors, and the array that finds one has 2m2^m copies of CC, each with Θ(m)\Theta(m) lines. The size of the array, not only the search in it, is exponential in the number of flip-flops. The scan design page shows the same effect on a 3-bit counter without the enable, where zz/0 needs 7 clock edges.

Example. Take the 2-bit counter with enable: d0=q0⊕ed_0 = q_0 \oplus e, c1=eq0c_1 = e q_0, d1=q1⊕c1d_1 = q_1 \oplus c_1 and z=q1q0z = q_1 q_0, reset to q1q0=00q_1 q_0 = 00. With the stems ee, q0q_0 and q1q_1 split into branches, CC has 14 lines and 28 single stuck-at faults. Target zz/0.

frames kk inputs of the array result
1 e1e_1 no test: q1q0=00q_1 q_0 = 00 in frame 1, so the good z1=0z_1 = 0
2 e1,e2e_1, e_2 no test: the count in frame 2 is at most 1
3 e1,e2,e3e_1, e_2, e_3 no test: the count in frame 3 is at most 2
4 e1,…,e4e_1, \ldots, e_4 test e=1,1,1e = 1, 1, 1, then any value

With the test 1,1,1,01, 1, 1, 0 the states in frames 1 to 4 are 00, 01, 10 and 11, the good zz is 0, 0, 0, 1 and the faulty zz is 0 in every frame, so the outputs differ in frame 4. The 4-frame array has 56 lines and 4 free inputs. A breadth-first search over pairs of states finds that every one of the 28 faults is detectable from reset, with shortest tests of 1 to 4 vectors. For example zz/1 needs 1 vector, and ee/0 and ee/1 need 4.

Cost. The array for kk frames has kLk L lines for LL lines of CC. Combinational test generation is NP-complete in the size of its circuit, so the search at line L6 can take time exponential in kk times the number of primary inputs, and the loop over kk repeats it. This is why sequential test generation is so much harder than combinational test generation, and why scan design exists.

Tests. The implementation builds the array as kk copies of the line list of CC, searches it with a complete branch and bound over the primary inputs, and is checked against brute force. On random sequential circuits with up to 2 inputs, 2 flip-flops and a random reset state, simulating the array equals simulating the machine cycle by cycle, the kk-frame array has a test exactly when one of the 2kn2^{k n} input sequences of length kk detects the fault, and the shortest test that time-frame expansion finds has the length found by breadth-first search over pairs of states, for every fault. For the counter, breadth-first search gives shortest tests of exactly 2m2^m vectors for m=1m = 1 to 6, and the array search finds no test in 2m−12^m - 1 frames for m=1m = 1 to 3.

Classic examples

  • Sequential ATPG. Test generators for circuits without scan, from the extension of the D-algorithm by Putzolu and Roth (1971) to HITEC (Niermann and Patel, 1991), work on an iterative logic array, often one frame at a time.
  • Partial scan. When the flip-flops left out of scan form no cycle, the circuit is a pipeline, and a number of frames equal to its sequential depth is enough. Partial scan picks the scanned flip-flops to make this true, as the scan design page explains.
  • Delay test. A two-pattern test for a transition fault is a test in two time frames. Launch on capture builds exactly this 2-frame array, as on the launch-on-capture and launch-on-shift page.
  • Bounded model checking. Bounded model checking unrolls a design for kk steps in the same way and asks a SAT solver for a path to a bad state. Its completeness threshold plays the role of the 4m4^m bound here.

Variations

  • Forward time processing. Start with the frame that activates the fault and add frames forward until the effect reaches an output.
  • Reverse time processing. Then justify the state that the first frame needs by adding frames backward, until the needed state is the reset state or has no constraint.
  • No reset. Without a reset, the initial state is all X, and a test must detect the fault for every initial state. Three-valued simulation of that X is safe but pessimistic, so a method based on it can miss tests that exist.
  • One frame at a time. Tools keep only a few frames in memory and move the window, trading completeness for memory.
  • SAT on the array. SAT-based ATPG turns the whole kk-frame array, with the good and the faulty machine, into one formula, as bounded model checking does.
  • Learning across frames. Implications learned between frames, as in static learning, cut the search in the array.

Pitfalls

  • Putting the fault in one frame only. The fault is in the hardware, so it is in every copy. A fault in one copy models a different defect.
  • Forgetting the faulty state. The faulty machine can reach states that the good machine never reaches, so the effect can hide in the state for many cycles. The bound counts pairs, not good states.
  • Reading a frame limit as a proof. "No test in 10 frames" says nothing about 11 frames, as the counter shows. Only a limit of at least the number of reachable state pairs proves that a fault is undetectable from reset.
  • Undetectable from reset is not redundant. A fault can be undetectable from reset and still change the behavior from another state. Scan can make it testable.
  • Size. The array grows linearly with kk, and the number of frames needed can grow exponentially with mm. Long sequential tests are the reason scan is used.

Code

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.

td2net.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the td2 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 three-valued simulation of the good
circuit and of one faulty circuit, and brute-force detection over all input
vectors. It holds no test generation, learning, testability or compaction
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)
time_frame_expansion.py 251 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/time-frame-expansion/. The authors are listed in prov/3RBAMV.jsonl.
"""Time-frame expansion: test generation for a sequential circuit from reset.

A synchronous sequential circuit is a combinational core (a td2net Circuit) and
m flip-flops. The core's inputs are the primary inputs followed by the m
present-state lines, and its outputs are the primary outputs followed by the m
next-state lines. Every clock cycle the flip-flops load the next state. The
circuit starts in a known reset state, the same in the good and the faulty
machine. A single stuck-at fault sits on a line of the core, so it is present in
every clock cycle.

unroll(seq, k) builds the iterative logic array: k copies of the core, where the
present-state inputs of copy t + 1 read the next-state outputs of copy t and the
present-state inputs of copy 1 are the reset values. find_test_sequence searches the
array for k = 1, 2, ... frames with a complete branch-and-bound over the primary
inputs (in the style of PODEM, without backtrace), so it finds a shortest test
sequence when one of at most k_max vectors exists. The brute forces in the tests
are shortest_test_length (breadth-first search over pairs of good and faulty
states) and plain enumeration of input sequences.
"""

from __future__ import annotations

from collections import deque
from itertools import product
from typing import Optional, Sequence

from td2net import X, Circuit, Fault, eval_gate


class SequentialCircuit:
    """A combinational core with n_pi primary inputs, n_ff flip-flops and n_po primary outputs."""

    def __init__(self, core: Circuit, n_pi: int, n_ff: int, reset: Optional[Sequence[int]] = None) -> None:
        if len(core.pi) != n_pi + n_ff or len(core.po) < n_ff:
            raise ValueError("the core needs n_pi + n_ff inputs and at least n_ff outputs")
        self.core = core
        self.n_pi = n_pi
        self.n_ff = n_ff
        self.n_po = len(core.po) - n_ff
        self.reset = tuple(reset) if reset is not None else (0,) * n_ff
        if len(self.reset) != n_ff:
            raise ValueError("the reset state needs one value per flip-flop")

    def step(self, state: Sequence[int], vector: Sequence[int], fault: Optional[Fault] = None):
        """One clock cycle: (primary outputs, next state)."""
        out = self.core.outputs(tuple(vector) + tuple(state), fault)
        return out[: self.n_po], out[self.n_po :]

    def run(self, vectors: Sequence[Sequence[int]], fault: Optional[Fault] = None) -> list[tuple[int, ...]]:
        """The primary outputs of each clock cycle, starting from reset."""
        state = self.reset
        outs = []
        for v in vectors:
            o, state = self.step(state, v, fault)
            outs.append(o)
        return outs

    def detects(self, vectors: Sequence[Sequence[int]], fault: Fault) -> bool:
        """True if some output of some cycle differs between the good and the faulty machine."""
        return self.run(vectors) != self.run(vectors, fault)


class IterativeLogicArray:
    """k copies of the core as one combinational circuit.

    Line (t, j) is line j of the core in frame t (t = 0 .. k-1). A present-state
    stem of frame t > 0 reads the next-state line of frame t - 1, and a
    present-state stem of frame 0 is the reset value. The array's inputs are
    the primary inputs of every frame and its outputs are the primary outputs of
    every frame.
    """

    def __init__(self, seq: SequentialCircuit, k: int) -> None:
        core = seq.core
        self.seq = seq
        self.k = k
        n = core.n_lines
        self.n_core = n
        state_line = core.pi[seq.n_pi :]
        next_line = core.po[seq.n_po :]
        # L2: one copy of the core for each frame
        self.source: list[Optional[int]] = [None] * (k * n)
        self.reset_value: dict[int, int] = {}
        self.inputs: list[int] = []
        for t in range(k):
            for p in core.pi[: seq.n_pi]:
                self.inputs.append(t * n + p)
            for i, s in enumerate(state_line):
                if t == 0:
                    # L4: the present state of frame 1 is the reset state
                    self.reset_value[s] = seq.reset[i]
                else:
                    # L3: next state of frame t - 1 feeds the present state of frame t
                    self.source[t * n + s] = (t - 1) * n + next_line[i]
        self.outputs = [t * n + o for t in range(k) for o in core.po[: seq.n_po]]

    def simulate(self, pi_values: Sequence[int], fault: Optional[Fault] = None) -> list[int]:
        """Three-valued values of all k * L lines; the fault is in every frame."""
        core = self.seq.core
        n = self.n_core
        vals = [X] * (self.k * n)
        free = iter(pi_values)
        for t in range(self.k):
            base = t * n
            for j in range(n):
                line = base + j
                kind = core.kind[j]
                if kind == "pi":
                    src = self.source[line]
                    if src is not None:
                        v = vals[src]
                    elif t == 0 and j in self.reset_value:
                        v = self.reset_value[j]
                    else:
                        v = next(free)
                else:
                    v = eval_gate(core.op[j], [vals[base + q] for q in core.fanin[j]])
                # L5: the fault is present in every copy
                if fault is not None and fault[0] == j:
                    v = fault[1]
                vals[line] = v
        return vals

    def frame_vectors(self, pi_values: Sequence[int]) -> list[tuple[int, ...]]:
        p = self.seq.n_pi
        return [tuple(pi_values[t * p : (t + 1) * p]) for t in range(self.k)]


def unroll(seq: SequentialCircuit, k: int) -> IterativeLogicArray:
    return IterativeLogicArray(seq, k)


def combinational_test(ila: IterativeLogicArray, fault: Fault) -> Optional[list[int]]:
    """Complete search over the array's inputs: a fully specified test, or None.

    Decisions set the primary inputs frame by frame. After each decision the good
    and the faulty array are simulated with X on the open inputs. A branch
    succeeds when some output has known, different values, and fails when every
    output is known and equal in both arrays.
    """
    n_in = len(ila.inputs)
    values = [X] * n_in

    def outcome() -> Optional[bool]:
        good = ila.simulate(values)
        bad = ila.simulate(values, fault)
        open_output = False
        for o in ila.outputs:
            g, b = good[o], bad[o]
            if g != X and b != X:
                if g != b:
                    return True
            else:
                open_output = True
        return None if open_output else False

    def search(i: int) -> bool:
        r = outcome()
        if r is not None:
            return r
        if i == n_in:
            return False
        for v in (0, 1):
            values[i] = v
            if search(i + 1):
                return True
        values[i] = X
        return False

    if not search(0):
        return None
    return [0 if v == X else v for v in values]


def find_test_sequence(seq: SequentialCircuit, fault: Fault, k_max: int) -> Optional[list[tuple[int, ...]]]:
    """A shortest test sequence of at most k_max vectors from reset, or None.

    unroll makes the k copies (L2), links the frames (L3) and fixes the reset
    state (L4); simulate puts the fault in every copy (L5).
    """
    for k in range(1, k_max + 1):  # @line L1
        # @line L2
        # @line L3
        # @line L4
        ila = unroll(seq, k)
        # @line L5
        t = combinational_test(ila, fault)  # @line L6
        if t is not None:
            return ila.frame_vectors(t)  # @line L7
    return None  # @line L8


def shortest_test_length(seq: SequentialCircuit, fault: Fault) -> Optional[int]:
    """Brute force: breadth-first search over pairs (good state, faulty state) from reset.

    Returns the length of a shortest detecting sequence, or None if the fault
    cannot be detected from reset by any sequence.
    """
    vectors = list(product((0, 1), repeat=seq.n_pi))
    start = (seq.reset, seq.reset)
    depth = {start: 0}
    queue = deque([start])
    while queue:
        pair = queue.popleft()
        g, b = pair
        for v in vectors:
            og, ng = seq.step(g, v)
            ob, nb = seq.step(b, v, fault)
            if og != ob:
                return depth[pair] + 1
            nxt = (ng, nb)
            if nxt not in depth:
                depth[nxt] = depth[pair] + 1
                queue.append(nxt)
    return None


def reachable_pairs(seq: SequentialCircuit, fault: Fault) -> int:
    """The number of (good state, faulty state) pairs reachable from reset."""
    vectors = list(product((0, 1), repeat=seq.n_pi))
    start = (seq.reset, seq.reset)
    seen = {start}
    stack = [start]
    while stack:
        g, b = stack.pop()
        for v in vectors:
            nxt = (seq.step(g, v)[1], seq.step(b, v, fault)[1])
            if nxt not in seen:
                seen.add(nxt)
                stack.append(nxt)
    return len(seen)


def counter_with_enable(m: int) -> SequentialCircuit:
    """An m-bit counter that counts up when e = 1, with the output z = q_{m-1} ... q_0."""
    inputs = ["e"] + [f"q{i}" for i in range(m)]
    gates: list[tuple[str, str, list[str]]] = []
    carry = "e"
    for i in range(m):
        gates.append((f"d{i}", "XOR", [f"q{i}", carry]))
        if i + 1 < m:
            gates.append((f"c{i + 1}", "AND", [carry, f"q{i}"]))
            carry = f"c{i + 1}"
    if m == 1:
        gates.append(("z", "BUF", ["q0"]))
    else:
        gates.append(("z", "AND", [f"q{i}" for i in range(m)]))
    core = Circuit(inputs, gates, ["z"] + [f"d{i}" for i in range(m)])
    return SequentialCircuit(core, 1, m)
test_time_frame_expansion.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/time-frame-expansion/. The authors are listed in prov/3RBAMV.jsonl.
"""Time-frame expansion against exhaustive sequential simulation from reset."""

from __future__ import annotations

import random
from itertools import product

import pytest

from td2net import Circuit
from time_frame_expansion import (
    SequentialCircuit,
    combinational_test,
    counter_with_enable,
    find_test_sequence,
    reachable_pairs,
    shortest_test_length,
    unroll,
)


def random_sequential(rng: random.Random, n_pi: int, n_ff: int, n_gates: int) -> SequentialCircuit:
    nets = [f"i{k}" for k in range(n_pi)] + [f"s{k}" for k in range(n_ff)]
    inputs = list(nets)
    gates = []
    for k in range(n_gates):
        op = rng.choice(["AND", "OR", "NAND", "NOR", "NOT", "XOR"])
        fanin = [rng.choice(nets)] if op == "NOT" else rng.sample(nets, 2)
        gates.append((f"g{k}", op, fanin))
        nets.append(f"g{k}")
    names = [g[0] for g in gates]
    outputs = [rng.choice(names)] + [rng.choice(names) for _ in range(n_ff)]
    reset = tuple(rng.randint(0, 1) for _ in range(n_ff))
    return SequentialCircuit(Circuit(inputs, gates, outputs), n_pi, n_ff, reset)


def detected_by_some_sequence(seq: SequentialCircuit, fault, k: int) -> bool:
    """Brute force: try every input sequence of exactly k vectors."""
    vectors = list(product((0, 1), repeat=seq.n_pi))
    return any(seq.detects(list(s), fault) for s in product(vectors, repeat=k))


def make(seed: int) -> SequentialCircuit:
    rng = random.Random(seed)
    return random_sequential(rng, rng.randint(1, 2), rng.randint(1, 2), rng.randint(3, 6))


@pytest.mark.parametrize("seed", range(40))
def test_array_simulation_equals_sequential_simulation(seed):
    seq = make(seed)
    rng = random.Random(1000 + seed)
    k = rng.randint(1, 5)
    ila = unroll(seq, k)
    for fault in [None] + seq.core.faults():
        pis = [rng.randint(0, 1) for _ in range(k * seq.n_pi)]
        vals = ila.simulate(pis, fault)
        outs = [tuple(vals[o] for o in ila.outputs[t * seq.n_po : (t + 1) * seq.n_po]) for t in range(k)]
        assert outs == seq.run(ila.frame_vectors(pis), fault)


@pytest.mark.parametrize("seed", range(25))
def test_shortest_sequence_matches_breadth_first_search(seed):
    seq = make(seed)
    k_max = 4
    for fault in seq.core.faults():
        length = shortest_test_length(seq, fault)
        found = find_test_sequence(seq, fault, k_max)
        if length is None or length > k_max:
            assert found is None
        else:
            assert found is not None and len(found) == length
            assert seq.detects(found, fault)


@pytest.mark.parametrize("seed", range(12))
def test_k_frame_array_has_a_test_iff_some_k_sequence_detects(seed):
    seq = make(500 + seed)
    for k in (1, 2, 3):
        ila = unroll(seq, k)
        for fault in seq.core.faults():
            assert (combinational_test(ila, fault) is not None) == detected_by_some_sequence(seq, fault, k)


@pytest.mark.parametrize("seed", range(25))
def test_shortest_test_within_reachable_pairs(seed):
    seq = make(seed)
    for fault in seq.core.faults():
        length = shortest_test_length(seq, fault)
        if length is not None:
            assert length <= reachable_pairs(seq, fault) <= 4**seq.n_ff


@pytest.mark.parametrize("m", range(1, 7))
def test_counter_needs_two_to_the_m_frames(m):
    seq = counter_with_enable(m)
    fault = (seq.core.line("z"), 0)
    assert shortest_test_length(seq, fault) == 2**m
    assert reachable_pairs(seq, fault) == 2**m


@pytest.mark.parametrize("m", range(1, 4))
def test_counter_array_search(m):
    seq = counter_with_enable(m)
    fault = (seq.core.line("z"), 0)
    assert combinational_test(unroll(seq, 2**m - 1), fault) is None
    found = find_test_sequence(seq, fault, 2**m)
    assert len(found) == 2**m
    assert all(v == (1,) for v in found[:-1])
    assert seq.detects(found, fault)


def test_two_bit_counter_example():
    seq = counter_with_enable(2)
    core = seq.core
    assert seq.run([(1,), (1,), (1,), (0,)]) == [(0,), (0,), (0,), (1,)]
    assert [shortest_test_length(seq, (core.line(n), v)) for n, v in [("z", 0), ("z", 1), ("e", 0), ("e", 1)]] == [4, 1, 4, 4]
    lengths = [shortest_test_length(seq, f) for f in core.faults()]
    assert len(lengths) == 28 and None not in lengths and max(lengths) == 4
    assert len(unroll(seq, 4).simulate([1, 1, 1, 0])) == 4 * core.n_lines

Exercises

  1. In the 2-bit counter, why does ee/1 need 4 vectors? Give a shortest test.
  2. Prove that the kk-frame array for a pipeline with no feedback and sequential depth dd has a test for a fault whenever any longer array has one, for k≥d+1k \ge d + 1.
  3. Change the counter so that its only primary output is the next-state line dm−1d_{m-1}, and target the fault on the branch of dm−1d_{m-1} that drives that output, stuck-at 0. How many frames does a test need now?

References

  1. G. R. Putzolu and J. P. Roth, A heuristic algorithm for the testing of asynchronous circuits, IEEE Transactions on Computers C-20(6), 639 to 647, 1971, the extension of the D-algorithm to sequential circuits through the iterative array model of the circuit
  2. P. Muth, A nine-valued circuit model for test generation, IEEE Transactions on Computers C-25(6), 630 to 636, 1976, the nine values (good value, faulty value), each 0, 1 or X, needed because the fault is present in every copy of the iterative array
  3. T. M. Niermann and J. H. Patel, HITEC, a test generation package for sequential circuits, Proceedings of the European Design Automation Conference, 214 to 218, 1991, forward and reverse time processing with a PODEM-based generator, without scan or a reset state
  4. K.-T. Cheng, Gate-level test generation for sequential circuits, ACM Transactions on Design Automation of Electronic Systems 1(4), 405 to 442, 1996, the survey of iterative logic array methods, forward and reverse time processing, and the cost of many time frames
  5. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on test generation for sequential circuits (the iterative array model)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises