Algorithm Search⌘K

Algorithmadvanced

TR-BDF2

Also called Bank-Coughran TR-BDF2, trapezoidal BDF2 method.

An L-stable second-order one-step integrator that does a trapezoidal stage to t + gamma h and a BDF2 stage to t + h, with gamma = 2 - sqrt(2) so both stages share one matrix.

Time
O(N K T) worst
Space
O(n) extra
Where
K = the Newton iterations per stage; N = the number of time steps; T = the cost of one sparse LU solve of the MNA matrix; n = the number of MNA unknowns
Properties
deterministicnot exactiterative
Origin
Randolph E. Bank, William M. Coughran Jr., Wolfgang Fichtner, Eric H. Grosse, Donald J. Rose, R. Kent Smith, 1985

TR-BDF2 is an implicit one-step method for stiff differential equations and for the differential-algebraic equations of circuits. Each step of size hh does a trapezoidal stage from tnt_n to tn+γht_n + \gamma h and then a second-order backward differentiation stage (BDF2) through tnt_n, tn+γht_n + \gamma h and tn+ht_n + h. With γ=2−2\gamma = 2 - \sqrt 2 both stages solve linear systems with the same matrix, and the method is second order and L-stable, so it does not ring on stiff components as the trapezoidal rule does. It is a general method of numerical analysis; this page frames it for transient circuit analysis in the circuit simulation half of the logic and circuit simulation sub-area.

In plain words

A circuit simulator computes voltages and currents at a sequence of time points. Each new point comes from the previous one by a formula that is solved like a resistive circuit. The trapezoidal formula is accurate, but when a part of the circuit reacts much faster than the time step, its answer flips sign from step to step and dies out slowly. The waveform then shows a false oscillation.

TR-BDF2 splits each step in two. The first part uses the trapezoidal formula for a fraction of the step. The second part uses a formula that looks back at both earlier points and damps the fast parts strongly. The fraction is chosen so that both parts need the same matrix, so the extra part costs little. The method stays as accurate as the trapezoidal formula, and fast parts die out at once instead of ringing.

The problem

Integrate the circuit equations of modified nodal analysis in charge form,

f(x)+ddtq(x)=u(t),x(t0)=x0,f(x) + \frac{d}{dt} q(x) = u(t), \qquad x(t_0) = x_0,

from t0t_0 to tendt_{\text{end}}, where xx holds node voltages and branch currents, ff the resistive currents and branch laws, qq the charges and fluxes, and uu the sources. Write G(x)=∂f/∂xG(x) = \partial f/\partial x and C(x)=∂q/∂xC(x) = \partial q/\partial x. CC is usually singular, so the system is a DAE, and the time constants differ by many orders of magnitude, so it is a stiff problem. The output is a sequence of time points and solution values whose local error is below a tolerance at each step.

The algorithm

Let γ=2−2\gamma = 2 - \sqrt 2, c=γ/2c = \gamma/2, F(t,x)=u(t)−f(x)F(t, x) = u(t) - f(x) (which is q˙\dot q on a solution), and k=(−3γ2+4γ−2)/(12(2−γ))≈−0.0404k = (-3\gamma^2 + 4\gamma - 2)/(12(2 - \gamma)) \approx -0.0404.

  1. TR-BDF2(f, q, u, x0, t0, t_end, h, rtol, atol)
  2. 1t ← t0; x ← x0
  3. 2while t < t_end do
  4. 3x_γ ← solve q(x_γ) + c·h·(f(x_γ) − u(t + γh)) = q(x) + c·h·F(t, x) by Newton ▷ trapezoidal stage
  5. 4x_new ← solve q(x_new) + c·h·(f(x_new) − u(t + h)) = (q(x_γ) − (1 − γ)²·q(x)) / (γ(2 − γ)) by Newton ▷ BDF2 stage
  6. 5E ← 2kh·(F(t, x)/γ − F(t + γh, x_γ)/(γ(1 − γ)) + F(t + h, x_new)/(1 − γ))
  7. 6r ← max_i |E_i| / (rtol·|q_i(x_new)| + atol)
  8. 7if r ≤ 1 then t ← t + h; x ← x_new; record (t, x)
  9. 8h ← h · min(2, max(1/5, 0.9 · r^(−1/3))); h ← min(h, t_end − t)
  10. 9return the recorded points

Lines L3 and L4 each run Newton's method with the Jacobian C(x)+ch G(x)C(x) + c h\, G(x), the same form in both stages. In companion model terms, a capacitor CC becomes a conductance 2C/(γh)2C/(\gamma h) in both stages, with a different current source; for a linear circuit one LU factorization serves both stages and all steps of the same size. Line L5 estimates the local error from the second divided difference of FF, line L6 scales it, and line L8 picks the next step from the third-order behavior of the local error. When Newton fails to converge, a code cuts hh (by 4 in the code of this page) and retries the step. The initial x0x_0 must be consistent, for example the result of a DC operating point, so that the algebraic rows hold at t0t_0.

Example

One step on an RC circuit. A 1 V source charges C=1C = 1 F through R=1 ΩR = 1\ \Omega from v=0v = 0, so v˙=1−v\dot v = 1 - v, and we take h=0.5h = 0.5. The stage point is γh=0.2929\gamma h = 0.2929.

quantity TR-BDF2 exact
vv at t=0.2929t = 0.2929 (line L3) 0.29289/1.14645=0.255480.29289 / 1.14645 = 0.25548 1−e−0.2929=0.253901 - e^{-0.2929} = 0.25390
vv at t=0.5t = 0.5 (line L4) (1.20711⋅0.25548+0.14645)/1.14645=0.39674(1.20711 \cdot 0.25548 + 0.14645)/1.14645 = 0.39674 1−e−0.5=0.393471 - e^{-0.5} = 0.39347
error estimate EE (line L5) −0.00385-0.00385 true error, exact minus numerical: −0.00327-0.00327

