Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 CC, which is the probability that the line is 1, and the observability OO, 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 LL lines in topological order (the stems of the inputs and gates and the fanout branches, as on the PODEM page) and a probability pip_i for each primary input, usually 1/21/2. The inputs are independent. For each line kk with good value vkv_k, the target values are

  • Pr⁡[vk=1]\Pr[v_k = 1], the exact controllability;
  • Pr⁡[Ek]\Pr[E_k], where EkE_k is the event that forcing kk to ¬vk\lnot v_k changes some primary output. This is the probability that the Boolean difference of the outputs with respect to kk is 1;
  • the detection probability of kk stuck at ss, 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 C[k]C[k], O[k]O[k] and d(k/s)d(k/s) in linear time.

The algorithm

  1. COP(C, p)
  2. 1for each line k in topological order
  3. 2if k is a primary input then C[k] ← p_k
  4. 3else if k is a fanout branch of the stem t then C[k] ← C[t]
  5. 4else if k is AND or NAND then c ← ∏ C[j] over the inputs j of k
  6. 5else if k is OR or NOR then c ← 1 − ∏ (1 − C[j])
  7. 6else 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]
  8. 7C[k] ← 1 − c if k inverts, else c
  9. 8for each line k in reverse topological order
  10. 9if k is a primary output then O[k] ← 1
  11. 10else if k is a stem with branches b_1, …, b_m then O[k] ← 1 − ∏ (1 − O[b_i])
  12. 11else if k feeds one gate g then O[k] ← O[g] times
  13. 12∏ S_g(j) over the other inputs j of g
  14. 13d(k/0) ← C[k] O[k]; d(k/1) ← (1 − C[k]) O[k]

Sg(j)S_g(j) is the probability that the side input jj is non-controlling, so that a change of kk passes the gate: C[j]C[j] for AND and NAND, 1−C[j]1 - C[j] for OR and NOR, and 1 for XOR, XNOR, NOT and BUF. A line with no fanout that is not an output keeps O[k]=0O[k] = 0. Line L10 combines the branches as if they reached the outputs independently.

Example

A tree. Take g=abg = ab, h=c+dh = c + d and z=gh‾z = \overline{g h}, with every pi=1/2p_i = 1/2. No net fans out.

line CC OO d(⋅/0)d(\cdot/0) d(⋅/1)d(\cdot/1)
aa, bb 1/2 3/4⋅1/2=3/83/4 \cdot 1/2 = 3/8 3/16 3/16
cc, dd 1/2 1/4⋅1/2=1/81/4 \cdot 1/2 = 1/8 1/16 1/16
gg 1/4 C[h]=3/4C[h] = 3/4 3/16 9/16
hh 3/4 C[g]=1/4C[g] = 1/4 3/16 1/16
zz 1−3/16=13/161 - 3/16 = 13/16 1 13/16 3/16

The observability of aa is O[g]⋅C[b]O[g] \cdot C[b], since bb must be 1 for a change of aa to pass the AND. The observability of cc is O[h]⋅(1−C[d])O[h] \cdot (1 - C[d]), since dd 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 dd, then NN vectors all miss it with probability (1−d)N(1 - d)^N. To detect cc stuck at 0 with probability 0.95, the circuit needs N≥ln⁡20/ln⁡(16/15)N \ge \ln 20 / \ln(16/15), which is 47 vectors. For aa stuck at 0 it needs 15.

Reconvergence. Take x=abx = ab, y=acy = ac and z=xyz = xy, so aa fans out and its branches meet at zz.

quantity COP exact
C[z]C[z] 1/4⋅1/4=1/161/4 \cdot 1/4 = 1/16 1/8
O[a]O[a] 1−(7/8)2=15/641 - (7/8)^2 = 15/64 1/4
d(a/0)d(a/0) 15/128 1/8
dd of the branch of aa into xx stuck at 1 1/16 0

