Algorithm Search⌘K

Algorithmadvanced

Shooting Newton periodic steady state

Also called Aprille-Trick shooting, periodic steady-state shooting.

Aprille and Trick's method that searches for the initial state whose transient over one period returns to itself, solved by Newton with the sensitivity matrix.

Time
O(I S n^3) worst
Space
O(n^2 + S n) extra
Where
I = the number of Newton iterations; S = the number of time steps per period; n = the number of MNA unknowns
Properties
deterministicnot exactiterative
Origin
Thomas J. Aprille, Timothy N. Trick, 1972

Shooting Newton finds the periodic steady state of a circuit with periodic sources by searching for the initial state from which one period of transient analysis returns to the same state. Aprille and Trick (1972) solved this condition, x(T)=x(0)x(T) = x(0), with Newton's method, and got the Jacobian from the sensitivity of the transient to its initial state, the monodromy matrix. It belongs to the circuit simulation half of the logic and circuit simulation sub-area, next to harmonic balance, and it suits circuits with sharp edges and slow time constants.

In plain words

A circuit with a slow filter can take thousands of periods to settle after power-up. A plain transient run must simulate all of them, even when only the final repeating waveform matters.

Shooting asks a sharper question: from which starting state does one period of simulation end exactly where it started? It guesses a start, simulates one period, and sees how far the end is from the start. It also tracks how the end would move if the start moved a little. With that information it corrects the guess, as a gunner corrects the aim after one shot. For a linear circuit the second guess is right; for a nonlinear one a few more corrections usually suffice, and each costs about one period of simulation.

The problem

The circuit is in modified nodal analysis form, f(x)+ddtq(x)=u(t)f(x) + \frac{d}{dt} q(x) = u(t), with x=(e1,…,en,j1,…,jm)x = (e_1, \ldots, e_n, j_1, \ldots, j_m), G=∂f/∂xG = \partial f/\partial x, C=∂q/∂xC = \partial q/\partial x, and every source has period TT. A periodic steady state is a solution with x(t+T)=x(t)x(t + T) = x(t). Its initial state is a root of

r(x0)=ϕT(x0)−x0,r(x_0) = \phi_T(x_0) - x_0,

where ϕT(x0)\phi_T(x_0) is the state at time TT of the transient that starts at x0x_0. This is the shooting method for a boundary value problem whose boundary condition is periodicity.

In practice ϕT\phi_T is the transient analysis with SS fixed steps of size h=T/Sh = T/S, with the trapezoidal rule (θ=12\theta = \tfrac12) or backward Euler (θ=1\theta = 1):

q(xk+1)−q(xk)+h[θ (f(xk+1)−uk+1)+(1−θ)(f(xk)−uk)]=0.q(x_{k+1}) - q(x_k) + h\big[\theta\,(f(x_{k+1}) - u_{k+1}) + (1 - \theta)(f(x_k) - u_k)\big] = 0.

The method finds the exact periodic solution of this discrete map, which differs from the continuous steady state by the integration error. Input: the circuit, TT, SS, θ\theta and a start. Output: x0x_0 and the states of one period. The device equations have fitted parameters: in the example, the diode saturation current ISI_S and emission coefficient NN are fitted to measurements.

The algorithm

  1. SHOOT(circuit, T, S, θ)
  2. 1x₀ ← a start state (zero, or the DC operating point); h ← T/S
  3. 2repeat
  4. 3for k = 0, ..., S − 1: x_{k+1} ← one implicit step from x_k at time kh
  5. 4Φ ← (C_{k+1} + θhG_{k+1})⁻¹ (C_k − (1 − θ)hG_k) Φ, starting from Φ = I
  6. 5r ← x_S − x₀
  7. 6solve (Φ − I)Δ = −r; x₀ ← x₀ + λΔ with a step limit λ ≤ 1
  8. 7until λ = 1 and Δ is small
  9. 8return x₀ and the states x_0, ..., x_S of one period

Line L3 is an ordinary transient step: Newton's method on the step equation, with the matrix Ck+1+θhGk+1C_{k+1} + \theta h G_{k+1} of the companion model. Line L4 is the extra work of shooting. Differentiating the step equation with respect to x0x_0 gives (Ck+1+θhGk+1) ∂xk+1/∂x0=(Ck−(1−θ)hGk) ∂xk/∂x0(C_{k+1} + \theta hG_{k+1})\,\partial x_{k+1}/\partial x_0 = (C_k - (1 - \theta)hG_k)\,\partial x_k/\partial x_0, and the matrix on the left is the one the step has just factored. After SS steps, Φ=∂xS/∂x0\Phi = \partial x_S/\partial x_0 is the monodromy matrix of the discrete map, and line L6 is exactly Newton's step for rr. The step limit keeps node voltages from moving more than 1 V per iteration.

The implementation stores Φ\Phi as a dense n×nn \times n matrix and solves line L6 directly. For large circuits, Telichevesky, Kundert and White (1995) never form Φ\Phi: they solve line L6 with GMRES, and each product Φv\Phi v is one pass of SS triangular solves with the stored factors of the steps.

