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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 does a trapezoidal stage from to and then a second-order backward differentiation stage (BDF2) through , and . With 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,
from to , where holds node voltages and branch currents, the resistive currents and branch laws, the charges and fluxes, and the sources. Write and . 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 , , (which is on a solution), and .
TR-BDF2(f, q, u, x0, t0, t_end, h, rtol, atol)- 1
t ← t0; x ← x0 - 2
while t < t_end do - 3
x_γ ← solve q(x_γ) + c·h·(f(x_γ) − u(t + γh)) = q(x) + c·h·F(t, x) by Newton ▷ trapezoidal stage - 4
x_new ← solve q(x_new) + c·h·(f(x_new) − u(t + h)) = (q(x_γ) − (1 − γ)²·q(x)) / (γ(2 − γ)) by Newton ▷ BDF2 stage - 5
E ← 2kh·(F(t, x)/γ − F(t + γh, x_γ)/(γ(1 − γ)) + F(t + h, x_new)/(1 − γ)) - 6
r ← max_i |E_i| / (rtol·|q_i(x_new)| + atol) - 7
if r ≤ 1 then t ← t + h; x ← x_new; record (t, x) - 8
h ← h · min(2, max(1/5, 0.9 · r^(−1/3))); h ← min(h, t_end − t) - 9
return the recorded points
Lines L3 and L4 each run Newton's method with the Jacobian , the same form in both stages. In companion model terms, a capacitor becomes a conductance 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 , 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 (by 4 in the code of this page) and retries the step. The initial must be consistent, for example the result of a DC operating point, so that the algebraic rows hold at .
Example
One step on an RC circuit. A 1 V source charges F through from , so , and we take . The stage point is .
| quantity | TR-BDF2 | exact |
|---|---|---|
| at (line L3) | ||
| at (line L4) | ||
| error estimate (line L5) | true error, exact minus numerical: |
The estimate has the right sign and size at this large step; on its ratio to the true error is within 10 percent of 1 for , measured by the test of this page.
Stiff decay. Let the capacitor start at 1 V and discharge with ms, sampled with ms, so . The exact value after one step is .
| step | trapezoidal | TR-BDF2 | backward Euler |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 5 |
The trapezoidal values are : they change sign at each step and are still 13 percent of the start after five steps. TR-BDF2 multiplies by per step, and its factor goes to 0 as . 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 the stability function is
whose Taylor series agrees with up to , with the term off by ; so the method is second order. On the imaginary axis with , its only pole is on the positive real axis, and at infinity; so it is A-stable and L-stable. The trapezoidal rule has , 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 of Dahlquist, written in circuit form with , , , and we put . One step maps to ; is the stability function. For a linear circuit with nonsingular , the same results hold for each eigenvalue of when is diagonalizable, because the step is linear and commutes with the change of basis.
Coefficients. The BDF2 formula through the three points , , is the derivative at of the quadratic that interpolates at those points. Writing it as and asking that it be exact for , and gives
whose solution is , , .
Lemma 1 (one matrix for both stages). if and only if , that is ; the root in is . Then the Newton matrices of the two stages, and , are equal.
Proof. is . The Newton matrix of a stage is , with for the trapezoidal stage and for the BDF2 stage.
From now on , and . Then and , so and .
Theorem 1 (stability function).
Proof. The trapezoidal stage gives , because . The BDF2 stage gives . So
and .
Theorem 2 (second order on the test equation). . So the local error of one step is (numerical minus exact), and the error constant of the page is in the convention exact minus numerical.
Proof. Expand and multiply by with . Use and . The coefficient of is . The coefficient of is . The coefficient of is . The coefficients of are , and . For , .
Theorem 3 (second order on smooth ODEs). For with smooth and nonsingular in the circuit form, the local error of one step is , so the global error on a fixed interval is .
Proof. Start the step from the exact value . The trapezoidal rule has local error for a step of , so . The BDF2 formula is exact for quadratics, so with the exact values , its residual at is . The stage 2 equation has a Jacobian with a bounded inverse for small , so the perturbations in the residual and in (multiplied by the fixed ) change by . A one-step method with local error and a Lipschitz increment has global error , see order of accuracy.
For index-1 DAEs, which is the usual case of MNA with a singular , 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 is A-stable: for . It is also L-stable: as .
Proof. The only pole of is , so is analytic on the closed left half plane. On the imaginary axis, :
With and , put ; then , and . So on the imaginary axis. The numerator has degree 1 and the denominator degree 2, so as , and in fact . By the maximum modulus principle on the left half plane (bounded, analytic, at most 1 on the boundary and tending to 0 at infinity), for all .
Theorem 5 (the trapezoidal rule is A-stable but not L-stable). The trapezoidal rule has , with for and as .
Proof. With , , so . The limit is .
So for a stiff component, , the trapezoidal rule multiplies the error by a number close to at each step: the error changes sign at each step and decays slowly. This is the ringing of the page's example, where gives and .
Theorem 6 (the error estimate). Let , which equals on a solution. For a smooth solution, the quantity
equals , the leading term of the local error.
Proof. The second divided difference of at , , is
by the formula . For a smooth function it equals for some in the step, so . The stage values differ from the exact ones by , so each and the bracket change by , and , which is times the bracket, changes by .
The value of 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 ; it is within 10 percent of 1 for .
Complexity
Each accepted step costs two nonlinear solves, each with Newton iterations, and each iteration costs one evaluation of the device models and one sparse LU solve, for example with KLU. The total is for steps, where is the cost of one factor and solve; rejected steps add to . 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 , the rate of a method whose local error is . Measured on over (atol , the code of this page):
| rtol | accepted steps | rejected steps | max error |
|---|---|---|---|
| 68 | 23 | ||
| 131 | 31 | ||
| 261 | 23 | ||
| 512 | 8 |
The step count roughly doubles per decade of tolerance, close to . 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 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 the stages share the Newton matrix form .
- Measured order. With fixed steps, the error at on the RC circuit above falls from () to , and as halves: ratios 4.02, 4.01, 4.00. On a series RLC circuit (, H, F, a 1 V step, full MNA with a singular matrix, max error of the capacitor voltage over ) the ratios are 4.02, 4.01, 4.00 from . 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 the error is , about half that of the trapezoidal rule at the same reported on the companion model page, but TR-BDF2 does two stage solves per step.
Variants and improvements
- Other values of . Any gives a second-order method, and the stability function still tends to 0 at infinity; only 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 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 , 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 , 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 of C on a F 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.
# 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
- 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
- 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
- Farid N. Najm, Circuit Simulation, Wiley-IEEE Press, 2010, Chapter 5, Sections 5.5 (trapezoidal ringing) and 5.6 (variable time-step methods)
- 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.
| 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 W1B2JC Edit this page History Report an error Markdown