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
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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 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, , with : node voltages first, then the currents of voltage sources and inductors. The sources are DC values plus small AC parts. Each AC source has a phasor, a complex number that stands for the signal ; the vector collects them in the rows of their sources, as the MNA stamps place the DC values. The output is a linear combination , usually a node voltage or a difference of two.
Input: the circuit with its device models, the AC phasors, an output vector and a list of angular frequencies . Output: for each , usually shown as in dB and in degrees.
The device parameters are fitted, not derived: in the example the MOSFET transconductance , threshold , channel-length modulation and the gate-drain overlap capacitance come from fits to measured devices. AC analysis uses whatever values the model card gives.
The algorithm
AC(circuit, ω_1..ω_F, ℓ)- 1
x₀ ← the DC operating point: solve f(x) = u₀ by Newton's method - 2
G ← ∂f/∂x at x₀; C ← ∂q/∂x at x₀ (the small-signal model of every device) - 3
b ← the vector of AC phasors of the sources - 4
for k = 1, ..., F - 5
Y ← G + jω_k C - 6
solve Y X = b by sparse complex LU factorization - 7
H_k ← ℓᵀ X - 8
return H_1, ..., H_F
Line L2 is where the devices enter. A resistor contributes its conductance to and a capacitor its capacitance to , 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 and the output conductance . An inductor's row becomes , the impedance . Nonlinear capacitances contribute their derivative at the operating point.
The matrix 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 kΩ in series with nF to ground. The output node has . At rad/s, : , which is dB, and the phase is .
A common-source amplifier. An n-channel MOSFET with , V and has its source at ground and its gate at a source of 0.8 V DC with AC phasor 1. A resistor kΩ connects the drain to V; a load fF goes from the drain to ground, and an overlap capacitance fF from the gate to the drain.
Operating point. In saturation with V, so V, above as saturation requires.
Small-signal model. S and S.
Transfer function. KCL at the drain gives
The DC gain is , or 9.90 dB with a phase of . The pole is at MHz, the right half plane zero at GHz, and at high frequency the gain tends to ( 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 | 104.41 | |
| 1 GHz | 65.62 | |
| 10 GHz | 11.69 | |
| 100 GHz | 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 .
Correctness
The proof in proofs/correctness.md shows the following. Write the small-signal circuit as , the first-order term in the amplitude of the response of the nonlinear circuit.
- If is nonsingular, with solves the small-signal circuit for the input exactly, and it is the only solution of that form.
- If every root of (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.
- is the Laplace transfer function of the small-signal circuit, so AC analysis evaluates it at .
- At , 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.
- against a central difference of two DC solves with a step of 1 µV, to a relative error below .
- A transient simulation of the amplifier with the input amplitude scaled by , at 31 MHz, with the trapezoidal rule for eight periods. The complex amplitude of the output's fundamental in the last period, divided by , matches the AC result to with 200 steps per period, and to 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 to and to , grows by a factor of about 100 for a tenfold , as .
Proof: AC analysis gives the exact sinusoidal steady state of the linearized circuitfull
We use the notation of the page. The circuit is in MNA form, is a DC operating point (), and , are the real matrices of the small-signal model. The AC sources are the complex vector : entry of is the phasor of the source in row , meaning the time signal . AC analysis computes and an output .
The linearized circuit. If the sources are and the solution that starts at is differentiable in , then at satisfies
Derivation. Differentiate in : , and at the solution is the constant , so the Jacobians are the constants and .
So on a bounded time interval: (1) is the small-signal model. Differentiability in holds for smooth and 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 is nonsingular and , then solves
for all , and it is the only solution of the form with a constant complex vector .
Proof. and are real, so commutes with them, and . So
For uniqueness, suppose solves (2), and let . Then for all . At this gives , and at (if ) it gives , so and . For the form is the constant , and only is determined; it equals .
By linearity, several sources at the same frequency with phasors give , and the transfer function from one source to the output is .
Theorem 2 (it is the steady state). Suppose the pencil is regular, , and every root of has . Then is nonsingular for every real , and every solution of (2) with consistent initial values tends to as .
Proof. The roots of are not on the imaginary axis, so is nonsingular. The difference solves . For a regular pencil there are nonsingular , (the Weierstrass canonical form; see Brenan, Campbell and Petzold, Chapter 2) with
where is nilpotent, . With , the system splits into and . The second gives . The first gives , and with , so the eigenvalues of are exactly the roots , all with negative real part, and .
The roots of 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 is singular at the resonance. An amplifier with feedback may have roots in the right half plane; AC analysis then still returns (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 and for a scalar input , the output is with , and AC analysis evaluates on the imaginary axis, .
Proof. The transform of is , so , and is defined wherever is nonsingular.
Theorem 4 (zero frequency). If is nonsingular, is the derivative of the DC output with respect to , where is the operating point for the DC sources (real ).
Proof. The operating point solves . Its Jacobian in at is , which is nonsingular, so by the implicit function theorem is differentiable near with .
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 ; 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 .
Complexity
The DC operating point is computed once. Each frequency then costs one factorization and one solve of an complex sparse matrix, of them in all. The sparsity pattern of is the union of those of and and does not depend on , so the ordering is computed once. The cost 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, 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 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 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 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 . 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 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 and , 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.
# 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
- 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)
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ZS7YDS Edit this page History Report an error Markdown