Example

An RC circuit, by hand. A current source cos⁡(ωt)/R\cos(\omega t)/R drives R=1R = 1 kΩ in parallel with CC, where ω=2π⋅1\omega = 2\pi \cdot 1 MHz and ωRC=1\omega RC = 1. The continuous steady state is v(t)=Re⁡(ejωt/(1+j))v(t) = \operatorname{Re}\big(e^{j\omega t}/(1 + j)\big), so v(0)=0.5v(0) = 0.5. With the trapezoidal rule and S=100S = 100, starting from x0=0x_0 = 0, one period ends at xS=0.49890x_S = 0.49890 V. Each step multiplies a change of the state by ρ=(1−a)/(1+a)\rho = (1 - a)/(1 + a) with a=h/(2RC)a = h/(2RC), so Φ=ρ100=0.0018636\Phi = \rho^{100} = 0.0018636, close to e−T/RC=e−2π=0.0018674e^{-T/RC} = e^{-2\pi} = 0.0018674. Newton gives x0=0−(0.49890−0)/(0.0018636−1)=0.49984x_0 = 0 - (0.49890 - 0)/(0.0018636 - 1) = 0.49984 V. A second period from this state returns to it to rounding, so the method stops after one correction. The value is the exact steady state of the discrete map, the AC phasor at the warped frequency 2htan⁡ωh2\tfrac2h\tan\tfrac{\omega h}2, and it differs from 0.5 by 1.6×10−41.6 \times 10^{-4}, the second-order error of the integration.

A rectifier with a slow load, measured. A 2 V, 1 MHz sine source behind 1 kΩ (with 10 pF at its node) drives a diode into a load of 100 kΩ in parallel with 1 nF, a time constant of 100 periods. The diode has IS=10−14I_S = 10^{-14} A and N=1N = 1, fitted values for a small silicon diode. With the trapezoidal rule and S=100S = 100, shooting from zero needs 7 Newton iterations. The residual max⁡∣xS−x0∣\max|x_S - x_0| of the successive iterations was:

iteration 1 2 3 4 5 6 7
residual (V) 0.286 0.0503 0.00745 4.97e-4 3.27e-6 1.47e-10 8.9e-16

The last steps show the quadratic convergence of Newton's method: from iteration 4 to 6, each residual is about 13 times the square of the one before, and iteration 7 reaches rounding. The output settles at a mean of 1.2569 V with a ripple of 10.7 mV. The plain transient from zero with the same steps needs 155 periods before x(T)x(T) changes by less than 1 nV in one period, and it then stops 7.3×10−97.3 \times 10^{-9} V from the shooting result. The dominant eigenvalue of Φ\Phi at the steady state is 0.8906, which is the factor by which the transient's error falls in each period. Measured with Python's process time on one machine, shooting took 0.04 s and the transient 0.69 s. With S=200S = 200 and S=400S = 400 the iteration counts and residuals are the same, and the output voltage at t=0t = 0 changes by 1.9×10−51.9 \times 10^{-5} V and then 4.8×10−64.8 \times 10^{-6} V, a factor of 4 per halving of hh.

Correctness

The proof in proofs/correctness.md shows:

  1. A periodic steady state is a root of x(T)−x(0)x(T) - x(0). The sources repeat after SS steps, so the step maps repeat, and a solution with xS=x0x_S = x_0 repeats forever. The same argument holds for the exact flow when its initial value problem has unique solutions.
  2. Shooting Newton uses the monodromy matrix. By implicit differentiation of each step and the chain rule, the product of line L4 is ∂xS/∂x0\partial x_S/\partial x_0, so Φ−I\Phi - I is the Jacobian of rr and line L6 is Newton's step; it converges quadratically near a root where Φ−I\Phi - I is nonsingular.
  3. Linear circuits. rr is affine, so one Newton step solves it, and the discrete steady state for a sinusoidal source is the AC phasor at the frequency j2htan⁡ωh2j\tfrac2h\tan\tfrac{\omega h}2 (trapezoidal) or (1−e−jωh)/h(1 - e^{-j\omega h})/h (backward Euler), within O(h2)O(h^2) or O(h)O(h) of the exact one.
  4. The trapezoidal rule and algebraic rows. For a row with no charge term, such as a voltage source, the trapezoidal rule gives gTΦ=(−1)SgTg^{\mathsf T}\Phi = (-1)^S g^{\mathsf T}, so Φ−I\Phi - I is singular for even SS; backward Euler gives gTΦ=0g^{\mathsf T}\Phi = 0.

The discretization error for nonlinear circuits and the convergence rate of the plain transient are measured, not proved.