The estimate has the right sign and size at this large step; on y˙=−y\dot y = -y its ratio to the true error is within 10 percent of 1 for h≤0.1h \le 0.1, measured by the test of this page.

Stiff decay. Let the capacitor start at 1 V and discharge with RC=1RC = 1 ms, sampled with h=10h = 10 ms, so hλ=−10h\lambda = -10. The exact value after one step is e−10≈4.5×10−5e^{-10} \approx 4.5 \times 10^{-5}.

step trapezoidal TR-BDF2 backward Euler
1 −0.6667-0.6667 −0.2036-0.2036 0.09090.0909
2 0.44440.4444 0.04140.0414 0.00830.0083
3 −0.2963-0.2963 −0.0084-0.0084 7.5×10−47.5 \times 10^{-4}
5 −0.1317-0.1317 −3.5×10−4-3.5 \times 10^{-4} 6.2×10−66.2 \times 10^{-6}

The trapezoidal values are (−2/3)n(-2/3)^n: they change sign at each step and are still 13 percent of the start after five steps. TR-BDF2 multiplies by R(−10)=−0.2036R(-10) = -0.2036 per step, and its factor goes to 0 as hλ→−∞h\lambda \to -\infty. Backward Euler damps even more but is only first order.

Correctness

TR-BDF2 is a consistent one-step method, so it converges with the order of its local error. With γ=2−2\gamma = 2 - \sqrt 2 the stability function is

R(z)=1+(2−1)z(1−2−22z)2,R(z) = \frac{1 + (\sqrt 2 - 1) z}{\left(1 - \tfrac{2 - \sqrt 2}{2} z\right)^2},

whose Taylor series agrees with eze^z up to z2z^2, with the z3z^3 term off by (32−4)/6≈0.0404(3\sqrt 2 - 4)/6 \approx 0.0404; so the method is second order. On the imaginary axis ∣R(iy)∣2=(1+s)/(1+s/2)2≤1|R(iy)|^2 = (1 + s)/(1 + s/2)^2 \le 1 with s=(3−22)y2s = (3 - 2\sqrt 2) y^2, its only pole is on the positive real axis, and R(z)→0R(z) \to 0 at infinity; so it is A-stable and L-stable. The trapezoidal rule has RT(z)=(1+z/2)/(1−z/2)→−1R_T(z) = (1 + z/2)/(1 - z/2) \to -1, so it is A-stable but not L-stable. The derivations, the second order on smooth ODEs and the error estimate are in the correctness proof. Second order for index-1 DAEs is shown by Bank et al. and Hosea and Shampine, and is cited, not proved there.

Proof: TR-BDF2 with gamma = 2 - sqrt(2) shares one matrix between its stages, is second order and is L-stablefull

We use the notation of the page. For the analysis we take the scalar test equation y′=λyy' = \lambda y of Dahlquist, written in circuit form with q(y)=yq(y) = y, f(y)=−λyf(y) = -\lambda y, u=0u = 0, and we put z=hλz = h\lambda. One step maps yny_n to yn+1=R(z) yny_{n+1} = R(z)\, y_n; RR is the stability function. For a linear circuit Cx˙+Gx=u(t)C\dot x + Gx = u(t) with nonsingular CC, the same results hold for each eigenvalue λ\lambda of −C−1G-C^{-1}G when C−1GC^{-1}G is diagonalizable, because the step is linear and commutes with the change of basis.

Coefficients. The BDF2 formula through the three points tnt_n, tn+γht_n + \gamma h, tn+ht_n + h is the derivative at tn+ht_n + h of the quadratic that interpolates qq at those points. Writing it as qn+1−dh qn+1′=a qn+γ−b qnq_{n+1} - d h\, q'_{n+1} = a\, q_{n+\gamma} - b\, q_n and asking that it be exact for q=1q = 1, q=t−tn+1q = t - t_{n+1} and q=(t−tn+1)2q = (t - t_{n+1})^2 gives

a−b=1,d=a(1−γ)−b,a(1−γ)2=b,a - b = 1, \qquad d = a(1 - \gamma) - b, \qquad a(1 - \gamma)^2 = b,

whose solution is a=1/(γ(2−γ))a = 1/(\gamma(2 - \gamma)), b=(1−γ)2/(γ(2−γ))b = (1 - \gamma)^2/(\gamma(2 - \gamma)), d=(1−γ)/(2−γ)d = (1 - \gamma)/(2 - \gamma).

Lemma 1 (one matrix for both stages). d=γ/2d = \gamma / 2 if and only if γ2−4γ+2=0\gamma^2 - 4\gamma + 2 = 0, that is γ=2±2\gamma = 2 \pm \sqrt 2; the root in (0,1)(0, 1) is γ=2−2\gamma = 2 - \sqrt 2. Then the Newton matrices of the two stages, C+(γh/2)GC + (\gamma h / 2) G and C+dh GC + d h\, G, are equal.

Proof. (1−γ)/(2−γ)=γ/2(1 - \gamma)/(2 - \gamma) = \gamma/2 is 2−2γ=2γ−γ22 - 2\gamma = 2\gamma - \gamma^2. The Newton matrix of a stage q(x)+β(f(x)−u)=constq(x) + \beta (f(x) - u) = \text{const} is C(x)+βG(x)C(x) + \beta G(x), with β=γh/2\beta = \gamma h/2 for the trapezoidal stage and β=dh\beta = d h for the BDF2 stage. □\square

