Algorithm Search⌘K

Algorithmintro

AC small-signal analysis

Also called AC analysis, small-signal frequency analysis.

Linearizes the circuit at its DC operating point and solves the complex MNA system at each frequency to get gains, phases and transfer functions.

Time
O(D + F S) worst
Space
O(n^2) extra
Where
D = the cost of the DC operating point; F = the number of frequency points; S = the cost of one sparse LU factorization and solve of the complex MNA matrix; n = the number of MNA unknowns
Properties
deterministicexactiterative
Origin
Laurence W. Nagel, 1975

AC small-signal analysis computes how a circuit responds to small sinusoidal inputs at each frequency: it finds the DC operating point, replaces every device by its linearization there, and solves one complex linear system (G+jωC)X=b(G + j\omega C)X = b per frequency. It belongs to the circuit simulation half of the logic and circuit simulation sub-area, and it is the analysis behind every gain, bandwidth, phase margin and Bode plot that a circuit simulator reports. The result is exact for the linearized circuit: it is the transfer function H(s)=ℓT(G+sC)−1bH(s) = \ell^{\mathsf T}(G + sC)^{-1} b evaluated on the imaginary axis.

In plain words

An amplifier sits at a quiet bias point. Wiggle its input a tiny bit, as a sine wave, and the output wiggles too: bigger or smaller, earlier or later. AC analysis asks how much bigger and how much later, for every frequency you care about.

Because the wiggle is tiny, every transistor behaves like a fixed resistor and a fixed controlled source around its bias point, and every capacitor is just a capacitor. The circuit becomes linear. For a linear circuit, a sine wave in gives a sine wave out at the same frequency, and one complex number per frequency says everything: its size is the gain and its angle is the phase shift. So the simulator solves one set of linear equations with complex numbers per frequency, and draws the gain and phase curves from the answers.

The problem

The circuit is written 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): node voltages first, then the currents of voltage sources and inductors. The sources are DC values u0u_0 plus small AC parts. Each AC source has a phasor, a complex number AejϕA e^{j\phi} that stands for the signal Acos⁡(ωt+ϕ)A\cos(\omega t + \phi); the vector bb collects them in the rows of their sources, as the MNA stamps place the DC values. The output is a linear combination ℓTx\ell^{\mathsf T} x, usually a node voltage or a difference of two.

Input: the circuit with its device models, the AC phasors, an output vector ℓ\ell and a list of angular frequencies ω1,…,ωF\omega_1, \ldots, \omega_F. Output: H(jωk)=ℓTX(ωk)H(j\omega_k) = \ell^{\mathsf T} X(\omega_k) for each kk, usually shown as 20log⁡10∣H∣20\log_{10}|H| in dB and arg⁡H\arg H in degrees.

The device parameters are fitted, not derived: in the example the MOSFET transconductance kk, threshold VTV_T, channel-length modulation λ\lambda and the gate-drain overlap capacitance come from fits to measured devices. AC analysis uses whatever values the model card gives.

The algorithm

  1. AC(circuit, ω_1..ω_F, ℓ)
  2. 1x₀ ← the DC operating point: solve f(x) = u₀ by Newton's method
  3. 2G ← ∂f/∂x at x₀; C ← ∂q/∂x at x₀ (the small-signal model of every device)
  4. 3b ← the vector of AC phasors of the sources
  5. 4for k = 1, ..., F
  6. 5Y ← G + jω_k C
  7. 6solve Y X = b by sparse complex LU factorization
  8. 7H_k ← ℓᵀ X
  9. 8return H_1, ..., H_F

Line L2 is where the devices enter. A resistor contributes its conductance to GG and a capacitor its capacitance to CC, as in the MNA stamps. A transistor contributes its small-signal parameters at the operating point: for the level-1 MOSFET in saturation, the transconductance gm=∂ID/∂VGSg_m = \partial I_D/\partial V_{GS} and the output conductance gds=∂ID/∂VDSg_{ds} = \partial I_D/\partial V_{DS}. An inductor's row ep−eq−L dj/dt=0e_p - e_q - L\, dj/dt = 0 becomes ep−eq−jωLJ=0e_p - e_q - j\omega L J = 0, the impedance jωLj\omega L. Nonlinear capacitances contribute their derivative dq/dvdq/dv at the operating point.

The matrix YY has the same sparsity pattern at every frequency, so the fill-reducing ordering and the symbolic analysis of a sparse solver such as KLU are done once and only the numerical factorization is repeated. Frequencies are usually spaced evenly on a log scale, a fixed number per decade.

Example

RC low-pass. A 1 V AC source drives R=1R = 1 kΩ in series with C=1C = 1 nF to ground. The output node has X=1/(1+jωRC)X = 1/(1 + j\omega RC). At ω=1/(RC)=106\omega = 1/(RC) = 10^6 rad/s, X=1/(1+j)X = 1/(1 + j): ∣X∣=1/2|X| = 1/\sqrt 2, which is −3.01-3.01 dB, and the phase is −45°-45°.