The tests check, with fixed seeds:

  • A parallel RLC circuit with the trapezoidal rule at S=40,80,160S = 40, 80, 160: one Newton step, and every state equal to the warped-frequency phasor to 10−1210^{-12}.
  • An RC circuit with a voltage source and backward Euler: the same against its discrete phasor.
  • The error against the analytic steady state: 1.50×10−31.50 \times 10^{-3}, 3.74×10−43.74 \times 10^{-4} and 9.35×10−59.35 \times 10^{-5} V, a ratio of 4.0 per halving.
  • Φ\Phi against central differences of the period map for random starts (seed 61), to a relative error of 10−610^{-6}.
  • The rectifier against the long transient, and the quadratic decrease of the residuals.
  • The identity gT(Φ−I)=0g^{\mathsf T}(\Phi - I) = 0 for S=64S = 64 and −2gT-2g^{\mathsf T} for S=65S = 65 with the trapezoidal rule, and gTΦ=0g^{\mathsf T}\Phi = 0 with backward Euler. With S=64S = 64, the Newton matrix has an exactly zero pivot.
Proof: A periodic steady state is a root of x(T) − x(0), and shooting Newton uses the monodromy matrixfull

We use the notation of the page. The circuit is f(x)+ddtq(x)=u(t)f(x) + \frac{d}{dt} q(x) = u(t) with NN unknowns, ff and qq continuously differentiable with Jacobians G(x)G(x) and C(x)C(x), and u(t+T)=u(t)u(t + T) = u(t). The step is h=T/Sh = T/S, tk=kht_k = kh, uk=u(tk)u_k = u(t_k), and θ=12\theta = \tfrac12 (trapezoidal rule) or θ=1\theta = 1 (backward Euler). One step from xkx_k to xk+1x_{k+1} solves

Ek(xk,xk+1)=q(xk+1)−q(xk)+h[θ (f(xk+1)−uk+1)+(1−θ)(f(xk)−uk)]=0.(1)E_k(x_k, x_{k+1}) = q(x_{k+1}) - q(x_k) + h\big[\theta\,(f(x_{k+1}) - u_{k+1}) + (1 - \theta)(f(x_k) - u_k)\big] = 0. \tag{1}

Put Ak=C(xk+1)+θh G(xk+1)A_k = C(x_{k+1}) + \theta h\, G(x_{k+1}) and Bk=C(xk)−(1−θ)h G(xk)B_k = C(x_k) - (1 - \theta) h\, G(x_k), so that ∂Ek/∂xk+1=Ak\partial E_k/\partial x_{k+1} = A_k and ∂Ek/∂xk=−Bk\partial E_k/\partial x_k = -B_k. We assume that every AkA_k met is nonsingular and that (1) has exactly one solution xk+1x_{k+1} in the region where the iterates stay. Then (1) defines a step map xk+1=ψk(xk)x_{k+1} = \psi_k(x_k), and by the implicit function theorem ψk\psi_k is continuously differentiable with ψk′(xk)=Ak−1Bk\psi_k'(x_k) = A_k^{-1} B_k. The period map is P=ψS−1∘⋯∘ψ0P = \psi_{S-1} \circ \cdots \circ \psi_0.

Fixed points are periodic steady states

Theorem 1. Let x0,x1,x2,…x_0, x_1, x_2, \ldots solve (1) for every k≥0k \ge 0. The sequence is periodic with period SS (that is, xk+S=xkx_{k+S} = x_k for all kk) if and only if xS=x0x_S = x_0, that is, if and only if x0x_0 is a root of r(x0)=P(x0)−x0r(x_0) = P(x_0) - x_0.

Proof. If the sequence is SS-periodic, then xS=x0x_S = x_0. Conversely, uk+S=u(tk+T)=uku_{k+S} = u(t_k + T) = u_k, and ff and qq do not depend on time, so Ek+S=EkE_{k+S} = E_k and ψk+S=ψk\psi_{k+S} = \psi_k for every kk. Suppose xS=x0x_S = x_0. By induction on kk, if xk+S=xkx_{k+S} = x_k then xk+1+S=ψk+S(xk+S)=ψk(xk)=xk+1x_{k+1+S} = \psi_{k+S}(x_{k+S}) = \psi_k(x_k) = x_{k+1}. □\square

The same argument holds for the exact solution. If the initial value problem has a unique solution from every consistent state, the solution from x(0)x(0) satisfies x(t+T)=x(t)x(t + T) = x(t) for all tt if and only if x(T)=x(0)x(T) = x(0), because t↦x(t+T)t \mapsto x(t + T) solves the same equation with the same value at t=0t = 0. So the periodic steady state of the circuit is a root of x(T)−x(0)x(T) - x(0), and the discrete problem replaces x(T)x(T) by P(x0)P(x_0).

The Newton matrix is the monodromy matrix minus the identity

Theorem 2. Let Φ0=I\Phi_0 = I and Φk+1=Ak−1BkΦk\Phi_{k+1} = A_k^{-1} B_k \Phi_k. Then ΦS=P′(x0)\Phi_S = P'(x_0), and the step of line L6, (ΦS−I)Δ=−r(x0)(\Phi_S - I)\Delta = -r(x_0), is the Newton step for rr.