From now on γ=2−2\gamma = 2 - \sqrt 2, and c=γ/2=1−1/2c = \gamma / 2 = 1 - 1/\sqrt 2. Then a=(2+1)/2a = (\sqrt 2 + 1)/2 and b=(2−1)/2b = (\sqrt 2 - 1)/2, so a−b=1a - b = 1 and a+b=2a + b = \sqrt 2.

Theorem 1 (stability function).

R(z)=1+(2−1)z(1−cz)2,c=2−22.R(z) = \frac{1 + (\sqrt 2 - 1) z}{(1 - c z)^2}, \qquad c = \frac{2 - \sqrt 2}{2}.

Proof. The trapezoidal stage gives yn+γ=1+cz1−cz yny_{n+\gamma} = \frac{1 + cz}{1 - cz}\, y_n, because γz/2=cz\gamma z / 2 = cz. The BDF2 stage gives (1−cz) yn+1=a yn+γ−b yn(1 - cz)\, y_{n+1} = a\, y_{n+\gamma} - b\, y_n. So

R(z)=a(1+cz)−b(1−cz)(1−cz)2=(a−b)+(a+b)cz(1−cz)2=1+2c z(1−cz)2,R(z) = \frac{a(1 + cz) - b(1 - cz)}{(1 - cz)^2} = \frac{(a - b) + (a + b) c z}{(1 - cz)^2} = \frac{1 + \sqrt 2 c\, z}{(1 - cz)^2},

and 2 c=2−1\sqrt 2\, c = \sqrt 2 - 1. □\square

Theorem 2 (second order on the test equation). R(z)−ez=32−46z3+O(z4)R(z) - e^z = \frac{3\sqrt 2 - 4}{6} z^3 + O(z^4). So the local error of one step is 32−46h3y′′′+O(h4)≈0.0404 h3y′′′\frac{3\sqrt 2 - 4}{6} h^3 y''' + O(h^4) \approx 0.0404\, h^3 y''' (numerical minus exact), and the error constant of the page is k=−(32−4)/6≈−0.0404k = -(3\sqrt 2 - 4)/6 \approx -0.0404 in the convention exact minus numerical.

Proof. Expand (1−cz)−2=1+2cz+3c2z2+4c3z3+O(z4)(1 - cz)^{-2} = 1 + 2cz + 3c^2 z^2 + 4c^3 z^3 + O(z^4) and multiply by 1+pz1 + pz with p=2−1p = \sqrt 2 - 1. Use c2=(3−22)/2c^2 = (3 - 2\sqrt 2)/2 and c3=(10−72)/4c^3 = (10 - 7\sqrt 2)/4. The coefficient of zz is p+2c=(2−1)+(2−2)=1p + 2c = (\sqrt 2 - 1) + (2 - \sqrt 2) = 1. The coefficient of z2z^2 is 2cp+3c2=(32−4)+(9−62)/2=1/22cp + 3c^2 = (3\sqrt 2 - 4) + (9 - 6\sqrt 2)/2 = 1/2. The coefficient of z3z^3 is 3c2p+4c3=(152−21)/2+(10−72)=(2−1)/23c^2 p + 4c^3 = (15\sqrt 2 - 21)/2 + (10 - 7\sqrt 2) = (\sqrt 2 - 1)/2. The coefficients of eze^z are 1,1,1/2,1/61, 1, 1/2, 1/6, and (2−1)/2−1/6=(32−4)/6(\sqrt 2 - 1)/2 - 1/6 = (3\sqrt 2 - 4)/6. For y′=λyy' = \lambda y, z3yn=h3y′′′(tn)z^3 y_n = h^3 y'''(t_n). □\square

Theorem 3 (second order on smooth ODEs). For y′=F(t,y)y' = F(t, y) with FF smooth and CC nonsingular in the circuit form, the local error of one step is O(h3)O(h^3), so the global error on a fixed interval is O(h2)O(h^2).

Proof. Start the step from the exact value y(tn)y(t_n). The trapezoidal rule has local error O(h3)O(h^3) for a step of γh\gamma h, so yn+γ=y(tn+γh)+O(h3)y_{n+\gamma} = y(t_n + \gamma h) + O(h^3). The BDF2 formula is exact for quadratics, so with the exact values y(tn)y(t_n), y(tn+γh)y(t_n + \gamma h) its residual at y(tn+h)y(t_n + h) is O(h3)O(h^3). The stage 2 equation yn+1−dhF(tn+1,yn+1)=ayn+γ−byny_{n+1} - dh F(t_{n+1}, y_{n+1}) = a y_{n+\gamma} - b y_n has a Jacobian I−dhFyI - dh F_y with a bounded inverse for small hh, so the O(h3)O(h^3) perturbations in the residual and in yn+γy_{n+\gamma} (multiplied by the fixed aa) change yn+1y_{n+1} by O(h3)O(h^3). A one-step method with local error O(hp+1)O(h^{p+1}) and a Lipschitz increment has global error O(hp)O(h^p), see order of accuracy. □\square

For index-1 DAEs, which is the usual case of MNA with a singular CC, the second order of the differential and algebraic parts is shown by Bank et al. (1985) and Hosea and Shampine (1996); it is not proved here.

Theorem 4 (L-stability). TR-BDF2 with γ=2−2\gamma = 2 - \sqrt 2 is A-stable: ∣R(z)∣≤1|R(z)| \le 1 for Re⁡z≤0\operatorname{Re} z \le 0. It is also L-stable: R(z)→0R(z) \to 0 as z→∞z \to \infty.