A common-source amplifier. 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}} has its source at ground and its gate at a source of 0.8 V DC with AC phasor 1. A resistor RD=50R_D = 50 kΩ connects the drain to VDD=1.8V_{DD} = 1.8 V; a load CL=100C_L = 100 fF goes from the drain to ground, and an overlap capacitance Cgd=5C_{gd} = 5 fF from the gate to the drain.

Operating point. In saturation k2Vov2(1+λVDS)RD=VDD−VDS\frac{k}{2} V_{ov}^2 (1 + \lambda V_{DS}) R_D = V_{DD} - V_{DS} with Vov=0.3V_{ov} = 0.3 V, so VDS=(1.8−0.45)/(1+0.45⋅0.05)=1.3203V_{DS} = (1.8 - 0.45)/(1 + 0.45 \cdot 0.05) = 1.3203 V, above VovV_{ov} as saturation requires.

Small-signal model. gm=kVov(1+λVDS)=63.96 μg_m = k V_{ov}(1 + \lambda V_{DS}) = 63.96\ \muS and gds=k2Vov2λ=0.45 μg_{ds} = \frac{k}{2} V_{ov}^2 \lambda = 0.45\ \muS.

Transfer function. KCL at the drain gives

H(jω)=−(gm−jωCgd)1/RD+gds+jω(CL+Cgd).H(j\omega) = \frac{-(g_m - j\omega C_{gd})}{1/R_D + g_{ds} + j\omega (C_L + C_{gd})}.

The DC gain is −gm/(1/RD+gds)=−3.128-g_m/(1/R_D + g_{ds}) = -3.128, or 9.90 dB with a phase of 180°180°. The pole is at (1/RD+gds)/(2π(CL+Cgd))=31.0(1/R_D + g_{ds})/(2\pi (C_L + C_{gd})) = 31.0 MHz, the right half plane zero at gm/(2πCgd)=2.04g_m/(2\pi C_{gd}) = 2.04 GHz, and at high frequency the gain tends to Cgd/(CL+Cgd)=0.048C_{gd}/(C_L + C_{gd}) = 0.048 (−26.44-26.44 dB), the signal that the overlap capacitance carries past the transistor. The AC analysis of the implementation gives:

frequency gain (dB) phase (degrees)
100 kHz 9.904 179.81
1 MHz 9.900 178.12
10 MHz 9.475 161.84
100 MHz −0.657-0.657 104.41
1 GHz −19.335-19.335 65.62
10 GHz −26.268-26.268 11.69
100 GHz −26.443-26.443 1.18

The gain crosses 0 dB at 92.0 MHz, found by bisection on the AC result. The test checks every point of a sweep with four points per decade from 1 kHz to 100 GHz against the formula above to a relative error of 10−1210^{-12}.

Correctness

The proof in proofs/correctness.md shows the following. Write the small-signal circuit as Gy+Cy˙=β(t)Gy + C\dot y = \beta(t), the first-order term in the amplitude of the response of the nonlinear circuit.

  1. If G+jωCG + j\omega C is nonsingular, Re⁡(Xejωt)\operatorname{Re}(X e^{j\omega t}) with (G+jωC)X=b(G + j\omega C)X = b solves the small-signal circuit for the input Re⁡(bejωt)\operatorname{Re}(b e^{j\omega t}) exactly, and it is the only solution of that form.
  2. If every root of det⁡(G+sC)=0\det(G + sC) = 0 (the poles) has a negative real part, every solution tends to this one: it is the sinusoidal steady state. The proof uses the Weierstrass canonical form, cited.
  3. ℓT(G+sC)−1b\ell^{\mathsf T}(G + sC)^{-1}b is the Laplace transfer function of the small-signal circuit, so AC analysis evaluates it at s=jωs = j\omega.
  4. At ω=0\omega = 0, H(0)H(0) is the derivative of the DC output with respect to the DC value of the source.

The step from the nonlinear circuit to the small-signal circuit is the approximation; it is measured, not proved. The tests check:

  • The RC and series RLC hand formulas.
  • 30 random RC networks (seed 72) against a nodal admittance matrix built independently.
  • The amplifier formula above.
  • H(0)H(0) against a central difference of two DC solves with a step of 1 µV, to a relative error below 10−710^{-7}.
  • A transient simulation of the amplifier with the input amplitude scaled by ε\varepsilon, at 31 MHz, with the trapezoidal rule for eight periods. The complex amplitude of the output's fundamental in the last period, divided by ε\varepsilon, matches the AC result to 5.9×10−55.9 \times 10^{-5} with 200 steps per period, and to 2.4×10−42.4 \times 10^{-4} with 100 steps, so this part of the error is the second-order error of the integration. The nonlinear part, the change of that amplitude from ε=10−4\varepsilon = 10^{-4} to ε=10−3\varepsilon = 10^{-3} and to 10−210^{-2}, grows by a factor of about 100 for a tenfold ε\varepsilon, as ε2\varepsilon^2.
