Algorithm Search⌘K

Algorithmadvanced

Harmonic balance analysis

Also called harmonic balance circuit simulation, spectral balance.

Finds the periodic steady state of a nonlinear circuit by writing node voltages as truncated Fourier series and solving KCL in the frequency domain with Newton.

Time
O(I n^3 K^3) worst
Space
O(n^2 K^2) extra
Where
I = the number of Newton iterations; K = the number of harmonics kept; n = the number of MNA unknowns
Properties
deterministicnot exactiterative
Origin
Kenneth S. Kundert, Alberto Sangiovanni Vincentelli, 1986

Harmonic balance finds the periodic steady state of a circuit driven by periodic sources without simulating the start-up transient. It writes every unknown as a Fourier series with KK harmonics, evaluates the devices in the time domain, and solves the circuit equations for the Fourier coefficients with Newton's method. It belongs to the circuit simulation half of the logic and circuit simulation sub-area, where it is the standard method for RF and microwave circuits, amplifiers and mixers with mostly sinusoidal signals.

In plain words

Drive a circuit with a sine wave and wait. After the start-up dies out, every voltage repeats with the period of the input. A transient simulation gets there by stepping through all of the start-up, which can take thousands of periods for a circuit with a slow bias network.

Harmonic balance skips the wait. It guesses each repeating waveform as a sum of sine waves: a constant, the input frequency, twice that frequency, and so on up to a limit. For a guess, it checks at a few points in one period whether the currents into each node add up to zero. If not, it corrects the sizes and phases of all the sine waves at once and checks again, until the currents balance. For a linear circuit one correction gives the exact answer; for a nonlinear one, more sine waves give a better 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), and every source is periodic with period T=2π/ωT = 2\pi/\omega. A periodic steady state is a solution with x(t+T)=x(t)x(t + T) = x(t) for all tt. Harmonic balance looks for it as a truncated Fourier series

x(t)≈∑k=−KKXkejkωt,X−k=Xk‾,x(t) \approx \sum_{k=-K}^{K} X_k e^{jk\omega t}, \qquad X_{-k} = \overline{X_k},

so the unknowns are the K+1K + 1 complex coefficient vectors X0,…,XKX_0, \ldots, X_K (the negative ones are their conjugates). With the discrete Fourier transform Fk\mathcal F_k on M=2K+1M = 2K + 1 equally spaced samples ti=iT/Mt_i = iT/M, the equations are

Rk(X)=Fk(f(x(ti)))+jkω Fk(q(x(ti)))−Fk(u(ti))=0,∣k∣≤K.R_k(X) = \mathcal F_k\big(f(x(t_i))\big) + jk\omega\,\mathcal F_k\big(q(x(t_i))\big) - \mathcal F_k\big(u(t_i)\big) = 0, \qquad |k| \le K.

Each RkR_k is Kirchhoff's current law at harmonic kk: resistive currents plus jkωjk\omega times charges, minus the sources. The term jkωQkjk\omega Q_k is the time derivative in the frequency domain, so linear elements are handled exactly as in AC analysis, at every harmonic. Nonlinear devices cannot be written in the frequency domain, so they are evaluated on the time samples.

Input: the circuit, ω\omega and KK. Output: the coefficients XkX_k, from which any waveform, spectrum, gain or distortion figure follows. The device equations have fitted parameters: in the example below, the diode saturation current ISI_S and emission coefficient NN are fitted to measurements, not derived.

The algorithm

  1. HB(circuit, ω, K)
  2. 1M ← 2K + 1; t_i ← 2πi/(Mω) for i = 0, ..., M − 1
  3. 2U ← DFT of the source samples u(t_i); X ← a start spectrum (zero, or a DC or AC solution)
  4. 3repeat
  5. 4x_i ← inverse DFT of X, at every t_i
  6. 5evaluate every device at every x_i: f(x_i), q(x_i), G_i = ∂f/∂x, C_i = ∂q/∂x
  7. 6R_k ← F_k + jkω Q_k − U_k for |k| ≤ K, where F, Q are the DFTs of f(x_i), q(x_i)
  8. 7J ← the blocks Ĝ_{k−l} + jkω Ĉ_{k−l}, where Ĝ, Ĉ are the DFTs of G_i, C_i
  9. 8solve J ΔX = −R; X ← X + λΔX with a step limit λ ≤ 1
  10. 9until λ = 1 and ΔX is small
  11. 10return X

Lines L4 to L6 move between the two domains: the waveforms go to the time domain, where each device is evaluated as in a transient step, and the currents and charges come back as spectra. Line L7 is the Jacobian. The derivative of the transform of f(x(ti))f(x(t_i)) with respect to XlX_l is the transform of GiejlωtiG_i e^{jl\omega t_i}, which depends only on k−lk - l. So JJ is block Toeplitz: a time-invariant circuit gives G^d=0\hat G_d = 0 for d≠0d \ne 0 and the blocks decouple by harmonic, while a device whose conductance varies over the period couples harmonic ll into harmonic kk through the (k−l)(k - l)th harmonic of that conductance. This coupling is how a mixer moves signals from one frequency to another.

The implementation uses direct sums of cost O(M2)O(M^2) for the transforms and a dense solve for line L8. A production code uses the FFT for lines L4 to L7 and solves line L8 with GMRES, where a product with JJ is two FFTs and a block-diagonal product, and a preconditioner built from the averaged blocks G^0+jkωC^0\hat G_0 + jk\omega \hat C_0 makes the iteration converge in few steps when the circuit is mildly nonlinear. The step limit of line L8 keeps every voltage sample from moving more than 0.1 V per iteration.

Example