Proof. The only pole of RR is z=1/c>0z = 1/c > 0, so RR is analytic on the closed left half plane. On the imaginary axis, z=iyz = iy:

∣R(iy)∣2=1+p2y2(1+c2y2)2.|R(iy)|^2 = \frac{1 + p^2 y^2}{(1 + c^2 y^2)^2}.

With p2=3−22p^2 = 3 - 2\sqrt 2 and c2=p2/2c^2 = p^2/2, put s=(3−22)y2≥0s = (3 - 2\sqrt 2) y^2 \ge 0; then ∣R(iy)∣2=(1+s)/(1+s/2)2|R(iy)|^2 = (1 + s)/(1 + s/2)^2, and (1+s/2)2=1+s+s2/4≥1+s(1 + s/2)^2 = 1 + s + s^2/4 \ge 1 + s. So ∣R∣≤1|R| \le 1 on the imaginary axis. The numerator has degree 1 and the denominator degree 2, so R(z)→0R(z) \to 0 as ∣z∣→∞|z| \to \infty, and in fact zR(z)→p/c2=2(2+1)z R(z) \to p/c^2 = 2(\sqrt 2 + 1). By the maximum modulus principle on the left half plane (bounded, analytic, at most 1 on the boundary and tending to 0 at infinity), ∣R(z)∣≤1|R(z)| \le 1 for all Re⁡z≤0\operatorname{Re} z \le 0. □\square

Theorem 5 (the trapezoidal rule is A-stable but not L-stable). The trapezoidal rule has RT(z)=(1+z/2)/(1−z/2)R_T(z) = (1 + z/2)/(1 - z/2), with ∣RT(z)∣≤1|R_T(z)| \le 1 for Re⁡z≤0\operatorname{Re} z \le 0 and RT(z)→−1R_T(z) \to -1 as z→−∞z \to -\infty.

Proof. With w=z/2w = z/2, ∣1+w∣2−∣1−w∣2=4Re⁡w≤0|1 + w|^2 - |1 - w|^2 = 4 \operatorname{Re} w \le 0, so ∣RT∣≤1|R_T| \le 1. The limit is lim⁡(1+z/2)/(1−z/2)=−1\lim (1 + z/2)/(1 - z/2) = -1. □\square

So for a stiff component, z=hλ≪−1z = h\lambda \ll -1, the trapezoidal rule multiplies the error by a number close to −1-1 at each step: the error changes sign at each step and decays slowly. This is the ringing of the page's example, where z=−10z = -10 gives RT=−2/3R_T = -2/3 and R=−0.2036R = -0.2036.

Theorem 6 (the error estimate). Let F=u−fF = u - f, which equals q˙\dot q on a solution. For a smooth solution, the quantity

E=2kh(Fnγ−Fn+γγ(1−γ)+Fn+11−γ)E = 2 k h \left( \frac{F_n}{\gamma} - \frac{F_{n+\gamma}}{\gamma(1 - \gamma)} + \frac{F_{n+1}}{1 - \gamma} \right)

equals kh3q...+O(h4)k h^3 \dddot q + O(h^4), the leading term of the local error.

Proof. The second divided difference of FF at tnt_n, tn+γht_n + \gamma h, tn+ht_n + h is

F[tn,tn+γh,tn+h]=1h2(Fnγ−Fn+γγ(1−γ)+Fn+11−γ),F[t_n, t_n + \gamma h, t_n + h] = \frac{1}{h^2} \left( \frac{F_n}{\gamma} - \frac{F_{n+\gamma}}{\gamma(1 - \gamma)} + \frac{F_{n+1}}{1 - \gamma} \right),

by the formula ∑iFi/∏j≠i(ti−tj)\sum_i F_i / \prod_{j \ne i} (t_i - t_j). For a smooth function it equals F¨(ξ)/2=q...(ξ)/2\ddot F(\xi)/2 = \dddot q(\xi)/2 for some ξ\xi in the step, so E=2kh⋅h2⋅q.../2+O(h4)E = 2 k h \cdot h^2 \cdot \dddot q/2 + O(h^4). The stage values differ from the exact ones by O(h3)O(h^3), so each FiF_i and the bracket change by O(h3)O(h^3), and EE, which is 2kh2kh times the bracket, changes by O(h4)O(h^4). □\square

The value of kk for general nonlinear systems, and the use of this estimate for step size control, are due to Bank et al. (1985) and analysed by Hosea and Shampine (1996). The test on this page measures the ratio of the estimate to the true error of one step on y′=−yy' = -y; it is within 10 percent of 1 for h≤0.1h \le 0.1.

Complexity

Each accepted step costs two nonlinear solves, each with KK Newton iterations, and each iteration costs one evaluation of the device models and one sparse LU solve, for example with KLU. The total is O(NKT)O(N K T) for NN steps, where TT is the cost of one factor and solve; rejected steps add to NN. For a linear circuit with a fixed step, one factorization serves the whole run, and each stage costs only a forward and back substitution. The number of steps for a given tolerance grows like tol−1/3\text{tol}^{-1/3}, the rate of a method whose local error is O(h3)O(h^3). Measured on v˙=sin⁡3t−v\dot v = \sin 3t - v over [0,4][0, 4] (atol 10−810^{-8}, the code of this page):

rtol accepted steps rejected steps max error
10−310^{-3} 68 23 9.2×10−49.2 \times 10^{-4}
10−410^{-4} 131 31 2.1×10−42.1 \times 10^{-4}
10−510^{-5} 261 23 4.9×10−54.9 \times 10^{-5}
10−610^{-6} 512 8 1.1×10−51.1 \times 10^{-5}

