Algorithm Search⌘K

Algorithmcore

Small-signal noise analysis

Also called AC noise analysis, adjoint noise analysis.

Sums the thermal, shot and flicker noise of every device at an output, using one adjoint solve per frequency as in Rohrer, Nagel, Meyer and Weber.

Time
O(D + F (S + K)) worst
Space
O(n^2 + K) extra
Where
D = the cost of the DC operating point; F = the number of frequency points; K = the number of noise sources; S = the cost of one sparse LU factorization and solve of the complex MNA matrix; n = the number of MNA unknowns
Properties
deterministicexactiterative
Origin
Ronald A. Rohrer, Laurence W. Nagel, Robert G. Meyer, L. Weber, 1971

Small-signal noise analysis computes the spectral density of the random noise at a circuit output: it linearizes the circuit at its DC operating point, gives every resistor, junction and transistor channel a noise current source, and adds the power that each source delivers to the output. It belongs to the circuit simulation half of the logic and circuit simulation sub-area. The key step, due to Rohrer, Nagel, Meyer and Weber (1971), is one solve with the transposed MNA matrix per frequency, which gives the transfer from every source to the output at once.

In plain words

Every resistor hisses, because the electrons in it move at random with the heat. Every diode crackles, because current crosses a junction in single charges. Transistors do both and also make a slow rumble that is strong at low frequencies. An amplifier amplifies all of these together with the signal, so its output is never perfectly clean.

The simulator wants to know how loud that hiss is at the output, frequency by frequency, and which device makes most of it. Each tiny noise source travels to the output through the circuit, which makes it louder or softer. The sources are independent, so their powers simply add. The trick is to find how strongly every source reaches the output with one calculation instead of one calculation per source: run the circuit backwards from the output once, and read off every answer.

The problem

The circuit is in modified nodal analysis form, f(x)+ddtq(x)=u(t)f(x) + \frac{d}{dt} q(x) = u(t), with x=(e1,…,en,j1,…,jm)x = (e_1, \ldots, e_n, j_1, \ldots, j_m). At the operating point x0x_0 the small-signal matrices are G=∂f/∂xG = \partial f/\partial x and C=∂q/∂xC = \partial q/\partial x, as in AC small-signal analysis, and at the frequency ff the complex MNA matrix is Y=G+jωCY = G + j\omega C with ω=2πf\omega = 2\pi f.

Noise source kk is a current that leaves node pkp_k and enters node qkq_k, with a one-sided power spectral density Sk(f)S_k(f) in A2/Hz\mathrm{A^2/Hz}, computed from the operating point. The standard sources are:

element source density Sk(f)S_k(f)
resistor RR thermal 4kT/R4kT/R
junction with current II shot 2q∣I∣2q\lvert I\rvert
MOSFET in saturation channel thermal 4kT⋅23gm4kT \cdot \tfrac23 g_m
MOSFET or junction flicker KF∣I∣AF/(f CoxLeff2)K_F \lvert I\rvert^{A_F} / (f\, C_{\mathrm{ox}} L_{\mathrm{eff}}^2)

Here kk is Boltzmann's constant, TT the temperature, qq the electron charge and gmg_m the transconductance at the operating point. The thermal density is Nyquist's result. The factor 23\tfrac23 is the long-channel value that ngspice uses in its level-1 MOSFET. The flicker coefficients KFK_F and AFA_F are fitted to measurements of each process and are not derived; CoxC_{\mathrm{ox}} and LeffL_{\mathrm{eff}} come from the geometry. The current and gmg_m come from the device model, whose parameters are fitted too: for the Shichman-Hodges model of the example, kk, VTV_T and λ\lambda.

Input: the circuit, an output vector ℓ\ell (the output is ℓTx\ell^{\mathsf T} x, usually a node voltage) and the frequencies f1,…,fFf_1, \ldots, f_F. Output: the output noise density Sout(fi)S_{\mathrm{out}}(f_i) in V2/Hz\mathrm{V^2/Hz} and the share of each source in it. The sources are assumed mutually uncorrelated.

The algorithm

  1. NOISE(circuit, f_1..f_F, ℓ)
  2. 1x₀ ← the DC operating point; G ← ∂f/∂x and C ← ∂q/∂x at x₀
  3. 2list the noise sources (p_k, q_k, S_k) with S_k evaluated at x₀
  4. 3for i = 1, ..., F
  5. 4Yᵀ ← (G + j2πf_i C)ᵀ, factored by sparse complex LU
  6. 5solve Yᵀ z = ℓ ▷ the adjoint system, one solve
  7. 6for every source k: share_k ← |z_{q_k} − z_{p_k}|² S_k(f_i)
  8. 7S_out(f_i) ← Σ_k share_k
  9. 8return S_out(f_1..f_F) and the shares

The transfer from source kk to the output is Hk=ℓTY−1akH_k = \ell^{\mathsf T} Y^{-1} a_k, where ak=eqk−epka_k = \mathbf e_{q_k} - \mathbf e_{p_k} is the KCL right side of a unit current from pkp_k to qkq_k. The direct method solves Yx=akY x = a_k once per source. Line L5 instead solves once with YTY^{\mathsf T}, and then Hk=zTak=zqk−zpkH_k = z^{\mathsf T} a_k = z_{q_k} - z_{p_k} for every kk. The transpose is the plain transpose, not the conjugate transpose. In circuit terms YTY^{\mathsf T} is the matrix of the adjoint network, the circuit with every controlled source turned around, driven by a unit current at the output; this is the same transposed solve as in adjoint sensitivity analysis, and the factors of YY serve for it, YT=UTLTPY^{\mathsf T} = U^{\mathsf T} L^{\mathsf T} P.