Proof. By the chain rule, ∂xk+1/∂x0=ψk′(xk) ∂xk/∂x0=Ak−1Bk ∂xk/∂x0\partial x_{k+1}/\partial x_0 = \psi_k'(x_k)\, \partial x_k/\partial x_0 = A_k^{-1} B_k\, \partial x_k / \partial x_0, with ∂x0/∂x0=I\partial x_0/\partial x_0 = I. So ∂xk/∂x0=Φk\partial x_k/\partial x_0 = \Phi_k for every kk by induction, and r′(x0)=ΦS−Ir'(x_0) = \Phi_S - I. □\square

ΦS\Phi_S is the monodromy matrix of the discrete map: it carries a small change of the state at t=0t = 0 to its change one period later. The cost of ΦS\Phi_S is small next to the transient itself, because AkA_k is the matrix that the last Newton iteration of step kk has already factored.

Corollary 1 (local convergence). If ff and qq are twice continuously differentiable and ΦS−I\Phi_S - I is nonsingular at a root x∗x^*, then the full-step iteration converges quadratically from every start close enough to x∗x^*. This is the local theorem for Newton's method for systems applied to rr, whose derivative is Lipschitz near x∗x^* under these assumptions.

Linear circuits

Theorem 3. Let f(x)=Gxf(x) = Gx and q(x)=Cxq(x) = Cx with constant matrices, and let ΦS−I\Phi_S - I be nonsingular. Then:

  1. rr is affine, so Newton reaches its unique root in one step from any start.
  2. If u(t)=Re⁡(Uejωt)u(t) = \operatorname{Re}(U e^{j\omega t}) with ω=2π/T\omega = 2\pi/T, the discrete steady state is xk=Re⁡(Xdejωtk)x_k = \operatorname{Re}(X_d e^{j\omega t_k}), where (G+sdC)Xd=U(G + s_d C) X_d = U and, with z=ejωhz = e^{j\omega h},
sd=2h z−1z+1=j 2htan⁡ωh2(θ=12),sd=1−z−1h(θ=1),s_d = \frac{2}{h}\,\frac{z - 1}{z + 1} = j\,\frac{2}{h}\tan\frac{\omega h}{2} \quad (\theta = \tfrac12), \qquad s_d = \frac{1 - z^{-1}}{h} \quad (\theta = 1),

provided G+sdCG + s_d C and G+sˉdCG + \bar s_d C are nonsingular.

  1. For the trapezoidal rule sd=jω(1+(ωh)212+O(h4))s_d = j\omega\big(1 + \tfrac{(\omega h)^2}{12} + O(h^4)\big), so XdX_d differs from the AC phasor X=(G+jωC)−1UX = (G + j\omega C)^{-1} U by O(h2)O(h^2); for backward Euler sd−jω=O(h)s_d - j\omega = O(h).

Proof. 1. Each ψk\psi_k is affine, ψk(x)=A−1(Bx+ck)\psi_k(x) = A^{-1}(Bx + c_k) with constant AA and BB, so PP and rr are affine and r(x0+Δ)=r(x0)+(ΦS−I)Δr(x_0 + \Delta) = r(x_0) + (\Phi_S - I)\Delta; the Newton step makes this zero.

  1. Put yk=Xdejωtky_k = X_d e^{j\omega t_k}, so yk+1=zyky_{k+1} = z y_k. For θ=12\theta = \tfrac12, the step (1) applied to yy with the complex source UejωtkU e^{j\omega t_k} reads (C(z−1)+h2G(z+1))yk=h2(z+1)Uejωtk\big(C(z - 1) + \tfrac h2 G(z + 1)\big) y_k = \tfrac h2 (z + 1) U e^{j\omega t_k}. Divide by h2(z+1)\tfrac h2(z + 1), which is nonzero because ωh<π\omega h < \pi, to get (G+sdC)Xd=U(G + s_d C) X_d = U. For θ=1\theta = 1, C(z−1)yk+hGzyk=hz UejωtkC(z - 1) y_k + hG z y_k = hz\,U e^{j\omega t_k}; divide by hzhz. The recurrence is real and linear, so the real part of a complex solution is a solution for the real source. The sequence is SS-periodic because zS=1z^S = 1, so by Theorem 1 and the uniqueness in 1 it is the discrete steady state. Finally (z−1)/(z+1)=jtan⁡(ωh/2)(z - 1)/(z + 1) = j\tan(\omega h/2) for ∣z∣=1|z| = 1.

  2. tan⁡y=y+y3/3+O(y5)\tan y = y + y^3/3 + O(y^5) gives 2htan⁡ωh2=ω+ω3h2/12+O(h4)\tfrac2h\tan\tfrac{\omega h}2 = \omega + \omega^3 h^2/12 + O(h^4). For backward Euler, (1−e−jωh)/h=jω+ω2h/2+O(h2)(1 - e^{-j\omega h})/h = j\omega + \omega^2 h/2 + O(h^2). Near s=jωs = j\omega the map s↦(G+sC)−1Us \mapsto (G + sC)^{-1}U is differentiable when G+jωCG + j\omega C is nonsingular, so Xd−X=O(∣sd−jω∣)X_d - X = O(|s_d - j\omega|). □\square