The step count roughly doubles per decade of tolerance, close to 101/3≈2.1510^{1/3} \approx 2.15. The error is a global error, so it is larger than the per-step tolerance. These are toy measurements, not benchmark results.

Properties

  • Second order and L-stable. No method of the BDF family above order 2 is A-stable, and the trapezoidal rule is not L-stable; TR-BDF2 has both properties at order 2.
  • One-step. It needs only xnx_n to start a step, so a change of step size or a restart after a breakpoint (a corner of a source waveform) costs nothing extra, unlike variable-step BDF2.
  • One matrix per step. With γ=2−2\gamma = 2 - \sqrt 2 the stages share the Newton matrix form C+(γh/2)GC + (\gamma h/2) G.
  • Measured order. With fixed steps, the error at t=1t = 1 on the RC circuit above falls from 1.50×10−41.50 \times 10^{-4} (h=0.1h = 0.1) to 3.74×10−53.74 \times 10^{-5}, 9.32×10−69.32 \times 10^{-6} and 2.33×10−62.33 \times 10^{-6} as hh halves: ratios 4.02, 4.01, 4.00. On a series RLC circuit (R=1 ΩR = 1\ \Omega, L=1L = 1 H, C=1C = 1 F, a 1 V step, full MNA with a singular CC matrix, max error of the capacitor voltage over [0,5][0, 5]) the ratios are 4.02, 4.01, 4.00 from h=0.1h = 0.1. These are measurements of the code of this page against the closed-form solutions.
  • Smaller error constant than the trapezoidal rule per step of size h. On the RC circuit at h=0.1h = 0.1 the error is 1.50×10−41.50 \times 10^{-4}, about half that of the trapezoidal rule at the same hh reported on the companion model page, but TR-BDF2 does two stage solves per step.

Variants and improvements

  • Other values of γ\gamma. Any γ∈(0,1)\gamma \in (0, 1) gives a second-order method, and the stability function still tends to 0 at infinity; only γ=2−2\gamma = 2 - \sqrt 2 makes the two matrices equal, which is why it is the standard choice.
  • As a Runge-Kutta method. TR-BDF2 is a three-stage implicit Runge-Kutta method with an explicit first stage and equal diagonal entries (an ESDIRK). This view gives a cheap embedded error estimate and a smooth interpolant between points, both used by Hosea and Shampine, and their method is the solver ode23tb of MATLAB.
  • Other L-stable methods. Radau IIA methods are L-stable of order 3 and above but need larger linear systems; backward Euler is L-stable of order 1.

When to use it

Use TR-BDF2 for transient simulation of stiff circuits where trapezoidal ringing would show, such as circuits with switches, ideal sources driving capacitors, or very fast parasitic time constants, and where second order is accurate enough. Use the trapezoidal rule when the circuit is not stiff relative to the step and the lack of numerical damping is wanted, for example for oscillators, where the damping of BDF methods reduces the amplitude. Use higher-order BDF or Radau methods for very tight tolerances.

Pitfalls

  • Inconsistent start. The trapezoidal stage carries the residual of the algebraic rows at tnt_n into the next stage. Start from a consistent DC operating point, or after a breakpoint take a backward Euler step first.
  • Error control on algebraic variables. The estimate of line L5 is for qq, which is zero for purely algebraic rows. The node voltages without capacitance are controlled only through the rows they couple to; check the result on those nodes.
  • Damping of true oscillations. L-stability damps components with ∣hλ∣≫1|h\lambda| \gg 1, including real fast oscillations sampled with too large a step. The method then reports a smooth waveform that is wrong.
  • Absolute tolerance in the wrong units. The estimate is in charge and flux units. An absolute tolerance chosen for volts can be orders of magnitude too loose, as with an atol\text{atol} of 10−610^{-6} C on a 100 μ100\ \muF node, which allows 10 mV per step.

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.

sim3dense.pyI0RawGitHub
# 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)))
tr_bdf2.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tr-bdf2/. The authors are listed in prov/W1B2JC.jsonl.
"""TR-BDF2 for circuit equations f(x) + d/dt q(x) = u(t).

A circuit is any object with the methods
  f(x) -> list, G(x) -> matrix (df/dx), q(x) -> list, C(x) -> matrix (dq/dx),
  u(t) -> list,
in the notation of modified nodal analysis: x holds node voltages and branch
currents, f the resistive part, q the charges and fluxes, u the sources.

One step of size h from (t, x):
  stage 1, trapezoidal rule to t + gamma h,
  stage 2, BDF2 on the points t, t + gamma h, t + h.
With gamma = 2 - sqrt(2) both stages solve a system with the same matrix
C + (gamma h / 2) G, so for a linear circuit one LU serves both stages.
The local error estimate is 2 k h F[t, t + gamma h, t + h] h^2, the second
divided difference of F = u - f = dq/dt, with the error constant k.
"""

import math

from sim3dense import solve

GAMMA = 2 - math.sqrt(2)


def error_constant(g=GAMMA):
    """k with (exact - numerical) = k h^3 q''' + O(h^4) for one TR-BDF2 step."""
    return (-3 * g * g + 4 * g - 2) / (12 * (2 - g))


def stability_function(z, g=GAMMA):
    """R(z) of TR-BDF2 for y' = lambda y, z = h lambda, any gamma in (0, 1)."""
    r1 = (1 + g * z / 2) / (1 - g * z / 2)  # trapezoidal stage
    a = 1 / (g * (2 - g))
    b = (1 - g) ** 2 / (g * (2 - g))
    d = (1 - g) / (2 - g)
    return (a * r1 - b) / (1 - d * z)