A linear RC circuit, by hand. A source v(t)=1+cos⁡ωtv(t) = 1 + \cos\omega t drives R=1R = 1 kΩ into C=1C = 1 nF, with ω=1/(RC)=106\omega = 1/(RC) = 10^6 rad/s, and K=1K = 1. The source spectrum is U0=1U_0 = 1 and U±1=1/2U_{\pm1} = 1/2. For a linear circuit G^d\hat G_d and C^d\hat C_d vanish for d≠0d \ne 0, so line L8 solves one small system per harmonic. At the output node, X0=1X_0 = 1 and X1=12/(1+jωRC)=(1−j)/4X_1 = \tfrac12/(1 + j\omega RC) = (1 - j)/4, so the output is 1+12cos⁡(ωt−45°)1 + \tfrac{1}{\sqrt2}\cos(\omega t - 45°). This is the exact steady state, and Newton needs one step.

A diode clipper, measured. A 1 V, 1 MHz sine source behind 1 kΩ drives a node with 100 pF and a diode to ground, with IS=10−14I_S = 10^{-14} A and N=1N = 1 (fitted values for a small silicon diode). The diode cuts the positive peaks near 0.63 V. The reference is a trapezoidal transient with 1000 and 2000 steps per period, run for 12 periods from zero and extrapolated with Richardson's rule; the two step sizes differ by 5.7×10−65.7 \times 10^{-6} V, and 5 periods and 12 periods give the same last period to 10−1410^{-14} V. The error is the largest difference over 1000 points of the period. Newton starts from zero and needs 11 to 13 iterations.

KK error (V) DC part (V) 1st harmonic amplitude (V)
1 0.155 −0.0923 0.7157
2 0.132 −0.0536 0.7932
4 0.048 −0.0545 0.7647
8 0.0132 −0.0520 0.7674
16 0.00257 −0.0519 0.7675
32 0.00014 −0.0519 0.7675

A cubic conductor, measured. The same source as 1 mA into 100 pF and a conductor with i=10−3(v+v3)i = 10^{-3}(v + v^3) A gives a smoother waveform. With the same reference, the error is 8.4×10−28.4 \times 10^{-2} V at K=1K = 1, 7.0×10−37.0 \times 10^{-3} at K=4K = 4, 6.7×10−56.7 \times 10^{-5} at K=8K = 8, 1.1×10−81.1 \times 10^{-8} at K=16K = 16 and 9×10−129 \times 10^{-12} at K=32K = 32, where it reaches the accuracy of the reference. Newton takes 10 iterations for every KK. The error falls geometrically, as expected for a waveform that is analytic, while the diode's steep exponential makes its spectrum fall much more slowly.

Correctness

The proof in proofs/correctness.md shows:

  1. HB is collocation. By the orthogonality of the sampled exponentials, the DFT is exact on trigonometric polynomials of degree KK, so R(X)=0R(X) = 0 holds exactly when the circuit equations hold at the MM sample times, with the derivative of the charge taken from its trigonometric interpolant.
  2. Real waveforms stay real. If X−k=Xk‾X_{-k} = \overline{X_k}, the residual and the Newton step have the same symmetry.
  3. The Jacobian. The derivative of RkR_k with respect to XlX_l is G^(k−l) mod M+jkω C^(k−l) mod M\hat G_{(k-l) \bmod M} + jk\omega\,\hat C_{(k-l) \bmod M}, the matrix of line L7; it is the transform of the time-domain collocation Jacobian, so Newton converges locally and quadratically under the usual conditions.
  4. Linear circuits are exact. If ff and qq are linear, the sources have no harmonic above KK and G+jkωCG + jk\omega C is nonsingular for every kk, then Xk=(G+jkωC)−1UkX_k = (G + jk\omega C)^{-1} U_k is the exact periodic steady state, and Newton reaches it in one step. With K=0K = 0 the equations are those of the DC operating point.

The truncation error for a nonlinear circuit is not proved; the tables above measure it.

The tests check, with fixed seeds:

  • The DFT round trip and the exact coefficients of a trigonometric polynomial.
  • A linear RLC circuit with a source that has harmonics 1 and 3, against the analytic phasors at each harmonic, to 10−1210^{-12}; Newton stops after its second iteration, whose step is below the tolerance.
  • K=0K = 0 against a bisection solution of the DC diode equation, to 10−1210^{-12} V.
  • The Jacobian of line L7 against central differences of RR in random symmetric directions (seed 51), to a relative error of 10−610^{-6}.
  • The symmetry of the result and a residual below 10−1210^{-12}.
  • The cubic and diode errors above against the transient reference, with fewer periods (5) to keep the test fast.
Proof: Harmonic balance is collocation, exact for linear circuits, with the Toeplitz Jacobianfull

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) with NN unknowns, ff and qq continuously differentiable, and uu periodic with period T=2π/ωT = 2\pi/\omega. Fix K≥0K \ge 0, put M=2K+1M = 2K + 1, θi=2πi/M\theta_i = 2\pi i/M and ti=θi/ωt_i = \theta_i/\omega for i=0,…,M−1i = 0, \ldots, M - 1. For samples y0,…,yM−1y_0, \ldots, y_{M-1} (scalars or vectors) the discrete Fourier transform is

Fk(y)=1M∑i=0M−1yi e−jkθi,k=−K,…,K.\mathcal F_k(y) = \frac{1}{M} \sum_{i=0}^{M-1} y_i\, e^{-jk\theta_i}, \qquad k = -K, \ldots, K.

A spectrum is X=(X−K,…,XK)X = (X_{-K}, \ldots, X_K) with Xk∈CNX_k \in \mathbb C^N, and pX(t)=∑∣k∣≤KXkejkωtp_X(t) = \sum_{|k| \le K} X_k e^{jk\omega t} is its trigonometric polynomial. Its samples are xi=pX(ti)x_i = p_X(t_i). The harmonic balance (HB) equations are