Algebraic rows and the trapezoidal rule

MNA equations are differential-algebraic: the row of a voltage source, for example, is ep−eq=v(t)e_p - e_q = v(t) and has no charge term.

Lemma 4. Let row aa of C(x)C(x) be zero for every xx and let row aa of ff be linear, fa(x)=gTxf_a(x) = g^{\mathsf T} x. Then gTΦS=(−1)SgTg^{\mathsf T}\Phi_S = (-1)^S g^{\mathsf T} for the trapezoidal rule, and gTΦS=0g^{\mathsf T}\Phi_S = 0 for backward Euler. So for the trapezoidal rule with even SS, gT(ΦS−I)=0g^{\mathsf T}(\Phi_S - I) = 0 and the Newton matrix is singular.

Proof. Row aa of AkA_k is θh gT\theta h\, g^{\mathsf T} and row aa of BkB_k is −(1−θ)h gT-(1 - \theta) h\, g^{\mathsf T}. Row aa of AkΦk+1=BkΦkA_k \Phi_{k+1} = B_k \Phi_k gives θ gTΦk+1=−(1−θ) gTΦk\theta\, g^{\mathsf T}\Phi_{k+1} = -(1 - \theta)\, g^{\mathsf T}\Phi_k. For θ=12\theta = \tfrac12 this is gTΦk+1=−gTΦkg^{\mathsf T}\Phi_{k+1} = -g^{\mathsf T}\Phi_k, and SS steps from Φ0=I\Phi_0 = I give (−1)SgT(-1)^S g^{\mathsf T}. For θ=1\theta = 1 it is gTΦk+1=0g^{\mathsf T}\Phi_{k+1} = 0. □\square

The cause is that the trapezoidal rule does not damp the algebraic part: an error in gTxg^{\mathsf T}x changes sign at every step and never decays. The remedies are backward Euler or another damped method, an odd SS, or shooting on the state variables only (capacitor charges and inductor fluxes), which is the form in which Aprille and Trick stated the method.

What is not proved

  • Existence and uniqueness of a periodic steady state, and the nonsingularity of ΦS−I\Phi_S - I at the root, are assumed. A Floquet multiplier (an eigenvalue of ΦS\Phi_S) equal to 1 makes the Newton matrix singular; this is always the case for an autonomous oscillator, which needs the period as an extra unknown.
  • Nonlinear discretization error. Theorem 3 gives the O(h2)O(h^2) error of the trapezoidal rule only for linear circuits. For nonlinear circuits the error is measured on the page.
  • Global convergence. The step limit is a heuristic; Newton can fail from a poor start.
  • The speed of plain transient analysis. Near the steady state the error of a plain transient run is multiplied by about ΦS\Phi_S each period, so it falls like the ppth power of the spectral radius of ΦS\Phi_S, as for any fixed-point iteration. The page measures this; it is not proved here for the nonlinear map.
  • Matrix-free Krylov solvers for (ΦS−I)Δ=−r(\Phi_S - I)\Delta = -r are not covered.

Complexity

One Newton iteration is one transient period of SS steps plus the sensitivity. With dense matrices, each step costs O(n3)O(n^3) for its own Newton solves and O(n3)O(n^3) for the product in line L4, so II iterations cost O(ISn3)O(I S n^3) time; the states of one period take O(Sn)O(Sn) space and Φ\Phi takes O(n2)O(n^2). With sparse factors, the sensitivity costs nn sparse solves per step, which is still too much for large nn. The matrix-free form replaces it by GMRES on line L6, where one product Φv\Phi v costs SS solves with stored factors, so an iteration costs about one transient period plus one period of solves per GMRES step. Compared with a plain transient, shooting costs O(I)O(I) periods instead of the number of periods the circuit needs to settle, which grows with its slowest time constant.

Properties

  • Time-domain accuracy. The waveform is computed by the same integration method as a transient run, so sharp edges, switching and strongly nonlinear devices cost no more than in transient analysis.
  • Independent of slow time constants. The number of Newton iterations does not grow with the settling time, unlike a plain transient.
  • Quadratic convergence near a root, as in the measured residuals.
  • Floquet information. The eigenvalues of Φ\Phi at the solution are the Floquet multipliers of the discrete steady state; one with magnitude above 1 shows that the steady state is unstable.
  • Exact for the discrete map. The result is the steady state of the integration method, with its error.

Variants and improvements

  • Matrix-free Krylov shooting. GMRES with products Φv\Phi v from stored step factors, as above; this makes shooting practical for large integrated circuits.
  • Autonomous circuits. For an oscillator the period is unknown. Add TT as an unknown and a phase condition, such as fixing one node voltage at t=0t = 0; the extended Newton matrix uses Φ\Phi and the derivative ∂xS/∂T=x˙(T)\partial x_S/\partial T = \dot x(T). The result feeds phase noise analysis.
  • Multiple shooting. Split the period into segments with their own start states, which helps when Φ\Phi is badly conditioned.
  • Damped integrators. Backward Euler, Gear's methods or TR-BDF2 avoid the singular algebraic rows of the trapezoidal rule.
  • Periodic small-signal analysis. The step matrices of the converged period give the periodic AC, transfer function and noise analyses of mixers and switched-capacitor circuits.

