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 clock cycles at once, make 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 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 flip-flops that all load their next state at each clock edge. Its combinational part has the primary inputs and the present-state lines as inputs, and the primary outputs and the next-state lines as outputs. As a machine it is a Mealy machine with 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 is enough.
- The fault is permanent, such as a single stuck-at fault on a line of 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 has its own inputs and outputs, and it also passes some signals to cell , 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 , whose passed signals are the state lines, and whose cell stands for clock cycle , also called time frame .
TIME-FRAME-EXPANSION(C, reset state s0, fault f, k_max)- 1
for k ← 1 to k_max - 2
A ← k copies C1, …, Ck of the combinational logic C - 3
connect the next-state outputs of Ct to the present-state inputs of Ct+1 - 4
fix the present-state inputs of C1 to s0 - 5
put the fault f in every copy - 6
T ← a complete combinational test generator on A, with the primary outputs of all copies as outputs - 7
if T is a test then return the primary input vectors of C1, …, Ck in T - 8
return 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 frames. For every sequence of input vectors , simulating the array with on the primary inputs of gives, in copy , the outputs and next state of cycle 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 . In cycle 1 the machine is in , and copy 1 reads by line L4. If copy has the state of cycle , it computes the same function as the machine in that cycle, so its next-state outputs are the state of cycle , which copy reads by line L3. So the array has a test exactly when some sequence of vectors makes some output of some cycle differ. A sequence of vectors that detects the fault still detects it after any more vectors, because later inputs do not change earlier outputs. So the -frame array has a test exactly when some sequence of at most 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 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 , which detects the fault only in cycle . If the pairs at the start of cycles were equal, dropping would give a shorter sequence that reaches the same pair at the start of cycle and then sees the same inputs, so it would also detect the fault, which is a contradiction. So the pairs are all different, and is at most the number of pairs reachable from , which is at most . With , 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 -bit counter with an enable input : in each cycle it adds to its count, with the next-state logic , AND , , AND , and the output . The reset state is 0. The fault stuck-at 0 (for , feeds only the output) leaves the state alone, and the faulty is always 0. The good is 1 only when the count is . The count grows by at most 1 per cycle, so in cycle it is at most , and can first be 1 in cycle , after cycles with . So every test needs at least vectors, and the array that finds one has copies of , each with 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 /0 needs 7 clock edges.
Example. Take the 2-bit counter with enable: , , and , reset to . With the stems , and split into branches, has 14 lines and 28 single stuck-at faults. Target /0.
| frames | inputs of the array | result |
|---|---|---|
| 1 | no test: in frame 1, so the good | |
| 2 | no test: the count in frame 2 is at most 1 | |
| 3 | no test: the count in frame 3 is at most 2 | |
| 4 | test , then any value |
With the test the states in frames 1 to 4 are 00, 01, 10 and 11, the good is 0, 0, 0, 1 and the faulty 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 /1 needs 1 vector, and /0 and /1 need 4.
Cost. The array for frames has lines for lines of . Combinational test generation is NP-complete in the size of its circuit, so the search at line L6 can take time exponential in times the number of primary inputs, and the loop over 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 copies of the line list of , 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 -frame array has a test exactly when one of the input sequences of length 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 vectors for to 6, and the array search finds no test in frames for 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 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 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 -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 , and the number of frames needed can grow exponentially with . 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.
# 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
- In the 2-bit counter, why does /1 need 4 vectors? Give a shortest test.
- Prove that the -frame array for a pipeline with no feedback and sequential depth has a test for a fault whenever any longer array has one, for .
- Change the counter so that its only primary output is the next-state line , and target the fault on the branch of that drives that output, stuck-at 0. How many frames does a test need now?
References
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 3RBAMV Edit this page History Report an error Markdown