Algorithmadvanced
SAT-based ATPG
Also called Larrabee ATPG.
Test generation that writes the good circuit and the faulty cone as one CNF formula with a miter on the outputs, so a model of the formula is a test and unsatisfiable means redundant.
- Time
- O(2^n (L + P)) worstO(L + P) best
- Space
- O(L + P) extra
- Where
- L = the number of lines; P = the number of gate input pins; n = the number of primary inputs
- Model
- Word RAM
- Properties
- completedeterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tracy Larrabee, 1992
SAT-based ATPG solves automatic test pattern generation for one single stuck-at fault by a reduction to SAT. It writes the good circuit and a faulty copy of the part that the fault can reach as one formula in conjunctive normal form, with the Tseitin transformation. Extra clauses fix the stuck value at the fault site and ask that some output differs, which is a miter of the two circuits. A model of the formula is a test, and a proof that the formula is unsatisfiable is a proof that the fault is redundant.
In plain words
Write the circuit as a set of small rules, one group per gate: "this wire is the AND of those two wires", in the form that a SAT solver reads. Then write a second copy for the broken circuit. The copy only needs the gates that the broken wire can reach, since all other gates behave the same in both.
Add three more rules: in the copy the broken wire has its stuck value, in the good circuit it has the other value, and at least one output is different in the two circuits.
Give all the rules to a SAT solver. If it finds values that make every rule true, the input values are a test. If it proves that no such values exist, no test exists, and the fault can never be seen.
The problem
The input is a combinational circuit with primary inputs and lines in topological order, a fault , and a flag for the optional active clauses. The lines are the primary inputs, the gate outputs and the fanout branches. Any gate type with a Tseitin encoding is allowed, XOR included. The output is a two-valued input vector that detects the fault, or "untestable".
The variables are , the good value of line , and , the faulty value, for each line of the cone of , that is, and every line reachable from it. Outside the faulty value equals the good value, so it needs no variable of its own.
The algorithm
SAT-ATPG(C, (ℓ, s), active)- 1
for each line k: a variable G_k, and the Tseitin clauses of the good gate of k - 2
K ← ℓ and every line reachable from ℓ - 3
for each k ∈ K: a variable F_k; if k ≠ ℓ, the Tseitin clauses of the gate of k, with F_j for its inputs j ∈ K and G_j for the others - 4
add the units F_ℓ = s and G_ℓ = ¬s - 5
for each primary output o ∈ K: a variable D_o and the clauses of D_o ↔ (G_o xor F_o) - 6
add the clause D_o1 ∨ D_o2 ∨ ... over these outputs (empty if K holds no output) - 7
if active then for each k ∈ K: a variable A_k with A_k → (G_k ≠ F_k), and A_k → ∨ A_w over the fanouts w of k if k is not an output; add the unit A_ℓ - 8
run a SAT solver on the clauses - 9
if the clauses are unsatisfiable then return "untestable" - 10
return the values of G at the primary inputs in the model
The Tseitin clauses of are , and . NAND, NOR and NOT use the clauses of AND, OR and BUF with negated. An XOR of inputs is a chain of two-input XORs with 4 clauses each. The variable of line L7 says "line is on a path of differences to an output". These clauses are implied in the sense that they keep satisfiability, but they let the solver see at once that the effect needs a path.
Example
The circuit is , , , so . The stem has the branches into and into . The fault is stuck at 0.
Line L1 gives the variables 1 to 8 for . The cone is , so line L3 adds and , and line L5 adds .
| line | clauses (DIMACS numbering) | meaning |
|---|---|---|
| L1 | (-3 2) (3 -2) (-4 2) (4 -2) | the branches copy |
| L1 | (6 1) (6 3) (-6 -1 -3) | |
| L1 | (7 4) (7 5) (-7 -4 -5) | |
| L1 | (8 6) (8 7) (-8 -6 -7) | |
| L3 | (10 6) (10 9) (-10 -6 -9) | |
| L4 | (-9) (7) | , |
| L5 | (-11 8 10) (-11 -8 -10) (11 -8 10) (11 8 -10) | |
| L6 | (11) | the output differs |
That is 11 variables and 23 clauses. The active clauses of line L7 add 2 variables and 6 clauses. Unit propagation alone gives , , , then from (10 9), from , and from (8 6). The solver then decides , and with no conflict, so the test is 000. Every vector with , or 010, would also do.
For a redundant fault, take , , , and , with stuck at 0. The formula has 17 variables and 38 clauses, and unit propagation refutes it with no decision. forces , and then . The differing output needs , so . With , forces , so and , a conflict. So the fault is redundant.
Correctness
The Tseitin clauses of a gate have, for each value of its inputs, exactly one satisfying value of its output. So once the input variables and are fixed, the clauses of lines L1 and L3 have exactly one solution, and it is the list of the true line values in the good and the faulty circuit. Lines outside the cone have the same value in both circuits, so outputs outside the cone never differ, and the clause of line L6 asks exactly that some output differs. A model therefore gives a test, and a test, which must put on the good site, gives a model. For the active clauses, set true when a path of differing lines leads from to an output. A test has such a path from , so the extended formula is satisfiable whenever the plain one is. The full proof gives the details.
Proof: The ATPG formula is satisfiable exactly when the fault is detectablefull
Let be a combinational circuit with lines in topological order and primary inputs , and let be the fault "line stuck at ". Let be the cone of : the line and every line reachable from it. For a two-valued input vector , write and for the values of line in the good and the faulty circuit. The formula built by lines L1 to L6 has these parts.
- : for every gate or branch , the Tseitin clauses of , from line L1.
- : for every with , the Tseitin clauses of , where if and otherwise, from line L3.
- The units and , from line L4.
- For every primary output , the clauses of , from line L5, and the clause , from line L6. If no output is in , this clause is empty.
The Tseitin clauses of a gate with output variable have, for each value of the input variables, exactly one satisfying value of , the gate value, and for XOR chains exactly one value of each helper variable (see the Tseitin transformation).
Lemma 1 (the variables are the circuit values). For every vector there is exactly one assignment of the variables of and , with and , that satisfies . In it, for every line, and for every .
Proof. Induction over the lines in topological order, using the Tseitin property. For this gives the good values. For , each input of is in , where by induction, or not in , where no path leads from to , so . So is the faulty gate value . And .
Lemma 2 (outputs outside the cone). For an output and every , .
Proof. The faulty circuit differs from the good one only at , and no path leads from to . Induction over the lines in topological order shows that every line outside has the same value in both circuits.
Theorem 1. is satisfiable if and only if the fault is detectable. For every model, the values of form a test.
Proof. Let detect the fault at output . By Lemma 2, . If , the two circuits agree on every line, so . Take the assignment of Lemma 1 for and set each to . All clauses hold, and is true for the detecting output, so the last clause holds.
Conversely, let be a model, and let . The restriction of to has and , so by Lemma 1 it is the assignment of the circuit values. The last clause makes some true, and then , that is, . So detects the fault.
The unit is implied by the other clauses, since a model has a differing output and that needs a differing site. It is there to give the solver the activation value at once.
Line L7 adds, for every , a variable and the clauses , the clause over the fanouts of when is not a primary output, and the unit . Call the result .
Lemma 3 (paths of differences). If detects the fault at output , then there are lines , each a fanout of the one before, that all differ under .
Proof. A line that differs is not a primary input, and since its gate is the same in both circuits, some input of differs. Walk back from along differing inputs. The walk ends, since the lines are in topological order, and it can end only at .
Theorem 2. is satisfiable if and only if is satisfiable. The input values of a model of form a test.
Proof. contains , so a model of is a model of after the variables are dropped, and Theorem 1 gives the test. Conversely, take a model of and its test . Set true exactly when some path of lines that all differ under leads from to a primary output. Such a path stays in . If is true, then differs, and if is not an output, the second line of its path is a fanout with true. By Lemma 3 applied to the detecting output, is true. So every new clause holds.
Complexity
The formula has variables and clauses of total size , where is the number of gate input pins, and building it takes time. Solving it is exponential in the worst case, since the problem is NP-complete. The solver of the implementation decides the input variables first. Without the active clauses, unit propagation then sets every other variable, because each gate output and each is a function of its inputs. So the search tree has depth at most , at most decisions, and time. The best case is one pass of unit propagation, as for the redundant fault of the example. The extra space is the formula and the trail, .
How fast real CDCL solvers are on these formulas is a measured result, not a theorem. Larrabee reported that the method was robust on the hard faults of benchmark circuits, and later tools use SAT as the engine for the faults that structural methods abort.
Properties
- Complete. The answer "untestable" is a proof of redundancy, and a CDCL solver can output a certificate for it, such as a DRAT proof.
- Any gate type. XOR, multiplexers and complex cells need only their clauses. Structural methods need special rules for gates without a controlling value.
- Two-valued tests. The model gives a value to every input. Inputs that the test does not need can be found afterwards by trying X on each one with three-valued simulation.
- Deterministic. The solver of the implementation has a fixed decision order. Real solvers are deterministic for a fixed seed.
- Off-the-shelf solver. All search work is in the solver, so ATPG gains each improvement in SAT solving without a change.
Variants and improvements
- Incremental SAT. The good circuit is the same for every fault. An incremental solver keeps its clauses and learned clauses, and adds the cone of each new fault under assumptions. This removes most of the cost of building and learning again.
- Structural information. Circuit-based solvers use the gate graph to choose decisions, for example on inputs and fanout stems only, and add implications found by structural analysis, much like the learning of FAN-type tools.
- Other fault models. Transition and path delay faults use two time frames of the circuit, and bridging faults change the faulty copy. The formula changes, and the solver does not.
- Sequential circuits. Unroll the circuit over clock cycles, as in bounded model checking, or use scan design so that the circuit is combinational for test.
- Other engines. A BDD of the Boolean difference of the outputs with respect to , together with the activation condition, gives all tests at once, but its size can be exponential.
When to use it
Use SAT-based ATPG for faults that structural methods such as PODEM abort after a backtrack limit, and to prove that faults are redundant. It is also the simplest correct ATPG to write when a good SAT solver is at hand, and the natural choice for circuits with much XOR logic, such as arithmetic and error correcting circuits. For the many easy faults, random patterns with fault simulation, followed by a structural method, cost less than building a formula for each fault.
Pitfalls
- A faulty copy of the whole circuit. Lines outside the cone are the same in both circuits. Copying them doubles the formula and hides nothing. But the faulty gates in the cone must read for their inputs outside the cone, not a fresh variable, or the copy is not tied to the inputs.
- Clauses for the fault site. The faulty copy of must get the unit and no gate clauses. With its gate clauses, is tied to the good inputs of , which give by the other unit, so the formula is unsatisfiable for every fault.
- No output in the cone. If the fault reaches no output, line L6 adds the empty clause. The formula is unsatisfiable, as it should be. Code that drops an empty clause instead finds false tests.
- Reading the test from the faulty copy. The test is the good input values. At a fault on a primary input, and differ there.
- Equating "satisfiable" with "easy". The formula of a redundant fault can be hard for the solver. A time limit and the label "aborted" are needed in practice, as for structural methods.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the tv3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate-level combinational circuits with single stuck-at faults.
A circuit is built from named primary inputs, gates in topological order and
named primary outputs. Every place where a fault can sit is a *line*:
- one stem line for each primary input and for each gate output;
- when a net feeds two or more sinks (gate input pins or primary outputs), one
branch line for each sink. A net with one sink has no branch line, and the
sink reads the stem.
Lines are numbered 0, 1, ... in topological order, so every line comes after
the lines it reads. A single stuck-at fault is a pair (line, value). Values are
0, 1 and X (unknown), with X = 2. Building a circuit and simulating one vector
take O(L + P) time for L lines and P gate input pins.
This module holds the circuit model, plain simulation of the good circuit and
of one faulty circuit, and brute-force detection over all input vectors. It
holds no test generation or fault simulation algorithm.
"""
from __future__ import annotations
import random
from itertools import product
from typing import Optional, Sequence
X = 2
OPS = ("AND", "OR", "NAND", "NOR", "NOT", "BUF", "XOR", "XNOR")
_CONTROL = {"AND": 0, "NAND": 0, "OR": 1, "NOR": 1}
_INVERT = {"AND": 0, "OR": 0, "NAND": 1, "NOR": 1, "NOT": 1, "BUF": 0, "XOR": 0, "XNOR": 1}
Fault = tuple[int, int]
def controlling(op: str) -> Optional[int]:
"""The controlling input value of a gate type, or None (NOT, BUF, XOR, XNOR)."""
return _CONTROL.get(op)
def inversion(op: str) -> int:
"""1 if the gate type inverts (NAND, NOR, NOT, XNOR), else 0."""
return _INVERT[op]
def eval_gate(op: str, vals: Sequence[int]) -> int:
"""Three-valued output of a gate for input values in {0, 1, X}."""
if op in ("XOR", "XNOR"):
if X in vals:
return X
r = 0
for v in vals:
r ^= v
return r ^ _INVERT[op]
if op in ("NOT", "BUF"):
v = vals[0]
return X if v == X else v ^ _INVERT[op]
c = _CONTROL[op]
if c in vals:
r = c
elif X in vals:
return X
else:
r = 1 - c
return r ^ _INVERT[op]
class Circuit:
"""A combinational circuit as a DAG of lines (see the module comment)."""
def __init__(
self,
inputs: Sequence[str],
gates: Sequence[tuple[str, str, Sequence[str]]],
outputs: Sequence[str],
) -> None:
nets = list(inputs) + [g[0] for g in gates]
if len(set(nets)) != len(nets):
raise ValueError("net names must be unique")
defined = set(inputs)
sinks: dict[str, list[tuple[str, int, int]]] = {n: [] for n in nets}
for gi, (name, op, fanin) in enumerate(gates):
if op not in OPS:
raise ValueError(f"unknown gate type {op}")
if (op in ("NOT", "BUF")) != (len(fanin) == 1) or not fanin:
raise ValueError(f"wrong number of inputs for {name}")
for pin, src in enumerate(fanin):
if src not in defined:
raise ValueError(f"{src} is used before it is defined")
sinks[src].append(("gate", gi, pin))
defined.add(name)
for k, src in enumerate(outputs):
if src not in defined:
raise ValueError(f"unknown output {src}")
sinks[src].append(("po", k, 0))
self.name: list[str] = []
self.kind: list[str] = []
self.op: list[str] = []
self.fanin: list[list[int]] = []
self.index: dict[str, int] = {}
pin_line: dict[tuple[str, int, int], int] = {}
def add(name: str, kind: str, op: str, fanin: list[int]) -> int:
line = len(self.name)
self.name.append(name)
self.kind.append(kind)
self.op.append(op)
self.fanin.append(fanin)
self.index[name] = line
return line
def add_net(net: str, kind: str, op: str, fanin: list[int]) -> None:
stem = add(net, kind, op, fanin)
sk = sinks[net]
if len(sk) < 2:
for s in sk:
pin_line[s] = stem
return
for s in sk:
if s[0] == "po":
label = f"{net}>out{s[1]}" if len(outputs) > 1 else f"{net}>out"
else:
gname = gates[s[1]][0]
same = sum(1 for t in sk if t[0] == "gate" and t[1] == s[1])
label = f"{net}>{gname}" + (f".{s[2]}" if same > 1 else "")
pin_line[s] = add(label, "branch", "BUF", [stem])
self.pi: list[int] = []
for net in inputs:
add_net(net, "pi", "PI", [])
self.pi.append(self.index[net])
for gi, (name, op, fanin) in enumerate(gates):
add_net(name, "gate", op, [pin_line[("gate", gi, p)] for p in range(len(fanin))])
self.po: list[int] = [pin_line[("po", k, 0)] for k in range(len(outputs))]
self.n_lines = len(self.name)
self.fanout: list[list[int]] = [[] for _ in range(self.n_lines)]
for line in range(self.n_lines):
for j in self.fanin[line]:
self.fanout[j].append(line)
self.level = [0] * self.n_lines
for line in range(self.n_lines):
if self.fanin[line]:
self.level[line] = 1 + max(self.level[j] for j in self.fanin[line])
def line(self, name: str) -> int:
return self.index[name]
def faults(self) -> list[Fault]:
"""All 2L single stuck-at faults, in line order."""
return [(line, v) for line in range(self.n_lines) for v in (0, 1)]
def fault_name(self, fault: Fault) -> str:
return f"{self.name[fault[0]]}/{fault[1]}"
def simulate(self, vector: Sequence[int], fault: Optional[Fault] = None) -> list[int]:
"""Values of all lines for one input vector (entries 0, 1 or X), with an optional fault."""
vals = [X] * self.n_lines
k = 0
for line in range(self.n_lines):
if self.kind[line] == "pi":
v = vector[k]
k += 1
else:
v = eval_gate(self.op[line], [vals[j] for j in self.fanin[line]])
if fault is not None and fault[0] == line:
v = fault[1]
vals[line] = v
return vals
def outputs(self, vector: Sequence[int], fault: Optional[Fault] = None) -> tuple[int, ...]:
vals = self.simulate(vector, fault)
return tuple(vals[o] for o in self.po)
def detects(self, vector: Sequence[int], fault: Fault) -> bool:
"""True if some output has a known value in both circuits and the values differ."""
good = self.outputs(vector)
bad = self.outputs(vector, fault)
return any(g != X and b != X and g != b for g, b in zip(good, bad))
def all_vectors(self) -> list[tuple[int, ...]]:
return list(product((0, 1), repeat=len(self.pi)))
def detecting_vectors(self, fault: Fault) -> list[tuple[int, ...]]:
"""Brute force: every two-valued input vector that detects the fault."""
return [v for v in self.all_vectors() if self.detects(v, fault)]
def detectable(self, fault: Fault) -> bool:
return any(self.detects(v, fault) for v in self.all_vectors())
def cone(self, line: int) -> set[int]:
"""The lines reachable from a line, the line included."""
seen = {line}
stack = [line]
while stack:
u = stack.pop()
for w in self.fanout[u]:
if w not in seen:
seen.add(w)
stack.append(w)
return seen
def completions(vector: Sequence[int]) -> list[tuple[int, ...]]:
"""All two-valued vectors that agree with a vector that may hold X."""
choices = [(0, 1) if v == X else (v,) for v in vector]
return list(product(*choices))
def random_circuit(
rng: random.Random,
n_inputs: int,
n_gates: int,
ops: Sequence[str] = ("AND", "OR", "NAND", "NOR", "NOT"),
max_fanin: int = 3,
) -> Circuit:
"""A random circuit. Every net with no sink becomes a primary output."""
inputs = [f"i{k}" for k in range(n_inputs)]
nets = list(inputs)
gates: list[tuple[str, str, list[str]]] = []
for k in range(n_gates):
op = rng.choice(list(ops))
arity = 1 if op in ("NOT", "BUF") else rng.randint(2, max(2, min(max_fanin, len(nets))))
arity = min(arity, len(nets))
if op not in ("NOT", "BUF") and arity < 2:
op, arity = "NOT", 1
fanin = rng.sample(nets, arity)
name = f"g{k}"
gates.append((name, op, fanin))
nets.append(name)
used = {src for _, _, fanin in gates for src in fanin}
outputs = [n for n in nets if n not in used]
extra = [g[0] for g in gates if g[0] in used]
if extra and rng.random() < 0.5:
outputs.append(rng.choice(extra))
return Circuit(inputs, gates, outputs)
sat_based_atpg.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-atpg/. The authors are listed in prov/PFQN6B.jsonl.
"""SAT-based ATPG (Larrabee 1992) for one single stuck-at fault.
The good circuit and the faulty copy of the fault cone are written as one CNF
formula with the Tseitin transformation. Extra clauses say that the fault site
has the stuck value in the faulty copy, the other value in the good circuit,
and that some primary output differs. The formula is satisfiable if and only
if the fault is detectable, and the primary input values of a model are a test.
Optional active clauses (Larrabee) add a variable A_l for each line of the
cone. A_l means that the line is on a path of differences to an output. These
clauses do not change satisfiability but give the solver more implications.
A small DPLL solver with two watched literals and chronological backtracking
is included so that the module needs only the standard library.
"""
from __future__ import annotations
from typing import Optional, Sequence
from gatenet import Circuit, Fault
Clause = list[int]
def gate_clauses(op: str, z: int, ins: Sequence[int], new_var) -> list[Clause]:
"""Tseitin clauses for the literal z = op(ins). new_var() returns a fresh variable."""
if op in ("NAND", "NOR", "NOT", "XNOR"):
op, z = {"NAND": "AND", "NOR": "OR", "NOT": "BUF", "XNOR": "XOR"}[op], -z
if op == "BUF":
a = ins[0]
return [[-z, a], [z, -a]]
if op == "AND":
return [[-z, a] for a in ins] + [[z] + [-a for a in ins]]
if op == "OR":
return [[z, -a] for a in ins] + [[-z] + list(ins)]
if op == "XOR":
out: list[Clause] = []
acc = ins[0]
for k, b in enumerate(ins[1:], start=1):
t = z if k == len(ins) - 1 else new_var()
out += [[-t, acc, b], [-t, -acc, -b], [t, -acc, b], [t, acc, -b]]
acc = t
return out
raise ValueError(f"unknown gate type {op}")
def encode(c: Circuit, fault: Fault, active: bool = False) -> tuple[int, list[Clause], list[int]]:
"""The CNF of the fault. Returns (number of variables, clauses, variables G of the inputs)."""
site, s = fault
n = 0
def new_var() -> int:
nonlocal n
n += 1
return n
clauses: list[Clause] = []
good = [new_var() for _ in range(c.n_lines)] # @line L1
for k in range(c.n_lines):
if c.kind[k] != "pi":
clauses += gate_clauses(c.op[k], good[k], [good[j] for j in c.fanin[k]], new_var)
cone = c.cone(site) # @line L2
bad = good[:]
for k in sorted(cone): # @line L3
bad[k] = new_var()
for k in sorted(cone):
if k != site:
clauses += gate_clauses(c.op[k], bad[k], [bad[j] for j in c.fanin[k]], new_var)
clauses.append([bad[site] if s else -bad[site]]) # @line L4
clauses.append([-good[site] if s else good[site]])
diff = []
for o in c.po: # @line L5
if o in cone:
d = new_var()
g, b = good[o], bad[o]
clauses += [[-d, g, b], [-d, -g, -b], [d, -g, b], [d, g, -b]]
diff.append(d)
clauses.append(diff) # @line L6: an empty clause if no output is in the cone
if active: # @line L7
po = set(c.po)
act = {k: new_var() for k in cone}
clauses.append([act[site]])
for k in cone:
a = act[k]
clauses += [[-a, good[k], bad[k]], [-a, -good[k], -bad[k]]]
if k not in po:
clauses.append([-a] + [act[w] for w in c.fanout[k]])
return n, clauses, [good[p] for p in c.pi]
class Solver:
"""DPLL with two watched literals, unit propagation and chronological backtracking."""
def __init__(self, n_vars: int, clauses: Sequence[Clause], order: Optional[Sequence[int]] = None) -> None:
self.n = n_vars
self.value = [0] * (n_vars + 1) # 0 unassigned, 1 true, -1 false
self.trail: list[int] = []
self.qhead = 0
self.levels: list[int] = [] # trail position of each decision
self.flipped: list[bool] = []
self.watches: dict[int, list[int]] = {}
self.clauses: list[Clause] = []
self.units: list[int] = []
self.empty = False
self.decisions = self.conflicts = 0
for cl in clauses:
cl = list(dict.fromkeys(cl))
if any(-a in cl for a in cl):
continue # always true
if not cl:
self.empty = True
elif len(cl) == 1:
self.units.append(cl[0])
else:
ci = len(self.clauses)
self.clauses.append(cl)
self.watches.setdefault(cl[0], []).append(ci)
self.watches.setdefault(cl[1], []).append(ci)
first = list(order or [])
seen = set(first)
self.order = first + [v for v in range(1, n_vars + 1) if v not in seen]
def val(self, lit: int) -> int:
v = self.value[abs(lit)]
return v if lit > 0 else -v
def assign(self, lit: int) -> None:
self.value[abs(lit)] = 1 if lit > 0 else -1
self.trail.append(lit)
def propagate(self) -> bool:
"""Unit propagation over the watched literals. False on a conflict."""
while self.qhead < len(self.trail):
false_lit = -self.trail[self.qhead]
self.qhead += 1
ws = self.watches.get(false_lit, [])
keep: list[int] = []
conflict = False
for ci in ws:
if conflict:
keep.append(ci)
continue
cl = self.clauses[ci]
if cl[0] == false_lit:
cl[0], cl[1] = cl[1], cl[0]
if self.val(cl[0]) == 1:
keep.append(ci)
continue
for k in range(2, len(cl)):
if self.val(cl[k]) != -1:
cl[1], cl[k] = cl[k], cl[1]
self.watches.setdefault(cl[1], []).append(ci)
break
else:
keep.append(ci)
if self.val(cl[0]) == -1:
conflict = True
else:
self.assign(cl[0])
self.watches[false_lit] = keep
if conflict:
return False
return True
def undo_to(self, pos: int) -> None:
while len(self.trail) > pos:
self.value[abs(self.trail.pop())] = 0
self.qhead = min(self.qhead, pos)
def solve(self) -> Optional[list[int]]:
"""A model as a list of values (index = variable), or None if unsatisfiable."""
if self.empty:
return None
for lit in self.units:
if self.val(lit) == -1:
return None
if self.val(lit) == 0:
self.assign(lit)
ok = self.propagate()
while True:
if ok:
var = next((v for v in self.order if self.value[v] == 0), None)
if var is None:
return [0] + [1 if self.value[v] == 1 else 0 for v in range(1, self.n + 1)]
self.decisions += 1
self.levels.append(len(self.trail))
self.flipped.append(False)
self.assign(-var) # try the value 0 first
else:
self.conflicts += 1
while self.flipped and self.flipped[-1]:
self.undo_to(self.levels.pop())
self.flipped.pop()
if not self.levels:
return None
lit = self.trail[self.levels[-1]]
self.undo_to(self.levels[-1])
self.flipped[-1] = True
self.assign(-lit)
ok = self.propagate()
def sat_based_atpg(
c: Circuit, fault: Fault, active: bool = False, stats: Optional[dict[str, int]] = None
) -> Optional[tuple[int, ...]]:
"""Return a test vector for the fault, or None if the fault is undetectable."""
n, clauses, inputs = encode(c, fault, active)
solver = Solver(n, clauses, order=inputs)
model = solver.solve() # @line L8
if stats is not None:
stats.update(variables=n, clauses=len(clauses), decisions=solver.decisions, conflicts=solver.conflicts)
if model is None: # @line L9
return None
return tuple(model[v] for v in inputs) # @line L10
test_sat_based_atpg.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sat-based-atpg/. The authors are listed in prov/PFQN6B.jsonl.
import random
from itertools import product
import pytest
from gatenet import Circuit, random_circuit
from sat_based_atpg import Solver, encode, sat_based_atpg
# The circuit of the page: z = NAND(NAND(a, b), NAND(b, c)) = ab + bc.
C3 = Circuit(["a", "b", "c"], [("g", "NAND", ["a", "b"]), ("h", "NAND", ["b", "c"]), ("z", "NAND", ["g", "h"])], ["z"])
C17 = Circuit(
["1", "2", "3", "6", "7"],
[
("10", "NAND", ["1", "3"]),
("11", "NAND", ["3", "6"]),
("16", "NAND", ["2", "11"]),
("19", "NAND", ["11", "7"]),
("22", "NAND", ["10", "16"]),
("23", "NAND", ["16", "19"]),
],
["22", "23"],
)
# z = ab + a'c + bc. The term bc is the consensus of the other two, so its AND gate is redundant.
CONSENSUS = Circuit(
["a", "b", "c"],
[
("na", "NOT", ["a"]),
("p", "AND", ["a", "b"]),
("q", "AND", ["na", "c"]),
("r", "AND", ["b", "c"]),
("z", "OR", ["p", "q", "r"]),
],
["z"],
)
def brute_sat(n, clauses):
for bits in product((0, 1), repeat=n):
if all(any((bits[abs(a) - 1] == 1) == (a > 0) for a in cl) for cl in clauses):
return True
return False
def check_against_brute_force(c, fault, active):
t = sat_based_atpg(c, fault, active=active)
if t is None:
assert not c.detectable(fault)
else:
assert c.detects(t, fault)
def test_page_example_h_stuck_at_0():
fault = (C3.line("h"), 0)
stats = {}
t = sat_based_atpg(C3, fault, stats=stats)
assert t in C3.detecting_vectors(fault)
n, clauses, _ = encode(C3, fault)
assert (stats["variables"], stats["clauses"]) == (n, len(clauses)) == (11, 23)
assert t == (0, 0, 0)
assert [-9] in clauses and [7] in clauses and [11] in clauses
n1, clauses1, _ = encode(C3, fault, active=True)
assert (n1, len(clauses1)) == (13, 29)
@pytest.mark.parametrize("seed", range(30))
def test_inputs_first_bounds_the_search(seed):
# Without active clauses, the inputs imply every other variable, so the decisions are on inputs only.
rng = random.Random(100 + seed)
c = random_circuit(rng, rng.randint(2, 7), rng.randint(2, 12), ops=("AND", "OR", "NAND", "NOR", "NOT", "XOR"))
for fault in c.faults():
stats = {}
sat_based_atpg(c, fault, stats=stats)
assert stats["decisions"] <= 2 ** len(c.pi) - 1
@pytest.mark.parametrize("active", [False, True])
def test_c3_and_c17_all_faults(active):
for c in (C3, C17):
for fault in c.faults():
check_against_brute_force(c, fault, active)
for fault in C17.faults():
assert sat_based_atpg(C17, fault, active=active) is not None
@pytest.mark.parametrize("active", [False, True])
def test_redundant_fault_is_unsatisfiable(active):
fault = (CONSENSUS.line("r"), 0)
assert not CONSENSUS.detectable(fault)
assert sat_based_atpg(CONSENSUS, fault, active=active) is None
def test_active_clauses_keep_satisfiability():
rng = random.Random(7)
for _ in range(60):
c = random_circuit(rng, rng.randint(2, 4), rng.randint(2, 6))
for fault in c.faults():
n0, cl0, _ = encode(c, fault)
n1, cl1, _ = encode(c, fault, active=True)
det = c.detectable(fault)
assert (Solver(n0, cl0).solve() is not None) == (Solver(n1, cl1).solve() is not None) == det
if n1 <= 12:
assert brute_sat(n0, cl0) == brute_sat(n1, cl1) == det
@pytest.mark.parametrize("seed", range(40))
def test_solver_against_brute_force(seed):
rng = random.Random(seed)
n = rng.randint(1, 10)
clauses = [[rng.choice((1, -1)) * rng.randint(1, n) for _ in range(rng.randint(1, 3))] for _ in range(rng.randint(1, 5 * n))]
model = Solver(n, clauses).solve()
assert (model is not None) == brute_sat(n, clauses)
if model is not None:
assert all(any((model[abs(a)] == 1) == (a > 0) for a in cl) for cl in clauses)
@pytest.mark.parametrize("seed", range(40))
def test_random_circuits_against_brute_force(seed):
rng = random.Random(seed)
ops = ("AND", "OR", "NAND", "NOR", "NOT", "XOR", "XNOR", "BUF") if seed % 2 else ("AND", "OR", "NAND", "NOR", "NOT")
c = random_circuit(rng, rng.randint(2, 8), rng.randint(2, 10), ops=ops)
for fault in c.faults():
check_against_brute_force(c, fault, active=bool(seed % 3 == 0))
History
Larrabee presented test generation as Boolean satisfiability in a conference paper of 1989, and the journal paper of 1992 gave the full method. It wrote the Boolean difference of the good and the faulty circuit as clauses, added the active clauses that tie the fault effect to a path, and solved the result with a simple SAT search. The idea is the same as the miter used in combinational equivalence checking. With the CDCL solvers of the late 1990s and 2000s, SAT became a standard engine in commercial ATPG, mainly for the hard and the redundant faults.
References
- T. Larrabee, Test pattern generation using Boolean satisfiability, IEEE Transactions on Computer-Aided Design 11(1), 4 to 15, 1992, the formula of the good and the faulty circuit, the Boolean difference at the outputs and the active clauses for the paths of the fault effect
- Michael L. Bushnell and Vishwani D. Agrawal, Essentials of Electronic Testing for Digital, Memory and Mixed-Signal VLSI Circuits, Kluwer, 2000, the chapter Combinational Circuit Test Generation (test generation as Boolean satisfiability)
- O. H. Ibarra and S. K. Sahni, Polynomially complete fault detection problems, IEEE Transactions on Computers C-24(3), 242 to 249, 1975, the NP-completeness of fault detection, which the reduction to SAT matches
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PFQN6B Edit this page History Report an error Markdown