Algorithm Search⌘K

Algorithmadvanced

Ternary simulation

Also called Eichelberger hazard detection, three-valued simulation.

Eichelberger's two-phase simulation with X for signals that may change: it finds static hazards and critical races, and each 0 or 1 it reports holds for all gate and wire delays.

Time
O(n (n + P)) worstO(n + P) best
Space
O(n + P) extra
Where
P = the number of gate input pins; n = the number of gates (state variables)
Properties
deterministicnot exactiterative
Origin
Edward B. Eichelberger, 1965

Ternary simulation evaluates a gate circuit with the three values 0, 1 and X, where X means "this signal may be 0 or 1, or may be changing". Eichelberger (1965) used it to find hazards and races caused by an input change. Phase A sets every input that changes to X and lets the X spread through the circuit until nothing more changes. Phase B then sets the inputs to their new values and lets the circuit settle again. A signal that is 0 or 1 after phase A cannot change at all, whatever the gate and wire delays are, so it has no glitch. A signal that has the same value before and after the change but is X after phase A may have a static hazard. A signal that is X after phase B may end in either value or never settle: a critical race. This page is in the logic simulation half of logic and circuit simulation. Its delay model is the weakest one: every gate and every wire may have any delay, and each 0 or 1 that ternary simulation gives holds for all of them. The price is pessimism: X can appear where a careful analysis would find a known value.

In plain words

Suppose an input switches from 1 to 0. While it switches, nobody knows which value the gates see, so call it X, for "unknown".

Phase A pushes this X forward. Each gate gives 0 or 1 if its known inputs already fix the answer, as 0 does for an AND, and X otherwise. The X can only spread, never shrink, so after at most one round per gate nothing changes. Every wire that is still 0 or 1 is safe: it cannot flicker, however slow or fast the gates are.

Phase B gives the input its new value and lets the circuit settle again. A wire that is still X after that has no final value that you can rely on.

A wire that starts at 1, ends at 1, but was X in phase A may show a short wrong pulse. That is a hazard.

The problem

The input is a gate circuit with primary inputs and nn gates, possibly with loops, as in latches and other asynchronous circuits. Each gate output is a state variable. For an input vector uu and a state ss, let F(u,s)F(u, s) be the state obtained by evaluating every gate once on these values. A state s0s_0 is stable under the input aa when F(a,s0)=s0F(a, s_0) = s_0. The input then changes from aa to bb.

The question is what can happen during and after this change: which signals may change for a short time, and which end in a value that depends on the delays. The values are ordered by information: 0⊑X0 \sqsubseteq X and 1⊑X1 \sqsubseteq X, and vectors are ordered position by position. The least upper bound of 0 and 1 is X. The gates use Kleene's three-valued tables, which give each gate the exact three-valued extension of its Boolean function: the output is 0 or 1 when all binary completions of the inputs agree, and X otherwise. See multi-valued logic simulation.

The algorithm

  1. TERNARY-SIM(C, a, b, s0) (s0 is stable under the input a)
  2. 1â ← lub(a, b): each input that differs between a and b becomes X
  3. 2s ← s0
  4. 3repeat (phase A)
  5. 4s' ← F(â, s), every gate evaluated with the three-valued tables
  6. 5done ← (s' = s); s ← s'
  7. 6until done
  8. 7t ← s (phase B)
  9. 8repeat
  10. 9t' ← F(b, t); done ← (t' = t); t ← t'
  11. 10until done
  12. 11return s_A = s and t_B = t

Read the results net by net, with s0s_0 the value before the change:

  • sA=s0s_A = s_0 (binary): the net does not change during the transition, for any delays.
  • s0=tBs_0 = t_B (binary) and sA=Xs_A = X: the net may have a static hazard, a short pulse to the other value.
  • s0≠tBs_0 \ne t_B, both binary: the net changes to its new value. Ternary simulation cannot tell whether it does so once or with extra pulses, a dynamic hazard, because both cases give sA=Xs_A = X.
  • tB=Xt_B = X: the final value is not determined by the circuit alone. In a sequential circuit this is a critical race or an oscillation.

Ternary simulation is sometimes said to detect dynamic hazards. It does not, for the reason in the third case above. Finding dynamic hazards needs more values, as in the hazard algebras of Brzozowski and Ésik.

For a combinational circuit with some inputs at X and no change at all, the same iteration from the all-X state gives the plain three-valued evaluation of the circuit, which is how X handling works in gate-level simulation, test generation and symbolic trajectory evaluation.

Example

Take y=ab+a′cy = ab + a'c built from aˉ=NOT(a)\bar a = \mathrm{NOT}(a), p=AND(a,b)p = \mathrm{AND}(a, b), q=AND(aˉ,c)q = \mathrm{AND}(\bar a, c) and y=OR(p,q)y = \mathrm{OR}(p, q). Let b=c=1b = c = 1 and let aa fall from 1 to 0. The stable start is s0=(aˉ,p,q,y)=(0,1,0,1)s_0 = (\bar a, p, q, y) = (0, 1, 0, 1). Phase A uses a^=(X,1,1)\hat a = (X, 1, 1), and phase B uses b=(0,1,1)b = (0, 1, 1).

step aˉ\bar a pp qq yy
s0s_0 0 1 0 1
A1 X X 0 1
A2 X X X X
A3 X X X X (no change, sAs_A found)
B1 1 0 X X
B2 1 0 1 X
B3 1 0 1 1
B4 1 0 1 1 (no change, tBt_B found)

