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 in parallel with a current source , so that the element current at the new time point is . With every dynamic element replaced, one step of transient simulation becomes one solve of a resistive circuit by modified nodal analysis, with depending on the step and on the past values. The technique belongs to the circuit simulation half of the logic and circuit simulation sub-area. For a capacitor , backward Euler gives and the trapezoidal rule gives .
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 and . 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 , 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 to node has the voltage and the current counted from through the element to . A companion model is a conductance from to in parallel with a current source from through it to , so the stamps of MNA apply: in the matrix, at row and at row of the right side.
TRANSIENT(netlist, e_0, h, K, method)- 1
for each capacitor and inductor el do set (v_el, i_el) from e_0 and the initial currents - 2
for k ← 1 to K do - 3
for each capacitor and inductor el do (G_el, J_el) ← COMPANION(el, method, h, v_el, i_el) - 4
M ← stamps of the resistors and of every G_el; factor M once for each (h, method) - 5
z ← stamps of the sources at t_k = k h and of every J_el - 6
e_k ← SOLVE(M, z) - 7
for each capacitor and inductor el do v_el ← e_p − e_q; i_el ← G_el v_el + J_el - 8
return e_0, e_1, ..., e_K
The holes are COMPANION, which holds the integration formula, and SOLVE. Line L4 factors only when 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 and an inductor . Apply each formula to these laws and solve for :
| Element and formula | Discrete law | ||
|---|---|---|---|
| capacitor, backward Euler | |||
| capacitor, trapezoidal | |||
| inductor, backward Euler | |||
| inductor, trapezoidal |
Each row is the discrete law rearranged, for example is . So a source from to is a source of that drives current into node , in parallel with . Every other element keeps its law, and KCL and KVL are unchanged, so the solution of the resistive circuit at step 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 with a series resistor charge a capacitor from , and let and . The exact solution is . With backward Euler, KCL at the capacitor node is , that is , so with . With the trapezoidal rule and the consistent start , , so . In both cases exactly.
The order of the error. At a fixed time the error is with . For backward Euler , so and the error is : first order in . For the trapezoidal rule, with , , so the error is : second order. These match the local truncation errors of the two formulas, for backward Euler and for the trapezoidal rule per step (local truncation error).
Worked example. Take V, , F and s, with the source in Norton form, 1 A into the node in parallel with . Backward Euler: , , so and . Trapezoidal with A: , , so the source drives 1 A into the node and , . The exact value is . Over the largest errors are:
| steps in | 10 | 20 | 40 | 80 |
|---|---|---|---|---|
| backward Euler | ||||
| trapezoidal |
Halving halves the backward Euler error and divides the trapezoidal error by 4. The leading term of the formula above gives for .
Energy of a lossless network. For a network of capacitors and inductors only, the trapezoidal rule keeps the stored energy exactly, and backward Euler lowers it at every step that changes the state. Proof. With the trapezoidal rule, the averages and satisfy KVL and KCL, because both laws are linear. By Tellegen's theorem, . For a capacitor, , so ; for an inductor, , so . The sum of these terms is the change of energy divided by , so the change is zero. With backward Euler, Tellegen's theorem on gives , and turns this into: the energy drops by .
Cost. For a linear circuit with MNA unknowns, steps and a fixed , the run costs one LU factorization plus pairs of triangular solves, 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 .
Variations
- Gear (BDF) models. The second-order backward differentiation formula gives and . Higher orders use more past points.
- Charge form. For a nonlinear capacitor with charge , the discrete law is linearized at each Newton iterate , which gives . Writing the law in charge conserves charge exactly, while a law in 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 changes, changes and 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 , the trapezoidal factor is close to , so the error flips sign at every step and decays very slowly. The rule is A-stable but not L-stable. Backward Euler has 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 , 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 adds only .
- 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 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.
# 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
- 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 .
- Show that backward Euler with the companion model of a capacitor gives for every on the RC circuit, and that as .
- A capacitor and an inductor in parallel start with V and . With F, H and s, compute three trapezoidal steps exactly and check that the energy stays J.
- Write the trapezoidal model of a capacitor in Thevenin form, and show that it gives the same node voltages as the Norton form.
References
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag JH4KPG Edit this page History Report an error Markdown