Algorithmcore
COP testability measure
Also called controllability-observability program, probabilistic testability.
Brglez's probabilistic measures of the chance that a line is 1 and that it is observed under random patterns, used to predict random pattern testability.
- Time
- O(L + P) worst
- Space
- O(L) extra
- Where
- L = the number of lines; P = the number of gate input pins
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Franc Brglez, 1984
COP is a testability measure for combinational circuits by Brglez (1984). For every line it computes two numbers under random input vectors: the controllability , which is the probability that the line is 1, and the observability , which is the probability that a change of the line reaches a primary output. The product of the two numbers estimates the probability that one random vector detects a stuck-at fault on the line. COP takes one forward and one backward pass, each with one rule per gate. It treats all signals as independent. The numbers are exact when the circuit has no fanout, and they can be wrong in either direction when a signal fans out and the branches meet again. Test engineers use COP to find the faults that random patterns will rarely detect, and to place test points for built-in self-test.
In plain words
Feed a circuit random inputs, each a fair coin. Some faults are found almost at once. Others need millions of vectors, because they need one rare input pattern to show up and another rare pattern to reach an output. COP estimates both chances for every wire.
It walks forward from the inputs and gives each wire the chance that it is 1. Then it walks back from the outputs and gives each wire the chance that a change on it gets through. Multiply the two and you get the chance that one random vector finds the fault. A small chance flags a hard fault. The method is fast because it never looks at more than one gate at a time, and that is also why it can be wrong when one signal reaches a gate along two paths.
The problem
The input is a combinational circuit with lines in topological order (the stems of the inputs and gates and the fanout branches, as on the PODEM page) and a probability for each primary input, usually . The inputs are independent. For each line with good value , the target values are
- , the exact controllability;
- , where is the event that forcing to changes some primary output. This is the probability that the Boolean difference of the outputs with respect to is 1;
- the detection probability of stuck at , the probability that a random vector detects it.
All three are #P-hard to compute exactly on general circuits (see signal probability propagation). COP gives estimates , and in linear time.
The algorithm
COP(C, p)- 1
for each line k in topological order - 2
if k is a primary input then C[k] ← p_k - 3
else if k is a fanout branch of the stem t then C[k] ← C[t] - 4
else if k is AND or NAND then c ← ∏ C[j] over the inputs j of k - 5
else if k is OR or NOR then c ← 1 − ∏ (1 − C[j]) - 6
else if k is XOR or XNOR then c ← 0, and for each input j, c ← c (1 − C[j]) + (1 − c) C[j]; for NOT and BUF, c ← C[j] - 7
C[k] ← 1 − c if k inverts, else c - 8
for each line k in reverse topological order - 9
if k is a primary output then O[k] ← 1 - 10
else if k is a stem with branches b_1, …, b_m then O[k] ← 1 − ∏ (1 − O[b_i]) - 11
else if k feeds one gate g then O[k] ← O[g] times - 12
∏ S_g(j) over the other inputs j of g - 13
d(k/0) ← C[k] O[k]; d(k/1) ← (1 − C[k]) O[k]
is the probability that the side input is non-controlling, so that a change of passes the gate: for AND and NAND, for OR and NOR, and 1 for XOR, XNOR, NOT and BUF. A line with no fanout that is not an output keeps . Line L10 combines the branches as if they reached the outputs independently.
Example
A tree. Take , and , with every . No net fans out.
| line | ||||
|---|---|---|---|---|
| , | 1/2 | 3/16 | 3/16 | |
| , | 1/2 | 1/16 | 1/16 | |
| 1/4 | 3/16 | 9/16 | ||
| 3/4 | 3/16 | 1/16 | ||
| 1 | 13/16 | 3/16 |
The observability of is , since must be 1 for a change of to pass the AND. The observability of is , since must be 0 to let it pass the OR. Every number in the table equals the value found by enumerating the 16 vectors. If one random vector detects a fault with probability , then vectors all miss it with probability . To detect stuck at 0 with probability 0.95, the circuit needs , which is 47 vectors. For stuck at 0 it needs 15.
Reconvergence. Take , and , so fans out and its branches meet at .
| quantity | COP | exact |
|---|---|---|
| 1/8 | ||
| 1/4 | ||
| 15/128 | 1/8 | |
| of the branch of into stuck at 1 | 1/16 | 0 |
The function is , but COP multiplies and as if they were independent. The last fault is redundant: with the branch at 1, still. COP still predicts that one vector in 16 finds it. In the consensus circuit , , , , the redundant fault stuck at 0 gets .
Correctness
The full proof shows that COP is exact on fanout-free circuits. In such a circuit, the inputs of one gate read disjoint sets of primary inputs, so their values are independent, and the gate rules of lines L4 to L7 are the exact formulas for independent events. For observability, a change of line with the single fanout gate reaches the output exactly when every side input of is non-controlling and a change of reaches the output. The side inputs depend on disjoint parts of the inputs, and the second event depends only on the inputs outside the tree of , so the probabilities multiply as in lines L11 and L12. A fault is detected when has the opposite value and a change of is observed, two events on disjoint inputs, which gives line L13.
With reconvergent fanout, the proof also shows by example that COP can be wrong. The stem rule of line L10 is neither an upper nor a lower bound: it is too low on the example above, and for , which is always 0, it gives where the exact value is 0.
Proof: COP is exact on fanout-free circuits and can be wrong under reconvergencefull
Let be a combinational circuit whose primary inputs are independent, with . Lines are the stems and fanout branches of the PODEM page. For a line with good value , let be the event that forcing to changes some primary output. So is the probability that the Boolean difference of the outputs with respect to is 1, and a vector detects stuck at exactly when and holds. The page computes at lines L1 to L7, at lines L8 to L12 and the detection estimate at line L13.
The circuit is fanout-free when every net feeds at most one sink (a gate input or a primary output). Then there are no fanout branches, every line other than a primary output has exactly one fanout or none, and following the fanouts from a line leads to one primary output . Let be the set of primary inputs from which is reached.
Lemma 1 (the trees). In a fanout-free circuit, the sets of the inputs of one gate are pairwise disjoint. Every path from an input of to passes through .
Proof. If an input were in and in , there would be two paths from to the gate, and the first line where they split would have two fanouts. For the second claim, a path from follows single fanouts, so it is the unique path out of , and it passes because is reached from .
Lemma 2 (controllability). In a fanout-free circuit, for every line .
Proof. Induction in topological order. A primary input gets at line L2. A gate with inputs has a value that is a function of the values of the , and the value of is a function of the inputs in . These sets are disjoint by Lemma 1, so the input values are independent. For independent events, (line L4), (line L5), and the parity of is 1 with probability if the parity of the first is 1 with probability (line L6). Line L7 takes the complement for an inverting gate. This is the exactness argument of signal probability propagation.
Lemma 3 (observability). In a fanout-free circuit, for every line .
Proof. Induction in reverse topological order. If is a primary output, always holds, and line L9 gives 1. If has no fanout and is not an output, never holds and . Otherwise has one fanout gate (line L11), and . No other output is reached from . By Lemma 1, the output is a function of the value of and of the inputs outside , so is the event and depends on only.
Forcing to its complement changes exactly when every other input of is non-controlling: for AND and NAND that is , for OR and NOR it is , and for XOR, XNOR, NOT and BUF a change of one input always changes the output. If changes, the output changes exactly when holds, because the rest of the circuit sees only through . If does not change, nothing else changes. So is the intersection of and of the events " is non-controlling" for the side inputs of .
The event for depends on only. The sets are disjoint from each other, they lie inside , and depends on inputs outside . So all these events are independent, and . By induction , and by Lemma 2 the factor for is , or 1, which is of line L12.
Theorem 1. In a fanout-free circuit, line L13 gives the exact probability that a random vector detects the fault stuck at .
Proof. The vector detects the fault exactly when and holds. The value depends on only, and by the argument of Lemma 3, depends on the inputs outside only. So the events are independent, and the probability is for and for , by Lemmas 2 and 3.
Theorem 2 (reconvergence). On circuits with reconvergent fanout, COP can be wrong in , in and in the detection estimate. The error can go either way, and COP can give a positive detection estimate to a redundant fault.
Proof. By examples, with every .
- Let , and . Then and , but line L4 gives , because it treats and as independent although both read . Forcing to its complement changes exactly when , so . Each branch of gets , and line L10 gives . The branch of into stuck at 1 makes , so the fault is redundant, but line L13 gives .
- Let , with two branches of into the XOR gate. Then always and . COP gives , each branch gets , and line L10 gives .
So the stem rule of line L10 is neither an upper nor a lower bound.
What is not proved here. Computing the exact signal probability of a general circuit is #P-hard, as the signal probability page shows from Valiant's result. So no polynomial-time rule is exact on all circuits unless P = #P (in the usual sense of counting complexity). How far COP is from the exact values on real circuits, and how well it predicts random-pattern fault coverage, are measured results, not theorems.
Complexity
Each line is visited once in each pass, and each gate input pin is read a constant number of times, so COP takes arithmetic operations and extra space, where is the number of gate input pins. With floating point numbers that is time on a word RAM. The code of this page uses exact fractions so that the tests can compare with enumeration, and then the numbers can grow.
The exact probabilities cost much more. Enumeration takes time for inputs, and the exact signal probability is #P-hard on general circuits. COP gives up exactness for linear time.
Properties
- Exact on fanout-free circuits. This is proved. With fanout, a line whose fanin cone has no line that reaches it along two paths still gets an exact , and the tests check that on random circuits.
- No error bound. Under reconvergence the error has no bound and no sign. It can reach almost 1, and a redundant fault can get a positive estimate.
- Measured error. On 500 random circuits with 4 to 6 inputs and 6 to 10 gates, drawn by
random.Random(2024)with the generator of the tests (27 720 faults), the COP detection estimate differed from the exact value on 18 810 faults, was too high on 11 066 and too low on 7 744, with a mean absolute error of 0.036 and a largest error of 0.93. All 6 166 redundant faults got a positive estimate. This is a measurement on small random circuits, not a property of real designs. - Probabilities, not costs. SCOAP counts how many lines a deterministic test must set. COP gives probabilities, which fit random-pattern test.
- Inputs need not be fair. Any in works, which is what weighted random patterns use.
Variants and improvements
- Exact methods. Parker and McCluskey (1975) keep each probability as a polynomial in the and replace by . The result is exact, but the polynomials can grow to terms. Exact counting with BDDs or model counting is also exact and can also blow up.
- Bounds. The cutting algorithm of Savir, Ditlow and Bardell (1984) cuts fanout branches, gives them the interval , and propagates intervals that are guaranteed to contain the exact values.
- Correlation corrections. Later methods carry pairwise correlations of the signals that meet at a gate, which removes much of the error at a quadratic cost.
- Sampling. Fault simulation of a few thousand random vectors, as in fault coverage estimation, measures the detection probabilities directly with a statistical error. STAFAN by Jain and Agrawal (1985) collects such counts from one good-circuit simulation.
- Test points. Test point insertion uses COP to find lines with low , or and to choose where a control or observation point helps most.
When to use it
Use COP early, to screen a design for faults that resist random patterns before you commit to built-in self-test or weighted random patterns, and inside test point insertion, where it must be recomputed after each candidate point. Its estimates rank lines well enough for these uses on many circuits. When you need the real coverage of a given number of vectors, run a fault simulator instead.
Pitfalls
- Trusting the numbers under reconvergence. COP can call a redundant fault easy and an easy fault hard. Treat it as a ranking heuristic, and confirm the hardest faults by simulation.
- The stem rule. Combining the branches by is a guess. Two branches can cancel each other, as in , or always act together.
- Fanout branches and stems are different faults. A fault on one branch is observed only through that branch. Give the branches their own lines, as the page does.
- Unused lines. A line that reaches no output has . Do not treat such lines as hard to test; their faults are redundant.
- Rounding. With floating point numbers, very small probabilities in deep circuits underflow to 0. Use logarithms or a floor when you rank hard faults.
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
# Part of https://algorithm.tamnd.com/cop-testability-measure/. The authors are listed in prov/ZPFC9R.jsonl.
"""COP (Brglez 1984): probabilistic controllability and observability of every line.
C[k] is the estimated probability that line k is 1 under random input
vectors, and O[k] the estimated probability that a change of k reaches a
primary output. Both treat all signals as independent. The detection
probability of k/0 is then C[k] O[k] and that of k/1 is (1 - C[k]) O[k].
Values are Fractions, so the code computes the COP numbers exactly; on a word
RAM with floating point numbers the cost is O(L + P) operations.
"""
from __future__ import annotations
from fractions import Fraction
from typing import Optional, Sequence
from td2net import Circuit, Fault, controlling, inversion
ONE = Fraction(1)
def controllability(c: Circuit, p: Optional[Sequence[Fraction]] = None) -> list[Fraction]:
"""C[k] for every line, from the input probabilities p (1/2 each by default)."""
if p is None:
p = [Fraction(1, 2)] * len(c.pi)
cc = [Fraction(0)] * c.n_lines
k_in = 0
for k in range(c.n_lines): # @line L1
op, ins = c.op[k], c.fanin[k]
if c.kind[k] == "pi": # @line L2
cc[k] = Fraction(p[k_in])
k_in += 1
continue
if c.kind[k] == "branch": # @line L3
cc[k] = cc[ins[0]]
continue
if op in ("AND", "NAND"): # @line L4
v = ONE
for j in ins:
v *= cc[j]
elif op in ("OR", "NOR"): # @line L5
v = ONE
for j in ins:
v *= ONE - cc[j]
v = ONE - v
elif op in ("XOR", "XNOR"): # @line L6
v = Fraction(0)
for j in ins:
v = v * (ONE - cc[j]) + (ONE - v) * cc[j]
else: # NOT, BUF
v = cc[ins[0]]
cc[k] = ONE - v if inversion(op) else v # @line L7
return cc
def sensitizing(op: str, cj: Fraction) -> Fraction:
"""S_g(j): the probability that side input j of a gate of type op lets a change through."""
cv = controlling(op)
if cv is None:
return ONE
return cj if cv == 0 else ONE - cj
def observability(c: Circuit, cc: Sequence[Fraction]) -> list[Fraction]:
"""O[k] for every line, by one sweep in reverse topological order."""
obs = [Fraction(0)] * c.n_lines
is_po = set(c.po)
for k in range(c.n_lines - 1, -1, -1): # @line L8
outs = c.fanout[k]
if k in is_po: # @line L9
obs[k] = ONE
elif len(outs) > 1: # @line L10: a stem and its branches
miss = ONE
for b in outs:
miss *= ONE - obs[b]
obs[k] = ONE - miss
elif len(outs) == 1: # @line L11
g = outs[0]
v = obs[g]
for j in c.fanin[g]:
if j != k:
v *= sensitizing(c.op[g], cc[j]) # @line L12
obs[k] = v
return obs
def cop(c: Circuit, p: Optional[Sequence[Fraction]] = None) -> tuple[list[Fraction], list[Fraction]]:
"""The COP controllability and observability of every line."""
cc = controllability(c, p)
return cc, observability(c, cc)
def detection_probability(cc: Sequence[Fraction], obs: Sequence[Fraction], fault: Fault) -> Fraction:
"""COP estimate of the probability that a random vector detects the fault."""
k, s = fault
return (cc[k] if s == 0 else ONE - cc[k]) * obs[k] # @line L13
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_cop_testability_measure.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cop-testability-measure/. The authors are listed in prov/ZPFC9R.jsonl.
"""COP against exact enumeration of all input vectors, in Fractions."""
from __future__ import annotations
import random
from fractions import Fraction
import pytest
from cop_testability_measure import controllability, cop, detection_probability, observability
from td2net import Circuit
HALF = Fraction(1, 2)
def exact(c: Circuit, p=None):
"""Exact C, O and detection probabilities by weighted enumeration of all vectors."""
if p is None:
p = [HALF] * len(c.pi)
cc = [Fraction(0)] * c.n_lines
obs = [Fraction(0)] * c.n_lines
det = {f: Fraction(0) for f in c.faults()}
for vec in c.all_vectors():
w = Fraction(1)
for bit, q in zip(vec, p):
w *= q if bit else 1 - q
vals = c.simulate(vec)
for k in range(c.n_lines):
if vals[k] == 1:
cc[k] += w
if c.detects(vec, (k, 1 - vals[k])):
obs[k] += w
det[(k, 1 - vals[k])] += w
return cc, obs, det
def tree_example() -> Circuit:
return Circuit(
["a", "b", "c", "d"],
[("g", "AND", ["a", "b"]), ("h", "OR", ["c", "d"]), ("z", "NAND", ["g", "h"])],
["z"],
)
def reconvergent() -> Circuit:
return Circuit(
["a", "b", "c"],
[("x", "AND", ["a", "b"]), ("y", "AND", ["a", "c"]), ("z", "AND", ["x", "y"])],
["z"],
)
def consensus() -> Circuit:
return 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 random_forest(rng: random.Random, n_inputs: int, n_gates: int) -> Circuit:
"""A fanout-free circuit: every net feeds at most one sink."""
inputs = [f"i{k}" for k in range(n_inputs)]
free = list(inputs)
gates = []
ops = ("AND", "OR", "NAND", "NOR", "XOR", "XNOR", "NOT", "BUF")
for k in range(n_gates):
if len(free) < 2:
break
op = rng.choice(ops)
arity = 1 if op in ("NOT", "BUF") else rng.randint(2, min(3, len(free)))
fanin = rng.sample(free, arity)
for f in fanin:
free.remove(f)
name = f"g{k}"
gates.append((name, op, fanin))
free.append(name)
return Circuit(inputs, gates, free)
def random_probabilities(rng: random.Random, n: int) -> list[Fraction]:
return [Fraction(rng.randint(0, 8), 8) for _ in range(n)]
def test_tree_example_numbers():
c = tree_example()
cc, obs = cop(c)
name = {c.name[k]: k for k in range(c.n_lines)}
assert cc[name["g"]] == Fraction(1, 4)
assert cc[name["h"]] == Fraction(3, 4)
assert cc[name["z"]] == Fraction(13, 16)
assert obs[name["g"]] == Fraction(3, 4)
assert obs[name["h"]] == Fraction(1, 4)
assert obs[name["a"]] == Fraction(3, 8)
assert obs[name["c"]] == Fraction(1, 8)
assert detection_probability(cc, obs, (name["a"], 0)) == Fraction(3, 16)
ec, eo, ed = exact(c)
assert cc == ec and obs == eo
assert all(detection_probability(cc, obs, f) == ed[f] for f in c.faults())
@pytest.mark.parametrize("seed", range(80))
def test_exact_on_fanout_free_circuits(seed):
rng = random.Random(seed)
c = random_forest(rng, rng.randint(1, 6), rng.randint(1, 7))
p = random_probabilities(rng, len(c.pi))
cc, obs = cop(c, p)
ec, eo, ed = exact(c, p)
assert cc == ec
assert obs == eo
for f in c.faults():
assert detection_probability(cc, obs, f) == ed[f]
def test_reconvergence_counterexample():
c = reconvergent()
cc, obs = cop(c)
ec, eo, ed = exact(c)
a, z, ax = c.line("a"), c.line("z"), c.line("a>x")
assert cc[z] == Fraction(1, 16) and ec[z] == Fraction(1, 8)
assert obs[a] == Fraction(15, 64) and eo[a] == Fraction(1, 4)
assert detection_probability(cc, obs, (a, 0)) == Fraction(15, 128)
assert ed[(a, 0)] == Fraction(1, 8)
# a>x stuck at 1 is redundant, yet COP gives it a positive detection probability.
assert ed[(ax, 1)] == 0
assert detection_probability(cc, obs, (ax, 1)) == Fraction(1, 16)
def test_consensus_redundant_fault():
c = consensus()
cc, obs = cop(c)
_, _, ed = exact(c)
r = c.line("r")
assert ed[(r, 0)] == 0
assert detection_probability(cc, obs, (r, 0)) == Fraction(9, 64)
z = c.line("z")
assert cc[z] == Fraction(37, 64)
def test_neither_bound():
"""The stem rule can be too high (here) and too low (the reconvergent example)."""
c = Circuit(["a"], [("z", "XOR", ["a", "a"])], ["z"])
cc, obs = cop(c)
ec, eo, _ = exact(c)
a, z = c.line("a"), c.line("z")
assert cc[z] == HALF and ec[z] == 0
assert obs[a] == 1 and eo[a] == 0
def no_reconvergence_into(c: Circuit, k: int) -> bool:
"""True if no line reaches k along two different paths."""
paths = [0] * c.n_lines
paths[k] = 1
for u in range(k - 1, -1, -1):
paths[u] = sum(paths[w] for w in c.fanout[u])
if paths[u] > 1:
return False
return True
@pytest.mark.parametrize("seed", range(60))
def test_controllability_exact_without_reconvergence(seed):
"""On any circuit, C[k] is exact when no line reaches k by two paths."""
from td2net import random_circuit
rng = random.Random(1000 + seed)
c = random_circuit(rng, rng.randint(2, 5), rng.randint(2, 8))
p = random_probabilities(rng, len(c.pi))
cc = controllability(c, p)
ec, _, _ = exact(c, p)
for k in range(c.n_lines):
assert 0 <= cc[k] <= 1
if no_reconvergence_into(c, k):
assert cc[k] == ec[k]
@pytest.mark.parametrize("seed", range(40))
def test_values_are_probabilities(seed):
from td2net import random_circuit
rng = random.Random(5000 + seed)
c = random_circuit(rng, rng.randint(2, 6), rng.randint(2, 10), ops=("AND", "OR", "NAND", "NOR", "NOT", "XOR"))
cc = controllability(c)
obs = observability(c, cc)
for k in range(c.n_lines):
assert 0 <= cc[k] <= 1 and 0 <= obs[k] <= 1
for o in c.po:
assert obs[o] == 1
def test_errors_appear_on_random_reconvergent_circuits():
"""Reconvergence makes COP differ from the exact values on some circuits."""
from td2net import random_circuit
rng = random.Random(7)
wrong = 0
for _ in range(40):
c = random_circuit(rng, 4, 7)
cc, obs = cop(c)
ec, eo, _ = exact(c)
if cc != ec or obs != eo:
wrong += 1
assert wrong > 0
History
Parker and McCluskey defined signal probabilities in 1975 and showed how reconvergent fanout breaks the gate formulas. In 1984 Franc Brglez added the observability side and the detection estimate in his paper on the testability analysis of combinational networks, and the method became known as COP. The same year, Savir, Ditlow and Bardell studied random pattern testability and gave the cutting algorithm with guaranteed bounds. COP then became a standard input to random-pattern test tools, to weighted random pattern generation and to test point insertion.
References
- F. Brglez, On testability analysis of combinational networks, Proc. ISCAS 1984, vol. 1, 221 to 225, the definitions of the probabilistic controllability and observability, the gate rules and the detection probability
- K. P. Parker and E. J. McCluskey, Probabilistic treatment of general combinational networks, IEEE Transactions on Computers C-24(6), 668 to 670, June 1975, signal probability, the independence assumption and the exact method for reconvergent fanout
- Jacob Savir, Gary S. Ditlow and Paul H. Bardell, Random pattern testability, IEEE Transactions on Computers C-33(1), 79 to 90, 1984, detection probabilities under random patterns and the cutting algorithm that bounds them under reconvergence
- Michael L. Bushnell and Vishwani D. Agrawal, Essentials of Electronic Testing for Digital, Memory and Mixed-Signal VLSI Circuits, Kluwer, 2000, the chapter on testability measures
Where this leads
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 ZPFC9R Edit this page History Report an error Markdown