Proof: AC analysis gives the exact sinusoidal steady state of the linearized circuitfull

We use the notation of the page. The circuit is f(x)+ddtq(x)=u(t)f(x) + \frac{d}{dt} q(x) = u(t) in MNA form, x0x_0 is a DC operating point (f(x0)=u0f(x_0) = u_0), and G=∂f/∂x(x0)G = \partial f/\partial x(x_0), C=∂q/∂x(x0)C = \partial q/\partial x(x_0) are the real N×NN \times N matrices of the small-signal model. The AC sources are the complex vector bb: entry kk of bb is the phasor AejϕA e^{j\phi} of the source in row kk, meaning the time signal Re⁡(Aejϕejωt)=Acos⁡(ωt+ϕ)\operatorname{Re}(A e^{j\phi} e^{j\omega t}) = A\cos(\omega t + \phi). AC analysis computes X(ω)=(G+jωC)−1bX(\omega) = (G + j\omega C)^{-1} b and an output H(jω)=ℓTX(ω)H(j\omega) = \ell^{\mathsf T} X(\omega).

The linearized circuit. If the sources are u0+ε β(t)u_0 + \varepsilon\, \beta(t) and the solution x(t,ε)x(t, \varepsilon) that starts at x0x_0 is differentiable in ε\varepsilon, then y=∂x/∂εy = \partial x/\partial \varepsilon at ε=0\varepsilon = 0 satisfies

Gy+Cy˙=β(t),y(0)=0.(1)G y + C \dot y = \beta(t), \qquad y(0) = 0. \tag{1}

Derivation. Differentiate f(x)+ddtq(x)=u0+εβf(x) + \frac{d}{dt} q(x) = u_0 + \varepsilon \beta in ε\varepsilon: ∂f∂x(x) y+ddt(∂q∂x(x) y)=β\frac{\partial f}{\partial x}(x)\, y + \frac{d}{dt}\big(\frac{\partial q}{\partial x}(x)\, y\big) = \beta, and at ε=0\varepsilon = 0 the solution is the constant x0x_0, so the Jacobians are the constants GG and CC. □\square

So x(t,ε)=x0+εy(t)+O(ε2)x(t, \varepsilon) = x_0 + \varepsilon y(t) + O(\varepsilon^2) on a bounded time interval: (1) is the small-signal model. Differentiability in ε\varepsilon holds for smooth ff and qq and an index-1 DAE by the standard dependence of solutions on parameters (see the DAE texts cited on the page); it is assumed here. Everything below is exact for (1).

Theorem 1 (the phasor solution). If Y=G+jωCY = G + j\omega C is nonsingular and YX=bYX = b, then xp(t)=Re⁡(Xejωt)x_p(t) = \operatorname{Re}(X e^{j\omega t}) solves

Gx+Cx˙=Re⁡(b ejωt)(2)G x + C \dot x = \operatorname{Re}(b\, e^{j\omega t}) \tag{2}

for all tt, and it is the only solution of the form Re⁡(Zejωt)\operatorname{Re}(Z e^{j\omega t}) with a constant complex vector ZZ.

Proof. GG and CC are real, so Re⁡\operatorname{Re} commutes with them, and ddtRe⁡(Xejωt)=Re⁡(jωXejωt)\frac{d}{dt} \operatorname{Re}(X e^{j\omega t}) = \operatorname{Re}(j\omega X e^{j\omega t}). So

Gxp+Cx˙p=Re⁡((G+jωC)Xejωt)=Re⁡(b ejωt).G x_p + C \dot x_p = \operatorname{Re}\big((G + j\omega C) X e^{j\omega t}\big) = \operatorname{Re}(b\, e^{j\omega t}).

For uniqueness, suppose Re⁡(Zejωt)\operatorname{Re}(Z e^{j\omega t}) solves (2), and let W=YZ−bW = Y Z - b. Then Re⁡(Wejωt)=0\operatorname{Re}(W e^{j\omega t}) = 0 for all tt. At t=0t = 0 this gives Re⁡W=0\operatorname{Re} W = 0, and at ωt=π/2\omega t = \pi/2 (if ω>0\omega > 0) it gives Re⁡(jW)=−Im⁡W=0\operatorname{Re}(jW) = -\operatorname{Im} W = 0, so W=0W = 0 and Z=Y−1b=XZ = Y^{-1} b = X. For ω=0\omega = 0 the form is the constant Re⁡Z\operatorname{Re} Z, and only Re⁡Z\operatorname{Re} Z is determined; it equals G−1Re⁡bG^{-1} \operatorname{Re} b. □\square

By linearity, several sources at the same frequency with phasors b1,b2,…b_1, b_2, \ldots give X=Y−1(b1+b2+⋯ )X = Y^{-1}(b_1 + b_2 + \cdots), and the transfer function from one source to the output is ℓTY−1bk\ell^{\mathsf T} Y^{-1} b_k.