When to use it

Use shooting for the periodic steady state of circuits with sharp edges or strong nonlinearity: switching power converters, switched-capacitor filters, frequency dividers and digital or sampling circuits, and any circuit with a slow bias or filter network that makes plain transient runs long. Use harmonic balance when the waveforms are nearly sinusoidal or when the circuit has distributed elements known only in the frequency domain.

Pitfalls

  • Trapezoidal rule with algebraic unknowns. With MNA unknowns and an even number of steps, Φ−I\Phi - I is singular for every voltage source row; the measured Newton matrix had an exactly zero pivot at S=64S = 64. Use a damped method, an odd SS, or shoot on the state variables only.
  • Multiplier near 1. If a Floquet multiplier is close to 1, as for a lightly damped resonance or an oscillator, Φ−I\Phi - I is nearly singular and Newton is slow or fails.
  • Fixed steps. The method needs the same steps in every period, or at least the same discrete map. Adaptive step control between iterations changes the map and can stop convergence; production codes fix the time points before the final iterations.
  • Cost of a dense Φ\Phi. Forming Φ\Phi costs nn solves per step. Use the matrix-free form for more than a few hundred unknowns.
  • Discretization error is not reported. The method returns the exact periodic solution of the discrete map; refine SS to check it, as in the example.
  • Fitted parameters. The rectified output depends on the diode's fitted ISI_S and NN; the steady state is only as good as the model.

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.

shooting_newton_steady_state.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shooting-newton-steady-state/. The authors are listed in prov/FS9DNT.jsonl.
"""Shooting Newton for the periodic steady state of a circuit.

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. One period of transient analysis
with S fixed steps is a map x0 -> x_S; shooting finds a fixed point of that
map with Newton's method, using the sensitivity (monodromy) matrix dx_S/dx0
that the transient steps give at little extra cost.
"""

import math

import sim3dense

VT_300 = 1.380649e-23 * 300.0 / 1.602176634e-19  # kT/q at 300 K, in volts
THETA = {"trap": 0.5, "be": 1.0}  # trapezoidal rule and backward Euler


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)))

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

    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)
        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


def step(net, x, t, h, method, ev=None, tol=1e-13, max_iter=50):
    """One step from (t, x) to t + h; returns (x_new, ev_new, A, B).

    The step solves q(y) - q(x) + h [theta (f(y) - u(t+h)) + (1 - theta)(f(x) - u(t))] = 0
    by Newton. A = C(y) + theta h G(y) and B = C(x) - (1 - theta) h G(x) are the
    matrices of the sensitivity recurrence A dy/dx0 = B dx/dx0.
    """
    th = THETA[method]
    N = net.size
    f, G, q, C = ev if ev else net.evaluate(x)
    u, un = net.sources(t), net.sources(t + h)
    y = list(x)
    for _ in range(max_iter):
        fn, Gn, qn, Cn = net.evaluate(y)
        r = [qn[a] - q[a] + h * (th * (fn[a] - un[a]) + (1 - th) * (f[a] - u[a])) for a in range(N)]
        A = [[Cn[a][b] + th * h * Gn[a][b] for b in range(N)] for a in range(N)]
        dy = sim3dense.solve(A, [-v for v in r])
        y = [y[a] + dy[a] for a in range(N)]
        if max(abs(v) for v in dy) <= tol * (1 + max(abs(v) for v in y)):
            break
    else:
        raise NoConvergence("transient step")
    evn = net.evaluate(y)
    fn, Gn, qn, Cn = evn
    A = [[Cn[a][b] + th * h * Gn[a][b] for b in range(N)] for a in range(N)]
    B = [[C[a][b] - (1 - th) * h * G[a][b] for b in range(N)] for a in range(N)]
    return y, evn, A, B


def period_map(net, x0, T, S, method="trap", sensitivity=True):
    """One period of S fixed steps from x0; returns (x_S, Phi, states).

    Phi = d x_S / d x0 is the monodromy matrix of the discrete map (None when
    sensitivity is False), and states are x_0, ..., x_S.
    """
    h = T / S
    N = net.size
    x, ev = list(x0), None
    Phi = sim3dense.identity(N, 1.0) if sensitivity else None
    states = [list(x)]
    for k in range(S):  # @line L3
        x, ev, A, B = step(net, x, k * h, h, method, ev)
        if sensitivity:
            Phi = sim3dense.solve(A, sim3dense.matmul(B, Phi))  # @line L4
        states.append(list(x))
    return x, Phi, states