class NewtonFailure(RuntimeError):
    """Newton's method did not converge for a stage."""


def _sub(a, b):
    return [x - y for x, y in zip(a, b)]


def _norm(v):
    return max((abs(x) for x in v), default=0.0)


def newton_stage(ckt, t, guess, qconst, beta, tol=1e-12, maxit=50):
    """Solve q(x) + beta (f(x) - u(t)) = qconst for x by Newton's method."""
    x = list(guess)
    ut = ckt.u(t)
    for it in range(maxit):
        r = [qi + beta * (fi - ui) - ci for qi, fi, ui, ci in zip(ckt.q(x), ckt.f(x), ut, qconst)]
        cm, gm = ckt.C(x), ckt.G(x)
        jac = [[c + beta * g for c, g in zip(crow, grow)] for crow, grow in zip(cm, gm)]
        dx = solve(jac, [-v for v in r])
        x = [a + b for a, b in zip(x, dx)]
        if _norm(dx) <= tol * (1 + _norm(x)):
            return x, it + 1
    raise NewtonFailure(f"no convergence at t = {t}")


def rate(ckt, t, x):
    """F = u - f, which equals dq/dt on a solution."""
    return [ui - fi for ui, fi in zip(ckt.u(t), ckt.f(x))]


def trapezoidal_step(ckt, t, x, h):
    """One step of the trapezoidal rule (used as stage 1 and for comparison)."""
    qn, fn = ckt.q(x), rate(ckt, t, x)
    qconst = [a + h / 2 * b for a, b in zip(qn, fn)]
    xn, _ = newton_stage(ckt, t + h, x, qconst, h / 2)
    return xn


def backward_euler_step(ckt, t, x, h):
    """One step of backward Euler (used for comparison)."""
    xn, _ = newton_stage(ckt, t + h, x, ckt.q(x), h)
    return xn


def tr_bdf2_step(ckt, t, x, h, g=GAMMA):
    """One TR-BDF2 step; returns (x_new, x_stage, error estimate in q)."""
    qn, fn = ckt.q(x), rate(ckt, t, x)
    qconst = [a + g * h / 2 * b for a, b in zip(qn, fn)]
    xg, _ = newton_stage(ckt, t + g * h, x, qconst, g * h / 2)  # @line L3
    qg = ckt.q(xg)
    a = 1 / (g * (2 - g))
    b = (1 - g) ** 2 / (g * (2 - g))
    d = (1 - g) / (2 - g)
    qconst2 = [a * p - b * r for p, r in zip(qg, qn)]
    xn, _ = newton_stage(ckt, t + h, xg, qconst2, d * h)  # @line L4
    k = error_constant(g)
    f0, f1, f2 = fn, rate(ckt, t + g * h, xg), rate(ckt, t + h, xn)
    est = [2 * k * h * (p / g - r / (g * (1 - g)) + s / (1 - g)) for p, r, s in zip(f0, f1, f2)]  # @line L5
    return xn, xg, est


def tr_bdf2_fixed(ckt, x0, t0, t1, steps):
    """Fixed step size; returns the list of (t, x)."""
    h = (t1 - t0) / steps
    out, x = [(t0, list(x0))], list(x0)
    for i in range(steps):
        x, _, _ = tr_bdf2_step(ckt, t0 + i * h, x, h)
        out.append((t0 + (i + 1) * h, x))
    return out


def tr_bdf2_adaptive(ckt, x0, t0, t1, h, rtol=1e-4, atol=1e-9, hmin=1e-15):
    """Adaptive step size from the local error estimate.

    Returns (points, rejected) where points is the list of accepted (t, x).
    """
    t, x = t0, list(x0)  # @line L1
    out, rejected = [(t, list(x))], 0
    while t < t1 and t1 - t > 1e-12 * max(1.0, abs(t1)):  # @line L2
        h = min(h, t1 - t)
        try:
            xn, _, est = tr_bdf2_step(ckt, t, x, h)
        except NewtonFailure:
            h /= 4
            rejected += 1
            if h < hmin:
                raise
            continue
        qn = ckt.q(xn)
        r = max(abs(e) / (rtol * abs(qv) + atol) for e, qv in zip(est, qn))  # @line L6
        if r <= 1:  # @line L7
            t, x = t + h, xn
            out.append((t, x))
        else:
            rejected += 1
        h *= min(2.0, max(0.2, 0.9 * (r if r > 0 else 1e-12) ** (-1 / 3)))  # @line L8
        if h < hmin:
            raise NewtonFailure("step size underflow")
    return out, rejected  # @line L9
test_tr_bdf2.py 259 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tr-bdf2/. The authors are listed in prov/W1B2JC.jsonl.

import cmath
import math
import random

from tr_bdf2 import (
    GAMMA,
    backward_euler_step,
    error_constant,
    stability_function,
    tr_bdf2_adaptive,
    tr_bdf2_fixed,
    tr_bdf2_step,
    trapezoidal_step,
)


class Scalar:
    """y' = lam y + s(t), written as f(y) + dq/dt = u with q = y, f = -lam y."""

    def __init__(self, lam, s=lambda t: 0.0):
        self.lam, self.s = lam, s

    def f(self, x):
        return [-self.lam * x[0]]

    def G(self, x):
        return [[-self.lam]]

    def q(self, x):
        return [x[0]]

    def C(self, x):
        return [[1.0]]

    def u(self, t):
        return [self.s(t)]