Rk(X)=Fk(f(xi))+jkω Fk(q(xi))−Fk(u(ti))=0,∣k∣≤K.(1)R_k(X) = \mathcal F_k\big(f(x_i)\big) + jk\omega\, \mathcal F_k\big(q(x_i)\big) - \mathcal F_k\big(u(t_i)\big) = 0, \qquad |k| \le K. \tag{1}

Interpolation and collocation

Lemma 1 (orthogonality). ∑i=0M−1ejdθi=M\sum_{i=0}^{M-1} e^{jd\theta_i} = M if d≡0(modM)d \equiv 0 \pmod M and 00 otherwise. For ∣k∣,∣l∣≤K|k|, |l| \le K, k≡l(modM)k \equiv l \pmod M holds only if k=lk = l.

Proof. The sum is a geometric series with ratio e2πjd/Me^{2\pi j d/M}, which is 1 exactly when MM divides dd; otherwise the sum is (1−e2πjd)/(1−e2πjd/M)=0(1 - e^{2\pi j d})/(1 - e^{2\pi j d/M}) = 0. If ∣k∣,∣l∣≤K|k|, |l| \le K then ∣k−l∣≤2K<M|k - l| \le 2K < M, so M∣k−lM \mid k - l forces k=lk = l. □\square

Lemma 2 (the transform is exact on degree K). For every spectrum XX, Fk(pX(ti))=Xk\mathcal F_k(p_X(t_i)) = X_k for ∣k∣≤K|k| \le K. Hence the map from spectra to samples is a bijection, and every set of samples has exactly one trigonometric polynomial of degree at most KK through it, the interpolant IKyI_K y with coefficients Fk(y)\mathcal F_k(y).

Proof. Fk(pX(ti))=∑lXl1M∑iej(l−k)θi=Xk\mathcal F_k(p_X(t_i)) = \sum_l X_l \frac{1}{M}\sum_i e^{j(l-k)\theta_i} = X_k by Lemma 1. So the linear map X↦(xi)X \mapsto (x_i) has a left inverse; both spaces have dimension MNMN over C\mathbb C, so it is a bijection with inverse F\mathcal F. □\square

Theorem 1 (HB is collocation). XX solves (1) if and only if, at every sample time,

f(xi)+ddt[IK q(x)](ti)=[IKu](ti),i=0,…,M−1,f(x_i) + \frac{d}{dt}\big[I_K\, q(x)\big](t_i) = \big[I_K u\big](t_i), \qquad i = 0, \ldots, M - 1,

where IKq(x)I_K q(x) is the interpolant of the samples q(x0),…,q(xM−1)q(x_0), \ldots, q(x_{M-1}).

Proof. The derivative of IKq(x)=∑kQkejkωtI_K q(x) = \sum_k Q_k e^{jk\omega t} has coefficients jkωQkjk\omega Q_k, so the left side minus the right side is the trigonometric polynomial with coefficients Rk(X)R_k(X), evaluated at tit_i. By Lemma 2 its samples are all zero exactly when all its coefficients are zero. □\square

So HB asks that the circuit equations hold exactly at MM equally spaced times, with the time derivative taken spectrally. The samples of f(x)f(x) and q(x)q(x) contain harmonics above KK in general; Lemma 1 shows that the transform folds harmonic k+Mk + M onto kk. This aliasing is part of the method as it is defined here.

Lemma 3 (real waveforms). Call XX symmetric if X−k=Xk‾X_{-k} = \overline{X_k} for every kk. If XX is symmetric, its samples are real, R(X)R(X) is symmetric, and the Newton step (2) below is symmetric when it exists.

Proof. For symmetric XX, the terms kk and −k-k of pX(ti)p_X(t_i) are conjugate, so xix_i is real. The transform of real samples satisfies F−k(y)=Fk(y)‾\mathcal F_{-k}(y) = \overline{\mathcal F_k(y)}, and j(−k)ω=jkω‾j(-k)\omega = \overline{jk\omega}, so R−k=Rk‾R_{-k} = \overline{R_k}. For the step, Theorem 2 gives J−k,−l=Jk,l‾J_{-k,-l} = \overline{J_{k,l}} because G^\hat G and C^\hat C below are transforms of real samples. If JΔ=−RJ\Delta = -R, then Δk′=Δ−k‾\Delta'_k = \overline{\Delta_{-k}} satisfies JΔ′=−RJ\Delta' = -R as well, so by uniqueness Δ′=Δ\Delta' = \Delta. □\square

The Newton step

Theorem 2 (the Jacobian). Let Gi=∂f/∂xG_i = \partial f/\partial x and Ci=∂q/∂xC_i = \partial q/\partial x at xix_i, and for d=0,…,M−1d = 0, \ldots, M - 1 put G^d=1M∑iGie−jdθi\hat G_d = \frac{1}{M}\sum_i G_i e^{-jd\theta_i} and C^d=1M∑iCie−jdθi\hat C_d = \frac1M \sum_i C_i e^{-jd\theta_i}. For a symmetric XX and a symmetric direction DD,

ddεRk(X+εD)∣ε=0=∑∣l∣≤K(G^(k−l) mod M+jkω C^(k−l) mod M)Dl.(2)\frac{d}{d\varepsilon} R_k(X + \varepsilon D)\Big|_{\varepsilon = 0} = \sum_{|l| \le K} \big(\hat G_{(k - l) \bmod M} + jk\omega\, \hat C_{(k-l) \bmod M}\big) D_l. \tag{2}