Theorem 2 (it is the steady state). Suppose the pencil is regular, det⁡(G+sC)≢0\det(G + sC) \not\equiv 0, and every root ss of det⁡(G+sC)=0\det(G + sC) = 0 has Re⁡s<0\operatorname{Re} s < 0. Then G+jωCG + j\omega C is nonsingular for every real ω\omega, and every solution of (2) with consistent initial values tends to xpx_p as t→∞t \to \infty.

Proof. The roots of det⁡(G+sC)\det(G + sC) are not on the imaginary axis, so YY is nonsingular. The difference d=x−xpd = x - x_p solves Gd+Cd˙=0G d + C \dot d = 0. For a regular pencil there are nonsingular PP, QQ (the Weierstrass canonical form; see Brenan, Campbell and Petzold, Chapter 2) with

PCQ=(I00M),PGQ=(J00I),P C Q = \begin{pmatrix} I & 0 \\ 0 & M \end{pmatrix}, \qquad P G Q = \begin{pmatrix} J & 0 \\ 0 & I \end{pmatrix},

where MM is nilpotent, Mν=0M^\nu = 0. With d=Q(w1,w2)d = Q (w_1, w_2), the system splits into w˙1+Jw1=0\dot w_1 + J w_1 = 0 and Mw˙2+w2=0M \dot w_2 + w_2 = 0. The second gives w2=−Mw˙2=M2w¨2=⋯=(−M)νw2(ν)=0w_2 = -M \dot w_2 = M^2 \ddot w_2 = \cdots = (-M)^\nu w_2^{(\nu)} = 0. The first gives w1(t)=e−Jtw1(0)w_1(t) = e^{-Jt} w_1(0), and det⁡(G+sC)=det⁡(P)−1det⁡(Q)−1det⁡(J+sI)det⁡(I+sM)\det(G + sC) = \det(P)^{-1} \det(Q)^{-1} \det(J + sI) \det(I + sM) with det⁡(I+sM)=1\det(I + sM) = 1, so the eigenvalues of −J-J are exactly the roots ss, all with negative real part, and w1→0w_1 \to 0. □\square

The roots of det⁡(G+sC)\det(G + sC) are the natural frequencies (poles) of the linearized circuit. A passive circuit of positive resistors, capacitors and inductors has no roots in the open right half plane, but a lossless LC loop puts roots on the imaginary axis, where YY is singular at the resonance. An amplifier with feedback may have roots in the right half plane; AC analysis then still returns XX (Theorem 1), but the sinusoidal response is not what a transient simulation settles to.

Theorem 3 (the transfer function). For the Laplace transforms of (1) with y(0)=0y(0) = 0 and β(t)=b v(t)\beta(t) = b\, v(t) for a scalar input vv, the output is ℓTy^(s)=H(s)v^(s)\ell^{\mathsf T} \hat y(s) = H(s) \hat v(s) with H(s)=ℓT(G+sC)−1bH(s) = \ell^{\mathsf T} (G + sC)^{-1} b, and AC analysis evaluates HH on the imaginary axis, s=jωs = j\omega.

Proof. The transform of Cy˙C\dot y is sCy^−Cy(0)=sCy^sC\hat y - C y(0) = sC\hat y, so (G+sC)y^=b v^(G + sC)\hat y = b\, \hat v, and H(s)H(s) is defined wherever G+sCG + sC is nonsingular. □\square

Theorem 4 (zero frequency). If GG is nonsingular, H(0)=ℓTG−1bH(0) = \ell^{\mathsf T} G^{-1} b is the derivative of the DC output ℓTxDC(σ)\ell^{\mathsf T} x_{\mathrm{DC}}(\sigma) with respect to σ\sigma, where xDC(σ)x_{\mathrm{DC}}(\sigma) is the operating point for the DC sources u0+σbu_0 + \sigma b (real bb).

Proof. The operating point solves f(x)=u0+σbf(x) = u_0 + \sigma b. Its Jacobian in xx at σ=0\sigma = 0 is GG, which is nonsingular, so by the implicit function theorem xDCx_{\mathrm{DC}} is differentiable near σ=0\sigma = 0 with G xDC′(0)=bG\, x_{\mathrm{DC}}'(0) = b. □\square

Summary. AC analysis is exact for the linearized circuit (1): Theorem 1 gives the unique sinusoidal solution, Theorem 2 shows it is the steady state when the linearized circuit is stable, and Theorem 3 identifies it with the transfer function. The approximation is in (1) itself, the first-order term in the amplitude ε\varepsilon; the test on the page measures that the fundamental of a transient simulation of the nonlinear circuit departs from the AC result by an amount that grows like ε2\varepsilon^2.

Complexity

The DC operating point is computed once. Each frequency then costs one factorization and one solve of an n×nn \times n complex sparse matrix, FF of them in all. The sparsity pattern of G+jωCG + j\omega C is the union of those of GG and CC and does not depend on ω\omega, so the ordering is computed once. The cost SS of one factorization depends on the fill-in, as in the Gilbert-Peierls analysis. The frequencies are independent and can be solved in parallel. The implementation uses dense complex Gaussian elimination, O(n3)O(n^3) per frequency, which is the reference method for small circuits.