So yy is 1 before and after but X after phase A: a static 1-hazard. A unit-delay simulation shows it as a pulse to 0 two time units after the change, as on the event-driven page. Adding the consensus term r=AND(b,c)r = \mathrm{AND}(b, c), so y=ab+a′c+bcy = ab + a'c + bc, removes it: in phase A, r=1r = 1 keeps y=1y = 1 at every step. This is an instance of a theorem of Eichelberger: a sum of products in which no term holds a variable together with its complement is free of hazards in the ternary sense exactly when it contains all prime implicants of its function.

For a sequential example, take a latch of two NAND gates, q=NAND(Sˉ,qˉ)q = \mathrm{NAND}(\bar S, \bar q) and qˉ=NAND(Rˉ,q)\bar q = \mathrm{NAND}(\bar R, q), at rest with Sˉ=Rˉ=0\bar S = \bar R = 0, so q=qˉ=1q = \bar q = 1. Let both inputs rise to 1 at once. Phase A gives q=qˉ=Xq = \bar q = X, and phase B keeps them at X, because NAND(1,X)=X\mathrm{NAND}(1, X) = X. The final state depends on which gate is faster: a critical race. A normal set, with Sˉ\bar S falling from 1 to 0 while q=0q = 0 and qˉ=1\bar q = 1, gives sA=(X,X)s_A = (X, X) and tB=(1,0)t_B = (1, 0), so the latch ends in a known state.

Correctness

The proof in proofs/correctness.md shows the following, all exactly.

  1. Every gate table is monotone in the information order and exact on binary inputs, so FF is monotone. So ternary evaluation is sound: if a net gets 0 or 1 under a vector with some X inputs, every binary completion of the vector gives the same value. On fanout-free circuits it is also exact.
  2. Phase A climbs: s0⊑F(a^,s0)⊑⋯s_0 \sqsubseteq F(\hat a, s_0) \sqsubseteq \cdots, so it stops after at most nn changing steps, at the least fixed point of F(a^,⋅)F(\hat a, \cdot) above s0s_0. Phase B descends from sAs_A and stops after at most nn changing steps at the greatest fixed point of F(b,⋅)F(b, \cdot) below sAs_A.
  3. In any run with any gate and wire delays, as long as every new value of a gate output is its gate function applied to values its inputs held earlier, every value of every net is below sAs_A. So a net that is binary in sAs_A never changes. Every stable state that such a run reaches is below tBt_B.

So the 0 and 1 results are sound for every delay assignment. The converse, that every X found by phase A is a real change under some gate and wire delays and that phase B finds exactly the final behaviors, is a theorem of Brzozowski and Seger (1987) that this page cites and does not prove. With delays only on gates and none on wires, the converse can fail.

The tests check the gate tables against all completions, soundness on random circuits against all completions, exactness on random fanout-free circuits, the step bounds and the bounds on every reachable state by an exhaustive search over the multiple-winner race model on random circuits with loops, and the absence of glitches on binary nets under random integer gate delays.

Proof: Ternary evaluation is monotone and sound, and Eichelberger's two phases bound every run under any delaysfull

Setting. The values are 0,1,X0, 1, X with the information order 0⊑X0 \sqsubseteq X, 1⊑X1 \sqsubseteq X, and v⊑vv \sqsubseteq v for each vv. Vectors are ordered position by position. A completion of a vector uu is a binary vector vv with v⊑uv \sqsubseteq u. For a Boolean function ff of kk arguments, its exact extension is $\hat f(u) = $ the common value of ff on all completions of uu if they all agree, and XX otherwise. Equivalently, f^(u)\hat f(u) is the least upper bound of {f(v):v⊑u binary}\{f(v) : v \sqsubseteq u \text{ binary}\}.

A circuit has primary inputs and nn gates, possibly in loops. For inputs uu and a state ss (the gate outputs), F(u,s)F(u, s) evaluates every gate once with the tables. Lines L1 to L11 refer to the pseudocode of the page.