Proof. The samples of X+εDX + \varepsilon D are xi+εδix_i + \varepsilon \delta_i with δi=∑lDlejlθi\delta_i = \sum_l D_l e^{jl\theta_i}, which is real by Lemma 3. By the chain rule, ddεf(xi+εδi)=Giδi\frac{d}{d\varepsilon} f(x_i + \varepsilon\delta_i) = G_i \delta_i, so

ddεFk(f)=1M∑iGi∑lDlejlθie−jkθi=∑l(1M∑iGie−j(k−l)θi)Dl,\frac{d}{d\varepsilon}\mathcal F_k\big(f\big) = \frac1M \sum_i G_i \sum_l D_l e^{jl\theta_i} e^{-jk\theta_i} = \sum_l \Big(\frac1M\sum_i G_i e^{-j(k-l)\theta_i}\Big) D_l,

and e−jdθie^{-jd\theta_i} depends only on d mod Md \bmod M. The qq term is the same with CiC_i and the factor jkωjk\omega; the source term does not depend on XX. □\square

The matrix in (2) is block Toeplitz in (k,l)(k, l), plus the diagonal factor jkωjk\omega on the CC part. It is the matrix of line L7. In matrix form it is Γ (diag⁡(Gi)+Ddiag⁡(Ci)) Γ−1\Gamma\,(\operatorname{diag}(G_i) + \mathcal D\operatorname{diag}(C_i))\,\Gamma^{-1}, where Γ\Gamma is the transform and D=Γ−1diag⁡(jkω)Γ\mathcal D = \Gamma^{-1} \operatorname{diag}(jk\omega)\Gamma is the spectral differentiation matrix on the samples. So the HB Newton step is the transform of the Newton step for the collocation equations of Theorem 1, and the two iterations produce the same waveforms. When the Jacobian is nonsingular at a root and ff and qq are twice continuously differentiable, the full-step iteration converges quadratically from a start close enough to the root, by the local theorem for Newton's method for systems.

Linear circuits

Theorem 3 (exact for linear circuits). Let f(x)=Gxf(x) = Gx and q(x)=Cxq(x) = Cx with constant matrices, let uu contain only harmonics ∣k∣≤K|k| \le K, with coefficients UkU_k, and let G+jkωCG + jk\omega C be nonsingular for every integer kk. Then:

  1. The HB equations have the unique solution Xk=(G+jkωC)−1UkX_k = (G + jk\omega C)^{-1} U_k.
  2. These are the Fourier coefficients of the unique periodic steady state of the circuit, which has no harmonics above KK.
  3. Newton's method reaches the solution in one full step from any start.

Proof. By Lemma 2, Fk(Gxi)=GXk\mathcal F_k(G x_i) = G X_k, Fk(Cxi)=CXk\mathcal F_k(C x_i) = C X_k and Fk(u(ti))=Uk\mathcal F_k(u(t_i)) = U_k. So Rk(X)=(G+jkωC)Xk−UkR_k(X) = (G + jk\omega C) X_k - U_k, which proves 1. For 2, let x(t)x(t) be a periodic solution with Fourier coefficients ξk\xi_k for all integers kk. The Fourier coefficients of ddt(Cx)\frac{d}{dt}(Cx) are jkωCξkjk\omega C\xi_k for periodic CxCx, so taking coefficients of the equation gives (G+jkωC)ξk=Uk(G + jk\omega C)\xi_k = U_k for every kk, with Uk=0U_k = 0 for ∣k∣>K|k| > K. Nonsingularity gives ξk=0\xi_k = 0 there and ξk=Xk\xi_k = X_k for ∣k∣≤K|k| \le K. Conversely pXp_X is a solution, so it is the unique one. For 3, RR is affine in XX, so its Jacobian is constant and one Newton step from any XX lands on the root. □\square

Corollary (K = 0). With M=1M = 1 the only sample is t0=0t_0 = 0 and (1) reads f(X0)=u(0)f(X_0) = u(0). For constant sources these are the equations of the DC operating point.

What is not proved

  • Truncation error for nonlinear circuits. For a nonlinear ff or qq the steady state has infinitely many harmonics, and HB with KK harmonics is an approximation. How fast the error falls with KK depends on how smooth the waveforms are; for analytic waveforms the Fourier coefficients fall geometrically. The page measures the error against a transient reference for two circuits; it is not proved here.
  • Existence and uniqueness of a periodic steady state of a nonlinear circuit, and the nonsingularity of the Jacobian at the root, are assumed.
  • Global convergence. The step limit of line L8 is a heuristic. Newton's method can fail from a poor start, and continuation in the source amplitude is the usual remedy.
  • Iterative solvers. Krylov methods such as GMRES with a block-diagonal preconditioner solve (2) approximately; their convergence is not covered.

Complexity

Each Newton iteration evaluates every device at M=2K+1M = 2K + 1 samples, computes the transforms (direct sums O(nK2)O(nK^2) here, O(nKlog⁡K)O(nK\log K) with the FFT), fills JJ in O(n2K2)O(n^2K^2), and solves a dense system of order nMnM in O(n3K3)O(n^3K^3). Over II iterations this is O(In3K3)O(I n^3 K^3) time and O(n2K2)O(n^2 K^2) space for JJ. The dense solve limits this form to small circuits. With the FFT, GMRES and a block-diagonal preconditioner, one iteration costs O(nKlog⁡K)O(nK\log K) per GMRES step plus one sparse factorization of each diagonal block, and the memory is O(nK)O(nK) plus those factors. The number of GMRES steps depends on how nonlinear the circuit is and is not bounded in advance.

