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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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, , with , and every source is periodic with period . A periodic steady state is a solution with for all . Harmonic balance looks for it as a truncated Fourier series
so the unknowns are the complex coefficient vectors (the negative ones are their conjugates). With the discrete Fourier transform on equally spaced samples , the equations are
Each is Kirchhoff's current law at harmonic : resistive currents plus times charges, minus the sources. The term 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, and . Output: the coefficients , from which any waveform, spectrum, gain or distortion figure follows. The device equations have fitted parameters: in the example below, the diode saturation current and emission coefficient are fitted to measurements, not derived.
The algorithm
HB(circuit, ω, K)- 1
M ← 2K + 1; t_i ← 2πi/(Mω) for i = 0, ..., M − 1 - 2
U ← DFT of the source samples u(t_i); X ← a start spectrum (zero, or a DC or AC solution) - 3
repeat - 4
x_i ← inverse DFT of X, at every t_i - 5
evaluate every device at every x_i: f(x_i), q(x_i), G_i = ∂f/∂x, C_i = ∂q/∂x - 6
R_k ← F_k + jkω Q_k − U_k for |k| ≤ K, where F, Q are the DFTs of f(x_i), q(x_i) - 7
J ← the blocks Ĝ_{k−l} + jkω Ĉ_{k−l}, where Ĝ, Ĉ are the DFTs of G_i, C_i - 8
solve J ΔX = −R; X ← X + λΔX with a step limit λ ≤ 1 - 9
until λ = 1 and ΔX is small - 10
return 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 with respect to is the transform of , which depends only on . So is block Toeplitz: a time-invariant circuit gives for and the blocks decouple by harmonic, while a device whose conductance varies over the period couples harmonic into harmonic through the 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 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 is two FFTs and a block-diagonal product, and a preconditioner built from the averaged blocks 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 drives kΩ into nF, with rad/s, and . The source spectrum is and . For a linear circuit and vanish for , so line L8 solves one small system per harmonic. At the output node, and , so the output is . 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 A and (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 V, and 5 periods and 12 periods give the same last period to V. The error is the largest difference over 1000 points of the period. Newton starts from zero and needs 11 to 13 iterations.
| 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 A gives a smoother waveform. With the same reference, the error is V at , at , at , at and at , where it reaches the accuracy of the reference. Newton takes 10 iterations for every . 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:
- HB is collocation. By the orthogonality of the sampled exponentials, the DFT is exact on trigonometric polynomials of degree , so holds exactly when the circuit equations hold at the sample times, with the derivative of the charge taken from its trigonometric interpolant.
- Real waveforms stay real. If , the residual and the Newton step have the same symmetry.
- The Jacobian. The derivative of with respect to is , 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.
- Linear circuits are exact. If and are linear, the sources have no harmonic above and is nonsingular for every , then is the exact periodic steady state, and Newton reaches it in one step. With 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 ; Newton stops after its second iteration, whose step is below the tolerance.
- against a bisection solution of the DC diode equation, to V.
- The Jacobian of line L7 against central differences of in random symmetric directions (seed 51), to a relative error of .
- The symmetry of the result and a residual below .
- 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 with unknowns, and continuously differentiable, and periodic with period . Fix , put , and for . For samples (scalars or vectors) the discrete Fourier transform is
A spectrum is with , and is its trigonometric polynomial. Its samples are . The harmonic balance (HB) equations are
Interpolation and collocation
Lemma 1 (orthogonality). if and otherwise. For , holds only if .
Proof. The sum is a geometric series with ratio , which is 1 exactly when divides ; otherwise the sum is . If then , so forces .
Lemma 2 (the transform is exact on degree K). For every spectrum , for . Hence the map from spectra to samples is a bijection, and every set of samples has exactly one trigonometric polynomial of degree at most through it, the interpolant with coefficients .
Proof. by Lemma 1. So the linear map has a left inverse; both spaces have dimension over , so it is a bijection with inverse .
Theorem 1 (HB is collocation). solves (1) if and only if, at every sample time,
where is the interpolant of the samples .
Proof. The derivative of has coefficients , so the left side minus the right side is the trigonometric polynomial with coefficients , evaluated at . By Lemma 2 its samples are all zero exactly when all its coefficients are zero.
So HB asks that the circuit equations hold exactly at equally spaced times, with the time derivative taken spectrally. The samples of and contain harmonics above in general; Lemma 1 shows that the transform folds harmonic onto . This aliasing is part of the method as it is defined here.
Lemma 3 (real waveforms). Call symmetric if for every . If is symmetric, its samples are real, is symmetric, and the Newton step (2) below is symmetric when it exists.
Proof. For symmetric , the terms and of are conjugate, so is real. The transform of real samples satisfies , and , so . For the step, Theorem 2 gives because and below are transforms of real samples. If , then satisfies as well, so by uniqueness .
The Newton step
Theorem 2 (the Jacobian). Let and at , and for put and . For a symmetric and a symmetric direction ,
Proof. The samples of are with , which is real by Lemma 3. By the chain rule, , so
and depends only on . The term is the same with and the factor ; the source term does not depend on .
The matrix in (2) is block Toeplitz in , plus the diagonal factor on the part. It is the matrix of line L7. In matrix form it is , where is the transform and 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 and 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 and with constant matrices, let contain only harmonics , with coefficients , and let be nonsingular for every integer . Then:
- The HB equations have the unique solution .
- These are the Fourier coefficients of the unique periodic steady state of the circuit, which has no harmonics above .
- Newton's method reaches the solution in one full step from any start.
Proof. By Lemma 2, , and . So , which proves 1. For 2, let be a periodic solution with Fourier coefficients for all integers . The Fourier coefficients of are for periodic , so taking coefficients of the equation gives for every , with for . Nonsingularity gives there and for . Conversely is a solution, so it is the unique one. For 3, is affine in , so its Jacobian is constant and one Newton step from any lands on the root.
Corollary (K = 0). With the only sample is and (1) reads . For constant sources these are the equations of the DC operating point.
What is not proved
- Truncation error for nonlinear circuits. For a nonlinear or the steady state has infinitely many harmonics, and HB with harmonics is an approximation. How fast the error falls with 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 samples, computes the transforms (direct sums here, with the FFT), fills in , and solves a dense system of order in . Over iterations this is time and space for . The dense solve limits this form to small circuits. With the FFT, GMRES and a block-diagonal preconditioner, one iteration costs per GMRES step plus one sparse factorization of each diagonal block, and the memory is 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 when the waveforms are analytic, and slowly when they have sharp edges.
- Collocation with aliasing. Harmonics of above fold onto lower harmonics. At the cubic example has a DC part of V although the exact one is 0: harmonic 3 folds onto harmonic 0.
- Dense coupling. 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 , 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 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 in the diode example is 48 mV, more than 5% of the swing. Check the result by doubling .
- Aliasing. The DFT folds harmonics above back into the band and produces false DC and low-order terms. At 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 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 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.
# 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
- 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
- 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
- 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.
| 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 WY97C5 Edit this page History Report an error Markdown