The function is z=abcz = abc, but COP multiplies C[x]C[x] and C[y]C[y] as if they were independent. The last fault is redundant: with the branch at 1, z=b⋅ac=abcz = b \cdot ac = abc still. COP still predicts that one vector in 16 finds it. In the consensus circuit p=abp = ab, q=a‾cq = \overline{a} c, r=bcr = bc, z=p+q+rz = p + q + r, the redundant fault rr stuck at 0 gets 9/649/64.

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 kk with the single fanout gate gg reaches the output exactly when every side input of gg is non-controlling and a change of gg 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 gg, so the probabilities multiply as in lines L11 and L12. A fault is detected when kk has the opposite value and a change of kk 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 z=a⊕az = a \oplus a, which is always 0, it gives O[a]=1O[a] = 1 where the exact value is 0.

Proof: COP is exact on fanout-free circuits and can be wrong under reconvergencefull

Let CC be a combinational circuit whose primary inputs are independent, with Pr⁡[xi=1]=pi\Pr[x_i = 1] = p_i. Lines are the stems and fanout branches of the PODEM page. For a line kk with good value vkv_k, let EkE_k be the event that forcing kk to ¬vk\lnot v_k changes some primary output. So Pr⁡[Ek]\Pr[E_k] is the probability that the Boolean difference of the outputs with respect to kk is 1, and a vector detects kk stuck at ss exactly when vk=¬sv_k = \lnot s and EkE_k holds. The page computes C[k]C[k] at lines L1 to L7, O[k]O[k] 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 kk leads to one primary output root(k)\mathrm{root}(k). Let T(k)T(k) be the set of primary inputs from which kk is reached.

Lemma 1 (the trees). In a fanout-free circuit, the sets T(j)T(j) of the inputs jj of one gate are pairwise disjoint. Every path from an input of T(k)T(k) to root(k)\mathrm{root}(k) passes through kk.

Proof. If an input xx were in T(j1)T(j_1) and in T(j2)T(j_2), there would be two paths from xx to the gate, and the first line where they split would have two fanouts. For the second claim, a path from x∈T(k)x \in T(k) follows single fanouts, so it is the unique path out of xx, and it passes kk because kk is reached from xx. □\square

Lemma 2 (controllability). In a fanout-free circuit, C[k]=Pr⁡[vk=1]C[k] = \Pr[v_k = 1] for every line kk.

Proof. Induction in topological order. A primary input gets pkp_k at line L2. A gate kk with inputs j1,…,jmj_1, \ldots, j_m has a value that is a function of the values of the jij_i, and the value of jij_i is a function of the inputs in T(ji)T(j_i). These sets are disjoint by Lemma 1, so the input values are independent. For independent events, Pr⁡[all ji=1]=∏C[ji]\Pr[\text{all } j_i = 1] = \prod C[j_i] (line L4), Pr⁡[some ji=1]=1−∏(1−C[ji])\Pr[\text{some } j_i = 1] = 1 - \prod (1 - C[j_i]) (line L5), and the parity of j1,…,jij_1, \ldots, j_i is 1 with probability c(1−C[ji])+(1−c)C[ji]c (1 - C[j_i]) + (1 - c) C[j_i] if the parity of the first i−1i - 1 is 1 with probability cc (line L6). Line L7 takes the complement for an inverting gate. This is the exactness argument of signal probability propagation. □\square

Lemma 3 (observability). In a fanout-free circuit, O[k]=Pr⁡[Ek]O[k] = \Pr[E_k] for every line kk.

Proof. Induction in reverse topological order. If kk is a primary output, EkE_k always holds, and line L9 gives 1. If kk has no fanout and is not an output, EkE_k never holds and O[k]=0O[k] = 0. Otherwise kk has one fanout gate gg (line L11), and root(k)=root(g)\mathrm{root}(k) = \mathrm{root}(g). No other output is reached from kk. By Lemma 1, the output root(g)\mathrm{root}(g) is a function F(vg,Y)F(v_g, Y) of the value of gg and of the inputs YY outside T(g)T(g), so EgE_g is the event F(0,Y)≠F(1,Y)F(0, Y) \ne F(1, Y) and depends on YY only.