The output noise is often referred to the input: divide SoutS_{\mathrm{out}} by ∣H∣2|H|^2, the squared gain from the signal source to the output from an AC analysis. The total noise in a band is the integral of SoutS_{\mathrm{out}} over the band, and its root is the RMS noise voltage.

Example

A divider. R1R_1 from a quiet source to the output and R2R_2 from the output to ground. Each resistor injects into the output node, whose impedance is R1∥R2R_1 \parallel R_2, so Sout=(4kT/R1+4kT/R2)(R1∥R2)2=4kT (R1∥R2)S_{\mathrm{out}} = (4kT/R_1 + 4kT/R_2)(R_1 \parallel R_2)^2 = 4kT\,(R_1 \parallel R_2): the thermal noise of the parallel resistance.

kT/C. Put a capacitor CC across the output of a resistor RR from a grounded source. The output impedance is R/(1+jωRC)R/(1 + j\omega RC), and the integral of 4kTR/(1+(2πfRC)2)4kTR/(1 + (2\pi fRC)^2) over all f≥0f \ge 0 is kT/CkT/C, whatever RR is. For 1 pF at 300 K that is 64.4 µV RMS.

The common-source amplifier. This is the amplifier of the AC analysis page: an n-channel MOSFET with k=200 μA/V2k = 200\ \mu\mathrm{A/V^2}, VT=0.5V_T = 0.5 V and λ=0.05 V−1\lambda = 0.05\ \mathrm{V^{-1}}, its gate at a quiet 0.8 V source, RD=50R_D = 50 kΩ to VDD=1.8V_{DD} = 1.8 V, CL=100C_L = 100 fF from the drain to ground and Cgd=5C_{gd} = 5 fF from the gate to the drain. The flicker parameters are KF=10−28K_F = 10^{-28} and AF=1A_F = 1 (fitted values), with CoxLeff2=8.6 mF/m2×(1 μm)2C_{\mathrm{ox}} L_{\mathrm{eff}}^2 = 8.6\ \mathrm{mF/m^2} \times (1\ \mu\mathrm m)^2. At the operating point ID=9.594 μI_D = 9.594\ \muA, gm=63.96 μg_m = 63.96\ \muS and gds=0.45 μg_{ds} = 0.45\ \muS.

Three sources reach the drain through the same impedance Z=1/(1/RD+gds+jω(CL+Cgd))Z = 1/(1/R_D + g_{ds} + j\omega(C_L + C_{gd})), since the gate is held by an ideal source:

Sout(f)=(4kTRD+83kTgm+KFIDf CoxLeff2) ∣Z∣2.S_{\mathrm{out}}(f) = \Big(\frac{4kT}{R_D} + \frac83 kT g_m + \frac{K_F I_D}{f\, C_{\mathrm{ox}} L_{\mathrm{eff}}^2}\Big)\, |Z|^2.

The white part is 3.31×10−25+7.06×10−25 A2/Hz3.31 \times 10^{-25} + 7.06 \times 10^{-25}\ \mathrm{A^2/Hz}, so the channel makes 68.1% of the white noise and RDR_D 31.9%. The flicker term equals the white part at the corner frequency KFID/(CoxLeff2⋅1.038×10−24)=107.5K_F I_D/(C_{\mathrm{ox}} L_{\mathrm{eff}}^2 \cdot 1.038 \times 10^{-24}) = 107.5 kHz. The implementation gives:

frequency output (nV/√Hz) referred to the input (nV/√Hz) flicker share
1 Hz 16333 5222 1.000
100 Hz 1634 522.4 0.999
10 kHz 170.8 54.6 0.915
100 kHz 71.76 22.94 0.518
1 MHz 52.40 16.76 0.097
10 MHz 47.66 16.01 0.011
100 MHz 14.76 15.92 0.001
1 GHz 1.543 14.30 0.000

The output falls above the 31.0 MHz pole. Referred to the input, the white floor is 4kT/RD+83kTgm/gm=15.93\sqrt{4kT/R_D + \frac83 kT g_m}/g_m = 15.93 nV/√Hz; it falls at the highest frequencies because the gain there includes the feedthrough of CgdC_{gd}. The white output noise integrated over all frequencies is 347.6 µV RMS, against 198.6 µV for kT/(CL+Cgd)kT/(C_L + C_{gd}) alone: the transistor adds noise beyond that of a resistor.

Correctness

The proof in proofs/correctness.md shows that line L5 gives every transfer exactly, ℓTY−1ak=(Y−Tℓ)Tak=zqk−zpk\ell^{\mathsf T} Y^{-1} a_k = (Y^{-\mathsf T}\ell)^{\mathsf T} a_k = z_{q_k} - z_{p_k}. For mutually uncorrelated sources the cross terms of the output autocorrelation vanish, so the output density is ∑k∣Hk∣2Sk\sum_k |H_k|^2 S_k by the filter rule of the power spectral density and the Wiener-Khinchin theorem, which are cited. It also derives the kT/C integral. The source densities and the small-signal model are models, not theorems; the proof states where they enter.

