Algorithm Search⌘K

Techniquecore

Companion model

Also called discretized companion model, associated discrete circuit.

Replace each capacitor or inductor, at one step of an implicit integration formula, by a conductance and a current source, so a transient step becomes a resistive circuit solve.

A companion model replaces a capacitor or an inductor, for one time step of an implicit integration formula, by a conductance GG in parallel with a current source JJ, so that the element current at the new time point is in+1=G vn+1+Ji_{n+1} = G\, v_{n+1} + J. With every dynamic element replaced, one step of transient simulation becomes one solve of a resistive circuit by modified nodal analysis, with GG depending on the step hh and JJ on the past values. The technique belongs to the circuit simulation half of the logic and circuit simulation sub-area. For a capacitor CC, backward Euler gives G=C/hG = C/h and the trapezoidal rule gives G=2C/hG = 2C/h.

In plain words

A capacitor's current depends on how fast its voltage changes, so a circuit with capacitors gives differential equations, not plain equations. A simulator walks through time in small steps instead.

Over one short step, the capacitor behaves like a resistor plus a small battery-like source. The resistor part says that a larger jump in voltage needs a larger current. The source part remembers where the voltage was at the end of the last step. An inductor gets the same treatment with the roles of voltage and current swapped.

Swap every capacitor and inductor for its stand-in, and the circuit at the end of the step has only resistors and sources. The simulator solves it like a DC circuit, updates what each stand-in remembers, and moves on to the next step.

When it applies