Forcing kk to its complement changes gg exactly when every other input jj of gg is non-controlling: for AND and NAND that is vj=1v_j = 1, for OR and NOR it is vj=0v_j = 0, and for XOR, XNOR, NOT and BUF a change of one input always changes the output. If gg changes, the output changes exactly when EgE_g holds, because the rest of the circuit sees kk only through gg. If gg does not change, nothing else changes. So EkE_k is the intersection of EgE_g and of the events "jj is non-controlling" for the side inputs jj of gg.

The event for jj depends on T(j)T(j) only. The sets T(j)T(j) are disjoint from each other, they lie inside T(g)T(g), and EgE_g depends on inputs outside T(g)T(g). So all these events are independent, and Pr⁡[Ek]=Pr⁡[Eg]∏jPr⁡[j non-controlling]\Pr[E_k] = \Pr[E_g] \prod_j \Pr[j \text{ non-controlling}]. By induction Pr⁡[Eg]=O[g]\Pr[E_g] = O[g], and by Lemma 2 the factor for jj is C[j]C[j], 1−C[j]1 - C[j] or 1, which is Sg(j)S_g(j) of line L12. □\square

Theorem 1. In a fanout-free circuit, line L13 gives the exact probability that a random vector detects the fault kk stuck at ss.

Proof. The vector detects the fault exactly when vk=¬sv_k = \lnot s and EkE_k holds. The value vkv_k depends on T(k)T(k) only, and by the argument of Lemma 3, EkE_k depends on the inputs outside T(k)T(k) only. So the events are independent, and the probability is Pr⁡[vk=1]Pr⁡[Ek]=C[k]O[k]\Pr[v_k = 1] \Pr[E_k] = C[k] O[k] for s=0s = 0 and (1−C[k])O[k](1 - C[k]) O[k] for s=1s = 1, by Lemmas 2 and 3. □\square

Theorem 2 (reconvergence). On circuits with reconvergent fanout, COP can be wrong in CC, in OO 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 pi=1/2p_i = 1/2.

  1. Let x=abx = ab, y=acy = ac and z=xyz = xy. Then z=abcz = abc and Pr⁡[z=1]=1/8\Pr[z = 1] = 1/8, but line L4 gives C[z]=C[x]C[y]=1/16C[z] = C[x] C[y] = 1/16, because it treats xx and yy as independent although both read aa. Forcing aa to its complement changes zz exactly when b=c=1b = c = 1, so Pr⁡[Ea]=1/4\Pr[E_a] = 1/4. Each branch of aa gets O=1/8O = 1/8, and line L10 gives O[a]=1−(7/8)2=15/64<1/4O[a] = 1 - (7/8)^2 = 15/64 < 1/4. The branch of aa into xx stuck at 1 makes z=b⋅ac=abcz = b \cdot ac = abc, so the fault is redundant, but line L13 gives (1−1/2)⋅1/8=1/16(1 - 1/2) \cdot 1/8 = 1/16.
  2. Let z=a⊕az = a \oplus a, with two branches of aa into the XOR gate. Then z=0z = 0 always and Pr⁡[Ea]=0\Pr[E_a] = 0. COP gives C[z]=1/2C[z] = 1/2, each branch gets O=1O = 1, and line L10 gives O[a]=1>0O[a] = 1 > 0.

So the stem rule of line L10 is neither an upper nor a lower bound. □\square

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 O(L+P)O(L + P) arithmetic operations and O(L)O(L) extra space, where PP is the number of gate input pins. With floating point numbers that is O(L+P)O(L + P) 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 O(2n(L+P))O(2^n (L + P)) time for nn 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 CC, 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 pip_i in [0,1][0, 1] 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 pip_i and replace pikp_i^k by pip_i. The result is exact, but the polynomials can grow to 2n2^n 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 [0,1][0, 1], 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 CC, 1−C1 - C or OO 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 1−∏(1−O[bi])1 - \prod (1 - O[b_i]) is a guess. Two branches can cancel each other, as in a⊕aa \oplus a, 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 O=0O = 0. 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.

cop_testability_measure.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example