Lemma 1 (gate tables). For AND, OR, NAND, NOR, XOR, XNOR, NOT and BUF with distinct inputs, Kleene's tables are the exact extensions. So each table is monotone, u⊑u′⇒f^(u)⊑f^(u′)u \sqsubseteq u' \Rightarrow \hat f(u) \sqsubseteq \hat f(u'), and agrees with ff on binary inputs.

Proof. AND: if some input is 0, every completion gives 0, and the table gives 0. If all inputs are 1, the table gives 1. Otherwise there is an X and no 0; setting all X to 1 gives 1 and setting one X to 0 gives 0, so the completions disagree, and the table gives X. OR is dual, and NAND, NOR, XNOR and NOT are these followed by negation, which maps the set of completion values {0},{1},{0,1}\{0\}, \{1\}, \{0, 1\} to {1},{0},{0,1}\{1\}, \{0\}, \{0, 1\}. XOR: if all inputs are binary, the table gives the parity. If one input is X, flipping it flips the result, so the completions disagree and the table gives X. Monotonicity: if u⊑u′u \sqsubseteq u', every completion of uu is a completion of u′u', so the set of values only grows, and its least upper bound can only go up. The tests check all tables with up to three inputs against all completions. □\square

Lemma 2 (FF is monotone). If u⊑u′u \sqsubseteq u' and s⊑s′s \sqsubseteq s', then F(u,s)⊑F(u′,s′)F(u, s) \sqsubseteq F(u', s').

Proof. Each component of FF is a gate table applied to some components of (u,s)(u, s), and these grow from (u,s)(u, s) to (u′,s′)(u', s'). Apply Lemma 1. □\square

Theorem 1 (soundness of three-valued evaluation). Let the circuit have no loop, let uu be an input vector with values in {0,1,X}\{0, 1, X\}, and let e(u)e(u) be the result of evaluating the gates in topological order with the tables. For every completion vv of uu and every net mm, e(v)m⊑e(u)me(v)_m \sqsubseteq e(u)_m. So if e(u)me(u)_m is 0 or 1, every completion gives the same value.

Proof. Induction in topological order. Inputs: v⊑uv \sqsubseteq u. A gate whose inputs satisfy the claim gets f^(inputs under v)⊑f^(inputs under u)\hat f(\text{inputs under } v) \sqsubseteq \hat f(\text{inputs under } u) by Lemma 1, and on the binary inputs under vv, f^=f\hat f = f. □\square

Iterating F(u,⋅)F(u, \cdot) from the all-X state gives the same result e(u)e(u) on a loop-free circuit: the sequence descends by Lemma 2 (since F(u,X)⊑XF(u, \mathbf{X}) \sqsubseteq \mathbf{X}), and after kk steps every net of level at most kk has its value e(u)e(u). This is the function evaluate of the implementation.

Theorem 2 (exactness without fanout). If every input and every gate output feeds at most one gate input, then for every net mm, e(u)me(u)_m is the least upper bound of e(v)me(v)_m over the completions vv of uu.

Proof. Induction in topological order. The subcircuits feeding the different inputs of a gate gg use disjoint sets of primary inputs, since there is no fanout. So as vv ranges over the completions of uu, the vector of values at the inputs of gg ranges over the product S1×⋯×SkS_1 \times \cdots \times S_k, where SiS_i is the set of values of input ii. By induction, the value of input ii under uu is the least upper bound of SiS_i, whose completions are exactly the elements of SiS_i. By Lemma 1 the table of gg gives the least upper bound of ff over S1×⋯×SkS_1 \times \cdots \times S_k, which is the least upper bound of the values of out(g)\mathrm{out}(g) over the completions. □\square

X pessimism. With fanout, Theorem 2 fails. In y=OR(AND(s,a),AND(NOT(s),b))y = \mathrm{OR}(\mathrm{AND}(s, a), \mathrm{AND}(\mathrm{NOT}(s), b)) with a=b=1a = b = 1 and s=Xs = X: the two AND gates give X and X, so y=OR(X,X)=Xy = \mathrm{OR}(X, X) = X. Both completions give y=1y = 1. The tables see two X values but not that one is the complement of the other. The simplest case is x∨¬xx \lor \lnot x with x=Xx = X, which gives X instead of 1.

Theorem 3 (phase A). Let F(a,s0)=s0F(a, s_0) = s_0 and a^=lub(a,b)\hat a = \mathrm{lub}(a, b) (L1). The sequence s0=s0s^0 = s_0, sh+1=F(a^,sh)s^{h+1} = F(\hat a, s^h) of L2 to L6 is increasing. It stops after at most nn steps that change the state, and its last element sAs_A is the least fixed point of F(a^,⋅)F(\hat a, \cdot) above s0s_0.

Proof. a⊑a^a \sqsubseteq \hat a, so s1=F(a^,s0)⊒F(a,s0)=s0s^1 = F(\hat a, s_0) \sqsupseteq F(a, s_0) = s_0 by Lemma 2. If sh+1⊒shs^{h+1} \sqsupseteq s^h, then sh+2=F(a^,sh+1)⊒F(a^,sh)=sh+1s^{h+2} = F(\hat a, s^{h+1}) \sqsupseteq F(\hat a, s^h) = s^{h+1}. In an increasing chain, a step that changes the state turns at least one binary component into X, and there are nn components, so at most nn steps change it. The last element satisfies F(a^,sA)=sAF(\hat a, s_A) = s_A and sA⊒s0s_A \sqsupseteq s_0. If rr is any fixed point of F(a^,⋅)F(\hat a, \cdot) with r⊒s0r \sqsupseteq s_0, then sh⊑rs^h \sqsubseteq r for all hh, by induction: sh+1=F(a^,sh)⊑F(a^,r)=rs^{h+1} = F(\hat a, s^h) \sqsubseteq F(\hat a, r) = r. □\square

Theorem 4 (phase B). The sequence t0=sAt^0 = s_A, th+1=F(b,th)t^{h+1} = F(b, t^h) of L7 to L10 is decreasing, stops after at most nn changing steps, and its last element tBt_B is the greatest fixed point of F(b,⋅)F(b, \cdot) below sAs_A.

Proof. b⊑a^b \sqsubseteq \hat a, so t1=F(b,sA)⊑F(a^,sA)=sAt^1 = F(b, s_A) \sqsubseteq F(\hat a, s_A) = s_A. Induction with Lemma 2 shows that the sequence decreases. Each changing step turns at least one X into a binary value, and a binary value never changes in a decreasing chain, so at most nn steps change it. If r=F(b,r)r = F(b, r) and r⊑sAr \sqsubseteq s_A, then r⊑thr \sqsubseteq t^h for all hh by the same induction. □\square

Delay model. Consider a run in continuous or discrete time, with binary values. Before time 0 the inputs are aa and the gates are in s0s_0. From time 0 each primary input has its new value; a gate may see the change of an input or of another gate later, after any wire delay, and its output may change after any gate delay. We need only one property: each value that a gate output takes is its value in s0s_0 or the gate function applied to a vector of values that its inputs, as seen through their wires, held at earlier times; and each input, as seen by a gate, has a value from aa or bb. Transport delays, inertial delays, gate and wire delays of any size, and the multiple-winner race model all have this property. We also assume that each bounded interval of time holds finitely many changes.

Theorem 5 (every value is below sAs_A). In every such run, at every time, the value of every gate output mm satisfies value(m)⊑(sA)m\mathrm{value}(m) \sqsubseteq (s_A)_m. In particular, a net with (sA)m∈{0,1}(s_A)_m \in \{0, 1\} keeps its value (s0)m(s_0)_m for ever, so it has no glitch.

Proof. The input values seen by gates are in {ai,bi}\{a_i, b_i\}, and both are ⊑a^i\sqsubseteq \hat a_i. The change times are well ordered, so we can use induction over them. The values before the first change are those of s0⊑sAs_0 \sqsubseteq s_A. When gate gg takes a new value, it is fg(w)f_g(w) for a vector ww of earlier values of its inputs. By induction each component of ww is ⊑\sqsubseteq the matching component of (a^,sA)(\hat a, s_A). By Lemma 1, fg(w)=f^g(w)⊑f^gf_g(w) = \hat f_g(w) \sqsubseteq \hat f_g at (a^,sA)(\hat a, s_A), which is F(a^,sA)g=(sA)gF(\hat a, s_A)_g = (s_A)_g. If (sA)m(s_A)_m is binary, every value of mm equals it, and (s0)m⊑(sA)m(s_0)_m \sqsubseteq (s_A)_m gives (sA)m=(s0)m(s_A)_m = (s_0)_m. □\square

Theorem 6 (stable end states are below tBt_B). If such a run reaches a state rr that is stable under bb, that is, F(b,r)=rF(b, r) = r, then r⊑tBr \sqsubseteq t_B.

Proof. By Theorem 5, r⊑sAr \sqsubseteq s_A, so by Theorem 4, rr is below the greatest fixed point of F(b,⋅)F(b, \cdot) under sAs_A, which is tBt_B. □\square

So if (tB)m(t_B)_m is binary, every run that settles ends with that value on mm, and if tBt_B is binary everywhere, every run that settles ends in the same state. Theorems 5 and 6 are the soundness of Eichelberger's procedure. The converse, that every X of sAs_A is a real change in some run with gate and wire delays, and that tBt_B is exactly the least upper bound of the possible final behaviors, is the theorem of Brzozowski and Seger (1987), cited on the page and not proved here.

Complexity

Each application of FF evaluates every gate once and costs O(n+P)O(n + P). Phase A changes at least one variable from binary to X at each step that is not the last, and phase B changes at least one from X to binary, so each phase makes at most n+1n + 1 applications. The total is O(n(n+P))O(n(n + P)), and the space is O(n+P)O(n + P). An event-driven version that evaluates only the fanout of the variables that changed brings the cost down to O(Pk)O(P k), with kk the largest fan-in, since each variable changes at most once per phase. A binary race analysis that tries every order of gate changes can need time exponential in nn.

Properties

  • Sound, not complete. Each 0 or 1 is right for every delay assignment and every binary completion. An X may hide a known value.
  • X pessimism on reconvergent fanout. In the multiplexer y=sa+s′by = s a + s' b with a=b=1a = b = 1 and s=Xs = X, the circuit gives y=Xy = X, although both completions give 1. The X reaches the OR gate along two paths, and the tables do not remember that the two copies are the same signal and opposite. On circuits without reconvergent fanout, ternary evaluation is exact.
  • Monotone. Replacing a binary input by X can only replace binary outputs by X, never change a 0 into 1.
  • Cheap. The cost is polynomial, while the exact analysis of all delay orders is exponential.

Variants and improvements

  • Plain X simulation. With no input change, evaluating from the all-X state gives the three-valued value of every net under inputs with X. Simulators use it for unknown initial states, and test tools for unknown values in scan cells.
  • More values. Five-valued and eight-valued algebras keep more history, such as "changed from 0 to 1", and the hazard algebras of Brzozowski and Ésik detect dynamic hazards.
  • Symbolic trajectory evaluation. STE runs ternary simulation over symbolic values and uses the information order to check properties of a circuit with a small number of symbolic variables.
  • Event-driven ternary simulation. Evaluate only the gates whose inputs changed in the last step, as in event-driven simulation.
  • Switch-level circuits. The same X value and the same monotone arguments work for transistor networks in switch-level simulation.

When to use it

Use ternary simulation to check an asynchronous circuit or a latch design for hazards and races after each input change, to screen a combinational circuit for static hazards, and to simulate designs whose initial state is unknown. It needs no delay values, which makes it a good first check before any timing is known. When it reports X, follow up with an exact method: a race analysis over the possible orders, or timed simulation with real delays.

Pitfalls

  • Reading every X as a real problem. X is a warning, not a proof. Reconvergent fanout gives X on safe nets.
  • Expecting dynamic hazards. A net that changes from 0 to 1 always gets X in phase A, with or without extra pulses.
  • Starting from an unstable state. The theorems need F(a,s0)=s0F(a, s_0) = s_0. From an unstable start, phase A need not climb.
  • Changing inputs one at a time. Setting the changing inputs to X one after another can miss a race between them. Set them all to X together, as line L1 does.
  • Gate delays without wire delays. A model that puts delays only on gates can call a circuit hazard-free when a wire delay would show a hazard. Ternary simulation is sound for the wider model, which is the safe side.

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.

logicnet.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the sim1 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Gate netlists and gate functions for the logic simulation pages.

A value is 0, 1 or X = 2, where X means "unknown, it can be 0 or 1".
A circuit has named primary inputs, gates (out, op, ins) and named primary
outputs. Every net is a primary input or the output of exactly one gate.
The gates may form loops, but direct_eval needs a circuit without loops.
This module holds no simulation algorithm. It gives the gate functions, the
netlist, a direct recursive evaluation that serves as the reference, random
circuits for tests and the binary completions of a three-valued vector.
"""

from __future__ import annotations

import itertools
import random
from typing import Dict, Iterator, List, Optional, Sequence, Tuple

X = 2
OPS = ("AND", "OR", "NAND", "NOR", "XOR", "XNOR", "NOT", "BUF")
ONE_INPUT = ("NOT", "BUF")


def eval2(op: str, vals: Sequence[int]) -> int:
    """The gate function on values in {0, 1}."""
    if op == "AND":
        return int(all(vals))
    if op == "OR":
        return int(any(vals))
    if op == "NAND":
        return 1 - int(all(vals))
    if op == "NOR":
        return 1 - int(any(vals))
    if op == "XOR":
        return sum(vals) & 1
    if op == "XNOR":
        return 1 - (sum(vals) & 1)
    if op == "NOT":
        return 1 - vals[0]
    if op == "BUF":
        return vals[0]
    raise ValueError(f"unknown gate {op}")


def not3(v: int) -> int:
    return X if v == X else 1 - v


def eval3(op: str, vals: Sequence[int]) -> int:
    """Kleene's strong three-valued gate function on values in {0, 1, X}."""
    if op in ("AND", "NAND"):
        r = 0 if 0 in vals else (X if X in vals else 1)
        return r if op == "AND" else not3(r)
    if op in ("OR", "NOR"):
        r = 1 if 1 in vals else (X if X in vals else 0)
        return r if op == "OR" else not3(r)
    if op in ("XOR", "XNOR"):
        r = X if X in vals else sum(vals) & 1
        return r if op == "XOR" else not3(r)
    if op == "NOT":
        return not3(vals[0])
    if op == "BUF":
        return vals[0]
    raise ValueError(f"unknown gate {op}")


class Circuit:
    """A gate netlist. gates is a list of (output net, op, list of input nets)."""

    def __init__(self, inputs: Sequence[str], gates: Sequence[Tuple[str, str, Sequence[str]]], outputs: Sequence[str]):
        self.inputs: List[str] = list(inputs)
        self.gates: List[Tuple[str, str, List[str]]] = [(out, op, list(ins)) for out, op, ins in gates]
        self.outputs: List[str] = list(outputs)
        self.driver: Dict[str, int] = {}
        for i, (out, op, ins) in enumerate(self.gates):
            if op not in OPS:
                raise ValueError(f"unknown gate {op}")
            if not ins or (op in ONE_INPUT and len(ins) != 1):
                raise ValueError(f"gate {out} has a wrong number of inputs")
            if out in self.driver or out in self.inputs:
                raise ValueError(f"net {out} has two drivers")
            self.driver[out] = i
        self.nets: List[str] = self.inputs + [g[0] for g in self.gates]
        self.fanout: Dict[str, List[int]] = {n: [] for n in self.nets}
        for i, (out, op, ins) in enumerate(self.gates):
            for n in ins:
                if n not in self.fanout:
                    raise ValueError(f"net {n} has no driver")
                if i not in self.fanout[n]:
                    self.fanout[n].append(i)
        for n in self.outputs:
            if n not in self.fanout:
                raise ValueError(f"output {n} has no driver")

    def is_acyclic(self) -> bool:
        """True when no gate depends on its own output (three-colour depth-first search)."""
        colour = [0] * len(self.gates)
        for root in range(len(self.gates)):
            if colour[root]:
                continue
            colour[root] = 1
            stack = [(root, iter(self.gates[root][2]))]
            while stack:
                g, it = stack[-1]
                nxt = None
                for n in it:
                    if n in self.driver:
                        nxt = self.driver[n]
                        break
                if nxt is None:
                    colour[g] = 2
                    stack.pop()
                elif colour[nxt] == 1:
                    return False
                elif colour[nxt] == 0:
                    colour[nxt] = 1
                    stack.append((nxt, iter(self.gates[nxt][2])))
        return True

    def direct_eval(self, vec: Dict[str, int], three: bool = False) -> Dict[str, int]:
        """Value of every net, each computed from its definition with memoization."""
        f = eval3 if three else eval2
        val: Dict[str, int] = {n: vec[n] for n in self.inputs}
        busy = set()

        def get(n: str) -> int:
            if n in val:
                return val[n]
            if n in busy:
                raise ValueError("the circuit has a loop")
            busy.add(n)
            out, op, ins = self.gates[self.driver[n]]
            val[n] = f(op, [get(m) for m in ins])
            return val[n]

        for n in self.nets:
            get(n)
        return val


def random_circuit(rng: random.Random, n_inputs: int, n_gates: int, n_outputs: Optional[int] = None,
                   loops: bool = False, ops: Sequence[str] = OPS) -> Circuit:
    """A random circuit. Without loops, gate k reads only inputs and gates 0..k-1."""
    inputs = [f"i{k}" for k in range(n_inputs)]
    names = [f"g{k}" for k in range(n_gates)]
    gates = []
    for k in range(n_gates):
        op = rng.choice(ops)
        pool = inputs + (names if loops else names[:k])
        arity = 1 if op in ONE_INPUT else rng.randint(2, 3)
        ins = rng.sample(pool, min(arity, len(pool)))
        if op not in ONE_INPUT and len(ins) < 2:
            op = "BUF"
        gates.append((names[k], op, ins))
    if n_outputs is None:
        n_outputs = min(3, n_gates)
    return Circuit(inputs, gates, names[n_gates - n_outputs:])


def all_vectors(names: Sequence[str]) -> Iterator[Dict[str, int]]:
    """Every assignment of 0 and 1 to the names."""
    for bits in itertools.product((0, 1), repeat=len(names)):
        yield dict(zip(names, bits))


def completions(vec: Dict[str, int]) -> Iterator[Dict[str, int]]:
    """Every binary vector that agrees with vec wherever vec is not X."""
    free = [n for n, v in vec.items() if v == X]
    for bits in itertools.product((0, 1), repeat=len(free)):
        out = dict(vec)
        out.update(zip(free, bits))
        yield out
ternary_simulation.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ternary-simulation/. The authors are listed in prov/9Z1Y7X.jsonl.
"""Ternary simulation with the values 0, 1 and X, and Eichelberger's two phases.

Every gate output is a state variable, and the gates may form loops. The
delay model is arbitrary: each gate and each wire may have any finite
delay, and ternary simulation gives results that hold for all of them.
F(u, s) evaluates every gate once with Kleene's tables, with the primary
inputs at u and the gate outputs at s.

Phase A starts from a stable state s0 under the old inputs a, with every
input that changes set to X, and iterates F upwards to a fixed point.
Phase B then sets the new inputs b and iterates F downwards to a fixed point.
"""

from __future__ import annotations

from typing import Dict, List, Tuple

from logicnet import X, Circuit, eval3

Vec = Dict[str, int]


def lub(u: int, v: int) -> int:
    """Least upper bound in the information order: equal values stay, different ones give X."""
    return u if u == v else X


def leq(u: Vec, v: Vec) -> bool:
    """u is below v in the information order: v agrees with u wherever v is not X."""
    return all(v[k] == X or v[k] == u[k] for k in v)


def step(c: Circuit, inputs: Vec, state: Vec) -> Vec:
    """F(inputs, state): every gate evaluated once on the present values."""
    val = dict(state)
    val.update(inputs)
    return {out: eval3(op, [val[n] for n in ins]) for out, op, ins in c.gates}


def settle(c: Circuit, inputs: Vec, state: Vec) -> Tuple[Vec, int]:
    """Iterate F(inputs, .) from state until it stops changing. Returns the fixed point and the step count."""
    s = dict(state)
    steps = 0
    while True:
        nxt = step(c, inputs, s)
        if nxt == s:
            return s, steps
        s = nxt
        steps += 1
        if steps > 3 * len(c.gates) + 3:
            raise RuntimeError("no fixed point; the start state was not monotone for this input")


def evaluate(c: Circuit, inputs: Vec) -> Vec:
    """Ternary value of every gate output of a loop-free circuit, from the all-X state."""
    s, _ = settle(c, inputs, {g[0]: X for g in c.gates})
    return s


def eichelberger(c: Circuit, a: Vec, b: Vec, s0: Vec) -> Tuple[Vec, Vec, int, int]:
    """Phases A and B for the input change from a to b. s0 must be stable under a.

    Returns (sA, tB, steps of phase A, steps of phase B).
    """
    a_hat = {n: lub(a[n], b[n]) for n in c.inputs}  # @line L1
    s = dict(s0)  # @line L2
    steps_a = 0
    while True:  # @line L3
        nxt = step(c, a_hat, s)  # @line L4
        done = nxt == s  # @line L5
        s = nxt
        if done:  # @line L6
            break
        steps_a += 1
    t = dict(s)  # @line L7
    steps_b = 0
    while True:  # @line L8
        nxt = step(c, b, t)  # @line L9
        done = nxt == t
        t = nxt
        if done:  # @line L10
            break
        steps_b += 1
    return s, t, steps_a, steps_b  # @line L11


def report(s0: Vec, s_a: Vec, t_b: Vec) -> Dict[str, List[str]]:
    """Read the result of the two phases.

    static_hazard: the net has the same binary value before and after, but X after phase A.
    undetermined: X after phase B, so the final value depends on the delays (a critical race or an oscillation).
    changes: the net goes from one binary value to the other; ternary simulation cannot say if it does so cleanly.
    """
    out: Dict[str, List[str]] = {"static_hazard": [], "undetermined": [], "changes": []}
    for n in s0:
        if t_b[n] == X:
            out["undetermined"].append(n)
        elif t_b[n] == s0[n] and s_a[n] == X:
            out["static_hazard"].append(n)
        elif t_b[n] != s0[n]:
            out["changes"].append(n)
    return out
test_ternary_simulation.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ternary-simulation/. The authors are listed in prov/9Z1Y7X.jsonl.

import itertools
import random

import pytest

from logicnet import OPS, X, Circuit, all_vectors, completions, eval2, eval3, random_circuit
from ternary_simulation import eichelberger, evaluate, leq, report, step

HAZARD = Circuit(
    ["a", "b", "c"],
    [("na", "NOT", ["a"]), ("p", "AND", ["a", "b"]), ("q", "AND", ["na", "c"]), ("y", "OR", ["p", "q"])],
    ["y"],
)
FIXED = Circuit(
    ["a", "b", "c"],
    [("na", "NOT", ["a"]), ("p", "AND", ["a", "b"]), ("q", "AND", ["na", "c"]), ("r", "AND", ["b", "c"]),
     ("y", "OR", ["p", "q", "r"])],
    ["y"],
)
NAND_LATCH = Circuit(["sn", "rn"], [("q", "NAND", ["sn", "qn"]), ("qn", "NAND", ["rn", "q"])], ["q"])


def gate_state(c, full):
    return {g[0]: full[g[0]] for g in c.gates}


def test_gate_tables_are_monotone_and_exact():
    for op in OPS:
        for k in ((1,) if op in ("NOT", "BUF") else (2, 3)):
            for u in itertools.product((0, 1, X), repeat=k):
                outs = {eval2(op, list(v)) for v in itertools.product(*[(0, 1) if x == X else (x,) for x in u])}
                assert eval3(op, list(u)) == (outs.pop() if len(outs) == 1 else X)
                for w in itertools.product((0, 1, X), repeat=k):
                    if all(wi == X or wi == ui for ui, wi in zip(u, w)):
                        r, rw = eval3(op, list(u)), eval3(op, list(w))
                        assert rw == X or rw == r


@pytest.mark.parametrize("seed", range(12))
def test_combinational_soundness_against_all_completions(seed):
    rng = random.Random(seed)
    c = random_circuit(rng, rng.randint(1, 8), rng.randint(1, 30))
    for _ in range(40):
        u = {n: rng.choice((0, 1, X)) for n in c.inputs}
        got = evaluate(c, u)
        assert got == gate_state(c, c.direct_eval(u, three=True))
        seen = {g[0]: set() for g in c.gates}
        for v in completions(u):
            full = c.direct_eval(v)
            for n in seen:
                seen[n].add(full[n])
        for n, vals in seen.items():
            if got[n] != X:
                assert vals == {got[n]}


def random_tree(rng, n_inputs):
    """A fanout-free circuit: every input and every gate output is read at most once."""
    free = [f"i{k}" for k in range(n_inputs)]
    gates = []
    while len(free) > 1:
        op = rng.choice(("AND", "OR", "NAND", "NOR", "XOR", "XNOR"))
        k = min(len(free), rng.randint(2, 3))
        ins = [free.pop(rng.randrange(len(free))) for _ in range(k)]
        out = f"g{len(gates)}"
        if rng.random() < 0.3:
            gates.append((out + "n", "NOT", [out]))
            gates.append((out, op, ins))
            out += "n"
        else:
            gates.append((out, op, ins))
        free.append(out)
    return Circuit([f"i{k}" for k in range(n_inputs)], gates, free)


@pytest.mark.parametrize("seed", range(8))
def test_exact_on_fanout_free_circuits(seed):
    rng = random.Random(30 + seed)
    c = random_tree(rng, rng.randint(2, 8))
    for _ in range(30):
        u = {n: rng.choice((0, 1, X)) for n in c.inputs}
        got = evaluate(c, u)[c.outputs[0]]
        vals = {c.direct_eval(v)[c.outputs[0]] for v in completions(u)}
        assert got == (vals.pop() if len(vals) == 1 else X)


def test_x_pessimism_on_reconvergent_fanout():
    mux = Circuit(["s", "a", "b"], [("ns", "NOT", ["s"]), ("p", "AND", ["s", "a"]), ("q", "AND", ["ns", "b"]),
                                    ("y", "OR", ["p", "q"])], ["y"])
    u = {"s": X, "a": 1, "b": 1}
    assert evaluate(mux, u)["y"] == X
    assert {mux.direct_eval(v)["y"] for v in completions(u)} == {1}


def test_page_example_hazard_and_consensus_fix():
    a, b = {"a": 1, "b": 1, "c": 1}, {"a": 0, "b": 1, "c": 1}
    s0 = gate_state(HAZARD, HAZARD.direct_eval(a))
    s_a, t_b, ka, kb = eichelberger(HAZARD, a, b, s0)
    assert s_a == {"na": X, "p": X, "q": X, "y": X} and (ka, kb) == (2, 3)
    assert t_b == {"na": 1, "p": 0, "q": 1, "y": 1}
    assert report(s0, s_a, t_b)["static_hazard"] == ["y"]
    s0 = gate_state(FIXED, FIXED.direct_eval(a))
    s_a, t_b, _, _ = eichelberger(FIXED, a, b, s0)
    assert s_a["y"] == 1 and report(s0, s_a, t_b)["static_hazard"] == []


def test_nand_latch_race_and_clean_set():
    s0 = {"q": 1, "qn": 1}  # stable with sn = rn = 0
    s_a, t_b, _, _ = eichelberger(NAND_LATCH, {"sn": 0, "rn": 0}, {"sn": 1, "rn": 1}, s0)
    assert t_b == {"q": X, "qn": X}
    s0 = {"q": 0, "qn": 1}  # stable with sn = rn = 1
    s_a, t_b, _, _ = eichelberger(NAND_LATCH, {"sn": 1, "rn": 1}, {"sn": 0, "rn": 1}, s0)
    assert s_a == {"q": X, "qn": X} and t_b == {"q": 1, "qn": 0}


def test_cannot_tell_a_clean_change_from_a_dynamic_hazard():
    buf = Circuit(["a"], [("y", "BUF", ["a"])], ["y"])
    s_a, t_b, _, _ = eichelberger(buf, {"a": 0}, {"a": 1}, {"y": 0})
    assert s_a == {"y": X} and t_b == {"y": 1}


def stable_states(c, a):
    names = [g[0] for g in c.gates]
    for bits in itertools.product((0, 1), repeat=len(names)):
        s = dict(zip(names, bits))
        if step(c, a, s) == s:
            yield s


def gmw_reachable(c, b, s0):
    """Every state reachable when any nonempty set of unstable gates may change at each step."""
    seen = {tuple(sorted(s0.items()))}
    todo = [s0]
    while todo:
        s = todo.pop()
        f = step(c, b, s)
        unstable = [n for n in s if f[n] != s[n]]
        for r in range(1, len(unstable) + 1):
            for sub in itertools.combinations(unstable, r):
                t = dict(s)
                for n in sub:
                    t[n] = f[n]
                key = tuple(sorted(t.items()))
                if key not in seen:
                    seen.add(key)
                    todo.append(t)
    return [dict(k) for k in seen]


@pytest.mark.parametrize("seed", range(40))
def test_phases_bound_every_gmw_run(seed):
    rng = random.Random(500 + seed)
    c = random_circuit(rng, rng.randint(1, 3), rng.randint(2, 6), loops=True)
    a = {n: rng.randint(0, 1) for n in c.inputs}
    b = {n: rng.randint(0, 1) for n in c.inputs}
    for s0 in list(stable_states(c, a))[:3]:
        s_a, t_b, ka, kb = eichelberger(c, a, b, s0)
        n = len(c.gates)
        assert ka <= n and kb <= n
        assert leq(s0, s_a) and leq(t_b, s_a)
        for r in gmw_reachable(c, b, s0):
            assert leq(r, s_a)
            if step(c, b, r) == r:
                assert leq(r, t_b)


def transport_run(c, delay, a, b, s0, t_end):
    """Unit-time step simulation with integer transport delays: out(t) = f(values at t - d).

    The inputs are a before time 0 and b from time 0. Before time 0 the circuit rests in s0, which is stable under a.
    """
    hist = []
    for t in range(t_end + 1):
        cur = dict(b)
        for out, op, ins in c.gates:
            d = delay[out]
            cur[out] = s0[out] if t - d < 0 else eval2(op, [hist[t - d][n] for n in ins])
        hist.append(cur)
    return hist


@pytest.mark.parametrize("seed", range(10))
def test_binary_after_phase_a_means_no_glitch_for_any_delays(seed):
    rng = random.Random(900 + seed)
    c = random_circuit(rng, rng.randint(2, 5), rng.randint(3, 12))
    for _ in range(5):
        a = {n: rng.randint(0, 1) for n in c.inputs}
        b = {n: rng.randint(0, 1) for n in c.inputs}
        s0 = gate_state(c, c.direct_eval(a))
        s_a, _, _, _ = eichelberger(c, a, b, s0)
        for _ in range(20):
            delay = {g[0]: rng.randint(1, 4) for g in c.gates}
            hist = transport_run(c, delay, a, b, s0, 4 * len(c.gates) + 4)
            for n, v in s_a.items():
                if v != X:
                    assert all(h[n] == v for h in hist)


def test_unit_delays_show_the_hazard_found_by_phase_a():
    a, b = {"a": 1, "b": 1, "c": 1}, {"a": 0, "b": 1, "c": 1}
    s0 = gate_state(HAZARD, HAZARD.direct_eval(a))
    hist = transport_run(HAZARD, {g[0]: 1 for g in HAZARD.gates}, a, b, s0, 6)
    assert [h["y"] for h in hist] == [1, 1, 0, 1, 1, 1, 1]

History

Edward Eichelberger at IBM presented ternary hazard detection at the Symposium on Switching Circuit Theory and Logical Design in 1964 and in the IBM Journal of Research and Development in 1965. He gave the two procedures, called A and B in later work, and used them for static hazards in combinational circuits and critical races in sequential circuits. Brzozowski and Yoeli (1979) related the ternary model to binary race analysis. Brzozowski and Seger (1987) proved that ternary simulation gives exactly the results of the binary analysis when every gate and every wire may have a delay, and their 1995 book gives the full theory. Bryant carried the X value into switch-level simulation in the 1980s, and Seger and Bryant built symbolic trajectory evaluation on it.

References

  1. E. B. Eichelberger, Hazard detection in combinational and sequential switching circuits, IBM Journal of Research and Development 9(2), 90 to 99, 1965, the two procedures with the third value for changing signals, the detection of static hazards in combinational circuits and of critical races in sequential circuits
  2. Janusz A. Brzozowski and Carl-Johan H. Seger, Asynchronous Circuits, Springer, New York, 1995, ISBN 0-387-94420-6, Chapter 7, Ternary Simulation, pages 113 to 141 (Algorithms A and B, and their relation to the binary race analysis)
  3. J. A. Brzozowski and C.-J. Seger, A characterization of ternary simulation of gate networks, IEEE Transactions on Computers C-36(11), 1318 to 1327, 1987, the results of ternary simulation equal the results of binary race analysis when every gate and every wire has a delay
  4. J. A. Brzozowski and M. Yoeli, On a ternary model of gate networks, IEEE Transactions on Computers C-28(3), 178 to 184, 1979, the ternary model and its relation to the multiple-winner race model

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.best
  • 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