The tests check, with measured tolerances:

  • The divider against 4kT(R1∥R2)4kT(R_1 \parallel R_2) and each share against 4kT/Ri⋅(R1∥R2)24kT/R_i \cdot (R_1 \parallel R_2)^2, to 10−1210^{-12} relative.
  • The RC integral, by the midpoint rule with 64 points on 2πfRC=tan⁡θ2\pi fRC = \tan\theta, against kT/CkT/C for RR from 100 Ω to 1 MΩ, to 10−910^{-9} relative. The substitution makes the integrand constant, so the rule is exact up to rounding and the test checks the density at every point.
  • The amplifier against the formula above at 45 frequencies from 1 Hz to 100 GHz, to 10−1210^{-12} relative, and the flicker share at the corner, 12\tfrac12.
  • A diode biased by a current IBI_B from 1 µA to 1 mA against 2qIB/gd22qI_B/g_d^2; at 1 mA this is 0.463 nV/√Hz.
  • 40 random networks (seed 81) of 3 to 7 nodes with resistors, capacitors, an inductor and controlled sources: the adjoint result matches the direct sum, one forward solve per source, within a relative difference of 3.9×10−153.9 \times 10^{-15} (measured worst case). Solving with YY in place of YTY^{\mathsf T} gives an error above 0.1% in 33 of the 40, because the controlled sources make YY unsymmetric.
Proof: One adjoint solve gives the output noise of every uncorrelated sourcefull

We use the notation of the page. The small-signal circuit at the operating point x0x_0 has the real matrices GG and CC, and at the frequency ff, with ω=2πf\omega = 2\pi f, its complex MNA matrix is Y=G+jωCY = G + j\omega C, assumed nonsingular. Noise source kk is a current iki_k that leaves node pkp_k and enters node qkq_k (node 0 is ground). Its one-sided power spectral density is Sk(f)S_k(f). The output is v=ℓTxv = \ell^{\mathsf T} x. The algorithm solves YTz=ℓY^{\mathsf T} z = \ell and returns

Sout(f)=∑k∣zqk−zpk∣2 Sk(f),S_{\mathrm{out}}(f) = \sum_k |z_{q_k} - z_{p_k}|^2\, S_k(f),

with z0=0z_0 = 0.

Lemma 1 (the injection vector). A current II that leaves node pp and enters node qq adds I akI\, a_k to the right side of the MNA equations, where ak=eq−epa_k = \mathbf e_{q} - \mathbf e_{p} (with e0=0\mathbf e_0 = 0).

Proof. The node rows of MNA are KCL in the form "the sum of the currents that leave the node through the elements equals the current that the sources put into it". The source puts II into node qq and takes II from node pp, so it adds +I+I to row qq and −I-I to row pp. It adds no element current and no branch row. □\square

Lemma 2 (the transfer of each source). The transfer function from iki_k to the output is Hk=ℓTY−1ak=zqk−zpkH_k = \ell^{\mathsf T} Y^{-1} a_k = z_{q_k} - z_{p_k}.

Proof. With only source kk active at the phasor II, the small-signal circuit is YX=IakY X = I a_k by Lemma 1, so the output phasor is ℓTY−1akI\ell^{\mathsf T} Y^{-1} a_k I, and Hk=ℓTY−1akH_k = \ell^{\mathsf T} Y^{-1} a_k. Since z=Y−Tℓz = Y^{-\mathsf T} \ell (the transpose, not the conjugate transpose),

ℓTY−1ak=(Y−Tℓ)Tak=zTak=zqk−zpk.□\ell^{\mathsf T} Y^{-1} a_k = (Y^{-\mathsf T} \ell)^{\mathsf T} a_k = z^{\mathsf T} a_k = z_{q_k} - z_{p_k}. \qquad \square