class RC:
    """Node voltage v of a capacitor C to ground, fed through R from a source vs(t)."""

    def __init__(self, r, c, vs):
        self.r, self.c, self.vs = r, c, vs

    def f(self, x):
        return [x[0] / self.r]

    def G(self, x):
        return [[1 / self.r]]

    def q(self, x):
        return [self.c * x[0]]

    def C(self, x):
        return [[self.c]]

    def u(self, t):
        return [self.vs(t) / self.r]


class SeriesRLC:
    """MNA of a source V at node 1, R from 1 to 2, L from 2 to 3, C from 3 to ground.

    x = (e1, e2, e3, jV, jL). The matrix C is singular: an index-1 DAE.
    """

    def __init__(self, r, l, c, v):
        self.r, self.l, self.c, self.v = r, l, c, v

    def f(self, x):
        e1, e2, e3, jv, jl = x
        g = 1 / self.r
        return [g * (e1 - e2) + jv, g * (e2 - e1) + jl, -jl, e1, e2 - e3]

    def G(self, x):
        g = 1 / self.r
        return [
            [g, -g, 0, 1, 0],
            [-g, g, 0, 0, 1],
            [0, 0, 0, 0, -1],
            [1, 0, 0, 0, 0],
            [0, 1, -1, 0, 0],
        ]

    def q(self, x):
        return [0.0, 0.0, self.c * x[2], 0.0, -self.l * x[4]]

    def C(self, x):
        m = [[0.0] * 5 for _ in range(5)]
        m[2][2] = self.c
        m[4][4] = -self.l
        return m

    def u(self, t):
        return [0.0, 0.0, 0.0, self.v(t), 0.0]


class Rectifier:
    """Half-wave rectifier: source at node 1, diode from 1 to 2, R and C from 2 to ground.

    x = (e1, e2, jV). Diode i = IS (exp(v / VT) - 1); IS and the emission
    coefficient inside VT are fitted model parameters (typical values here).
    The exponential is continued linearly above 40 VT, as SPICE-like codes do.
    """

    IS, VT = 1e-14, 0.025875

    def __init__(self, r, c, amp, freq):
        self.r, self.c, self.amp, self.freq = r, c, amp, freq

    def _diode(self, v):
        vmax = 40 * self.VT
        if v <= vmax:
            e = math.exp(v / self.VT)
            return self.IS * (e - 1), self.IS * e / self.VT
        e = math.exp(vmax / self.VT)
        return self.IS * (e * (1 + (v - vmax) / self.VT) - 1), self.IS * e / self.VT

    def f(self, x):
        e1, e2, jv = x
        i, _ = self._diode(e1 - e2)
        return [i + jv, -i + e2 / self.r, e1]

    def G(self, x):
        e1, e2, _ = x
        _, g = self._diode(e1 - e2)
        return [[g, -g, 1], [-g, g + 1 / self.r, 0], [1, 0, 0]]

    def q(self, x):
        return [0.0, self.c * x[1], 0.0]

    def C(self, x):
        return [[0.0, 0.0, 0.0], [0.0, self.c, 0.0], [0.0, 0.0, 0.0]]

    def u(self, t):
        return [0.0, 0.0, self.amp * math.sin(2 * math.pi * self.freq * t)]


def test_gamma_makes_stage_matrices_equal():
    g = GAMMA
    d = (1 - g) / (2 - g)
    assert abs(d - g / 2) < 1e-15
    a = 1 / (g * (2 - g))
    b = (1 - g) ** 2 / (g * (2 - g))
    assert abs(a - b - 1) < 1e-14  # consistency
    assert abs(a + b - math.sqrt(2)) < 1e-14


def test_stability_function_closed_form_and_step():
    c = (2 - math.sqrt(2)) / 2
    rng = random.Random(41)
    for _ in range(200):
        z = complex(rng.uniform(-50, 5), rng.uniform(-50, 50))
        closed = (1 + (math.sqrt(2) - 1) * z) / (1 - c * z) ** 2
        assert abs(stability_function(z) - closed) < 1e-12 * max(1, abs(closed))
    for z in (-0.5, -3.0, -10.0, -1000.0):
        y1, _, _ = tr_bdf2_step(Scalar(z), 0.0, [1.0], 1.0)
        assert abs(y1[0] - stability_function(z)) < 1e-12


def test_l_stability():
    for k in range(-400, 401):
        y = k / 4
        assert abs(stability_function(complex(0, y))) <= 1 + 1e-14
    # R(z) -> 0 like 2 (sqrt 2 + 1) / z as z -> -infinity
    for z in (-1e6, -1e9):
        assert abs(z * stability_function(z) - 2 * (math.sqrt(2) + 1)) < 1e-4
    # |R(iy)|^2 = (1 + s) / (1 + s/2)^2 with s = (3 - 2 sqrt 2) y^2
    for y in (0.3, 1.0, 7.0, 100.0):
        s = (3 - 2 * math.sqrt(2)) * y * y
        assert abs(abs(stability_function(complex(0, y))) ** 2 - (1 + s) / (1 + s / 2) ** 2) < 1e-12


def test_second_order_on_taylor_series():
    # R(z) - e^z = -k z^3 + O(z^4), with the error constant k
    k = error_constant()
    assert abs(k - (-(3 * math.sqrt(2) - 4) / 6)) < 1e-15
    for z in (1e-2, 5e-3):
        lead = (stability_function(z) - math.exp(z)) / z**3
        assert abs(lead + k) < 0.05 * abs(k)


def rc_error(steps):
    ckt = RC(1.0, 1.0, lambda t: 1.0)
    out = tr_bdf2_fixed(ckt, [0.0], 0.0, 1.0, steps)
    return abs(out[-1][1][0] - (1 - math.exp(-1.0)))