Properties

  • No start-up transient. The cost does not depend on the time constants of the circuit, so slow bias networks and high-Q filters cost nothing extra, unlike transient analysis.
  • Exact for linear elements. Distributed and frequency-dependent elements, such as transmission lines and S-parameter blocks, enter as their admittance at each harmonic, which time-domain methods cannot do directly.
  • Spectral accuracy for smooth waveforms. The error falls geometrically with KK when the waveforms are analytic, and slowly when they have sharp edges.
  • Collocation with aliasing. Harmonics of f(x(t))f(x(t)) above KK fold onto lower harmonics. At K=1K = 1 the cubic example has a DC part of −0.046-0.046 V although the exact one is 0: harmonic 3 folds onto harmonic 0.
  • Dense coupling. JJ is dense in the harmonic index whenever a device is strongly nonlinear.

Variants and improvements

  • Multitone and quasi-periodic harmonic balance. Mixers and intermodulation tests have two or more unrelated frequencies. The series then runs over the sums k1ω1+k2ω2k_1\omega_1 + k_2\omega_2, and the transforms use a multidimensional DFT or almost-periodic Fourier transforms.
  • Krylov harmonic balance. GMRES with FFT matrix-vector products and a block-diagonal preconditioner, as above; this made harmonic balance usable for integrated circuits with many nodes.
  • Oversampling. Using more than 2K+12K + 1 samples reduces aliasing at the cost of a larger transform.
  • Continuation. Ramp the source amplitude from zero, or start from the AC solution, to help Newton converge for strongly driven circuits.
  • Periodic small-signal and noise analysis. Linearizing around the steady state gives the conversion gain and noise of mixers; for autonomous oscillators the frequency becomes an unknown and the steady state feeds phase noise analysis.
  • Time-domain alternative. Shooting Newton finds the same steady state with transient steps over one period and is better for circuits with sharp edges.

When to use it

Use harmonic balance for circuits whose waveforms are close to sums of a few sinusoids: RF amplifiers, power amplifiers near compression, mixers, frequency multipliers and microwave circuits with distributed elements. Use it when the circuit has long time constants that would make a transient run long. Use shooting or a transient run for switching circuits, digital dividers and other circuits with fast edges, where the spectrum falls slowly, as the diode table shows.

Pitfalls

  • Too few harmonics. The error at K=4K = 4 in the diode example is 48 mV, more than 5% of the swing. Check the result by doubling KK.
  • Aliasing. The DFT folds harmonics above KK back into the band and produces false DC and low-order terms. At K=1K = 1 the DC part is wrong by 40 mV in the diode example and by 46 mV in the cubic example.
  • Newton failure. Exponential devices make Newton diverge from a poor start. Limit the step, as in line L8, or use continuation in the source amplitude.
  • Several steady states. A circuit can have more than one periodic solution, for example a divider or a circuit with hysteresis. Newton finds one of them, which depends on the start.
  • Autonomous circuits. An oscillator has no external period. Plain harmonic balance with a fixed ω\omega finds the trivial DC solution or fails; the frequency must be an extra unknown with a phase condition.
  • Memory of the dense Jacobian. The direct form stores (nM)2(nM)^2 entries. Use the Krylov form for more than a few nodes.
  • Fitted parameters. The harmonics of a nonlinear device depend on high derivatives of its model, which the fitted parameters often reproduce badly. Distortion predictions are only as good as the model's fit of those derivatives.

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.

harmonic_balance_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harmonic-balance-analysis/. The authors are listed in prov/WY97C5.jsonl.
"""Harmonic balance 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. The sources have period T = 2 pi / w. Harmonic balance writes
each unknown as a truncated Fourier series with harmonics -K..K and solves the
circuit equations for the coefficients with Newton's method.

The transforms are direct sums of cost O(M^2) with M = 2K + 1 samples. A
production code uses the fast Fourier transform for them.
"""

import cmath
import math

import sim3dense

VT_300 = 1.380649e-23 * 300.0 / 1.602176634e-19  # kT/q at 300 K, in volts


class NoConvergence(RuntimeError):
    pass


def _wave(w):
    return w if callable(w) else (lambda t, c=float(w): c)


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

    def __init__(self, nodes):
        self.n = nodes
        self.m = 0
        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, wave):
        """Voltage source e_p - e_q = wave(t); wave is a function of t or a constant."""
        self.el.append(("V", p, q, _wave(wave), self._branch()))

    def isource(self, p, q, wave):
        """Current source that moves wave(t) out of p and into q."""
        self.el.append(("I", p, q, _wave(wave)))

    def diode(self, a, c, i_s, n=1.0, tt=0.0):
        """Junction diode from a to c with diffusion charge tt * i.

        The saturation current i_s, the emission coefficient n and the transit
        time tt are fitted model parameters.
        """
        self.el.append(("D", a, c, (i_s, n, tt)))

    def cubic(self, p, q, g1, g3):
        """Nonlinear conductor with current g1 v + g3 v^3 from p to q."""
        self.el.append(("N", p, q, (g1, g3)))

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

    @property
    def linear(self):
        return all(el[0] not in "DN" for el in self.el)

    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 branch(vec, mat, p, qn, val, dval):
            """Add val leaving p and entering qn; dval = d val / d(e_p - e_q)."""
            rp, rq = p - 1, qn - 1
            for r, s in ((rp, 1.0), (rq, -1.0)):
                if r < 0:
                    continue
                vec[r] += s * val
                if rp >= 0:
                    mat[r][rp] += s * dval
                if rq >= 0:
                    mat[r][rq] -= s * dval

        for el in self.el:
            kind = el[0]
            if kind in "RC":
                _, p, qn, val = el
                v = e(p) - e(qn)
                if kind == "R":
                    branch(f, G, p, qn, val * v, val)
                else:
                    branch(q, C, p, qn, val * v, val)
            elif kind in "LV":
                p, qn, k = el[1], el[2], self.n + el[4]
                for r, s in ((p - 1, 1.0), (qn - 1, -1.0)):
                    if r >= 0:
                        f[r] += s * x[k]
                        G[r][k] += s
                        G[k][r] += s
                f[k] += e(p) - e(qn)
                if kind == "L":
                    q[k] -= el[3] * x[k]
                    C[k][k] -= el[3]
            elif kind == "D":
                _, a, c, (i_s, n, tt) = el
                nvt = n * VT_300
                v, vmax = e(a) - e(c), 40.0 * nvt
                if v <= vmax:
                    ex = math.exp(v / nvt)
                    i, g = i_s * (ex - 1.0), i_s * ex / nvt
                else:
                    ex = math.exp(40.0)
                    i, g = i_s * (ex * (1.0 + (v - vmax) / nvt) - 1.0), i_s * ex / nvt
                branch(f, G, a, c, i, g)
                branch(q, C, a, c, tt * i, tt * g)
            elif kind == "N":
                _, p, qn, (g1, g3) = el
                v = e(p) - e(qn)
                branch(f, G, p, qn, g1 * v + g3 * v ** 3, g1 + 3 * g3 * v * v)
        return f, G, q, C

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