def shooting(net, T, S, x0=None, method="trap", tol=1e-11, max_iter=50, step_limit=1.0):
    """Initial state of the periodic steady state of the S-step discrete map.

    Returns (x0, iterations, residual history, states of one period). Newton
    steps are scaled so that no node voltage moves more than step_limit volts.
    """
    N = net.size
    x = list(x0) if x0 else [0.0] * N  # @line L1
    history = []
    for it in range(1, max_iter + 1):  # @line L2
        xT, Phi, states = period_map(net, x, T, S, method)
        r = [xT[a] - x[a] for a in range(N)]  # @line L5
        history.append(max(abs(v) for v in r))
        J = [[Phi[a][b] - (1.0 if a == b else 0.0) for b in range(N)] for a in range(N)]
        dx = sim3dense.solve(J, [-v for v in r])  # @line L6
        big = max((abs(v) for v in dx[: net.n]), default=0.0)
        lam = min(1.0, step_limit / big) if big > 0 else 1.0
        x = [x[a] + lam * dx[a] for a in range(N)]
        if lam == 1.0 and max(abs(v) for v in dx) <= tol * (1 + max(abs(v) for v in x)):  # @line L7
            _, _, states = period_map(net, x, T, S, method, sensitivity=False)
            return x, it, history, states  # @line L8
    raise NoConvergence("shooting")


def transient_until_periodic(net, T, S, x0=None, method="trap", tol=1e-9, max_periods=100000):
    """Plain transient, period after period, until x(kT) changes by at most tol.

    Returns (x at the last period start, number of periods). This is what
    shooting replaces.
    """
    x = list(x0) if x0 else [0.0] * net.size
    for p in range(1, max_periods + 1):
        xT, _, _ = period_map(net, x, T, S, method, sensitivity=False)
        if max(abs(a - b) for a, b in zip(xT, x)) <= tol:
            return xT, p
        x = xT
    raise NoConvergence("transient did not settle")
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_shooting_newton_steady_state.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shooting-newton-steady-state/. The authors are listed in prov/FS9DNT.jsonl.

import cmath
import math
import random

import sim3dense
from shooting_newton_steady_state import Netlist, period_map, shooting, transient_until_periodic

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 rectifier():
    """2 V, 1 MHz source behind 1 kOhm (Norton form), diode, 100 kOhm || 1 nF load."""
    net = Netlist(2)
    net.isource(0, 1, lambda t: 2e-3 * math.sin(W * t))
    net.resistor(1, 0, 1e3)
    net.capacitor(1, 0, 10e-12)
    net.diode(1, 2, IS, N)
    net.resistor(2, 0, 100e3)
    net.capacitor(2, 0, 1e-9)
    return net


def parallel_rlc(r=200.0, l=10e-6, c=2e-9):
    """1 mA cosine source into R, L and C in parallel; unknowns e1 and the L current."""
    net = Netlist(1)
    net.isource(0, 1, lambda t: 1e-3 * math.cos(W * t))
    net.resistor(1, 0, r)
    net.inductor(1, 0, l)
    net.capacitor(1, 0, c)
    return net, r, l, c


def phasor(r, l, c, s):
    """Node voltage phasor of parallel_rlc for the complex frequency s (source phasor 1 mA)."""
    return 1e-3 / (1 / r + 1 / (s * l) + s * c)


def test_linear_trapezoidal_is_exact_for_the_discrete_map_in_one_newton_step():
    net, r, l, c = parallel_rlc()
    for S in (40, 80, 160):
        h = T / S
        x, it, hist, states = shooting(net, T, S, method="trap")
        assert it == 2  # the first step solves the affine problem
        # the trapezoidal recurrence has the periodic solution of the frequency
        # s_d = j (2/h) tan(w h / 2), the warped frequency of the bilinear map
        sd = 2j / h * math.tan(W * h / 2)
        v = phasor(r, l, c, sd)
        for k in range(S + 1):
            assert abs(states[k][0] - (v * cmath.exp(1j * W * k * h)).real) < 1e-12


def test_linear_backward_euler_matches_its_discrete_phasor():
    net = Netlist(2)  # voltage source with an algebraic row, R, C
    net.vsource(1, 0, lambda t: math.cos(W * t))
    net.resistor(1, 2, 1e3)
    net.capacitor(2, 0, 100e-12)
    S = 64
    h = T / S
    x, it, _, states = shooting(net, T, S, method="be")
    assert it == 2
    z = cmath.exp(1j * W * h)
    sd = (1 - 1 / z) / h  # backward Euler: (x_k - x_{k-1}) / h
    v2 = 1 / (1 + sd * 1e3 * 100e-12)
    for k in range(S + 1):
        assert abs(states[k][1] - (v2 * cmath.exp(1j * W * k * h)).real) < 1e-12


def test_error_against_the_analytic_steady_state_is_second_order():
    net, r, l, c = parallel_rlc()
    exact = phasor(r, l, c, 1j * W)
    errs = []
    for S in (40, 80, 160):
        x, _, _, _ = shooting(net, T, S, method="trap")
        errs.append(abs(x[0] - exact.real))
    # measured ratios: about 4 per halving of the step
    assert 3.8 < errs[0] / errs[1] < 4.2 and 3.8 < errs[1] / errs[2] < 4.2


