Techniquecore
Static test compaction
Also called reverse-order fault simulation, test set compaction.
Shrinks a finished test set by merging compatible cubes and by dropping patterns that reverse-order fault simulation or set covering shows are not needed.
Static test compaction takes a test set that is already finished and makes it smaller without losing fault coverage. A test set from automatic test pattern generation usually holds one test cube per targeted fault, with many inputs left unspecified (X). Two cheap steps remove most of the waste. First, merge cubes that do not conflict in any specified position into one cube. Second, fill the remaining X positions and fault-simulate the vectors from the last one to the first, keeping a vector only when it detects a fault that the vectors already kept do not. Test time on the tester and tester memory grow with the number of vectors, so each vector removed saves money on every chip. This page proves that the second step never loses a fault, that the first step never loses a fault that a cube was made for, and that finding a minimum test set is NP-hard, as hard as set cover.
In plain words
A test generator works one fault at a time and writes down each test as soon as it finds it. Later tests often happen to catch the faults that earlier tests were made for, so some early tests do nothing new. Also, a test usually fixes only a few inputs and does not care about the others, so two tests that fix different inputs can be joined into one.
Static compaction cleans up after the generator. It joins tests that fit together, then walks the list from the end and throws away every test that catches nothing new. Walking from the end works well because the last tests were made for the hardest faults, and such tests tend to catch many easy faults along the way.
When it applies
- The circuit under test is combinational, or a full scan design makes it so. A test is one input vector.
- The fault list is fixed, for example all single stuck-at faults, and a fault simulator can tell which faults a vector detects. With PPSFP this is fast even for large circuits.
- The test set is given as a list of test cubes, vectors over . A test cube of a fault is a cube whose every completion (every way to replace each X by 0 or 1) detects .
- The goal is fewer vectors with the same coverage. Compaction that merges tests during generation is dynamic test compaction, and the two are used together.
The template
Two cubes are compatible when no position holds 0 in one and 1 in the other. Their intersection takes, at each position, the specified value of either cube, and X where both have X. Its completions are exactly the vectors that are completions of both cubes.
STATIC-COMPACT(T, F)- 1
C ← empty list of cubes - 2
for each cube t in T, in order - 3
if some cube u in C is compatible with t then u ← u ∩ t - 4
else append t to C - 5
V ← the cubes of C with every X filled - 6
R ← F; K ← empty - 7
for each vector v of V, last first - 8
D ← the faults of R that v detects - 9
if D is not empty then add v to K; R ← R \ D - 10
return K
Lines L1 to L4 merge cubes by first fit: each cube joins the first merged cube it is compatible with. Line L5 fills the X positions, with a constant or with random values. Lines L6 to L10 are the reverse-order pass: one fault simulation with fault dropping over the vectors in reverse order. The holes are the rule that picks at line L3, the fill at line L5 and the order of at line L7.
Why the reverse-order pass never loses a fault. Let be a fault of that some vector of detects, and let be the last vector of that detects it. Line L7 handles after all the vectors behind it. A fault leaves only at line L9, and only when the vector being handled detects it. No vector after detects , so is still in when line L8 handles . So , is not empty, and line L9 keeps . So detects every fault of that detects, and is a subset of . The same argument works with any fault simulator that answers correctly, and with any order of . The order changes only which vectors are kept.
Why merging never loses a target fault. Say is a test cube of , and ends up inside the merged cube . Each intersection at line L3 keeps the specified values of both cubes, so by induction on the cubes that join , every specified position of holds the same value in the final . Any filling of at line L5 then agrees with on every specified position, so it is a completion of , and it detects . If every fault of has a test cube in , the vectors detect all of , and by the step before so does . The proof needs the cube to be a test cube for every completion. A fault that a filled cube detects only through the values chosen for its X positions is not protected, as the pitfalls show.
Why a minimum test set is hard to find. The decision problem is: given a circuit, a fault list and a number , is there a set of at most vectors that detects every fault of ? It is in NP, since the vectors are a certificate that fault simulation checks in polynomial time, and one may take . It is NP-hard by a reduction from set cover, which Karp (1972) proved NP-complete. Take sets , , over a universe . Build a circuit with inputs :
- a NAND gate of and for each pair , and $a = $ the AND of all , so exactly when at most one input is 1;
- for each element , $y_e = $ the OR of the with , and an output AND ;
- the fault list .
A vector with no 1 makes every good equal to 0, the faulty value, so it detects nothing. A vector with two or more 1s makes , so every is 0 in both circuits, and it detects nothing either. The fault on does not reach . The vector with a single 1 at makes and , so it detects /0 exactly when . So the useful vectors are the unit vectors, unit vector detects the faults of the elements of , and test sets of size correspond to set covers of size . The circuit has gates, so the reduction is polynomial, and it keeps sizes exactly. So any approximation ratio for minimum test sets would give the same ratio for set cover, and the limits on approximating set cover hold here too.
Krishnamurthy and Akers (1984) proved that finding the size of a minimum test set is NP-hard. This page does not repeat their proof; the reduction above is a simple one for a given fault list, in the same spirit. Note that the hardness here does not come from test generation: in this circuit every fault has an easy test, and only the choice among them is hard.
The set cover view. Fault-simulate every vector of against without fault dropping. The result is the detection matrix: vector detects the set . A smallest subset of with the same coverage is a minimum set cover of by the sets . This is exactly the set cover problem, with the vectors as sets and the faults as elements. Greedy set cover picks the vector that detects the most faults not yet detected, and it uses at most times the minimum number of vectors, where is the largest number of faults one vector detects and . The reverse-order pass gives no such bound. It is cheaper, because it needs only one simulation with fault dropping, not the full matrix.
A lower bound. Call faults independent when no vector detects two of them. If contains pairwise independent faults, every complete test set has at least vectors, because each vector detects at most one of them. This bound is how one can show that a compacted set is a minimum without searching all subsets.
Example. Take , and with inputs . It has 7 lines and 14 single stuck-at faults, all detectable. Some faults have one test only: /0 needs 1110, /0 needs 1101, and /1, /1 and /1 need 1100. The tests of /1 are 01X1 and 0110, and those of /1 are 10X1 and 1010. Say a test generator, with no fault dropping, made these 8 cubes in this order:
| cube | made for | first-fit merged cube after this cube |
|---|---|---|
| XX00 | /0 | 1: XX00 |
| 11X1 | /0 | 2: 11X1 |
| 01X1 | /1 | 3: 01X1 |
| 10X1 | /1 | 4: 10X1 |
| 1110 | /0 | 5: 1110 |
| 1100 | /1 | 1: 1100 |
| 1101 | /0 | 2: 1101 |
| X0X1 | /1 | 4: 10X1 |
Merging leaves 5 cubes: 1100, 1101, 01X1, 10X1 and 1110. Filling with 0 gives 1100, 1101, 0101, 1001 and 1110. The reverse-order pass keeps all 5: 1110 detects /0, /0, /0, /0, /0 and /1; 1001 adds /1, /1 and /0; 0101 adds /1; 1101 adds /0; 1100 adds /1, /1 and /1. The faults /1, /1, /0, /0 and /1 are pairwise independent, so 5 is the minimum, and this result is optimal. The reverse-order pass alone, on the 8 cubes filled with 0, keeps 6 vectors: it drops 1101 (the filling of 11X1), whose faults the later 1101 detects, and 0000, whose only fault /0 the last vector 0001 detects.
Cost. Merging by first fit takes time for inputs, or less with an index on the specified positions. The reverse-order pass is one fault simulation with fault dropping, which is the main cost on large circuits. Building the detection matrix for set covering needs a simulation without dropping, which costs more, and the greedy cover then takes time about linear in the size of the matrix with a bucket queue.
Tests. The implementation is checked against brute force on random circuits of 2 to 4 inputs and up to 7 gates, with fixed seeds. The reverse-order pass keeps exactly the coverage of its input and keeps a vector exactly when it detects a fault that no later vector detects. Merged and filled cubes detect every fault that some cube of the input is a test cube for. The result of the whole method is never smaller than the minimum test set found by trying all subsets of the input vectors, and the greedy cover is within of that minimum. On random set systems with up to 5 sets and 5 elements, the minimum test set of the reduction circuit has the size of the minimum set cover found by enumeration. The example above and the loss example below are checked as given.
Measured, not proved. These numbers come from toy inputs, not from benchmark circuits. With random.Random(7), 200 random circuits of 3 or 4 inputs and 3 to 7 gates, and one test cube per detectable fault (5073 cubes in total, each made by turning positions of a random detecting vector into X while it stays a test cube), merging left 853 cubes, and the reverse-order pass then left 825 vectors. The reverse-order pass alone, on the 5073 filled cubes, left 1030. Greedy set cover over all input vectors used 822, and the exact minimum is 804. The compacted set was larger than the minimum in 19 of the 200 circuits, the greedy cover in 18, and the reverse-order pass alone in 136.
Classic examples
- Compaction after ATPG. Every production test flow for scan designs runs a pass like lines L6 to L10 after test generation, often several times with different orders.
- Redundant Vector Elimination. Hamzaoglu and Patel (1998) drop vectors whose faults are all detected by other vectors, and reduce the faults that only one vector detects, which they call essential faults, to bring the test set close to their estimate of the minimum size.
- Set covering with the detection matrix. When the matrix is affordable, greedy set covering or an integer linear program on it gives smaller sets than the reverse-order pass.
- N-detect test sets. An N-detect test set must detect each fault times. Compaction then becomes set multicover, and the reverse-order pass keeps a vector while some fault still needs a detection.
Variations
- Several orders. Repeat the reverse-order pass with the vectors sorted in other orders, for example by the number of faults each detects or at random. Each pass is safe, so the best result can be kept.
- Forward then reverse. A pass in the original order with fault dropping, then a pass in reverse, removes vectors whose faults the earlier and later vectors share.
- Merging with a fault check. Instead of merging any compatible cubes, merge only when the result still detects the faults of both cubes, or fault-simulate after merging and keep the lost faults as new targets.
- Better merge order. First fit depends on the cube order. Merging is a coloring problem on the graph whose edges join incompatible cubes, so graph coloring heuristics can be used, and the minimum number of merged cubes is itself NP-hard to find.
- X filling for compression. With test compression, leave the X positions open for the decompressor rather than filling them at line L5.
Pitfalls
- Merging loses chance detections. After the fill, a cube can detect faults it was not made for, and a generator with fault dropping then skips those faults. Merging changes the fill, and those faults can be lost. In the circuit , with outputs and , the cubes 11X, 01X and XX1 fill to 110, 010 and 001, and 001 detects /1. First fit merges them into 111 and 01X, which fill to 111 and 010, and neither detects /1, whose only tests are 00X. Measured with
random.Random(7)on 200 random circuits of 3 or 4 inputs and 3 to 7 gates, with cubes made as a generator with fault dropping makes them, merging lost 472 faults in 111 circuits. Always fault-simulate after merging. - Reverse order is not minimal. The pass keeps a vector when it detects a fault that the later kept vectors miss, but an earlier vector may detect that fault too. The result can still hold vectors that could be removed, and it can be far from the minimum.
- Keeping coverage of the wrong fault list. Compaction keeps the faults it is told about. A test set compacted for stuck-at faults can lose detections of bridges, delays or other unmodelled defects that the extra vectors caught by chance. This is one reason for N-detect tests.
- Fill and compression. A fill that is good for compaction (random values catch more faults by chance) is bad for test power and for compression, which want long runs of equal values.
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
# Part of https://algorithm.tamnd.com/static-test-compaction/. The authors are listed in prov/DV4CEE.jsonl.
"""Static test compaction of a finished test set.
static_compact merges compatible test cubes, fills the remaining X positions,
and then drops vectors by reverse-order fault simulation. greedy_cover is the
set covering alternative on the detection matrix, and minimum_test_set is the
exact minimum by enumeration, for small inputs only. set_cover_circuit builds
the circuit of the NP-hardness reduction from set cover.
A cube is a tuple over {0, 1, X}. A test cube of a fault is a cube whose every
completion detects the fault.
"""
from __future__ import annotations
from itertools import combinations
from typing import Optional, Sequence
from td2net import X, Circuit, Fault, completions
def compatible(u: Sequence[int], t: Sequence[int]) -> bool:
"""True if no position has 0 in one cube and 1 in the other."""
return all(a == X or b == X or a == b for a, b in zip(u, t))
def intersect(u: Sequence[int], t: Sequence[int]) -> tuple[int, ...]:
"""The cube of the vectors in both cubes (the cubes must be compatible)."""
return tuple(b if a == X else a for a, b in zip(u, t))
def merge_cubes(cubes: Sequence[Sequence[int]]) -> list[tuple[int, ...]]:
"""First-fit merging: each cube joins the first compatible merged cube."""
merged: list[tuple[int, ...]] = [] # @line L1
for t in cubes: # @line L2
for i, u in enumerate(merged):
if compatible(u, t): # @line L3
merged[i] = intersect(u, t)
break
else:
merged.append(tuple(t)) # @line L4
return merged
def fill(cube: Sequence[int], value: int = 0) -> tuple[int, ...]:
"""Replace every X by a fixed value."""
return tuple(value if v == X else v for v in cube)
def reverse_order_fault_simulation(
c: Circuit, vectors: Sequence[Sequence[int]], faults: Sequence[Fault]
) -> list[tuple[int, ...]]:
"""Keep a vector only if, simulated last first, it detects a fault not yet detected.
Returns the kept vectors in their original order.
"""
remaining = set(faults) # @line L6
kept: list[tuple[int, ...]] = []
for v in reversed(vectors): # @line L7
hit = {f for f in remaining if c.detects(v, f)} # @line L8
if hit: # @line L9
kept.append(tuple(v))
remaining -= hit
kept.reverse()
return kept # @line L10
def static_compact(c: Circuit, cubes: Sequence[Sequence[int]], faults: Sequence[Fault], value: int = 0) -> list[tuple[int, ...]]:
"""Merge compatible cubes, fill the X positions, then reverse-order fault simulation."""
merged = merge_cubes(cubes)
vectors = [fill(u, value) for u in merged] # @line L5
return reverse_order_fault_simulation(c, vectors, faults)
def detection_masks(c: Circuit, vectors: Sequence[Sequence[int]], faults: Sequence[Fault]) -> list[int]:
"""One bit mask per vector: bit i is set when the vector detects faults[i]."""
masks = []
for v in vectors:
m = 0
for i, f in enumerate(faults):
if c.detects(v, f):
m |= 1 << i
masks.append(m)
return masks
def greedy_cover(c: Circuit, vectors: Sequence[Sequence[int]], faults: Sequence[Fault]) -> list[tuple[int, ...]]:
"""Greedy set cover on the detection matrix: take the vector that detects the most new faults."""
masks = detection_masks(c, vectors, faults)
goal = 0
for m in masks:
goal |= m
covered = 0
chosen: list[int] = []
while covered != goal:
best = max(range(len(vectors)), key=lambda i: (bin(masks[i] & ~covered).count("1"), -i))
chosen.append(best)
covered |= masks[best]
return [tuple(vectors[i]) for i in sorted(chosen)]
def minimum_test_set(c: Circuit, vectors: Sequence[Sequence[int]], faults: Sequence[Fault]) -> list[tuple[int, ...]]:
"""Exact by enumeration: a smallest subset of the vectors that detects every fault any of them detects."""
masks = detection_masks(c, vectors, faults)
goal = 0
for m in masks:
goal |= m
useful = [i for i, m in enumerate(masks) if m]
for size in range(len(useful) + 1):
for subset in combinations(useful, size):
got = 0
for i in subset:
got |= masks[i]
if got == goal:
return [tuple(vectors[i]) for i in subset]
raise AssertionError("unreachable")
def relax_to_cube(c: Circuit, fault: Fault, vector: Sequence[int]) -> Optional[tuple[int, ...]]:
"""Brute force: turn positions of a detecting vector into X while every completion still detects."""
if not c.detects(vector, fault):
return None
cube = list(vector)
for i in range(len(cube)):
old = cube[i]
cube[i] = X
if not all(c.detects(w, fault) for w in completions(cube)):
cube[i] = old
return tuple(cube)
def set_cover_circuit(m: int, sets: Sequence[set[int]]) -> tuple[Circuit, list[Fault]]:
"""The reduction from set cover with m >= 2 sets over the elements 0 .. n-1.
Inputs x0 .. x_{m-1}; y_e is the OR of the x_i with e in S_i; a = 1 when at
most one x_i is 1; z_e = y_e AND a. The target faults are y_e stuck-at 0, so
a vector detects y_e/0 exactly when it has one 1, at an x_i with e in S_i.
"""
elements = sorted(set().union(*sets))
inputs = [f"x{i}" for i in range(m)]
gates: list[tuple[str, str, list[str]]] = []
pair_names = []
for i in range(m):
for j in range(i + 1, m):
gates.append((f"n{i}_{j}", "NAND", [f"x{i}", f"x{j}"]))
pair_names.append(f"n{i}_{j}")
gates.append(("a", "AND" if len(pair_names) > 1 else "BUF", pair_names))
for e in elements:
members = [f"x{i}" for i in range(m) if e in sets[i]]
gates.append((f"y{e}", "OR" if len(members) > 1 else "BUF", members))
gates.append((f"z{e}", "AND", [f"y{e}", "a"]))
circuit = Circuit(inputs, gates, [f"z{e}" for e in elements])
return circuit, [(circuit.line(f"y{e}"), 0) for e in elements]
td2net.py 239 lines
# 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)
test_static_test_compaction.py 250 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/static-test-compaction/. The authors are listed in prov/DV4CEE.jsonl.
"""Static test compaction checked against the exhaustive minimum test set.
All circuits are small enough to enumerate every input vector and every subset
of the useful vectors. Seeds are fixed.
"""
from __future__ import annotations
import random
from itertools import combinations, product
import pytest
from td2net import X, Circuit, completions, random_circuit
from static_test_compaction import (
compatible,
detection_masks,
fill,
greedy_cover,
intersect,
merge_cubes,
minimum_test_set,
relax_to_cube,
reverse_order_fault_simulation,
set_cover_circuit,
static_compact,
)
def covers(c, vectors, faults):
return {f for f in faults if any(c.detects(v, f) for v in vectors)}
def is_subsequence(small, big):
it = iter(big)
return all(any(v == w for w in it) for v in small)
def per_fault_cubes(c, rng):
"""One test cube for each detectable fault, in a random order."""
faults = [f for f in c.faults() if c.detectable(f)]
rng.shuffle(faults)
return faults, [relax_to_cube(c, f, rng.choice(c.detecting_vectors(f))) for f in faults]
def dropping_cubes(c, rng):
"""Cubes as an ATPG with fault dropping makes them, after a fill with 0."""
faults = [f for f in c.faults() if c.detectable(f)]
rng.shuffle(faults)
cubes, done = [], set()
for f in faults:
if f in done:
continue
cube = relax_to_cube(c, f, rng.choice(c.detecting_vectors(f)))
cubes.append(cube)
done |= {g for g in faults if c.detects(fill(cube), g)}
return faults, cubes
def harmonic(d):
return sum(1.0 / i for i in range(1, d + 1))
def example_circuit():
return Circuit(
["a", "b", "c", "d"],
[("g", "AND", ["a", "b"]), ("h", "OR", ["c", "d"]), ("z", "NAND", ["g", "h"])],
["z"],
)
def test_cube_operations():
assert compatible((0, X, 1), (X, 1, 1))
assert not compatible((0, X, 1), (1, X, X))
assert intersect((0, X, X), (X, 1, X)) == (0, 1, X)
assert fill((X, 1, X)) == (0, 1, 0)
assert fill((X, 1, X), 1) == (1, 1, 1)
assert merge_cubes([(0, X, X), (1, X, X), (X, 1, X), (1, X, 0)]) == [(0, 1, X), (1, X, 0)]
def test_relax_to_cube_is_a_test_cube():
rng = random.Random(3)
for _ in range(40):
c = random_circuit(rng, rng.randint(2, 4), rng.randint(2, 6))
for f in c.faults():
vs = c.detecting_vectors(f)
if not vs:
assert relax_to_cube(c, f, c.all_vectors()[0]) is None
continue
cube = relax_to_cube(c, f, rng.choice(vs))
assert all(c.detects(w, f) for w in completions(cube))
@pytest.mark.parametrize("seed", range(6))
def test_reverse_order_keeps_coverage(seed):
rng = random.Random(100 + seed)
for _ in range(25):
c = random_circuit(rng, rng.randint(2, 4), rng.randint(2, 7))
faults = c.faults()
vectors = [tuple(rng.randint(0, 1) for _ in c.pi) for _ in range(rng.randint(1, 12))]
kept = reverse_order_fault_simulation(c, vectors, faults)
assert covers(c, kept, faults) == covers(c, vectors, faults)
assert is_subsequence(kept, [tuple(v) for v in vectors])
# a vector is kept exactly when it detects a fault that no later vector detects
needed = sum(
1 for i, v in enumerate(vectors)
if {f for f in faults if c.detects(v, f)} - covers(c, vectors[i + 1:], faults)
)
assert len(kept) == needed
@pytest.mark.parametrize("seed", range(4))
def test_merging_keeps_every_target_fault(seed):
rng = random.Random(200 + seed)
for _ in range(30):
c = random_circuit(rng, rng.randint(3, 4), rng.randint(2, 7))
faults, cubes = dropping_cubes(c, rng)
merged = merge_cubes(cubes)
assert len(merged) <= len(cubes)
for t in cubes:
# some merged cube lies inside t, so all its completions detect t's fault
inside = [u for u in merged if all(a == X or a == b for a, b in zip(t, u))]
assert inside
targets = {f for f in faults if any(all(c.detects(w, f) for w in completions(u)) for u in cubes)}
vectors = [fill(u) for u in merged]
assert targets <= covers(c, vectors, faults)
kept = static_compact(c, cubes, faults)
assert targets <= covers(c, kept, faults)
def test_one_cube_per_fault_keeps_all_faults_and_beats_the_minimum_bound():
rng = random.Random(7)
total = [0, 0, 0]
for _ in range(60):
c = random_circuit(rng, rng.randint(3, 4), rng.randint(3, 7))
faults, cubes = per_fault_cubes(c, rng)
kept = static_compact(c, cubes, faults)
best = minimum_test_set(c, c.all_vectors(), faults)
assert covers(c, kept, faults) == set(faults)
assert covers(c, best, faults) == set(faults)
assert len(kept) >= len(best)
total[0] += len(cubes)
total[1] += len(kept)
total[2] += len(best)
assert total[2] <= total[1] < total[0]
def test_minimum_test_set_is_minimum():
rng = random.Random(11)
for _ in range(40):
c = random_circuit(rng, rng.randint(2, 3), rng.randint(2, 5))
faults = [f for f in c.faults() if c.detectable(f)]
vectors = c.all_vectors()
best = minimum_test_set(c, vectors, faults)
assert covers(c, best, faults) == set(faults)
for subset in combinations(vectors, len(best) - 1):
assert covers(c, subset, faults) != set(faults)
def test_greedy_cover_bound():
rng = random.Random(13)
for _ in range(60):
c = random_circuit(rng, rng.randint(3, 4), rng.randint(3, 7))
faults = [f for f in c.faults() if c.detectable(f)]
vectors = c.all_vectors()
greedy = greedy_cover(c, vectors, faults)
best = minimum_test_set(c, vectors, faults)
assert covers(c, greedy, faults) == set(faults)
d = max(bin(m).count("1") for m in detection_masks(c, vectors, faults))
assert len(best) <= len(greedy) <= harmonic(d) * len(best) + 1e-9
def brute_force_set_cover(m, sets):
universe = set().union(*sets)
for size in range(m + 1):
for pick in combinations(range(m), size):
if set().union(*(sets[i] for i in pick)) == universe:
return size
raise AssertionError("unreachable")
def test_set_cover_reduction():
rng = random.Random(17)
for _ in range(60):
m = rng.randint(2, 5)
n = rng.randint(1, 5)
sets = [set(e for e in range(n) if rng.random() < 0.4) for _ in range(m)]
for e in range(n):
if not any(e in s for s in sets):
sets[rng.randrange(m)].add(e)
if not set().union(*sets):
continue
c, faults = set_cover_circuit(m, sets)
elements = sorted(set().union(*sets))
# a vector detects y_e/0 exactly when it has one 1, at some x_i with e in S_i
for v in product((0, 1), repeat=m):
ones = [i for i in range(m) if v[i]]
for e, f in zip(elements, faults):
assert c.detects(v, f) == (len(ones) == 1 and e in sets[ones[0]])
best = minimum_test_set(c, c.all_vectors(), faults)
assert len(best) == brute_force_set_cover(m, sets)
def test_example_circuit():
c = example_circuit()
faults = c.faults()
assert len(faults) == 14
assert all(c.detectable(f) for f in faults)
best = minimum_test_set(c, c.all_vectors(), faults)
assert len(best) == 5
for subset in combinations(c.all_vectors(), 4):
assert covers(c, subset, faults) != set(faults)
named = {c.fault_name(f): f for f in faults}
assert c.detecting_vectors(named["c/0"]) == [(1, 1, 1, 0)]
assert c.detecting_vectors(named["d/0"]) == [(1, 1, 0, 1)]
for name in ("c/1", "d/1", "h/1"):
assert c.detecting_vectors(named[name]) == [(1, 1, 0, 0)]
assert sorted(best) == [(0, 1, 0, 1), (1, 0, 0, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0)]
def test_worked_example_of_the_page():
c = example_circuit()
faults = c.faults()
cubes = [(X, X, 0, 0), (1, 1, X, 1), (0, 1, X, 1), (1, 0, X, 1), (1, 1, 1, 0), (1, 1, 0, 0), (1, 1, 0, 1), (X, 0, X, 1)]
named = {c.fault_name(f): f for f in faults}
for cube, name in zip(cubes, ("z/0", "a/0", "a/1", "b/1", "c/0", "c/1", "d/0", "g/1")):
assert all(c.detects(w, named[name]) for w in completions(cube))
assert merge_cubes(cubes) == [(1, 1, 0, 0), (1, 1, 0, 1), (0, 1, X, 1), (1, 0, X, 1), (1, 1, 1, 0)]
kept = static_compact(c, cubes, faults)
assert kept == [(1, 1, 0, 0), (1, 1, 0, 1), (0, 1, 0, 1), (1, 0, 0, 1), (1, 1, 1, 0)]
only = reverse_order_fault_simulation(c, [fill(u) for u in cubes], faults)
assert only == [(0, 1, 0, 1), (1, 0, 0, 1), (1, 1, 1, 0), (1, 1, 0, 0), (1, 1, 0, 1), (0, 0, 0, 1)]
# five faults with pairwise disjoint test sets give the lower bound 5
independent = [set(c.detecting_vectors(named[n])) for n in ("a/1", "b/1", "c/0", "d/0", "h/1")]
for p, q in combinations(independent, 2):
assert not p & q
def test_merging_can_lose_a_chance_detection():
c = Circuit(["a", "b", "c"], [("g", "NOT", ["a"]), ("h", "NAND", ["b", "g"])], ["h", "c"])
faults = c.faults()
cubes = [(1, 1, X), (0, 1, X), (X, X, 1)]
b1 = (c.line("b"), 1)
assert c.detecting_vectors(b1) == [(0, 0, 0), (0, 0, 1)]
assert b1 in covers(c, [fill(u) for u in cubes], faults)
assert merge_cubes(cubes) == [(1, 1, 1), (0, 1, X)]
kept = static_compact(c, cubes, faults)
assert b1 not in covers(c, kept, faults)
Exercises
- In the example, the reverse-order pass on the 8 filled cubes keeps 6 vectors. Find an order of the same 8 vectors for which the pass keeps 5.
- Prove that the minimum number of merged cubes from a list of cubes equals the chromatic number of the graph whose vertices are the cubes and whose edges join incompatible cubes.
- Change the reduction so that the fault list is all single stuck-at faults of the circuit. Which faults must you remove or make easy so that the minimum test set still equals the minimum set cover?
References
- B. Krishnamurthy and S. B. Akers, On the complexity of estimating the size of a test set, IEEE Transactions on Computers C-33(8), 750 to 753, 1984, the proof that finding the size of a minimum test set of a combinational circuit is NP-hard
- Richard M. Karp, Reducibility among combinatorial problems, in Complexity of Computer Computations, Plenum, 85 to 103, 1972, set covering in the list of NP-complete problems
- P. Goel and B. C. Rosales, Test generation and dynamic compaction of tests, Digest of Papers, IEEE Test Conference, 189 to 192, 1979, test cubes with unspecified inputs and their compaction during generation, the counterpart of the compaction after generation on this page
- I. Hamzaoglu and J. H. Patel, Test set compaction algorithms for combinational circuits, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design, 1998, Redundant Vector Elimination, Essential Fault Reduction, and the estimate of the minimum test set size
- Michael L. Bushnell and Vishwani D. Agrawal, Essentials of Electronic Testing for Digital, Memory and Mixed-Signal VLSI Circuits, Kluwer, 2000, the chapter on combinational test generation (test compaction, static and dynamic)
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 DV4CEE Edit this page History Report an error Markdown