Properties

  • Exact for the linear model. No time stepping and no truncation error: the result is the transfer function of the linearized circuit up to rounding.
  • Linear in the AC sources. Doubling every phasor doubles the result, so the source magnitude is a convention; 1 V or 1 A gives the transfer function directly.
  • Local. The model holds near one operating point. Distortion, clipping and slewing are outside it.
  • Independent frequencies. Any frequency grid can be used, and points can be added near a resonance.

Variants and improvements

  • Noise analysis. Propagate the noise sources of all devices to the output; with the adjoint system, one transposed solve per frequency serves every source: small-signal noise analysis.
  • Sensitivity. The derivative of H(jω)H(j\omega) with respect to every element value, again with one adjoint solve per frequency: adjoint sensitivity analysis.
  • Pole-zero analysis and model order reduction. Instead of sampling HH on a grid, compute its poles and zeros, or a reduced model that matches its moments: Padé via Lanczos.
  • Periodic small-signal analysis. Linearize around a periodic steady state found by harmonic balance or shooting instead of a DC point, for mixers and sampled circuits.
  • DC transfer function. The ω=0\omega = 0 case alone gives small-signal DC gains and input and output resistances.

When to use it

Use AC analysis for the gain, bandwidth, phase margin, input and output impedance and frequency response of any circuit that works around a fixed bias point: amplifiers, filters, regulators and their feedback loops. Use transient analysis or harmonic balance when signals are large, when the circuit switches, or when distortion matters.

Pitfalls

  • The wrong operating point. Every result depends on x0x_0. A circuit with several DC solutions, such as a latch, or a bias point that a DC solver reached with the wrong device in saturation, gives a correct analysis of the wrong circuit.
  • Small means small. The response is exact only in the limit of zero amplitude. A 1 V AC source on a transistor gate does not produce 1 V of real signal; it only scales the transfer function.
  • Unstable circuits. If the linearized circuit has poles in the right half plane, AC analysis still returns finite numbers, but no steady state exists. Check the poles or a transient run.
  • Singular at resonance. A lossless LC loop makes G+jωCG + j\omega C singular at its resonance frequency.
  • A coarse grid. A sharp resonance can fall between frequency points and be missed. Refine the grid where the phase changes fast.
  • Fitted parameters. The gain depends on gmg_m and gdsg_{ds}, which come from fitted model parameters. The output conductance in particular is often poorly fitted by simple models.

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.

ac_small_signal_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ac-small-signal-analysis/. The authors are listed in prov/ZS7YDS.jsonl.
"""AC small-signal analysis on modified nodal analysis (MNA) equations.

The circuit equations are f(x) + d/dt q(x) = u(t), with x = (e_1..e_n, j_1..j_m):
node voltages first (node 0 is ground), then the currents of voltage sources
and inductors. AC analysis finds the DC operating point x0, linearizes there
(G = df/dx, C = dq/dx) and solves (G + j w C) X = b at each frequency.
"""

import cmath
import math

import sim3dense


class NoConvergence(RuntimeError):
    pass


def mos_current(kind, k, vt, lam, vd, vg, vs):
    """Level-1 (Shichman-Hodges) channel current from d to s and its partials in (vd, vg, vs).

    k, vt and lam are fitted model parameters. For a p device vt is the
    magnitude of the threshold.
    """
    if kind == "p":
        i, gd, gg, gs = mos_current("n", k, vt, lam, -vd, -vg, -vs)
        return -i, gd, gg, gs
    if vd < vs:
        i, gd, gg, gs = mos_current("n", k, vt, lam, vs, vg, vd)
        return -i, -gs, -gg, -gd
    vov, vds = vg - vs - vt, vd - vs
    if vov <= 0:
        return 0.0, 0.0, 0.0, 0.0
    if vds < vov:
        a = vov * vds - vds * vds / 2
        i = k * a * (1 + lam * vds)
        gm = k * vds * (1 + lam * vds)
        gds = k * (vov - vds) * (1 + lam * vds) + k * a * lam
    else:
        i = k / 2 * vov * vov * (1 + lam * vds)
        gm = k * vov * (1 + lam * vds)
        gds = k / 2 * vov * vov * lam
    return i, gds, gm, -gds - gm