def rlc_exact(t):
    alpha, wd = 0.5, math.sqrt(0.75)
    return 1 - math.exp(-alpha * t) * (math.cos(wd * t) + alpha / wd * math.sin(wd * t))


def rlc_error(steps):
    ckt = SeriesRLC(1.0, 1.0, 1.0, lambda t: 1.0)
    out = tr_bdf2_fixed(ckt, [1.0, 1.0, 0.0, 0.0, 0.0], 0.0, 5.0, steps)
    return max(abs(x[2] - rlc_exact(t)) for t, x in out)


def test_order_two_on_rc_and_rlc():
    e = [rc_error(s) for s in (10, 20, 40, 80)]
    ratios = [e[i] / e[i + 1] for i in range(3)]
    assert all(3.7 < r < 4.3 for r in ratios), ratios
    e = [rlc_error(s) for s in (50, 100, 200, 400)]
    ratios = [e[i] / e[i + 1] for i in range(3)]
    assert all(3.7 < r < 4.3 for r in ratios), ratios


def test_stiff_damping_versus_trapezoidal_ringing():
    # RC = 1 ms, h = 10 ms: h lambda = -10. The capacitor starts at 1 V, the source is 0.
    ckt = RC(1e-3, 1.0, lambda t: 0.0)
    x_tr, x_tb, x_be = [1.0], [1.0], [1.0]
    trap, trbdf, be = [], [], []
    for n in range(10):
        x_tr = trapezoidal_step(ckt, n * 0.01, x_tr, 0.01)
        x_tb, _, _ = tr_bdf2_step(ckt, n * 0.01, x_tb, 0.01)
        x_be = backward_euler_step(ckt, n * 0.01, x_be, 0.01)
        trap.append(x_tr[0])
        trbdf.append(x_tb[0])
        be.append(x_be[0])
    for n, v in enumerate(trap, 1):
        assert abs(v - (-2 / 3) ** n) < 1e-12
    assert abs(trbdf[0] - stability_function(-10.0)) < 1e-12
    assert abs(trap[4]) > 0.13 and abs(trbdf[4]) < 4e-4 and abs(be[4]) < 1e-5


def test_error_estimate_matches_true_error():
    ckt = Scalar(-1.0)
    for h in (0.1, 0.05, 0.025):
        y1, _, est = tr_bdf2_step(ckt, 0.0, [1.0], h)
        true = math.exp(-h) - y1[0]
        assert abs(est[0] / true - 1) < 0.1


def test_adaptive_rc_and_rectifier():
    ckt = RC(1.0, 1.0, lambda t: math.sin(3 * t))
    out, rej = tr_bdf2_adaptive(ckt, [0.0], 0.0, 4.0, 1e-3, rtol=1e-6, atol=1e-8)

    def exact(t):  # v' = sin 3t - v, v(0) = 0
        return (math.sin(3 * t) - 3 * math.cos(3 * t) + 3 * math.exp(-t)) / 10

    assert max(abs(x[0] - exact(t)) for t, x in out) < 2e-5
    assert len(out) < 600
    # the step count grows by about 10^(1/3) per decade of tolerance (local error h^3)
    n3 = len(tr_bdf2_adaptive(ckt, [0.0], 0.0, 4.0, 1e-3, rtol=1e-3, atol=1e-8)[0])
    n6 = len(out)
    assert 5 < n6 / n3 < 12

    rect = Rectifier(1e3, 1e-4, 5.0, 50.0)
    x0 = [0.0, 0.0, 0.0]
    out, rej = tr_bdf2_adaptive(rect, x0, 0.0, 0.04, 1e-5, rtol=1e-4, atol=1e-10)
    ref = tr_bdf2_fixed(rect, x0, 0.0, 0.04, 4000)
    assert abs(out[-1][1][1] - ref[-1][1][1]) < 2e-3
    assert len(out) < 200
    peak = max(x[1] for _, x in ref)
    assert 4.2 < peak < 4.4  # about one diode drop below 5 V

History

Bank, Coughran, Fichtner, Grosse, Rose and Smith introduced TR-BDF2 in 1985, in a paper on the transient simulation of silicon devices and circuits, to remove the ringing of the trapezoidal rule while keeping one matrix per step. Hosea and Shampine (1996) analysed it as a one-step Runge-Kutta method, and derived its error constant, an embedded error estimate and an interpolant. Najm's textbook presents trapezoidal ringing and variable-step methods in the circuit setting.

References

  1. Randolph E. Bank, William M. Coughran Jr., Wolfgang Fichtner, Eric H. Grosse, Donald J. Rose and R. Kent Smith, Transient simulation of silicon devices and circuits, IEEE Transactions on Computer-Aided Design 4(4), 436 to 451, 1985, the composite trapezoidal and BDF2 step, the choice of gamma, and the error estimate for step control
  2. M. E. Hosea and L. F. Shampine, Analysis and implementation of TR-BDF2, Applied Numerical Mathematics 20, 1996, the analysis as a one-step method, the error constant, the error estimate and the interpolant
  3. Farid N. Najm, Circuit Simulation, Wiley-IEEE Press, 2010, Chapter 5, Sections 5.5 (trapezoidal ringing) and 5.6 (variable time-step methods)
  4. Ernst Hairer and Gerhard Wanner, Solving Ordinary Differential Equations II, Stiff and Differential-Algebraic Problems, second edition, Springer, 1996, the chapter on stability of implicit Runge-Kutta methods (A-stability, L-stability and the stability function)

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