def test_monodromy_matches_finite_differences():
    rng = random.Random(61)
    net = rectifier()
    for _ in range(3):
        x0 = [rng.uniform(-0.5, 0.5), rng.uniform(0.5, 1.5)]
        _, Phi, _ = period_map(net, x0, T, 50)
        eps = 1e-6
        for b in range(2):
            xp, xm = list(x0), list(x0)
            xp[b] += eps
            xm[b] -= eps
            fp, _, _ = period_map(net, xp, T, 50, sensitivity=False)
            fm, _, _ = period_map(net, xm, T, 50, sensitivity=False)
            for a in range(2):
                fd = (fp[a] - fm[a]) / (2 * eps)
                assert abs(fd - Phi[a][b]) < 1e-6 * (1 + abs(Phi[a][b]))


def test_rectifier_agrees_with_a_long_transient_and_converges_quadratically():
    net = rectifier()
    S = 100
    x, it, hist, _ = shooting(net, T, S)
    xt, periods = transient_until_periodic(net, T, S, tol=1e-9)
    # measured: 7 Newton iterations against 155 periods of plain transient
    assert it <= 8 and periods > 100
    # the transient stops 1e-9 per period from its limit, which is about 1e-8 away
    assert max(abs(a - b) for a, b in zip(x, xt)) < 2e-8
    # quadratic convergence: each residual is at most about the square of the last
    tail = [h for h in hist if h < 1e-2]
    for a, b in zip(tail, tail[1:]):
        assert b < 50 * a * a + 1e-14


def test_trapezoidal_rule_makes_algebraic_rows_singular_for_even_step_counts():
    net = Netlist(2)
    net.vsource(1, 0, lambda t: math.cos(W * t))
    net.resistor(1, 2, 1e3)
    net.capacitor(2, 0, 100e-12)
    x0 = [0.3, 0.1, -1e-4]
    _, G, _, _ = net.evaluate(x0)
    row = G[2]  # the source row e_1 = v(t) has no charge term
    for S, sign in ((64, 1.0), (65, -1.0)):
        _, Phi, _ = period_map(net, x0, T, S, method="trap")
        # proved: row^T Phi = (-1)^S row^T, so row^T (Phi - I) is 0 or -2 row^T
        prod = [sum(row[a] * (Phi[a][b] - (a == b)) for a in range(3)) for b in range(3)]
        target = [0.0 if sign > 0 else -2 * v for v in row]
        assert max(abs(p - t) for p, t in zip(prod, target)) < 1e-9
    _, Phi, _ = period_map(net, x0, T, 64, method="be")
    prod = [sum(row[a] * (Phi[a][b] - (a == b)) for a in range(3)) for b in range(3)]
    assert max(abs(p + v) for p, v in zip(prod, row)) < 1e-9  # backward Euler: row^T Phi = 0
    try:
        sim3dense.solve([[Phi[a][b] - (a == b) for b in range(3)] for a in range(3)], [1.0, 0.0, 0.0])
    except sim3dense.SingularMatrixError:
        raise AssertionError("backward Euler should give a nonsingular Newton matrix")

History

Aprille and Trick (1972) formulated the periodic steady state of a nonlinear circuit as the boundary value problem x(T)=x(0)x(T) = x(0) and solved it with Newton's method, computing the needed sensitivity matrix along the transient. Colon and Trick (1973) made the method faster for large-signal circuits. The book of Kundert, White and Sangiovanni-Vincentelli (1990) described shooting next to harmonic balance as one of the two main steady-state methods. Telichevesky, Kundert and White (1995) removed the dense sensitivity matrix with a matrix-free Krylov solver, which made shooting usable on large RF integrated circuits.

References

  1. Thomas J. Aprille and Timothy N. Trick, Steady-state analysis of nonlinear circuits with periodic inputs, Proceedings of the IEEE 60(1), 108 to 114, 1972, the formulation of the periodic steady state as x(T) = x(0), the Newton iteration and the sensitivity (state transition) matrix computed along the transient
  2. F. R. Colon and Timothy N. Trick, Fast periodic steady-state analysis for large-signal electronic circuits, IEEE Journal of Solid-State Circuits 8(4), 260 to 269, 1973, the faster computation of the periodic steady state that followed the 1972 method
  3. Ricardo Telichevesky, Kenneth S. Kundert and Jacob K. White, Efficient steady-state analysis based on matrix-free Krylov-subspace methods, Proceedings of the 32nd Design Automation Conference, 480 to 484, 1995, the solution of the shooting Newton equations with GMRES and matrix-vector products from the stored step matrices
  4. Kenneth S. Kundert, Jacob K. White and Alberto Sangiovanni-Vincentelli, Steady-State Methods for Simulating Analog and Microwave Circuits, Kluwer, 1990, the chapter Time-Domain Methods, pages 55 to 79, on shooting methods for circuits

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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