class Netlist:
    """Elements between nodes; node 0 is ground. Stamps follow the MNA page."""

    def __init__(self, nodes):
        self.n = nodes  # nodes 1..n are unknown
        self.m = 0  # branch currents
        self.el = []

    def _branch(self):
        self.m += 1
        return self.m - 1

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

    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._branch()))

    def vsource(self, p, q, dc=0.0, ac=0.0):
        """Voltage source e_p - e_q = dc (+ the phasor ac in AC analysis)."""
        self.el.append(("V", p, q, (dc, ac), self._branch()))
        return self.m - 1

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

    def vccs(self, p, q, c, d, g):
        self.el.append(("G", p, q, c, d, g))

    def mosfet(self, kind, d, g, s, k, vt, lam):
        self.el.append(("M", d, g, s, (kind, k, vt, lam)))

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

    def _row(self, node):
        return node - 1  # ground (0) gives -1 and is dropped

    def evaluate(self, x):
        """Return 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 add(vec, r, val):
            if r >= 0:
                vec[r] += val

        def addm(mat, r, c, val):
            if r >= 0 and c >= 0:
                mat[r][c] += val

        for el in self.el:
            kind = el[0]
            if kind in "RC":
                _, p, qn, val = el
                rp, rq = self._row(p), self._row(qn)
                vec, mat = (f, G) if kind == "R" else (q, C)
                add(vec, rp, val * (e(p) - e(qn)))
                add(vec, rq, -val * (e(p) - e(qn)))
                for r, s1 in ((rp, 1), (rq, -1)):
                    addm(mat, r, rp, s1 * val)
                    addm(mat, r, rq, -s1 * val)
            elif kind in "LV":
                p, qn, k = el[1], el[2], self.n + el[4]
                rp, rq = self._row(p), self._row(qn)
                add(f, rp, x[k])
                add(f, rq, -x[k])
                addm(G, rp, k, 1.0)
                addm(G, rq, k, -1.0)
                f[k] += e(p) - e(qn)
                addm(G, k, rp, 1.0)
                addm(G, k, rq, -1.0)
                if kind == "L":
                    q[k] -= el[3] * x[k]
                    C[k][k] -= el[3]
            elif kind == "G":
                _, p, qn, c, d, g = el
                cur = g * (e(c) - e(d))
                for r, s1 in ((self._row(p), 1), (self._row(qn), -1)):
                    add(f, r, s1 * cur)
                    addm(G, r, self._row(c), s1 * g)
                    addm(G, r, self._row(d), -s1 * g)
            elif kind == "M":
                _, d, g, s, (mk, k, vt, lam) = el
                i, gd, gg, gs = mos_current(mk, k, vt, lam, e(d), e(g), e(s))
                for r, s1 in ((self._row(d), 1), (self._row(s), -1)):
                    add(f, r, s1 * i)
                    addm(G, r, self._row(d), s1 * gd)
                    addm(G, r, self._row(g), s1 * gg)
                    addm(G, r, self._row(s), s1 * gs)
        return f, G, q, C

    def sources(self, which):
        """The source vector u (which = 0 for DC values, 1 for AC phasors)."""
        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":
                rp, rq = self._row(el[1]), self._row(el[2])
                if rp >= 0:
                    u[rp] -= el[3][which]
                if rq >= 0:
                    u[rq] += el[3][which]
        return u


def dc_operating_point(net, x0=None, tol=1e-12, max_iter=100):
    """Newton on f(x) = u_DC with a step limit of 0.5 V per iteration."""
    x = list(x0) if x0 else [0.0] * net.size
    u = net.sources(0)
    for _ in range(max_iter):
        f, G, _, _ = net.evaluate(x)
        dx = sim3dense.solve(G, [ui - fi for ui, fi in zip(u, f)])
        big = max(abs(d) for d in dx[: net.n]) if net.n else 0.0
        scale = min(1.0, 0.5 / big) if big > 0 else 1.0
        x = [xi + scale * di for xi, di in zip(x, dx)]
        if max(abs(d) for d in dx) <= tol * (1 + max(abs(v) for v in x)):
            return x
    raise NoConvergence("DC operating point")


def ac_analysis(net, omegas, out):
    """Transfer function out^T X(w) for each angular frequency w.

    out is a vector over the unknowns (for example a unit vector on the
    output node). Returns (x0, list of complex values H(j w)).
    """
    x0 = dc_operating_point(net)  # @line L1
    _, G, _, C = net.evaluate(x0)  # @line L2
    b = net.sources(1)  # @line L3
    result = []
    for w in omegas:  # @line L4
        Y = [[complex(G[i][j], w * C[i][j]) for j in range(net.size)] for i in range(net.size)]  # @line L5
        X = sim3dense.solve(Y, [complex(v) for v in b])  # @line L6
        result.append(sum(o * xi for o, xi in zip(out, X)))  # @line L7
    return x0, result  # @line L8


def decade_sweep(f_start, f_stop, per_decade):
    """Angular frequencies spaced evenly in log scale, per_decade points per decade."""
    n = round(per_decade * math.log10(f_stop / f_start))
    return [2 * math.pi * f_start * 10 ** (k / per_decade) for k in range(n + 1)]


def bode(h):
    """Magnitude in dB and phase in degrees of a complex value."""
    return 20 * math.log10(abs(h)), math.degrees(cmath.phase(h))


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_ac_small_signal_analysis.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ac-small-signal-analysis/. The authors are listed in prov/ZS7YDS.jsonl.

import cmath
import math
import random

import sim3dense
from ac_small_signal_analysis import (
    Netlist,
    ac_analysis,
    bode,
    dc_operating_point,
    decade_sweep,
    unit,
)

# Level-1 MOSFET parameters: K (transconductance), VT (threshold) and LAM
# (channel-length modulation) are fitted model parameters, as is the overlap
# capacitance CGD; these are typical teaching values.
K, VT, LAM = 200e-6, 0.5, 0.05
VDD, RD, CL, CGD, VG = 1.8, 50e3, 100e-15, 5e-15, 0.8


def cs_amp(vg=VG):
    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)
    net.capacitor(3, 2, CGD)
    net.capacitor(2, 0, CL)
    return net


def test_rc_lowpass():
    r, c = 1e3, 1e-9
    net = Netlist(2)
    net.vsource(1, 0, 0.0, 1.0)
    net.resistor(1, 2, r)
    net.capacitor(2, 0, c)
    ws = decade_sweep(1.0, 1e9, 5)
    assert len(ws) == 46
    _, H = ac_analysis(net, ws, unit(net, 2))
    for w, h in zip(ws, H):
        assert abs(h - 1 / (1 + 1j * w * r * c)) < 1e-12
    _, (h,) = ac_analysis(net, [1 / (r * c)], unit(net, 2))
    db, ph = bode(h)
    assert abs(db + 10 * math.log10(2)) < 1e-9 and abs(ph + 45) < 1e-9


def series_rlc(r, l, c):
    net = Netlist(3)
    net.vsource(1, 0, 0.0, 1.0)
    net.resistor(1, 2, r)
    net.inductor(2, 3, l)
    net.capacitor(3, 0, c)
    return net


def test_series_rlc_and_the_time_domain_identity():
    r, l, c = 10.0, 1e-6, 1e-9
    net = series_rlc(r, l, c)
    w0 = 1 / math.sqrt(l * c)
    ws = [w0 * 10 ** (k / 10) for k in range(-20, 21)]
    _, H = ac_analysis(net, ws, unit(net, 3))
    for w, h in zip(ws, H):
        assert abs(h - 1 / (1 - w * w * l * c + 1j * w * r * c)) < 1e-9 * abs(h)
    # at resonance the gain is the quality factor (1/R) sqrt(L/C)
    assert abs(abs(H[20]) - math.sqrt(l / c) / r) < 1e-9
    # Re(X e^{jwt}) solves G x + C x' = Re(b e^{jwt}) at every t
    x0 = dc_operating_point(net)
    _, G, _, C = net.evaluate(x0)
    b = net.sources(1)
    w = 0.7 * w0
    Y = [[G[i][j] + 1j * w * C[i][j] for j in range(5)] for i in range(5)]
    X = sim3dense.solve(Y, [complex(v) for v in b])
    rng = random.Random(71)
    for _ in range(20):
        t = rng.uniform(0, 10 / w)
        x = [(xi * cmath.exp(1j * w * t)).real for xi in X]
        dx = [(1j * w * xi * cmath.exp(1j * w * t)).real for xi in X]
        lhs = [sum(G[i][j] * x[j] + C[i][j] * dx[j] for j in range(5)) for i in range(5)]
        rhs = [(bi * cmath.exp(1j * w * t)).real for bi in b]
        assert max(abs(p - q) for p, q in zip(lhs, rhs)) < 1e-9


def test_common_source_amplifier_against_hand_analysis():
    net = cs_amp()
    ws = decade_sweep(1e3, 1e11, 4)
    x0, H = ac_analysis(net, ws, unit(net, 2))
    # DC point in closed form: (K/2) vov^2 (1 + LAM vds) RD = VDD - vds
    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
    for w, h in zip(ws, H):
        hand = -(gm - 1j * w * CGD) / (1 / RD + gds + 1j * w * (CL + CGD))
        assert abs(h - hand) < 1e-12 * abs(hand)
    assert abs(H[0] + gm / (1 / RD + gds)) < 2e-4  # at 1 kHz, far below the pole
    assert abs(H[-1] - CGD / (CL + CGD)) < 1e-3  # feedthrough of the gate-drain capacitance


def test_zero_frequency_is_the_dc_gain():
    _, (h0,) = ac_analysis(cs_amp(), [0.0], unit(cs_amp(), 2))
    d = 1e-6
    fd = (dc_operating_point(cs_amp(VG + d))[1] - dc_operating_point(cs_amp(VG - d))[1]) / (2 * d)
    assert abs(h0.imag) == 0
    assert abs(h0.real - fd) < 1e-7 * abs(fd)


def test_random_rc_networks_against_nodal_admittance():
    rng = random.Random(72)
    for _ in range(30):
        n = rng.randint(2, 7)
        net = Netlist(n)
        Y = lambda w: [[0j] * n for _ in range(n)]
        edges = []
        for _ in range(2 * n):
            p, q = rng.sample(range(n + 1), 2)
            g, c = rng.uniform(0.1, 2), rng.uniform(0.1, 2)
            net.resistor(p, q, 1 / g)
            net.capacitor(p, q, c)
            edges.append((p, q, g, c))
        for i in range(1, n + 1):
            net.resistor(i, 0, 10.0)
            edges.append((i, 0, 0.1, 0.0))
        net.isource(0, 1, 0.0, 1.0)  # inject 1 A (phasor) into node 1
        w = rng.uniform(0.1, 10)
        Ym = Y(w)
        for p, q, g, c in edges:
            y = g + 1j * w * c
            for a, b2, s in ((p, p, 1), (q, q, 1), (p, q, -1), (q, p, -1)):
                if a and b2:
                    Ym[a - 1][b2 - 1] += s * y
        inj = [0j] * n
        inj[0] = 1
        ref = sim3dense.solve(Ym, inj)
        for node in range(1, n + 1):
            _, (h,) = ac_analysis(net, [w], unit(net, node))
            assert abs(h - ref[node - 1]) < 1e-10 * (1 + abs(ref[node - 1]))


def transient_fundamental(net, x0, eps, w, periods, m):
    """Trapezoidal transient with the AC sources scaled by eps cos(wt); the
    complex amplitude of the output's fundamental over the last period, over eps."""
    b, u0 = net.sources(1), net.sources(0)
    h = 2 * math.pi / w / m

    def u(t):
        return [a + eps * bb * math.cos(w * t) for a, bb in zip(u0, b)]

    x = list(x0)
    f, _, q, _ = net.evaluate(x)
    acc = 0j
    for k in range(periods * m):
        un, un1 = u(k * h), u((k + 1) * h)
        y = list(x)
        for _ in range(30):
            f1, g1, q1, c1 = net.evaluate(y)
            r = [q1[i] - q[i] + h / 2 * (f1[i] - un1[i] + f[i] - un[i]) for i in range(len(y))]
            jac = [[c1[i][j] + h / 2 * g1[i][j] for j in range(len(y))] for i in range(len(y))]
            dy = sim3dense.solve(jac, [-v for v in r])
            y = [a + d for a, d in zip(y, dy)]
            if max(abs(d) for d in dy) < 1e-13:
                break
        x = y
        f, _, q, _ = net.evaluate(x)
        if k + 1 > (periods - 1) * m:
            acc += x[1] * cmath.exp(-1j * w * (k + 1) * h)
    return 2 * acc / m / eps


