Techniqueadvanced
Recursive learning
Also called Kunz-Pradhan recursive learning.
Kunz and Pradhan's method that tries each way to justify an unjustified gate up to a depth and keeps the implications common to all, used in ATPG and verification.
Recursive learning is a method by Kunz and Pradhan (1992, journal version 1994) that finds the values a set of signal assignments forces on the other lines of a circuit. Simple rules, one gate at a time, miss many of these values. Recursive learning looks at each gate whose output value is not yet explained by its inputs, tries every way to explain it, makes all implications of each way, and keeps the values on which all the ways agree. Inside each way it does the same again, up to a depth . Depth 0 gives the plain one-gate implications. With enough depth the method finds every conflict, and so, with one extra check per line, every value that the assignments force. Test generators such as FAN use it to find conflicts before they search and to prove faults redundant, and equivalence checkers use it to find related signals in two circuits.
In plain words
Say an AND gate must output 0. Then one of its inputs is 0, but you do not know which. A simple implication engine stops here. Recursive learning does not. It tries "the first input is 0" and works out what follows, then "the second input is 0" and works out what follows. Whatever follows in every case is true for sure, so it learns it.
While it works out one case, it meets new gates of the same kind, and it can split them again. Each extra level of splitting finds more facts and costs more time. At full depth it is a complete search, but in practice a small depth already finds most of the useful facts.
When it applies
- The circuit is combinational, or the combinational part of a scan design, with lines (stems and fanout branches) as on the PODEM page.
- A situation is given: some lines have values 0 or 1, for example the values that a test generator has set so far. The task is to find more values that every input vector agreeing with the situation also has, or to see that no such vector exists.
- Plain implications are too weak. This happens at reconvergent fanout, where the effect of one value reaches a gate along two paths.
- The cost of case splits is acceptable. It grows exponentially with the depth, so a depth limit is part of the method.
The template
A consistent extension of a situation is an input vector whose simulation gives every line of its value in . A value is necessary for when every consistent extension gives line the value . A direct implication uses one gate: forward, known inputs fix the output, and backward, for example, an AND output 1 sets all inputs to 1, an AND output 0 with all inputs but one at 1 sets the last input to 0, and a branch and its stem take the same value. A gate is unjustified when its output has a value and three-valued evaluation of its inputs still gives X, for example an AND at 0 with two inputs at X. A justification of such a gate is one assignment that would explain it: for an AND at 0, one X input set to 0. The set of all of them is complete: every consistent extension satisfies at least one, since an AND at 0 has some input at 0. For XOR, the two values of one X input form a complete set.
MAKE-ALL-IMPLICATIONS(S, r, r_max)- 1
S ← S with all direct implications; if a line gets both values then return CONFLICT - 2
if r = r_max then return S - 3
repeat - 4
for each unjustified gate g of S - 5
for each justification J of g - 6
S_J ← MAKE-ALL-IMPLICATIONS(S ∪ J, r + 1, r_max) - 7
if every S_J is CONFLICT then return CONFLICT - 8
C ← the values on which all S_J that are not CONFLICT agree - 9
S ← S ∪ C with all direct implications; if a line gets both values then return CONFLICT - 10
until a whole pass adds no value - 11
return S
The holes are the logic values (two-valued here; test generators use the five values of the D-algorithm), the set of justifications of each gate type, and the depth . The call MAKE-ALL-IMPLICATIONS is the recursive learning of to depth .
Soundness. Every value returned at any depth is necessary, and CONFLICT means that has no consistent extension. The proof is by induction on . Each direct implication follows from the function of one gate, so a consistent extension of also satisfies all of them, and a conflict at line L1 or L9 leaves no consistent extension. At line L6, take any consistent extension of . The justifications of are complete, so satisfies some and is a consistent extension of . By induction, is not CONFLICT and satisfies all of , so satisfies the common values . If every is CONFLICT, no such exists, which is line L7.
Enough depth finds every conflict. Suppose first that after line L1, has no conflict and no unjustified gate. Then has a consistent extension: take the values of on the inputs and anything on the other inputs. In topological order, every line with a value in is a primary input, a branch whose stem has the same value, or a gate whose assigned inputs already force its value. Three-valued simulation is monotone, so the full simulation gives each such line its value in . Now let be the number of lines at X in . If and has no consistent extension, the call returns CONFLICT. By induction on : if line L1 finds no conflict, then by the remark above some gate is unjustified, since otherwise a consistent extension would exist. Each justification of the first one handled sets one more line, so has at most lines at X, has no consistent extension, and gets depth . By induction every is CONFLICT, and line L7 returns CONFLICT. When , every gate has known inputs, and line L1 finds the conflict.
All necessary values. A value is necessary for exactly when has no consistent extension, so with , the number of lines, it is necessary exactly when that call returns CONFLICT. Two calls per line therefore find every necessary assignment, and soundness says that they find nothing else. Kunz and Pradhan state that recursive learning with enough depth gives all necessary assignments. This page proves it in this conflict form. A single call on can miss values that do not come from justifying a gate. With nothing assigned, no gate is unjustified, so the constant line never gets its value 0. With , the gate NAND is 1 in every consistent extension, and a single call does not see it. In a run on 3116 random situations that have a consistent extension, on random circuits with 2 to 4 inputs and 2 to 7 gates and with 1 to 3 assigned lines, drawn by random.Random(5), a single call at full depth missed 563 necessary values, of which 377 hold for every input vector of the circuit. This is a measurement on toy inputs, not a benchmark result, and the tests check the conflict form against enumeration.
Relation to static learning. Static learning stores implications between two single values, found by direct implication from one value and then by contraposition, once before the search. Recursive learning works on the whole current situation, with many values at once, and splits cases inside cases. Both give only necessary values. In the example below, static learning also finds , because directly implies , then , then . The example shows how the depth levels work, not a gap between the two methods.
Example. Take the inputs , and , the gates and (two separate OR gates, so and fan out), , and the output . The situation is . In every consistent extension, or , and either one forces , so and are necessary.
- Depth 0: no direct implication applies, since is an OR at 1 with two inputs at X.
- Depth 1: is unjustified with the justifications and . The first one implies nothing more, since is an OR at 1 with two inputs at X. The second one implies and . The two cases agree on no new line, so nothing is learned.
- Depth 2: inside the case , the gate is unjustified. Its cases and both imply , which is learned in this case. Inside the case , the gate is unjustified, and its cases and both imply . Now both cases of have and , so recursive learning at depth 2 learns them.
So depth 1 misses the two necessary values, and depth 2 finds them. Adding to the situation also gives at depth 2.
Cost. One call at depth 0 takes time polynomial in the size of the circuit. A call at depth can make up to calls at depth for each unjustified gate, where is the largest number of justifications of a gate, so the work grows like for gates in the worst case. This is expected: deciding whether a situation has a consistent extension is circuit satisfiability, which is NP-complete, so a complete method must take exponential time in the worst case unless P = NP.
Classic examples
- Test generation. A FAN-based ATPG calls recursive learning on the current situation to find necessary values, often at depth 1 or 2. Kunz and Pradhan showed that it can replace the search of the decision tree for many hard faults, including the proof that a fault is redundant.
- Equivalence checking. To check two circuits, recursive learning finds pairs of internal signals that are equal or complementary, which cuts the problem into small parts.
- Logic optimization. Necessary values found by learning show where a wire or gate can be removed or replaced.
- SAT solving. Splitting on a clause, deriving the consequences of each case, and keeping the common ones is the same idea as the dilemma rule of Stålmarck's method. CDCL solvers instead learn clauses from conflicts during search.
Variations
- Depth limit. Tools use a fixed small depth, or raise the depth only for the faults that a fixed small depth does not solve.
- Learning only near the fault. In test generation, only the unjustified gates in the part of the circuit that matters for the current fault are handled.
- Stored learning. The values learned for one situation can be stored as implications, as in static learning, and used again.
- Other logic values. The method works with the five values 0, 1, D, D' and X, or with the values of sequential test generation, as long as each gate type has a complete set of justifications.
- Implication graphs. The learned implications between pairs of values can be added as edges of an implication graph, where unit propagation uses them.
Pitfalls
- An incomplete set of justifications. If one way to explain a gate is left out, the common values can be wrong. For an AND at 0, every X input must have its own case.
- Forgetting to recompute. A value learned from one gate can justify another gate or make a new gate unjustified. Line L10 repeats the pass until nothing changes.
- Reading a depth limit as a proof. At limited depth, the absence of a conflict says nothing. Only CONFLICT and the learned values are facts.
- Cost of depth. Each level multiplies the work. A depth that is fine for one fault can be far too slow for another, so tools use limits.
- Constants and forward facts. A single call learns from unjustified gates. Values forced by the circuit structure alone, such as a constant line, need the conflict test or a separate pass.
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/recursive-learning/. The authors are listed in prov/HZB5S0.jsonl.
"""Recursive learning (Kunz and Pradhan) on a gate-level circuit.
A situation is a partial assignment of 0 and 1 to the lines of a circuit (the
other lines are X). Direct implications follow one gate at a time, forward and
backward. A gate is unjustified when its output has a value that its input
values do not yet force. Recursive learning tries every justification of each
unjustified gate, makes all implications of each case up to a depth r_max, and
keeps the values common to all the cases that do not end in a conflict.
The values are lists indexed by line, with X = 2. The time is exponential in
r_max in the worst case: each level multiplies the work by the number of
justifications of each unjustified gate.
"""
from __future__ import annotations
from typing import Optional, Sequence
from td2net import X, Circuit, controlling, eval_gate, inversion
Values = list[int]
def _set(vals: Values, k: int, v: int, changed: list[int]) -> bool:
if vals[k] == X:
vals[k] = v
changed.append(k)
return True
return vals[k] == v
def direct_implications(c: Circuit, vals: Values) -> Optional[Values]:
"""All direct implications of a situation, or None on a conflict."""
vals = list(vals)
changed = [0]
while changed:
changed = []
for k in range(c.n_lines):
if c.kind[k] == "pi":
continue
ins = c.fanin[k]
op = c.op[k]
e = eval_gate(op, [vals[j] for j in ins])
if e != X and not _set(vals, k, e, changed): # forward
return None
v = vals[k]
if v == X:
continue
if op in ("BUF", "NOT"): # also fanout branches
if not _set(vals, ins[0], v ^ inversion(op), changed):
return None
continue
open_ins = [j for j in ins if vals[j] == X]
cv = controlling(op)
if cv is None: # XOR, XNOR
if len(open_ins) == 1:
parity = v ^ inversion(op)
for j in ins:
if j != open_ins[0]:
parity ^= vals[j]
if not _set(vals, open_ins[0], parity, changed):
return None
continue
core = v ^ inversion(op)
if core == 1 - cv: # every input is non-controlling
for j in open_ins:
if not _set(vals, j, 1 - cv, changed):
return None
elif len(open_ins) == 1 and all(vals[j] == 1 - cv for j in ins if j != open_ins[0]):
if not _set(vals, open_ins[0], cv, changed):
return None
return vals
def unjustified_gates(c: Circuit, vals: Values) -> list[int]:
"""Gates whose output value is not forced by the values of their inputs."""
return [
k
for k in range(c.n_lines)
if c.kind[k] == "gate" and vals[k] != X and eval_gate(c.op[k], [vals[j] for j in c.fanin[k]]) == X
]
def justifications(c: Circuit, vals: Values, g: int) -> list[tuple[int, int]]:
"""A complete set of justifications: every consistent extension satisfies one."""
op = c.op[g]
open_ins = [j for j in c.fanin[g] if vals[j] == X]
cv = controlling(op)
if cv is None:
return [(open_ins[0], 0), (open_ins[0], 1)]
return [(j, cv) for j in open_ins]
def make_all_implications(c: Circuit, vals: Values, r: int, r_max: int) -> Optional[Values]:
"""Kunz and Pradhan's make_all_implications(r, r_max). None means a conflict."""
s = direct_implications(c, vals) # @line L1
if s is None:
return None
if r >= r_max: # @line L2
return s
progress = True
while progress: # @line L3
progress = False
for g in unjustified_gates(c, s): # @line L4
if not (s[g] != X and eval_gate(c.op[g], [s[j] for j in c.fanin[g]]) == X):
continue # justified by a value learned in this pass
common: Optional[Values] = None
for j, v in justifications(c, s, g): # @line L5
t = list(s)
t[j] = v
sj = make_all_implications(c, t, r + 1, r_max) # @line L6
if sj is None:
continue
if common is None:
common = sj
else: # @line L8
common = [a if a == b else X for a, b in zip(common, sj)]
if common is None: # @line L7
return None
learned = [k for k in range(c.n_lines) if s[k] == X and common[k] != X]
if learned:
t = list(s)
for k in learned:
t[k] = common[k]
s = direct_implications(c, t) # @line L9
if s is None:
return None
progress = True # @line L10
return s # @line L11
def from_assignment(c: Circuit, assignment: dict[int, int]) -> Values:
vals = [X] * c.n_lines
for k, v in assignment.items():
vals[k] = v
return vals
def learn(c: Circuit, assignment: dict[int, int], r_max: int) -> Optional[dict[int, int]]:
"""The values that recursive learning to depth r_max finds for a situation, or None."""
s = make_all_implications(c, from_assignment(c, assignment), 0, r_max)
if s is None:
return None
return {k: s[k] for k in range(c.n_lines) if s[k] != X}
def necessary_assignments(c: Circuit, assignment: dict[int, int], r_max: Optional[int] = None) -> Optional[dict[int, int]]:
"""Every necessary assignment, by one conflict test per line and value.
(k, v) is necessary when the situation with k set to the other value has a
conflict. With r_max at least the number of lines, the test is exact.
"""
if r_max is None:
r_max = c.n_lines
base = make_all_implications(c, from_assignment(c, assignment), 0, r_max)
if base is None:
return None
out = {}
for k in range(c.n_lines):
if base[k] != X:
out[k] = base[k]
continue
for v in (0, 1):
trial = dict(assignment)
trial[k] = 1 - v
if make_all_implications(c, from_assignment(c, trial), 0, r_max) is None:
out[k] = v
return out
def consistent_vectors(c: Circuit, assignment: dict[int, int]) -> list[Sequence[int]]:
"""Brute force: the input vectors whose simulation agrees with the situation."""
out = []
for vec in c.all_vectors():
vals = c.simulate(vec)
if all(vals[k] == v for k, v in assignment.items()):
out.append(vec)
return out
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_recursive_learning.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/recursive-learning/. The authors are listed in prov/HZB5S0.jsonl.
"""Recursive learning against the necessary assignments found by enumeration."""
from __future__ import annotations
import random
import pytest
from recursive_learning import consistent_vectors, direct_implications, from_assignment, learn, necessary_assignments
from td2net import Circuit, random_circuit
def necessary_by_enumeration(c: Circuit, assignment):
"""The values shared by every input vector that agrees with the situation, or None."""
vecs = consistent_vectors(c, assignment)
if not vecs:
return None
sims = [c.simulate(v) for v in vecs]
return {k: sims[0][k] for k in range(c.n_lines) if all(s[k] == sims[0][k] for s in sims)}
def two_ors() -> Circuit:
"""p and q are both b + c, r = a p and z = q + r."""
return Circuit(
["a", "b", "c"],
[("p", "OR", ["b", "c"]), ("q", "OR", ["b", "c"]), ("r", "AND", ["a", "p"]), ("z", "OR", ["q", "r"])],
["z"],
)
def named(c, values):
return {c.name[k]: v for k, v in values.items() if c.kind[k] != "branch"}
def test_depth_one_misses_depth_two_finds():
c = two_ors()
s = {c.line("z"): 1}
assert named(c, learn(c, s, 0)) == {"z": 1}
assert named(c, learn(c, s, 1)) == {"z": 1}
assert named(c, learn(c, s, 2)) == {"z": 1, "p": 1, "q": 1}
assert named(c, necessary_by_enumeration(c, s)) == {"z": 1, "p": 1, "q": 1}
def test_depth_two_with_a():
c = two_ors()
s = {c.line("z"): 1, c.line("a"): 1}
assert named(c, learn(c, s, 1)) == {"a": 1, "z": 1}
assert named(c, learn(c, s, 2)) == {"a": 1, "z": 1, "p": 1, "q": 1, "r": 1}
def test_direct_implications_example():
c = Circuit(["a", "b"], [("g", "AND", ["a", "b"]), ("h", "NOT", ["g"])], ["h"])
vals = direct_implications(c, from_assignment(c, {c.line("h"): 0}))
assert vals[c.line("a")] == 1 and vals[c.line("b")] == 1
assert direct_implications(c, from_assignment(c, {c.line("h"): 0, c.line("a"): 0})) is None
def test_single_call_misses_a_constant_line():
"""With nothing assigned, no gate is unjustified, so nothing is learned."""
c = Circuit(["b"], [("nb", "NOT", ["b"]), ("y", "AND", ["b", "nb"])], ["y"])
assert learn(c, {}, 5) == {}
assert necessary_assignments(c, {})[c.line("y")] == 0
assert necessary_by_enumeration(c, {})[c.line("y")] == 0
def random_situation(rng, c, size):
return {rng.randrange(c.n_lines): rng.randint(0, 1) for _ in range(size)}
@pytest.mark.parametrize("seed", range(150))
def test_sound_at_every_depth(seed):
rng = random.Random(seed)
c = random_circuit(rng, rng.randint(2, 4), rng.randint(2, 6), ops=("AND", "OR", "NAND", "NOR", "NOT", "XOR"))
s = random_situation(rng, c, rng.randint(1, 3))
truth = necessary_by_enumeration(c, s)
for depth in range(4):
got = learn(c, s, depth)
if got is None:
assert truth is None
elif truth is not None:
assert all(truth.get(k) == v for k, v in got.items())
@pytest.mark.parametrize("seed", range(150))
def test_enough_depth_finds_conflicts_and_all_necessary_assignments(seed):
rng = random.Random(10_000 + seed)
c = random_circuit(rng, rng.randint(2, 4), rng.randint(2, 6), ops=("AND", "OR", "NAND", "NOR", "NOT", "XOR"))
s = random_situation(rng, c, rng.randint(1, 3))
truth = necessary_by_enumeration(c, s)
assert (learn(c, s, c.n_lines) is None) == (truth is None)
assert necessary_assignments(c, s) == truth
Exercises
- In the example, take the situation . Which values do depth 0 and depth 1 give? (Depth 0 gives and , and depth 1 adds .)
- In the example, how many calls does depth 2 make? How many does depth 3 make?
- Give a complete set of justifications for a three-input XOR gate with output 1 and all inputs at X, with fewer than 4 cases.
References
- W. Kunz and D. K. Pradhan, Recursive learning, a new implication technique for efficient solutions to CAD problems (test, verification and optimization), IEEE Transactions on Computer-Aided Design 13(9), 1143 to 1158, 1994, the procedure make_all_implications, unjustified gates and complete sets of justifications, the depth r_max, and the claim that enough depth gives all necessary assignments
- W. Kunz and D. K. Pradhan, Recursive learning, an attractive alternative to the decision tree for test generation in digital circuits, Proc. International Test Conference 1992, 816 to 825, the first form of recursive learning, inside a FAN-based test generator
- M. H. Schulz, E. Trischler and T. M. Sarfert, SOCRATES, a highly efficient automatic test pattern generation system, IEEE Transactions on Computer-Aided Design 7(1), 126 to 137, 1988, static learning, the weaker method that recursive learning extends
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 HZB5S0 Edit this page History Report an error Markdown