So one solve with YTY^{\mathsf T} gives every HkH_k, and the cost of each is one subtraction. This is the identity (A−1)T=(AT)−1(A^{-1})^{\mathsf T} = (A^{\mathsf T})^{-1} and nothing more. In circuit terms YTY^{\mathsf T} is the matrix of the adjoint network, which turns every controlled source around, and zz is the response of the adjoint network to a unit source at the output (see the adjoint sensitivity page and Tellegen's theorem); the proof above does not need that reading.

Lemma 3 (the sum of uncorrelated sources). Let n1,…,nKn_1, \ldots, n_K be zero-mean, jointly wide-sense stationary processes, mutually uncorrelated, E[nk(t)nl(s)]=0E[n_k(t) n_l(s)] = 0 for k≠lk \ne l, with spectral densities SkS_k. Let y=∑khk∗nky = \sum_k h_k * n_k for stable real impulse responses hkh_k with frequency responses HkH_k. Then Sy=∑k∣Hk∣2SkS_y = \sum_k |H_k|^2 S_k.

Proof. The autocorrelation of yy is

Ry(τ)=E[y(t+τ)y(t)]=∑k,l∬hk(a)hl(b) E[nk(t+τ−a) nl(t−b)] da db.R_y(\tau) = E[y(t+\tau) y(t)] = \sum_{k,l} \iint h_k(a) h_l(b)\, E[n_k(t+\tau-a)\, n_l(t-b)]\, da\, db.

The terms with k≠lk \ne l vanish because the sources are uncorrelated. The term with k=lk = l is the autocorrelation of hk∗nkh_k * n_k, so Ry=∑kRhk∗nkR_y = \sum_k R_{h_k * n_k}. The spectral density is the Fourier transform of the autocorrelation (the Wiener-Khinchin theorem), which is linear, so Sy=∑kShk∗nkS_y = \sum_k S_{h_k * n_k}. Each term is ∣Hk∣2Sk|H_k|^2 S_k by the filter rule of the power spectral density, which we cite. □\square

The rule holds for one-sided densities as well as for two-sided ones, since both sides of the identity are even in ff and the one-sided density is twice the two-sided one at f>0f > 0.

Theorem (correctness). If the noise sources are mutually uncorrelated, the value Sout(f)S_{\mathrm{out}}(f) that the algorithm returns is the spectral density of the output noise of the small-signal circuit, and the share of source kk is ∣Hk∣2Sk(f)|H_k|^2 S_k(f).

Proof. The small-signal circuit is linear and time invariant, so the output noise is ∑khk∗ik\sum_k h_k * i_k, where hkh_k is the impulse response whose transform is the transfer HkH_k of Lemma 2. Lemma 3 gives the sum, and Lemma 2 shows that the algorithm computes each ∣Hk∣2|H_k|^2 exactly as ∣zqk−zpk∣2|z_{q_k} - z_{p_k}|^2. □\square

What is not proved. Three steps are models, and the proof does not cover them.

  1. The source densities. 4kT/R4kT/R for a resistor is Nyquist's result, 2qI2qI for a junction is the shot-noise formula, 4kT⋅23gm4kT \cdot \frac23 g_m for a long-channel MOSFET in saturation and KFIDAF/(f CoxLeff2)K_F I_D^{A_F}/(f\, C_{\mathrm{ox}} L_{\mathrm{eff}}^2) for its flicker noise are device-model formulas with fitted KFK_F and AFA_F. They are cited on the page.
  2. The linearization. The noise is small, so the circuit is replaced by its small-signal model at x0x_0, as in AC analysis. Noise that moves the operating point, or mixes with a large signal, is outside this model.
  3. Independence. Sources in different devices are uncorrelated by the physics of the model. Correlated sources, such as the induced gate noise and the channel noise of one transistor, need the cross spectrum, and the sum of Lemma 3 then gains the terms 2Re⁡(HkHl‾Skl)2 \operatorname{Re}(H_k \overline{H_l} S_{kl}).

The kT/C result. For a resistor RR from a grounded source to a node with a capacitor CC to ground, H=R/(1+jωRC)H = R/(1 + j\omega RC) for the resistor current injected into the node, so

∫0∞4kTR⋅R21+(2πfRC)2 df=4kTR⋅12πRC⋅π2=kTC,\int_0^\infty \frac{4kT}{R} \cdot \frac{R^2}{1 + (2\pi f R C)^2}\, df = 4kTR \cdot \frac{1}{2\pi R C} \cdot \frac{\pi}{2} = \frac{kT}{C},

with the substitution 2πfRC=tan⁡θ2\pi f R C = \tan\theta. The total does not depend on RR. The test on the page computes the integral from the densities that the algorithm returns.

Complexity

The operating point is computed once, at cost DD. Each frequency costs one factorization and one solve, SS, plus O(1)O(1) per source in lines L6 and L7, so the total is O(D+F(S+K))O(D + F(S + K)). The direct method costs O(D+F(S+Ks))O(D + F(S + K s)), where ss is the cost of one extra solve with the factors, so it is slower by a factor that grows with KK. The implementation uses dense elimination; on an RC ladder its CPU time per frequency, measured with time.process_time, was 5.3 times less than the direct method's with 18 sources, 12 times less with 38 and 38 times less with 78. The extra space is the factors and one adjoint vector, plus the KK shares.

Properties

  • One solve for all sources. The cost per frequency hardly depends on the number of noise sources.
  • Exact for the linear model. Up to rounding, the result is the output density of the small-signal circuit with the given source densities.
  • A breakdown by source. The shares come free and tell the designer which device to change.
  • Powers add, not amplitudes. Uncorrelated sources add in ∣Hk∣2Sk|H_k|^2 S_k. Two equal sources give 2\sqrt2 times the noise voltage of one, not twice.

Variants and improvements

  • Input-referred noise and noise figure. Divide by the squared gain from an AC analysis, or compare with the noise of the source resistance.
  • Correlated sources. Two sources in one device with a cross spectrum SklS_{kl} add the terms 2Re⁡(HkHl‾Skl)2\operatorname{Re}(H_k \overline{H_l} S_{kl}); the adjoint still gives every HkH_k.
  • Integrated noise. Integrate SoutS_{\mathrm{out}} over a band, as in the kT/C example. A model reduced by Padé via Lanczos can give the transfer functions at many frequencies cheaply.
  • Periodic and cyclostationary noise. Mixers and switched circuits are linearized around a periodic steady state from harmonic balance or shooting, and noise is folded between sidebands.
  • Oscillator phase noise. In an oscillator the noise accumulates in the phase, which the small-signal model cannot describe; phase noise analysis treats it.

When to use it

Use noise analysis for the noise floor, input-referred noise, noise figure and signal-to-noise ratio of amplifiers, filters, references and receivers that work around a fixed bias point. Do not use it for oscillators, for circuits that switch, or for noise large enough to change the operating point; use phase noise analysis or a transient analysis with noise there.

Pitfalls

  • The transpose, not the conjugate transpose. YY is complex symmetric for RLC circuits but not with controlled sources; solving with YY, or with YHY^{\mathsf H}, gives wrong transfers. The random test measures this.
  • Fitted noise parameters. KFK_F and AFA_F are fitted per process, and the factor 23\tfrac23 is the long-channel value. The flicker corner and the low-frequency noise are only as good as the fit.
  • Noiseless sources. Ideal sources and controlled sources make no noise. A bias network built from them can hide noise that a real one would add.
  • One-sided and two-sided densities. 4kT/R4kT/R is one-sided, over f≥0f \ge 0. Mixing it with a two-sided density from another tool gives a factor of 2.
  • The operating point. The densities and transfers depend on x0x_0, like every small-signal result.
  • Flicker at zero frequency. The 1/f1/f density has no finite integral down to f=0f = 0; integrate from a stated low frequency.

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.

circuit_noise_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/circuit-noise-analysis/. The authors are listed in prov/P2C0RA.jsonl.
"""Small-signal noise analysis with one adjoint solve per frequency.

The circuit is in MNA form f(x) + d/dt q(x) = u(t), x = (e_1..e_n, j_1..j_m),
node 0 is ground. Each noise source is a current between two nodes with a
one-sided power spectral density S(f) in A^2/Hz, computed at the DC operating
point. The output noise density at a frequency is sum_k |H_k|^2 S_k(f), where
H_k is the transfer from source k to the output; all H_k come from one solve
with the transposed matrix.
"""

import math

import sim3dense

BOLTZMANN = 1.380649e-23  # J/K, exact in the SI
CHARGE = 1.602176634e-19  # C, exact in the SI


class NoConvergence(RuntimeError):
    pass


def _level1(k, vt, lam, vgs, vds):
    """Shichman-Hodges current for vds >= 0 and its partials (i, gds, gm)."""
    vov = vgs - vt
    if vov <= 0:
        return 0.0, 0.0, 0.0
    if vds < vov:
        a = vov * vds - vds * vds / 2
        return k * a * (1 + lam * vds), k * (vov - vds) * (1 + lam * vds) + k * a * lam, k * vds * (1 + lam * vds)
    return k / 2 * vov * vov * (1 + lam * vds), k / 2 * vov * vov * lam, k * vov * (1 + lam * vds)


def mosfet_eval(kind, k, vt, lam, vd, vg, vs):
    """Current d -> s, its partials (gd, gg, gs) in (vd, vg, vs), and gm >= 0."""
    if kind == "p":
        i, gd, gg, gs, gm = mosfet_eval("n", k, vt, lam, -vd, -vg, -vs)
        return -i, gd, gg, gs, gm
    if vd < vs:
        i, gd, gg, gs, gm = mosfet_eval("n", k, vt, lam, vs, vg, vd)
        return -i, -gs, -gg, -gd, gm
    i, gds, gm = _level1(k, vt, lam, vg - vs, vd - vs)
    return i, gds, gm, -gds - gm, gm


class Netlist:
    """MNA netlist; the stamps follow the modified nodal analysis page."""

    def __init__(self, nodes, temperature=300.0):
        self.n, self.m, self.el = nodes, 0, []
        self.kt = BOLTZMANN * temperature

    @property
    def size(self):
        return self.n + self.m

    def resistor(self, p, q, r, noisy=True):
        self.el.append(("R", p, q, 1.0 / r, noisy))

    def capacitor(self, p, q, c):
        self.el.append(("C", p, q, c))

    def inductor(self, p, q, l):
        self.el.append(("L", p, q, l, self.m))
        self.m += 1

    def vsource(self, p, q, dc=0.0, ac=0.0):
        self.el.append(("V", p, q, (dc, ac), self.m))
        self.m += 1

    def isource(self, p, q, dc=0.0, ac=0.0):
        """Moves its current out of p and into q. Noiseless."""
        self.el.append(("I", p, q, (dc, ac)))

    def vccs(self, p, q, c, d, g):
        """Current g (e_c - e_d) out of p and into q. Noiseless."""
        self.el.append(("G", p, q, (c, d, g)))

    def mosfet(self, kind, d, g, s, k, vt, lam, kf=0.0, af=1.0, cox_l2=1.0):
        """Level-1 MOSFET. k, vt, lam, kf and af are fitted; cox_l2 is Cox Leff^2."""
        self.el.append(("M", d, g, s, (kind, k, vt, lam, kf, af, cox_l2)))

    def diode(self, a, c, i_s, n=1.0, kf=0.0, af=1.0):
        """Junction diode from a to c; i_s, n, kf and af are fitted."""
        self.el.append(("D", a, c, (i_s, n, kf, af)))

    def _diode(self, v, i_s, n):
        nvt = n * self.kt / CHARGE
        vmax = 40 * nvt
        if v <= vmax:
            e = math.exp(v / nvt)
            return i_s * (e - 1), i_s * e / nvt
        e = math.exp(40.0)
        return i_s * (e * (1 + (v - vmax) / nvt) - 1), i_s * e / nvt

    def evaluate(self, x):
        """f(x), G = df/dx, q(x), C = dq/dx."""
        N = self.size
        f, q = [0.0] * N, [0.0] * N
        G = [[0.0] * N for _ in range(N)]
        C = [[0.0] * N for _ in range(N)]

        def e(node):
            return x[node - 1] if node else 0.0

        def two(vec, mat, p, qn, cur, partials):
            """Current cur leaving p and entering qn, with partials {node: d cur}."""
            for r, s in ((p, 1), (qn, -1)):
                if r:
                    vec[r - 1] += s * cur
                    for node, d in partials:
                        if node:
                            mat[r - 1][node - 1] += s * d

        for el in self.el:
            kind = el[0]
            if kind in "RC":
                p, qn, val = el[1], el[2], el[3]
                vec, mat = (f, G) if kind == "R" else (q, C)
                two(vec, mat, p, qn, val * (e(p) - e(qn)), ((p, val), (qn, -val)))
            elif kind in "LV":
                p, qn, k = el[1], el[2], self.n + el[4]
                for r, s in ((p, 1), (qn, -1)):
                    if r:
                        f[r - 1] += s * x[k]
                        G[r - 1][k] += s
                        G[k][r - 1] += s
                f[k] += e(p) - e(qn)
                if kind == "L":
                    q[k] -= el[3] * x[k]
                    C[k][k] -= el[3]
            elif kind == "G":
                p, qn, (c, d, g) = el[1], el[2], el[3]
                two(f, G, p, qn, g * (e(c) - e(d)), ((c, g), (d, -g)))
            elif kind == "M":
                d, g, s, (mk, k, vt, lam, *_rest) = el[1], el[2], el[3], el[4]
                i, gd, gg, gs, _ = mosfet_eval(mk, k, vt, lam, e(d), e(g), e(s))
                two(f, G, d, s, i, ((d, gd), (g, gg), (s, gs)))
            elif kind == "D":
                a, c, (i_s, n, _, _) = el[1], el[2], el[3]
                i, gdd = self._diode(e(a) - e(c), i_s, n)
                two(f, G, a, c, i, ((a, gdd), (c, -gdd)))
        return f, G, q, C

    def sources(self, which):
        u = [0.0] * self.size
        for el in self.el:
            if el[0] == "V":
                u[self.n + el[4]] += el[3][which]
            elif el[0] == "I":
                if el[1]:
                    u[el[1] - 1] -= el[3][which]
                if el[2]:
                    u[el[2] - 1] += el[3][which]
        return u

    def noise_sources(self, x0):
        """List of (name, p, q, S) with S a function of f in A^2/Hz (one-sided)."""
        kt, out = self.kt, []

        def e(node):
            return x0[node - 1] if node else 0.0

        for idx, el in enumerate(self.el):
            if el[0] == "R" and el[4]:
                g = el[3]
                out.append((f"R{idx} thermal", el[1], el[2], lambda f, g=g: 4 * kt * g))
            elif el[0] == "M":
                d, g, s, (mk, k, vt, lam, kf, af, cox_l2) = el[1], el[2], el[3], el[4]
                i, _, _, _, gm = mosfet_eval(mk, k, vt, lam, e(d), e(g), e(s))
                out.append((f"M{idx} thermal", d, s, lambda f, gm=gm: 4 * kt * 2 / 3 * abs(gm)))
                if kf:
                    out.append((f"M{idx} flicker", d, s,
                                lambda f, a=kf * abs(i) ** af / cox_l2: a / f))
            elif el[0] == "D":
                a, c, (i_s, n, kf, af) = el[1], el[2], el[3]
                i, _ = self._diode(e(a) - e(c), i_s, n)
                out.append((f"D{idx} shot", a, c, lambda f, i=i: 2 * CHARGE * abs(i)))
                if kf:
                    out.append((f"D{idx} flicker", a, c, lambda f, b=kf * abs(i) ** af: b / f))
        return out


def dc_operating_point(net, tol=1e-12, max_iter=200):
    """Newton on f(x) = u_DC, with node voltage steps limited to 0.1 V."""
    x, u = [0.0] * net.size, net.sources(0)
    for _ in range(max_iter):
        f, G, _, _ = net.evaluate(x)
        dx = sim3dense.solve(G, [a - b for a, b in zip(u, f)])
        big = max([abs(d) for d in dx[: net.n]] + [0.0])
        scale = min(1.0, 0.1 / big) if big > 0 else 1.0
        x = [a + scale * d for a, d in zip(x, dx)]
        if scale == 1.0 and max(abs(d) for d in dx) <= tol * (1 + max(abs(v) for v in x)):
            return x
    raise NoConvergence("DC operating point")


def _injection(net, p, q):
    """KCL right side of a unit current out of p and into q."""
    a = [0.0] * net.size
    if p:
        a[p - 1] -= 1.0
    if q:
        a[q - 1] += 1.0
    return a


def noise_analysis(net, freqs, out):
    """Output noise density (V^2/Hz for a voltage output) at each frequency in Hz.

    Returns (x0, totals, contributions) where contributions[i] maps each
    source name to its share of totals[i].
    """
    x0 = dc_operating_point(net)  # @line L1
    _, G, _, C = net.evaluate(x0)
    srcs = net.noise_sources(x0)  # @line L2
    totals, parts = [], []
    for fr in freqs:  # @line L3
        w = 2 * math.pi * fr
        yt = [[complex(G[j][i], w * C[j][i]) for j in range(net.size)] for i in range(net.size)]  # @line L4
        z = sim3dense.solve(yt, [complex(o) for o in out])  # @line L5
        share = {}
        for name, p, q, s in srcs:  # @line L6
            h = (z[q - 1] if q else 0) - (z[p - 1] if p else 0)
            share[name] = abs(h) ** 2 * s(fr)
        totals.append(sum(share.values()))  # @line L7
        parts.append(share)
    return x0, totals, parts  # @line L8


def noise_direct(net, freqs, out):
    """Reference: one forward solve per noise source and frequency, then the sum."""
    x0 = dc_operating_point(net)
    _, G, _, C = net.evaluate(x0)
    srcs = net.noise_sources(x0)
    totals = []
    for fr in freqs:
        w = 2 * math.pi * fr
        y = [[complex(G[i][j], w * C[i][j]) for j in range(net.size)] for i in range(net.size)]
        tot = 0.0
        for _, p, q, s in srcs:
            xk = sim3dense.solve(y, [complex(v) for v in _injection(net, p, q)])
            tot += abs(sum(o * v for o, v in zip(out, xk))) ** 2 * s(fr)
        totals.append(tot)
    return totals


def transfer(net, freqs, out):
    """AC transfer from the AC sources to the output (for input-referred noise)."""
    x0 = dc_operating_point(net)
    _, G, _, C = net.evaluate(x0)
    b = net.sources(1)
    res = []
    for fr in freqs:
        w = 2 * math.pi * fr
        y = [[complex(G[i][j], w * C[i][j]) for j in range(net.size)] for i in range(net.size)]
        xk = sim3dense.solve(y, [complex(v) for v in b])
        res.append(sum(o * v for o, v in zip(out, xk)))
    return res


def unit(net, node):
    v = [0.0] * net.size
    v[node - 1] = 1.0
    return v
sim3dense.py 70 lines
# SPDX-License-Identifier: MIT
# Shared helper of the sim3 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra for Fraction, float or complex entries.

The circuit pages of group sim3 use this module as a reference solver and for
the small dense systems inside their tests. It holds no sparse method and no
circuit method. Matrices are lists of rows.
"""

from fractions import Fraction


class SingularMatrixError(ValueError):
    """The matrix has no inverse (a zero pivot in exact arithmetic)."""


def _exact(x):
    return Fraction(x) if isinstance(x, int) else x


def solve(a, b, tol=0.0):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    With Fraction entries the result is exact. b is a vector or a matrix
    (a list of rows); the result has the same shape.
    """
    n = len(a)
    m = [[_exact(x) for x in row] for row in a]
    vec = not (b and isinstance(b[0], list))
    rhs = [[_exact(x)] for x in b] if vec else [[_exact(x) for x in row] for row in b]
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(m[i][k]))
        if abs(m[p][k]) <= tol:
            raise SingularMatrixError(f"zero pivot in column {k}")
        m[k], m[p] = m[p], m[k]
        rhs[k], rhs[p] = rhs[p], rhs[k]
        for i in range(k + 1, n):
            if m[i][k] != 0:
                f = m[i][k] / m[k][k]
                for j in range(k, n):
                    m[i][j] -= f * m[k][j]
                for j in range(len(rhs[i])):
                    rhs[i][j] -= f * rhs[k][j]
    x = [[0] * len(rhs[0]) for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(len(rhs[0])):
            s = rhs[i][j] - sum(m[i][k] * x[k][j] for k in range(i + 1, n))
            x[i][j] = s / m[i][i]
    return [r[0] for r in x] if vec else x


def transpose(a):
    return [list(r) for r in zip(*a)]


def matvec(a, x):
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def matmul(a, b):
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def identity(n, one=1):
    return [[one if i == j else 0 * one for j in range(n)] for i in range(n)]


def inverse(a):
    return solve(a, identity(len(a)))
test_circuit_noise_analysis.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/circuit-noise-analysis/. The authors are listed in prov/P2C0RA.jsonl.

import math
import random

import sim3dense
from circuit_noise_analysis import (
    BOLTZMANN,
    CHARGE,
    Netlist,
    noise_analysis,
    noise_direct,
    transfer,
    unit,
)

KT = BOLTZMANN * 300.0

# Level-1 MOSFET: K, VT and LAM are fitted model parameters, and so are the
# flicker coefficients KF and AF. COX_L2 = Cox Leff^2 for Cox = 8.6 mF/m^2 and
# Leff = 1 um is a geometry value. These are typical teaching values.
K, VT, LAM = 200e-6, 0.5, 0.05
KF, AF, COX_L2 = 1e-28, 1.0, 8.6e-15
VDD, RD, CL, CGD, VG = 1.8, 50e3, 100e-15, 5e-15, 0.8


def cs_amp(kf=KF):
    net = Netlist(3)  # node 1 supply, 2 drain (output), 3 gate (input)
    net.vsource(1, 0, VDD)
    net.vsource(3, 0, VG, 1.0)
    net.resistor(1, 2, RD)
    net.mosfet("n", 2, 3, 0, K, VT, LAM, kf, AF, COX_L2)
    net.capacitor(3, 2, CGD)
    net.capacitor(2, 0, CL)
    return net


def test_divider_is_the_thermal_noise_of_the_parallel_resistance():
    for r1, r2 in ((1e3, 1e3), (1e3, 3e3), (47e3, 2.2e3)):
        net = Netlist(2)
        net.vsource(1, 0, 1.0)
        net.resistor(1, 2, r1)
        net.resistor(2, 0, r2)
        _, (s,), (share,) = noise_analysis(net, [1e3], unit(net, 2))
        rp = r1 * r2 / (r1 + r2)
        assert abs(s - 4 * KT * rp) < 1e-12 * s
        # each resistor contributes 4kT/R_i times (R1 || R2)^2
        assert abs(share["R1 thermal"] - 4 * KT / r1 * rp * rp) < 1e-12 * s
        assert abs(share["R2 thermal"] - 4 * KT / r2 * rp * rp) < 1e-12 * s


def test_rc_total_noise_is_kt_over_c_for_every_r():
    c = 1e-12
    for r in (1e2, 1e4, 1e6):
        net = Netlist(2)
        net.vsource(1, 0, 0.0)
        net.resistor(1, 2, r)
        net.capacitor(2, 0, c)
        fc = 1 / (2 * math.pi * r * c)
        # f = fc tan(theta) maps [0, inf) onto [0, pi/2); midpoint rule
        m = 64
        thetas = [(i + 0.5) * (math.pi / 2) / m for i in range(m)]
        _, dens, _ = noise_analysis(net, [fc * math.tan(t) for t in thetas], unit(net, 2))
        total = sum(s * fc / math.cos(t) ** 2 for s, t in zip(dens, thetas)) * (math.pi / 2) / m
        assert abs(total - KT / c) < 1e-9 * KT / c


def test_common_source_amplifier_against_hand_analysis():
    net = cs_amp()
    fs = [10 ** (k / 4) for k in range(0, 45)]
    x0, dens, parts = noise_analysis(net, fs, unit(net, 2))
    vov = VG - VT
    a = K / 2 * vov**2 * RD
    vds = (VDD - a) / (1 + a * LAM)
    assert abs(x0[1] - vds) < 1e-12
    gm = K * vov * (1 + LAM * vds)
    gds = K / 2 * vov**2 * LAM
    idd = K / 2 * vov**2 * (1 + LAM * vds)
    white = 4 * KT / RD + 8 / 3 * KT * gm
    for f, s in zip(fs, dens):
        w = 2 * math.pi * f
        z2 = 1 / abs(1 / RD + gds + 1j * w * (CL + CGD)) ** 2
        hand = (white + KF * idd ** AF / (f * COX_L2)) * z2
        assert abs(s - hand) < 1e-12 * hand
    # at the flicker corner the flicker share is one half of the device noise
    corner = KF * idd / (COX_L2 * white)
    _, (s,), (share,) = noise_analysis(net, [corner], unit(net, 2))
    assert abs(share["M3 flicker"] / s - 0.5) < 1e-12
    # input-referred white noise is the output noise over the gain squared
    _, (s,), _ = noise_analysis(cs_amp(0.0), [1e3], unit(net, 2))
    (h,) = transfer(cs_amp(0.0), [1e3], unit(net, 2))
    assert abs(s / abs(h) ** 2 - white / gm**2) < 1e-6 * white / gm**2


def test_diode_shot_noise():
    for ib in (1e-6, 1e-4, 1e-3):
        net = Netlist(1)
        net.isource(0, 1, ib)  # bias current into the anode
        net.diode(1, 0, 1e-14)  # the saturation current is a fitted value
        x0, (s,), _ = noise_analysis(net, [1e4], unit(net, 1))
        nvt = KT / CHARGE
        gd = 1e-14 * math.exp(x0[0] / nvt) / nvt
        assert abs(s - 2 * CHARGE * ib / gd**2) < 1e-9 * s
        # gd is close to ib / VT, so the density is close to 2 q VT^2 / ib
        assert abs(s / (2 * CHARGE * nvt**2 / ib) - 1) < 1e-7


def random_network(rng, n):
    net = Netlist(n)
    for _ in range(2 * n):
        p, q = rng.sample(range(n + 1), 2)
        net.resistor(p, q, rng.uniform(0.5, 10))
        net.capacitor(p, q, rng.uniform(0.1, 2))
    for i in range(1, n + 1):
        net.resistor(i, 0, 20.0)
    for _ in range(n):
        p, q, c, d = rng.sample(range(n + 1), 4)
        net.vccs(p, q, c, d, rng.uniform(-1.0, 1.0))
    p, q = rng.sample(range(1, n + 1), 2)
    net.inductor(p, q, rng.uniform(0.1, 2))
    net.vsource(1, 0, 0.0)
    return net


def test_adjoint_equals_direct_summation_on_random_networks():
    rng = random.Random(81)
    wrong = 0
    for _ in range(40):
        n = rng.randint(3, 7)
        net = random_network(rng, n)
        out = [0.0] * net.size
        out[rng.randrange(1, n)] = 1.0
        fs = [rng.uniform(0.001, 1.0) for _ in range(3)]
        _, adj, _ = noise_analysis(net, fs, out)
        ref = noise_direct(net, fs, out)
        for a, b in zip(adj, ref):
            assert abs(a - b) <= 1e-10 * b
        # solving with Y instead of its transpose gives wrong gains when Y is not symmetric
        _, G, _, C = net.evaluate([0.0] * net.size)
        w = 2 * math.pi * fs[0]
        y = [[complex(G[i][j], w * C[i][j]) for j in range(net.size)] for i in range(net.size)]
        z = sim3dense.solve(y, [complex(o) for o in out])
        bad = 0.0
        for _, p, q, s in net.noise_sources([0.0] * net.size):
            h = (z[q - 1] if q else 0) - (z[p - 1] if p else 0)
            bad += abs(h) ** 2 * s(fs[0])
        if abs(bad - ref[0]) > 1e-3 * ref[0]:
            wrong += 1
    assert wrong >= 30

History

Johnson measured the thermal noise of resistors in 1928, and Nyquist derived its density from thermodynamics in the same issue of the Physical Review. Rohrer, Nagel, Meyer and Weber (1971) gave the method of this page: one analysis of the interreciprocal adjoint network yields the transfer from every uncorrelated noise source to the output, so the work no longer grows with the number of sources. SPICE2 (Nagel, 1975) included a noise analysis, and the ngspice simulator still solves the AC system and then the adjoint system once per frequency and sums the contribution of every generator.

References

  1. Ronald Rohrer, Laurence Nagel, Robert Meyer and L. Weber, Computationally efficient electronic-circuit noise calculations, IEEE Journal of Solid-State Circuits 6(4), 204 to 213, 1971, the interreciprocal adjoint network, which gives the transfer from every noise source to the output with one analysis
  2. H. Nyquist, Thermal agitation of electric charge in conductors, Physical Review 32(1), 110 to 113, 1928, the thermal noise of a resistor from thermodynamics, the density 4kTR for the voltage
  3. J. B. Johnson, Thermal agitation of electricity in conductors, Physical Review 32(1), 97 to 109, 1928, the measurement of the thermal noise of resistors
  4. ngspice source code, src/spicelib/analysis/nevalsrc.c, the function NevalSrc, which multiplies 2 q |I| (shot noise) or 4 k T G (thermal noise) by the squared magnitude of the adjoint voltage across the source
  5. ngspice source code, src/spicelib/devices/mos1/mos1noi.c, the channel thermal noise 4 k T (2/3) |gm| and the flicker noise KF |Id|^AF / (f Cox Leff^2) of the level-1 MOSFET
  6. ngspice source code, src/spicelib/analysis/noisean.c, the frequency loop, which solves the AC system and then the adjoint system once per frequency and sums the contributions of every generator
  7. Laurence W. Nagel, SPICE2, A Computer Program to Simulate Semiconductor Circuits, Memorandum UCB/ERL M520, University of California, Berkeley, May 1975, the noise analysis of SPICE2; the section was not checked

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