def test_small_sinusoid_transient_matches_ac():
    net = cs_amp()
    w = 2 * math.pi * 31e6  # near the pole
    x0, (H,) = ac_analysis(net, [w], unit(net, 2))
    e100 = abs(transient_fundamental(net, x0, 1e-3, w, 8, 100) - H) / abs(H)
    t4 = transient_fundamental(net, x0, 1e-4, w, 8, 200)
    t3 = transient_fundamental(net, x0, 1e-3, w, 8, 200)
    t2 = transient_fundamental(net, x0, 1e-2, w, 8, 200)
    e200 = abs(t3 - H) / abs(H)
    assert e200 < 1e-4
    assert 3.5 < e100 / e200 < 4.5  # the trapezoidal error, second order in the step
    # the nonlinear part of the response grows like the square of the amplitude
    d3, d2 = abs(t3 - t4) / abs(H), abs(t2 - t4) / abs(H)
    assert 60 < d2 / d3 < 140

History

SPICE2 (Nagel, 1975) offered small-signal AC analysis next to DC and transient analysis. It linearized the device models at the DC operating point, as in line L2, and solved the complex nodal equations at each frequency of a linear, decade or octave sweep. The modified nodal formulation of Ho, Ruehli and Brennan (1975) is the form that SPICE and most later simulators solve, in the frequency domain as in the time domain.