The technique applies to any lumped circuit with capacitors and inductors, integrated by an implicit linear multistep formula: backward Euler, the trapezoidal rule, backward differentiation formulas (Gear's methods, as in SPICE2) and the two stages of TR-BDF2. Each formula gives its own GG and JJ. Circuit equations are stiff, with time constants that differ by many orders of magnitude, so explicit formulas would need tiny steps; this is why simulators use implicit ones and need companion models (stiff ODE problem). Nonlinear capacitors use the same idea on the charge q(v)q(v), inside each Newton iteration of the step. The full time loop with step control and Newton iterations is transient circuit analysis.

The template

Convention. An element from node pp to node qq has the voltage v=ep−eqv = e_p - e_q and the current ii counted from pp through the element to qq. A companion model (G,J)(G, J) is a conductance GG from pp to qq in parallel with a current source JJ from pp through it to qq, so the stamps of MNA apply: GG in the matrix, −J-J at row pp and +J+J at row qq of the right side.

  1. TRANSIENT(netlist, e_0, h, K, method)
  2. 1for each capacitor and inductor el do set (v_el, i_el) from e_0 and the initial currents
  3. 2for k ← 1 to K do
  4. 3for each capacitor and inductor el do (G_el, J_el) ← COMPANION(el, method, h, v_el, i_el)
  5. 4M ← stamps of the resistors and of every G_el; factor M once for each (h, method)
  6. 5z ← stamps of the sources at t_k = k h and of every J_el
  7. 6e_k ← SOLVE(M, z)
  8. 7for each capacitor and inductor el do v_el ← e_p − e_q; i_el ← G_el v_el + J_el
  9. 8return e_0, e_1, ..., e_K

The holes are COMPANION, which holds the integration formula, and SOLVE. Line L4 factors MM only when hh or the method changes, because for a linear circuit the conductances depend on nothing else; then each step costs one forward and one back substitution. A production simulator adds a Newton loop around lines L3 to L7 for nonlinear devices and a step size control after line L7.

The models and why they are exact. A capacitor obeys i=C dv/dti = C\, dv/dt and an inductor v=L di/dtv = L\, di/dt. Apply each formula to these laws and solve for in+1i_{n+1}:

Element and formula Discrete law GG JJ
capacitor, backward Euler C(vn+1−vn)/h=in+1C (v_{n+1} - v_n)/h = i_{n+1} C/hC/h −(C/h) vn-(C/h)\, v_n
capacitor, trapezoidal C(vn+1−vn)/h=(in+1+in)/2C (v_{n+1} - v_n)/h = (i_{n+1} + i_n)/2 2C/h2C/h −(2C/h) vn−in-(2C/h)\, v_n - i_n
inductor, backward Euler L(in+1−in)/h=vn+1L (i_{n+1} - i_n)/h = v_{n+1} h/Lh/L ini_n
inductor, trapezoidal L(in+1−in)/h=(vn+1+vn)/2L (i_{n+1} - i_n)/h = (v_{n+1} + v_n)/2 h/(2L)h/(2L) in+(h/2L) vni_n + (h/2L)\, v_n

Each row is the discrete law rearranged, for example C(vn+1−vn)/h=in+1C(v_{n+1} - v_n)/h = i_{n+1} is in+1=(C/h)vn+1−(C/h)vni_{n+1} = (C/h) v_{n+1} - (C/h) v_n. So a source J=−(C/h)vnJ = -(C/h) v_n from pp to qq is a source of Cvn/hC v_n / h that drives current into node pp, in parallel with G=C/hG = C/h. Every other element keeps its law, and KCL and KVL are unchanged, so the solution of the resistive circuit at step n+1n + 1 is exactly the solution of the circuit equations discretized by the formula. The companion model adds no error of its own; all the error is the error of the integration formula.

Exact solution of the RC circuit. Let a source EE with a series resistor RR charge a capacitor CC from v0=0v_0 = 0, and let τ=RC\tau = RC and wk=E−vkw_k = E - v_k. The exact solution is v(t)=E(1−e−t/τ)v(t) = E(1 - e^{-t/\tau}). With backward Euler, KCL at the capacitor node is C(vk+1−vk)/h=(E−vk+1)/RC(v_{k+1} - v_k)/h = (E - v_{k+1})/R, that is (wk−wk+1)τ/h=wk+1(w_k - w_{k+1})\tau/h = w_{k+1}, so wk+1=ρ wkw_{k+1} = \rho\, w_k with ρ=1/(1+h/τ)\rho = 1/(1 + h/\tau). With the trapezoidal rule and the consistent start i0=E/Ri_0 = E/R, (wk−wk+1)τ/h=(wk+1+wk)/2(w_k - w_{k+1})\tau/h = (w_{k+1} + w_k)/2, so ρ=(1−h/2τ)/(1+h/2τ)\rho = (1 - h/2\tau)/(1 + h/2\tau). In both cases vk=E(1−ρk)v_k = E(1 - \rho^k) exactly.

The order of the error. At a fixed time t=kht = kh the error is vk−v(t)=E(e−t/τ−ρk)v_k - v(t) = E(e^{-t/\tau} - \rho^k) with ρk=ekln⁡ρ\rho^k = e^{k \ln \rho}. For backward Euler ln⁡ρ=−ln⁡(1+h/τ)=−h/τ+h2/(2τ2)+O(h3)\ln \rho = -\ln(1 + h/\tau) = -h/\tau + h^2/(2\tau^2) + O(h^3), so kln⁡ρ=−t/τ+th/(2τ2)+O(h2)k \ln \rho = -t/\tau + t h/(2\tau^2) + O(h^2) and the error is −Ee−t/τ th/(2τ2)+O(h2)-E e^{-t/\tau}\, t h / (2\tau^2) + O(h^2): first order in hh. For the trapezoidal rule, with x=h/(2τ)x = h/(2\tau), ln⁡ρ=ln⁡(1−x)−ln⁡(1+x)=−2x−2x3/3+O(x5)=−h/τ−h3/(12τ3)+O(h5)\ln\rho = \ln(1 - x) - \ln(1 + x) = -2x - 2x^3/3 + O(x^5) = -h/\tau - h^3/(12\tau^3) + O(h^5), so the error is Ee−t/τ th2/(12τ3)+O(h4)E e^{-t/\tau}\, t h^2 / (12\tau^3) + O(h^4): second order. These match the local truncation errors of the two formulas, −h22x′′-\tfrac{h^2}{2} x'' for backward Euler and −h312x′′′-\tfrac{h^3}{12} x''' for the trapezoidal rule per step (local truncation error).

Worked example. Take E=1E = 1 V, R=1 ΩR = 1\ \Omega, C=1C = 1 F and h=0.1h = 0.1 s, with the source in Norton form, 1 A into the node in parallel with 1 Ω1\ \Omega. Backward Euler: G=10G = 10, J=0J = 0, so (1+10) v1=1(1 + 10)\, v_1 = 1 and v1=1/11≈0.09091v_1 = 1/11 \approx 0.09091. Trapezoidal with i0=1i_0 = 1 A: G=20G = 20, J=−20⋅0−1=−1J = -20 \cdot 0 - 1 = -1, so the source drives 1 A into the node and (1+20) v1=1+1(1 + 20)\, v_1 = 1 + 1, v1=2/21≈0.09524v_1 = 2/21 \approx 0.09524. The exact value is 1−e−0.1≈0.095161 - e^{-0.1} \approx 0.09516. Over 0≤t≤10 \le t \le 1 the largest errors are:

steps in [0,1][0, 1] 10 20 40 80
backward Euler 1.766×10−21.766 \times 10^{-2} 9.010×10−39.010 \times 10^{-3} 4.551×10−34.551 \times 10^{-3} 2.287×10−32.287 \times 10^{-3}
trapezoidal 3.069×10−43.069 \times 10^{-4} 7.666×10−57.666 \times 10^{-5} 1.916×10−51.916 \times 10^{-5} 4.790×10−64.790 \times 10^{-6}

Halving hh halves the backward Euler error and divides the trapezoidal error by 4. The leading term e−1h2/12e^{-1} h^2/12 of the formula above gives 3.066×10−43.066 \times 10^{-4} for h=0.1h = 0.1.

Energy of a lossless network. For a network of capacitors and inductors only, the trapezoidal rule keeps the stored energy ∑12Cv2+∑12Li2\sum \tfrac12 C v^2 + \sum \tfrac12 L i^2 exactly, and backward Euler lowers it at every step that changes the state. Proof. With the trapezoidal rule, the averages vˉ=(vn+1+vn)/2\bar v = (v_{n+1} + v_n)/2 and iˉ=(in+1+in)/2\bar i = (i_{n+1} + i_n)/2 satisfy KVL and KCL, because both laws are linear. By Tellegen's theorem, ∑jvˉjiˉj=0\sum_j \bar v_j \bar i_j = 0. For a capacitor, iˉ=C(vn+1−vn)/h\bar i = C(v_{n+1} - v_n)/h, so vˉiˉ=C(vn+12−vn2)/(2h)\bar v \bar i = C(v_{n+1}^2 - v_n^2)/(2h); for an inductor, vˉ=L(in+1−in)/h\bar v = L(i_{n+1} - i_n)/h, so vˉiˉ=L(in+12−in2)/(2h)\bar v \bar i = L(i_{n+1}^2 - i_n^2)/(2h). The sum of these terms is the change of energy divided by hh, so the change is zero. With backward Euler, Tellegen's theorem on (vn+1,in+1)(v_{n+1}, i_{n+1}) gives ∑Cvn+1(vn+1−vn)+∑Lin+1(in+1−in)=0\sum C v_{n+1}(v_{n+1} - v_n) + \sum L i_{n+1}(i_{n+1} - i_n) = 0, and a(a−b)=12(a2−b2)+12(a−b)2a(a - b) = \tfrac12(a^2 - b^2) + \tfrac12(a - b)^2 turns this into: the energy drops by 12∑C(vn+1−vn)2+12∑L(in+1−in)2\tfrac12 \sum C (v_{n+1} - v_n)^2 + \tfrac12 \sum L (i_{n+1} - i_n)^2. ■\blacksquare

Cost. For a linear circuit with NN MNA unknowns, KK steps and a fixed hh, the run costs one LU factorization plus KK pairs of triangular solves, Θ(N3+KN2)\Theta(N^3 + K N^2) with dense LU, and lines L3, L5 and L7 cost time linear in the number of elements per step. The code of this page does exactly this, with exact fractions or floats.

Classic examples

  • Transient circuit analysis in SPICE: trapezoidal and Gear companion models with a step chosen from the truncation error estimate.
  • TR-BDF2: a trapezoidal stage followed by a second-order BDF stage, each a companion model solve, which damps the ringing of the plain trapezoidal rule.
  • Power grid analysis in time: with a fixed step, the grid matrix with its companion conductances is factored once and reused for thousands of steps.
  • The Crank-Nicolson method for a discretized heat equation is the trapezoidal rule on an RC network, and its matrix is the MNA matrix with the companion conductances 2C/h2C/h.

Variations

  • Gear (BDF) models. The second-order backward differentiation formula 32vn+1−2vn+12vn−1=h in+1/C\tfrac{3}{2} v_{n+1} - 2 v_n + \tfrac12 v_{n-1} = h\, i_{n+1}/C gives G=3C/(2h)G = 3C/(2h) and J=−(C/h)(2vn−12vn−1)J = -(C/h)(2 v_n - \tfrac12 v_{n-1}). Higher orders use more past points.
  • Charge form. For a nonlinear capacitor with charge q(v)q(v), the discrete law in+1=(q(vn+1)−q(vn))/hi_{n+1} = (q(v_{n+1}) - q(v_n))/h is linearized at each Newton iterate v(m)v^{(m)}, which gives G=q′(v(m))/hG = q'(v^{(m)})/h. Writing the law in charge conserves charge exactly, while a law in C(v) dv/dtC(v)\, dv/dt does not.
  • Thevenin form. A voltage source in series with a resistance gives the same model and suits inductors in a formulation that keeps their currents as unknowns.
  • Variable step. When hh changes, GG changes and MM must be factored again. The step is chosen so that an estimate of the local truncation error, for example from divided differences of the last few solutions as in SPICE2, stays below a tolerance (adaptive step size control).

Pitfalls

  • Trapezoidal ringing. For a fast mode with h≫τh \gg \tau, the trapezoidal factor ρ=(1−h/2τ)/(1+h/2τ)\rho = (1 - h/2\tau)/(1 + h/2\tau) is close to −1-1, so the error flips sign at every step and decays very slowly. The rule is A-stable but not L-stable. Backward Euler has ρ→0\rho \to 0 and damps such modes, which is why simulators take a backward Euler step after a breakpoint or switch to Gear's methods.
  • The trapezoidal rule needs the current. The companion source of the trapezoidal rule uses ini_n, so the run needs consistent initial capacitor currents. SPICE avoids the problem by taking the first step with backward Euler, which keeps the global order 2, since one step of local error O(h2)O(h^2) adds only O(h2)O(h^2).
  • Backward Euler adds loss. In a lossless LC circuit it lowers the energy at every step, as proved above, so an oscillator simulated with backward Euler decays although the real one does not.
  • Breakpoints. A source with a corner, such as a pulse edge, breaks the smoothness that the error order needs. Simulators place a time point at each corner.
  • Refactoring. A change of hh changes every companion conductance, so the matrix must be factored again; changing the step on every step loses the saving of a fixed step.

Code

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.

companion_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/companion-model/. The authors are listed in prov/JH4KPG.jsonl.
"""Companion models of capacitors and inductors, and a fixed-step transient run.

Every companion model is a conductance G in parallel with a current source J,
so that the element current at the new time point is i = G v + J. Currents
are counted from the first node p of the element, through it, to its second
node q, and v = e_p - e_q.

The transient run uses nodal analysis, so a netlist holds only:

- ("R", p, q, r): a resistor;
- ("I", p, q, f): a current source whose current f(t), a function of time,
  flows from p through the source to q;
- ("C", p, q, c): a capacitor;
- ("L", p, q, l): an inductor.

Node 0 is ground. Values are Fraction (exact) or float.
"""

from densela import lu_factor, lu_solve

METHODS = ("be", "tr")


def capacitor_be(c, h, v_old):
    """Backward Euler: i_new = (c/h) (v_new - v_old)."""
    g = c / h
    return g, -g * v_old


def capacitor_tr(c, h, v_old, i_old):
    """Trapezoidal rule: i_new = (2c/h) (v_new - v_old) - i_old."""
    g = 2 * c / h
    return g, -g * v_old - i_old


def inductor_be(l, h, i_old):
    """Backward Euler: i_new = i_old + (h/l) v_new."""
    return h / l, i_old


def inductor_tr(l, h, v_old, i_old):
    """Trapezoidal rule: i_new = i_old + (h/(2l)) (v_new + v_old)."""
    g = h / (2 * l)
    return g, i_old + g * v_old


def _companion(el, method, h, state):
    kind, value = el[0], el[3]
    v_old, i_old = state
    if kind == "C":
        return capacitor_be(value, h, v_old) if method == "be" else capacitor_tr(value, h, v_old, i_old)
    return inductor_be(value, h, i_old) if method == "be" else inductor_tr(value, h, v_old, i_old)


def _stamp_g(a, p, q, g):
    for r, c, s in ((p, p, 1), (q, q, 1), (p, q, -1), (q, p, -1)):
        if r > 0 and c > 0:
            a[r - 1][c - 1] += s * g


def _stamp_j(b, p, q, j):
    # A current j from p to q leaves node p and enters node q.
    if p > 0:
        b[p - 1] -= j
    if q > 0:
        b[q - 1] += j


def transient(netlist, n, e0, h, steps, method="tr", inductor_currents=None, capacitor_currents=None):
    """Integrate from t = 0 with the fixed step h.

    e0 lists the node voltages at t = 0 (e0[0] = 0). inductor_currents and
    capacitor_currents map the netlist index of an element to its current at
    t = 0. Inductor currents default to 0. The trapezoidal rule needs the
    capacitor currents at t = 0; when they are not given, the first step uses
    backward Euler, as SPICE does.

    Return the list of node voltage vectors at t = 0, h, ..., steps h.
    """
    if method not in METHODS:
        raise ValueError(f"method must be one of {METHODS}")
    inductor_currents = dict(inductor_currents or {})
    state = {}
    for k, el in enumerate(netlist):  # @line L1
        if el[0] in ("C", "L"):
            v = e0[el[1]] - e0[el[2]]
            if el[0] == "L":
                state[k] = (v, inductor_currents.get(k, 0 * v))
            else:
                state[k] = (v, capacitor_currents[k] if capacitor_currents else None)
    first = method
    if method == "tr" and any(netlist[k][0] == "C" and s[1] is None for k, s in state.items()):
        first = "be"
    out = [list(e0)]
    factors = {}
    for step in range(1, steps + 1):  # @line L2
        m = first if step == 1 else method
        t = step * h
        comp = {k: _companion(netlist[k], m, h, state[k]) for k in state}  # @line L3
        if m not in factors:
            # The conductances depend only on h and the method, so one LU serves every step.
            a = [[0] * n for _ in range(n)]
            for k, el in enumerate(netlist):
                if el[0] == "R":
                    _stamp_g(a, el[1], el[2], 1 / el[3])
                elif k in comp:
                    _stamp_g(a, el[1], el[2], comp[k][0])
            factors[m] = lu_factor(a)  # @line L4
        b = [0] * n  # @line L5
        for k, el in enumerate(netlist):
            if el[0] == "I":
                _stamp_j(b, el[1], el[2], el[3](t))
            elif k in comp:
                _stamp_j(b, el[1], el[2], comp[k][1])
        x = lu_solve(factors[m], b)  # @line L6
        e = [0 * h] + x
        for k in state:  # @line L7
            el = netlist[k]
            v = e[el[1]] - e[el[2]]
            g, j = comp[k]
            state[k] = (v, g * v + j)
        out.append(e)
    return out  # @line L8
densela.py 95 lines
# SPDX-License-Identifier: MIT
# Shared helper of the sim2 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense LU factorization with partial pivoting, for Fraction or float entries.

The circuit pages build a matrix and then call this module to solve it. With
Fraction entries every step is exact, so a zero pivot means that the matrix is
singular. With float entries a pivot whose absolute value is at most ``tol``
counts as zero.

lu_factor returns factors with P A = L U. lu_solve solves A x = b and
lu_solve_transpose solves A^T z = c with the same factors, so a second right
hand side or a transposed system costs only two triangular solves.
"""

from fractions import Fraction


class SingularMatrixError(ValueError):
    """The matrix has no inverse (a zero pivot in exact arithmetic)."""


def _exact(x):
    # An int entry becomes a Fraction, so that int / int never turns into a float.
    return Fraction(x) if isinstance(x, int) else x


def lu_factor(a, tol=0):
    n = len(a)
    lu = [[_exact(x) for x in row] for row in a]
    for row in lu:
        if len(row) != n:
            raise ValueError("the matrix is not square")
    perm = list(range(n))
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if abs(lu[p][k]) <= tol:
            raise SingularMatrixError(f"zero pivot in column {k}")
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
        piv = lu[k][k]
        rowk = lu[k]
        for i in range(k + 1, n):
            rowi = lu[i]
            f = rowi[k] / piv
            rowi[k] = f
            if f:
                for j in range(k + 1, n):
                    rowi[j] -= f * rowk[j]
    return lu, perm


def lu_solve(factors, b):
    lu, perm = factors
    n = len(lu)
    y = [b[perm[i]] for i in range(n)]
    for i in range(n):
        s = y[i]
        for j in range(i):
            s -= lu[i][j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        for j in range(i + 1, n):
            s -= lu[i][j] * y[j]
        y[i] = s / lu[i][i]
    return y


def lu_solve_transpose(factors, c):
    lu, perm = factors
    n = len(lu)
    w = list(c)
    for i in range(n):
        s = w[i]
        for j in range(i):
            s -= lu[j][i] * w[j]
        w[i] = s / lu[i][i]
    for i in range(n - 1, -1, -1):
        s = w[i]
        for j in range(i + 1, n):
            s -= lu[j][i] * w[j]
        w[i] = s
    z = [None] * n
    for i in range(n):
        z[perm[i]] = w[i]
    return z


def solve(a, b, tol=0):
    return lu_solve(lu_factor(a, tol), b)


def matvec(a, x):
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
test_companion_model.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/companion-model/. The authors are listed in prov/JH4KPG.jsonl.

import math
import random
from fractions import Fraction as F

import pytest

from companion_model import capacitor_be, capacitor_tr, inductor_be, inductor_tr, transient


def rc_circuit(e_src, r, c):
    # A source e_src with series resistor r, as its Norton form: e_src / r into node 1 and r from 1 to ground.
    return [("I", 0, 1, lambda t: e_src / r), ("R", 1, 0, r), ("C", 1, 0, c)]


def test_single_step_formulas():
    c, h, v0, i0 = F(3), F(1, 2), F(2), F(5)
    g, j = capacitor_be(c, h, v0)
    v1 = F(7)
    assert g * v1 + j == c * (v1 - v0) / h
    g, j = capacitor_tr(c, h, v0, i0)
    i1 = g * v1 + j
    assert (i1 + i0) / 2 == c * (v1 - v0) / h  # the trapezoidal rule for c dv/dt = i
    l = F(4)
    g, j = inductor_be(l, h, i0)
    assert (g * v1 + j - i0) / h == v1 / l
    g, j = inductor_tr(l, h, v0, i0)
    assert (g * v1 + j - i0) / h == (v1 + v0) / (2 * l)


@pytest.mark.parametrize("method", ["be", "tr"])
def test_rc_matches_the_exact_recurrence(method):
    e_src, r, c, h = F(5), F(2), F(3, 4), F(1, 10)
    tau = r * c
    net = rc_circuit(e_src, r, c)
    steps = 12
    cap_i = {2: e_src / r} if method == "tr" else None
    out = transient(net, 1, [F(0), F(0)], h, steps, method, capacitor_currents=cap_i)
    if method == "be":
        rho = 1 / (1 + h / tau)
    else:
        rho = (1 - h / (2 * tau)) / (1 + h / (2 * tau))
    for k, e in enumerate(out):
        assert e[1] == e_src * (1 - rho**k)


def rc_error(method, steps, give_current=True):
    e_src, r, c, t_end = 1.0, 1.0, 1.0, 1.0
    h = t_end / steps
    cap_i = {2: e_src / r} if give_current else None
    out = transient(rc_circuit(e_src, r, c), 1, [0.0, 0.0], h, steps, method, capacitor_currents=cap_i)
    exact = [e_src * (1 - math.exp(-k * h / (r * c))) for k in range(steps + 1)]
    return max(abs(e[1] - x) for e, x in zip(out, exact))


def test_backward_euler_error_falls_like_h():
    errs = [rc_error("be", s) for s in (20, 40, 80, 160, 320)]
    ratios = [a / b for a, b in zip(errs, errs[1:])]
    assert all(1.9 < q < 2.1 for q in ratios), ratios
    assert errs[-1] < 2e-3


def test_trapezoidal_error_falls_like_h_squared():
    errs = [rc_error("tr", s) for s in (20, 40, 80, 160, 320)]
    ratios = [a / b for a, b in zip(errs, errs[1:])]
    assert all(3.9 < q < 4.1 for q in ratios), ratios
    assert errs[-1] < 2e-6


def test_one_backward_euler_start_keeps_second_order():
    errs = [rc_error("tr", s, give_current=False) for s in (20, 40, 80, 160, 320)]
    ratios = [a / b for a, b in zip(errs, errs[1:])]
    assert all(3.5 < q < 4.5 for q in ratios), ratios


def test_rl_current_converges_with_the_right_order():
    # A current source s into node 1, r from 1 to ground and l from 1 to ground: i_L = s (1 - exp(-t r / l)).
    s, r, l = 2.0, 3.0, 1.5
    net = [("I", 0, 1, lambda t: s), ("R", 1, 0, r), ("L", 1, 0, l)]

    def err(method, steps):
        h = 1.0 / steps
        out = transient(net, 1, [0.0, s * r], h, steps, method, inductor_currents={2: 0.0})
        worst = 0.0
        i_l = 0.0
        for k in range(1, steps + 1):
            i_l = s - out[k][1] / r  # KCL at node 1
            worst = max(worst, abs(i_l - s * (1 - math.exp(-k * h * r / l))))
        return worst

    be = [err("be", n) for n in (40, 80, 160, 320)]
    tr = [err("tr", n) for n in (40, 80, 160, 320)]
    assert all(1.8 < a / b < 2.2 for a, b in zip(be, be[1:])), be
    assert all(3.8 < a / b < 4.2 for a, b in zip(tr, tr[1:])), tr


def lc_energy(e, i_l, c, l):
    return (c * e * e + l * i_l * i_l) / 2


def test_trapezoidal_keeps_lc_energy_and_backward_euler_loses_it():
    c, l, h = F(1, 2), F(2), F(1, 5)
    net = [("C", 1, 0, c), ("L", 1, 0, l)]
    for method in ("tr", "be"):
        # e(0) = 1, i_L(0) = 0, so KCL gives i_C(0) = 0.
        out = transient(net, 1, [F(0), F(1)], h, 25, method, inductor_currents={1: F(0)}, capacitor_currents={0: F(0)})
        energies = []
        i_l = F(0)
        v_old = F(1)
        for e in out[1:]:
            v = e[1]
            if method == "tr":
                i_l = i_l + h / (2 * l) * (v + v_old)
            else:
                i_l = i_l + h / l * v
            v_old = v
            energies.append(lc_energy(v, i_l, c, l))
        if method == "tr":
            assert all(en == F(1, 4) for en in energies)
        else:
            assert all(b < a for a, b in zip([F(1, 4)] + energies, energies))


def test_random_linear_circuits_against_a_fine_reference():
    # Random RC ladders: the trapezoidal answer at h and at h/2 must agree to the order h^2.
    rng = random.Random(4242)
    for _ in range(5):
        n = rng.randint(2, 4)
        net = [("I", 0, 1, lambda t: 1.0)]
        for k in range(1, n + 1):
            net.append(("C", k, 0, rng.uniform(0.5, 2.0)))
            net.append(("R", k, 0, rng.uniform(0.5, 2.0)))
            if k < n:
                net.append(("R", k, k + 1, rng.uniform(0.5, 2.0)))
        e0 = [0.0] * (n + 1)
        cap_i = {k: (1.0 if net[k][1] == 1 else 0.0) for k, el in enumerate(net) if el[0] == "C"}
        coarse = transient(net, n, e0, 0.02, 50, "tr", capacitor_currents=cap_i)[-1]
        fine = transient(net, n, e0, 0.01, 100, "tr", capacitor_currents=cap_i)[-1]
        finer = transient(net, n, e0, 0.005, 200, "tr", capacitor_currents=cap_i)[-1]
        d1 = max(abs(a - b) for a, b in zip(coarse, fine))
        d2 = max(abs(a - b) for a, b in zip(fine, finer))
        assert d1 < 1e-3
        assert 3.5 < d1 / d2 < 4.5

Exercises

  1. Derive the BDF2 capacitor model of the Variations section, and check that it reduces the RC recurrence to a two-term linear recurrence whose roots give a global error of order h2h^2.
  2. Show that backward Euler with the companion model of a capacitor gives ∣ρ∣<1|\rho| < 1 for every h>0h > 0 on the RC circuit, and that ρ→0\rho \to 0 as h→∞h \to \infty.
  3. A capacitor and an inductor in parallel start with v0=1v_0 = 1 V and i0=0i_0 = 0. With C=1/2C = 1/2 F, L=2L = 2 H and h=1/5h = 1/5 s, compute three trapezoidal steps exactly and check that the energy stays 1/41/4 J.
  4. Write the trapezoidal model of a capacitor in Thevenin form, and show that it gives the same node voltages as the Norton form.

References

  1. Farid N. Najm, Circuit Simulation, Wiley-IEEE Press, 2010, Chapter 2, Section 2.5.1 (dynamic element stamps), and Chapter 5 (solution of differential circuit equations)
  2. Laurence W. Nagel, SPICE2, A Computer Program to Simulate Semiconductor Circuits, Memorandum UCB/ERL M520, University of California, Berkeley, May 1975, the chapter on transient analysis (implicit integration of capacitors and inductors, trapezoidal and Gear formulas, truncation error and time step control)
  3. Leon O. Chua and Pen-Min Lin, Computer-Aided Analysis of Electronic Circuits, Prentice-Hall, 1975, the chapters on numerical integration of circuit equations (associated discrete circuit models of capacitors and inductors)
  4. Lawrence T. Pillage, Ronald A. Rohrer and Chandramouli Visweswariah, Electronic Circuit and System Simulation Methods, McGraw-Hill, 1994, the chapters on numerical integration and companion models

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW3 standard
  • five exercises