class Spectrum:
    """Direct DFT on M = 2K + 1 points, coefficient index k = -K..K stored at k + K."""

    def __init__(self, K):
        self.K, self.M = K, 2 * K + 1
        M = self.M
        self.root = [cmath.exp(-2j * math.pi * r / M) for r in range(M)]

    def forward(self, samples):
        """X_k = (1/M) sum_i x_i exp(-j k 2 pi i / M) for k = -K..K."""
        M, K, root = self.M, self.K, self.root
        return [sum(samples[i] * root[(k * i) % M] for i in range(M)) / M for k in range(-K, K + 1)]

    def backward(self, coeffs):
        """x_i = sum_k X_k exp(j k 2 pi i / M), the real part (the imaginary part is rounding)."""
        M, K, root = self.M, self.K, self.root
        return [sum(coeffs[k + K] * root[(-k * i) % M] for k in range(-K, K + 1)).real for i in range(M)]

    def aliased(self, samples):
        """D_d = (1/M) sum_i x_i exp(-j d 2 pi i / M) for d = 0..M-1 (index taken mod M)."""
        M, root = self.M, self.root
        return [sum(samples[i] * root[(d * i) % M] for i in range(M)) / M for d in range(M)]


def source_spectrum(net, omega, K):
    """U[a][k + K], the Fourier coefficients of the source samples u(t_i)."""
    sp = Spectrum(K)
    M = sp.M
    ts = [2 * math.pi * i / (M * omega) for i in range(M)]
    us = [net.sources(t) for t in ts]
    return [sp.forward([us[i][a] for i in range(M)]) for a in range(net.size)]


def hb_system(net, X, omega, U):
    """The HB residual R (a flat list) and its Jacobian J at the spectrum X.

    Row a * M + (k + K) is the equation of unknown a at harmonic k, and column
    b * M + (l + K) is the coefficient of unknown b at harmonic l.
    """
    K = (len(X[0]) - 1) // 2
    sp = Spectrum(K)
    M, N = sp.M, net.size
    jw = [1j * k * omega for k in range(-K, K + 1)]
    xs = [sp.backward(X[a]) for a in range(N)]  # @line L4
    ev = [net.evaluate([xs[a][i] for a in range(N)]) for i in range(M)]  # @line L5
    R = []  # @line L6
    for a in range(N):
        F = sp.forward([ev[i][0][a] for i in range(M)])
        Q = sp.forward([ev[i][2][a] for i in range(M)])
        R.extend(F[k] + jw[k] * Q[k] - U[a][k] for k in range(M))
    J = [[0j] * (N * M) for _ in range(N * M)]  # @line L7
    for a in range(N):
        for b in range(N):
            gs = [ev[i][1][a][b] for i in range(M)]
            cs = [ev[i][3][a][b] for i in range(M)]
            if not any(gs) and not any(cs):
                continue
            Gd, Cd = sp.aliased(gs), sp.aliased(cs)
            for k in range(M):
                row = J[a * M + k]
                for l in range(M):
                    d = (k - l) % M  # the samples alias index k - l to (k - l) mod M
                    row[b * M + l] = Gd[d] + jw[k] * Cd[d]
    return R, J


def harmonic_balance(net, omega, K, X0=None, tol=1e-10, max_iter=100, step_limit=0.1):
    """Periodic steady state as Fourier coefficients X[a][k + K] of each unknown a.

    Returns (X, iterations, samples), where samples[i] is x at t_i = 2 pi i / (M omega).
    Newton steps are scaled so that no node voltage sample moves more than
    step_limit volts in one iteration.
    """
    sp = Spectrum(K)  # @line L1
    M, N = sp.M, net.size
    U = source_spectrum(net, omega, K)  # @line L2
    X = [list(row) for row in X0] if X0 else [[0j] * M for _ in range(N)]
    for it in range(1, max_iter + 1):  # @line L3
        R, J = hb_system(net, X, omega, U)
        dX = sim3dense.solve(J, [-r for r in R])  # @line L8
        dxs = [sp.backward(dX[a * M:(a + 1) * M]) for a in range(net.n)]
        big = max((abs(v) for row in dxs for v in row), default=0.0)
        lam = min(1.0, step_limit / big) if big > 0 else 1.0
        for a in range(N):
            for k in range(M):
                X[a][k] += lam * dX[a * M + k]
        size = max(abs(v) for v in dX)
        scale = 1.0 + max(abs(v) for row in X for v in row)
        if lam == 1.0 and size <= tol * scale:  # @line L9
            xs = [sp.backward(X[a]) for a in range(N)]
            return X, it, [[xs[a][i] for a in range(N)] for i in range(M)]  # @line L10
    raise NoConvergence("harmonic balance")