References

  1. Laurence W. Nagel, SPICE2, A Computer Program to Simulate Semiconductor Circuits, Memorandum UCB/ERL M520, University of California, Berkeley, May 1975, the small-signal AC analysis (linearized device models at the operating point and the complex nodal solve at each frequency)
  2. Chung-Wen Ho, Albert E. Ruehli and Pierce A. Brennan, The modified nodal approach to network analysis, IEEE Transactions on Circuits and Systems 22(6), 504 to 509, 1975, the modified nodal formulation, which holds in the frequency domain with complex admittances
  3. Jiri Vlach and Kishore Singhal, Computer Methods for Circuit Analysis and Design, second edition, Van Nostrand Reinhold, 1994, the chapters on frequency-domain analysis of linear networks and on small-signal models of nonlinear devices; the chapter numbers were not checked
  4. K. E. Brenan, S. L. Campbell and L. R. Petzold, Numerical Solution of Initial-Value Problems in Differential-Algebraic Equations, SIAM Classics in Applied Mathematics 14, 1996, Chapter 2, linear constant-coefficient systems and the Weierstrass (Kronecker) canonical form of a regular pencil
  5. Harold Shichman and David A. Hodges, Modeling and simulation of insulated-gate field-effect transistor switching circuits, IEEE Journal of Solid-State Circuits 3(3), 285 to 289, 1968, the square-law MOSFET model of the amplifier example

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