def evaluate_series(X, omega, t):
    """Value of the Fourier series of every unknown at time t."""
    K = (len(X[0]) - 1) // 2
    return [sum(row[k + K] * cmath.exp(1j * k * omega * t) for k in range(-K, K + 1)).real for row in X]


def residual(net, X, omega):
    """The HB residual R at the spectrum X (the function whose root Newton finds)."""
    K = (len(X[0]) - 1) // 2
    return hb_system(net, X, omega, source_spectrum(net, omega, K))[0]


def transient(net, T, steps_per_period, periods, x0=None):
    """Trapezoidal-rule transient with a fixed step; returns the samples of the last period.

    This is the reference for the nonlinear tests: it runs from x0 (zero by
    default) until the start-up transient has died out.
    """
    h = T / steps_per_period
    N = net.size
    x = list(x0) if x0 else [0.0] * N
    f, G, q, C = net.evaluate(x)
    u = net.sources(0.0)
    out = []
    for s in range(1, steps_per_period * periods + 1):
        t = s * h
        un = net.sources(t)
        y = list(x)
        for _ in range(50):
            fn, Gn, qn, Cn = net.evaluate(y)
            r = [qn[a] - q[a] + h / 2 * (fn[a] + f[a] - un[a] - u[a]) for a in range(N)]
            Jt = [[Cn[a][b] + h / 2 * Gn[a][b] for b in range(N)] for a in range(N)]
            dy = sim3dense.solve(Jt, [-v for v in r])
            y = [y[a] + dy[a] for a in range(N)]
            if max(abs(v) for v in dy) <= 1e-13 * (1 + max(abs(v) for v in y)):
                break
        else:
            raise NoConvergence("transient step")
        x, u = y, un
        f, G, q, C = net.evaluate(x)
        if s > steps_per_period * (periods - 1):
            out.append(list(x))
    return out
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_harmonic_balance_analysis.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harmonic-balance-analysis/. The authors are listed in prov/WY97C5.jsonl.

import math
import random

from harmonic_balance_analysis import (
    VT_300,
    Netlist,
    Spectrum,
    evaluate_series,
    harmonic_balance,
    hb_system,
    residual,
    source_spectrum,
    transient,
)

F0 = 1e6
W = 2 * math.pi * F0
T = 1 / F0

# Diode parameters: the saturation current IS and the emission coefficient N
# are fitted model parameters (typical values for a small silicon diode).
IS, N = 1e-14, 1.0


def clipper():
    """1 V, 1 MHz source behind 1 kOhm (as its Norton form), 100 pF and a diode to ground."""
    net = Netlist(1)
    net.isource(0, 1, lambda t: 1e-3 * math.sin(W * t))
    net.resistor(1, 0, 1e3)
    net.capacitor(1, 0, 100e-12)
    net.diode(1, 0, IS, N)
    return net


def cubic():
    """1 mA, 1 MHz source into 100 pF and a conductor with i = 1e-3 (v + v^3)."""
    net = Netlist(1)
    net.isource(0, 1, lambda t: 1e-3 * math.sin(W * t))
    net.cubic(1, 0, 1e-3, 1e-3)
    net.capacitor(1, 0, 100e-12)
    return net


def reference(net, periods=5):
    """Trapezoidal transient with 1000 and 2000 steps per period, Richardson-extrapolated.

    Returns the values at t_j = (j + 1) T / 1000 of the last period.
    """
    r1 = transient(net, T, 1000, periods)
    r2 = transient(net, T, 2000, periods)
    return [r2[2 * j + 1][0] + (r2[2 * j + 1][0] - r1[j][0]) / 3 for j in range(1000)]


def test_dft_round_trip_and_exact_trigonometric_polynomials():
    sp = Spectrum(3)
    xs = [math.cos(2 * math.pi * i / 7) + 0.5 * math.sin(3 * 2 * math.pi * i / 7) + 2 for i in range(7)]
    X = sp.forward(xs)
    assert abs(X[3] - 2) < 1e-15
    assert abs(X[4] - 0.5) < 1e-15 and abs(X[2] - 0.5) < 1e-15
    assert abs(X[6] - (-0.25j)) < 1e-15 and abs(X[0] - 0.25j) < 1e-15
    back = sp.backward(X)
    assert max(abs(a - b) for a, b in zip(xs, back)) < 1e-14


def test_linear_rlc_is_exact_and_newton_takes_one_step():
    # source with harmonics 1 and 3: v(t) = cos(wt) + 0.3 sin(3wt), K = 3 holds them
    r, l, c = 50.0, 10e-6, 2e-9
    net = Netlist(2)
    net.vsource(1, 0, lambda t: math.cos(W * t) + 0.3 * math.sin(3 * W * t))
    net.resistor(1, 2, r)
    net.inductor(2, 0, l)
    net.capacitor(2, 0, c)
    X, it, _ = harmonic_balance(net, W, 3, step_limit=math.inf)
    assert it == 2  # the first step solves it; the second confirms
    K = 3
    for k, vk in ((1, 0.5), (3, -0.15j)):
        y = 1 / (1j * k * W * l) + 1j * k * W * c  # admittance of L parallel C
        v2 = vk / (1 + r * y)
        assert abs(X[1][K + k] - v2) < 1e-12
        assert abs(X[1][K - k] - v2.conjugate()) < 1e-12
    for k in (0, 2):
        assert abs(X[1][K + k]) < 1e-12


def test_k_zero_is_the_dc_operating_point():
    net = Netlist(1)
    net.isource(0, 1, 1e-3)
    net.resistor(1, 0, 1e3)
    net.diode(1, 0, IS, N)
    X, _, _ = harmonic_balance(net, W, 0)
    lo, hi = 0.0, 1.0  # bisection on 1e-3 = v / 1e3 + IS (exp(v / VT) - 1)
    for _ in range(200):
        mid = (lo + hi) / 2
        if mid / 1e3 + IS * (math.exp(mid / (N * VT_300)) - 1) < 1e-3:
            lo = mid
        else:
            hi = mid
    assert abs(X[0][0].real - lo) < 1e-12


def test_jacobian_matches_finite_differences():
    rng = random.Random(51)
    for _ in range(3):
        net = Netlist(2)
        net.isource(0, 1, lambda t: 1e-3 * math.sin(W * t) + 2e-4)
        net.resistor(1, 0, rng.uniform(500, 2000))
        net.resistor(1, 2, rng.uniform(500, 2000))
        net.capacitor(1, 2, rng.uniform(10e-12, 100e-12))
        net.diode(2, 0, IS, N, rng.uniform(1e-9, 20e-9))
        net.cubic(1, 0, 1e-4, 1e-4)
        K = 2
        M = 2 * K + 1
        X = [[0j] * M for _ in range(2)]
        for a in range(2):
            for k in range(1, K + 1):
                z = complex(rng.uniform(-0.2, 0.2), rng.uniform(-0.2, 0.2))
                X[a][K + k], X[a][K - k] = z, z.conjugate()
            X[a][K] = complex(rng.uniform(0.3, 0.6))
        # a direction with conjugate symmetry keeps the samples real
        D = [[0j] * M for _ in range(2)]
        for a in range(2):
            for k in range(1, K + 1):
                z = complex(rng.gauss(0, 1), rng.gauss(0, 1))
                D[a][K + k], D[a][K - k] = z, z.conjugate()
            D[a][K] = complex(rng.gauss(0, 1))
        eps = 1e-6

        def shifted(s):
            return [[X[a][k] + s * D[a][k] for k in range(M)] for a in range(2)]

        Rp, Rm = residual(net, shifted(eps), W), residual(net, shifted(-eps), W)
        fd = [(p - m) / (2 * eps) for p, m in zip(Rp, Rm)]
        _, J = hb_system(net, X, W, source_spectrum(net, W, K))
        flat = D[0] + D[1]
        Jd = [sum(j * d for j, d in zip(row, flat)) for row in J]
        scale = max(abs(v) for v in fd)
        assert max(abs(a - b) for a, b in zip(fd, Jd)) < 1e-6 * scale


def test_samples_are_real_and_satisfy_collocation():
    net = clipper()
    X, _, samples = harmonic_balance(net, W, 8)
    for a in range(net.size):
        for k in range(1, 9):
            assert abs(X[a][8 + k] - X[a][8 - k].conjugate()) < 1e-12
    # the residual of the returned spectrum is zero to rounding
    assert max(abs(v) for v in residual(net, X, W)) < 1e-12
    assert len(samples) == 17


def test_cubic_converges_spectrally_against_a_transient():
    net = cubic()
    ref = reference(net)
    errs = {}
    for K in (4, 8, 16):
        X, _, _ = harmonic_balance(net, W, K)
        errs[K] = max(abs(evaluate_series(X, W, (j + 1) * T / 1000)[0] - ref[j]) for j in range(0, 1000, 5))
    # measured: 7.0e-3, 6.7e-5, 1.1e-8
    assert errs[4] < 1e-2 and errs[8] < 1e-4 and errs[16] < 1e-7
    assert errs[16] < errs[8] / 100 < errs[4] / 1e4


def test_diode_clipper_error_falls_with_k_against_a_transient():
    net = clipper()
    ref = reference(net)
    errs = {}
    for K in (4, 8, 16):
        X, _, _ = harmonic_balance(net, W, K)
        errs[K] = max(abs(evaluate_series(X, W, (j + 1) * T / 1000)[0] - ref[j]) for j in range(0, 1000, 5))
    # measured: 4.8e-2, 1.3e-2, 2.5e-3 (slower than the cubic: the diode is stiff)
    assert errs[16] < 3e-3 < errs[8] < 2e-2 < errs[4] < 6e-2

History

The idea of balancing harmonics is older than circuit simulation, and microwave engineers used it for nonlinear circuits in the 1970s. Nakhla and Vlach (1976) split a circuit into a linear part, which they solved in the frequency domain, and a nonlinear part, which they evaluated in the time domain, and balanced the currents at the interface. Kundert and Sangiovanni-Vincentelli (1986) made it a general method for circuit simulation, with device models evaluated in the time domain, the DFT between the domains and Newton's method on the frequency-domain equations. The book of Kundert, White and Sangiovanni-Vincentelli (1990) compared it with the time-domain steady-state methods. Later work replaced the direct solve with Krylov solvers that use FFT products, which made harmonic balance practical for larger integrated RF circuits.

References

  1. Kenneth S. Kundert and Alberto Sangiovanni-Vincentelli, Simulation of nonlinear circuits in the frequency domain, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 5(4), 521 to 535, 1986, the harmonic balance equations, the evaluation of nonlinear devices in the time domain with the DFT, and the Newton iteration with its Jacobian
  2. Kenneth S. Kundert, Jacob K. White and Alberto Sangiovanni-Vincentelli, Steady-State Methods for Simulating Analog and Microwave Circuits, Kluwer, 1990, the chapters on harmonic balance and on the solution of its Newton equations; the chapter numbers were not checked
  3. Michel S. Nakhla and Jiri Vlach, A piecewise harmonic balance technique for determination of periodic response of nonlinear systems, IEEE Transactions on Circuits and Systems 23(2), 85 to 91, 1976, the split of a circuit into a linear part solved in the frequency domain and a nonlinear part evaluated in the time domain

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