Techniquecore
Source stepping
Also called source ramping, supply stepping.
Ramps all independent sources from zero to their full values and solves the DC operating point at each step, a continuation method for hard circuits.
Source stepping finds the DC operating point of a circuit by multiplying every independent source by a factor and raising from 0 to 1 in steps. At every source is off and the answer is known, all voltages and currents zero; at each later step Newton's method starts from the previous answer, which is close to the new one when the step is small. It is a technique of the circuit simulation half of the logic and circuit simulation sub-area, and a homotopy continuation whose parameter is the strength of the supplies.
In plain words
Newton's method needs a good first guess. For a circuit switched off, the guess is easy: nothing flows and every voltage is zero.
So turn the supplies up slowly. Raise them to one tenth of their value, and solve the circuit starting from the switched-off state. The answer changes only a little, so this works. Raise them again, and start from the last answer. Keep going until the supplies reach their full value. If a step is too large and Newton fails, go back and take a smaller step. If steps go well, take larger ones.
When it applies
Use it for the DC operating point when Newton from the usual start fails, and as the alternative to gmin stepping. It needs one thing from the circuit: with all sources off, the zero vector must be an operating point. That holds when every device carries no current at zero bias, as diodes, bipolar transistors and the Shichman-Hodges model do. It works best when the solution moves smoothly with the supply, and it fails when the solution path turns back, as in circuits with positive feedback. It changes only the right side of the MNA system, not the matrix.
The template
Let be the operating point equations with every independent source value replaced by . In the notation of DC operating point analysis,
SOURCE-STEPPING(F, Δ_0, Δ_min)- 1
λ ← 0; x ← 0 ▷ every source off: x = 0 solves F(·, 0) - 2
Δ ← Δ_0 - 3
while λ < 1 do - 4
λ' ← min(λ + Δ, 1) - 5
(x', ok) ← NEWTON(F(·, λ'), x) ▷ hole: the corrector, Newton with limiting - 6
if ok then λ ← λ'; x ← x'; Δ ← 2Δ ▷ hole: the step rule - 7
else Δ ← Δ / 2; if Δ < Δ_min then return FAILURE - 8
return x
The code of this page follows these lines, with plain Newton as the corrector, a limit of 20 iterations per Newton run and the step doubled after each success and halved after each failure. SPICE3 uses equal steps and stops at the first failure. The adaptive version of ngspice first solves the circuit with all sources off under gmin stepping, then raises by a step that starts at , grows by a factor 1.5 after fast Newton runs, shrinks by half after slow ones and by ten after failures, and gives up when the step falls below .
The end points. is the given circuit. At , gives and , so solves when every device law passes through the origin. If, in addition, the devices are two-terminal with nondecreasing laws and the voltage sources form no loop, is the only solution at (the uniqueness argument with Tellegen's theorem), so the path starts at a known, unique point.
Theorem (the path is smooth for monotone circuits). Assume every resistive device is a two-terminal element with a continuously differentiable law, the voltage sources form no loop, and the devices are uniformly monotone on with a constant : when . This holds, for example, when linear resistors alone connect every node to ground or to a node held by a voltage source. Then for every the circuit has exactly one solution , and is continuously differentiable.
Proof. Fix and pick with . As on the gmin stepping page, the node equations projected onto form a map of into itself that is uniformly monotone with constant , so the uniform monotonicity theorem (Ortega and Rheinboldt, Section 6.4) gives exactly one , and then exactly one because has independent columns. For the smoothness, the Jacobian in is with , and uniform monotonicity of a differentiable map gives for . If is in the null space, then and , so , then and . The Jacobian is nonsingular everywhere, and the implicit function theorem gives a continuously differentiable curve through each , which by uniqueness is .
Corollary (the stepping succeeds). Under the theorem's assumptions, with device laws whose derivatives are Lipschitz on bounded sets, there is a such that Newton started at converges to whenever . Proof sketch. The path is compact, so is bounded along it and the Jacobian is Lipschitz near it; the Kantorovich theorem then gives one radius of quadratic convergence around every . The path is uniformly continuous on , so a small enough keeps within of . So in exact arithmetic, with an iteration limit large enough for that radius, the step of line L7 never falls below , each accepted step except the last is at least , and the loop ends after finitely many steps if . The value of is not known in advance, which is why the step is adapted.
What is proved and what is measured. The theorem and the corollary cover monotone circuits: diodes, resistors and sources. Transistor circuits are not monotone, and for them no general guarantee holds; the success of source stepping on them is measured, not proved. The table below is measured with the code of this page.
Worked example. A source drives a diode ( A, mV) through . Plain Newton from zero first puts nearly all of on the diode.
| plain Newton from 0 | source stepping, | answer | |
|---|---|---|---|
| 5 V | 173 iterations | = 0.1, 0.2, 0.4, 0.8, 1; one rejected step; 41 iterations | 0.692544 V |
| 20 V | overflow: in iteration 2 | = 0.05, 0.15, 0.35, 0.75, 1; one rejected step; 46 iterations | 0.731273 V |
The answers agree with bisection on the KCL residual of the diode node to V. Both runs use plain Newton as the corrector; with junction voltage limiting in the corrector the counts fall further.
A turning point. Drive the tunnel-diode law by volts through . KCL is , so along the path . This has at , where . Below this value the path from rises smoothly; above it the low branch no longer exists, and at the only solution is , on another branch. The Jacobian is zero at the fold, so no step size lets the corrector follow the path past it: it must jump, and whether it lands on the far branch is luck.
Classic examples
- The DC analysis of SPICE3 and ngspice tries source stepping when Newton and gmin stepping fail.
- A DC sweep in a simulator is source stepping on one source, with the answers kept at every step; it traces transfer curves and is how the folds of latches are seen.
- Pseudo-transient analysis can ramp the supplies in time, which is source stepping with added capacitors.
- Homotopy continuation with arc-length parametrization follows the same path through turning points, at the price of a larger system per step.
Variations
- Equal steps. Take for and stop at the first failure. Simple, but a hard spot near needs a large everywhere.
- Adaptive steps. Grow the step after easy Newton runs and shrink it after slow runs or failures, as in the code of this page and in ngspice.
- Predictor. Start Newton at instead of ; solves one linear system with the Jacobian already factored, since , and the tangent prediction allows longer steps.
- Arc-length continuation. Make the arc length the parameter and solve for together; this passes turning points (homotopy continuation).
- Supply only. Ramp only the supply voltages and keep the signal sources fixed, or the reverse; the start point must still be known.
Pitfalls
- Turning points. Positive feedback makes the path fold, as in the tunnel-diode example; natural-parameter stepping fails or jumps there.
- The start must be a solution. A device that carries current at zero bias, or a current source that is not scaled, breaks the end point at .
- Which solution. For a circuit with several operating points, the stepping finds the one connected to the zero state along the path, which need not be the one the circuit settles in after power-up.
- Tolerances. The corrector at an intermediate need not be accurate; only the last solve at needs the full tolerances, and loose intermediate solves save iterations.
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
# 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]
source_stepping.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/source-stepping/. The authors are listed in prov/QF22WC.jsonl.
"""Source stepping for the DC operating point of a circuit with diodes.
A netlist is a list of elements. Node 0 is ground.
- ("R", p, q, r): a resistor;
- ("V", p, q, s): a voltage source with e_p - e_q = s;
- ("I", p, q, s): a current source; the current s flows from p through the source to q;
- ("D", p, q, i_s, v_t): a diode with anode p and cathode q, whose current from
p to q is i_s (exp((e_p - e_q) / v_t) - 1).
The unknowns are those of modified nodal analysis: the voltages e_1..e_n and
one current per voltage source, in netlist order. Every independent source is
multiplied by the parameter lam, so lam = 0 gives the circuit with all sources
off and lam = 1 gives the circuit itself.
"""
import math
from densela import SingularMatrixError, lu_factor, lu_solve
class NewtonFailure(ArithmeticError):
"""Newton's method overflowed, met a singular Jacobian or did not converge."""
def _branch_rows(netlist, n):
rows, size = {}, n
for k, el in enumerate(netlist):
if el[0] == "V":
rows[k] = size
size += 1
return rows, size
def _diode(i_s, v_t, v):
# math.exp raises OverflowError above about 709.78; that is the failure of plain Newton.
x = math.exp(v / v_t)
return i_s * (x - 1), i_s * x / v_t
def residual(netlist, n, x, lam):
"""F(x, lam): the KCL sum of the currents leaving each node, then e_p - e_q - lam s per voltage source."""
rows, size = _branch_rows(netlist, n)
f = [0 * x[0]] * size
e = [0 * x[0]] + list(x[:n])
def leave(p, q, i):
if p > 0:
f[p - 1] += i
if q > 0:
f[q - 1] -= i
for k, el in enumerate(netlist):
kind, p, q = el[0], el[1], el[2]
if kind == "R":
leave(p, q, (e[p] - e[q]) / el[3])
elif kind == "I":
leave(p, q, lam * el[3])
elif kind == "D":
leave(p, q, _diode(el[3], el[4], e[p] - e[q])[0])
elif kind == "V":
leave(p, q, x[rows[k]])
f[rows[k]] = e[p] - e[q] - lam * el[3]
else:
raise ValueError(f"unknown element {kind!r}")
return f
def jacobian(netlist, n, x):
"""The derivative of F with respect to x; it does not depend on lam."""
rows, size = _branch_rows(netlist, n)
a = [[0 * x[0]] * size for _ in range(size)]
e = [0 * x[0]] + list(x[:n])
def stamp(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
for k, el in enumerate(netlist):
kind, p, q = el[0], el[1], el[2]
if kind == "R":
stamp(p, q, 1 / el[3])
elif kind == "D":
stamp(p, q, _diode(el[3], el[4], e[p] - e[q])[1])
elif kind == "V":
m = rows[k]
for node, s in ((p, 1), (q, -1)):
if node > 0:
a[node - 1][m] += s
a[m][node - 1] += s
return a
def newton(netlist, n, x0, lam=1, max_iter=50, reltol=1e-9, abstol=1e-12):
"""Plain Newton on F(x, lam) = 0 from x0. Return (x, iterations) or raise NewtonFailure."""
x = list(x0)
for it in range(1, max_iter + 1):
try:
f = residual(netlist, n, x, lam)
a = jacobian(netlist, n, x)
dx = lu_solve(lu_factor(a), [-v for v in f])
except (OverflowError, SingularMatrixError) as exc:
raise NewtonFailure(f"iteration {it}: {exc}") from exc
x_new = [u + d for u, d in zip(x, dx)]
if not all(math.isfinite(v) for v in x_new):
raise NewtonFailure(f"iteration {it}: the iterate is not finite")
if all(abs(d) <= reltol * abs(u) + abstol for d, u in zip(dx, x_new)):
return x_new, it
x = x_new
raise NewtonFailure(f"no convergence in {max_iter} iterations")
def source_stepping(netlist, n, first_step=0.1, min_step=1e-6, max_iter=20, grow=2):
"""Trace the solution from lam = 0 to lam = 1, with Newton as the corrector.
Return (x, stats). stats["path"] lists the accepted pairs (lam, x),
stats["failures"] counts the rejected steps and stats["iterations"] the
Newton iterations of all corrector runs.
"""
_, size = _branch_rows(netlist, n)
zero = 0 * first_step
lam = zero # @line L1
x = [zero] * size # with every source off, x = 0 solves F, since every element carries no current at zero bias
step = first_step # @line L2
stats = {"path": [(lam, list(x))], "failures": 0, "iterations": 0}
while lam < 1: # @line L3
target = min(lam + step, 1 + zero) # @line L4
try:
x_new, its = newton(netlist, n, x, target, max_iter) # @line L5
except NewtonFailure:
stats["failures"] += 1
step = step / 2 # @line L7
if step < min_step:
raise NewtonFailure(f"the step fell below {min_step} at lam = {lam}") from None
continue
stats["iterations"] += its
lam, x = target, x_new # @line L6
step = step * grow
stats["path"].append((lam, list(x)))
return x, stats # @line L8
test_source_stepping.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/source-stepping/. The authors are listed in prov/QF22WC.jsonl.
import math
import random
from fractions import Fraction as F
import pytest
from source_stepping import NewtonFailure, newton, residual, source_stepping
IS, VT = 1e-14, 0.025852
def diode_circuit(e, r=1000.0):
# A source e at node 1, a resistor r from node 1 to node 2 and a diode from node 2 to ground.
return [("V", 1, 0, e), ("R", 1, 2, r), ("D", 2, 0, IS, VT)]
def safe_exp(u):
return math.inf if u > 700 else math.exp(u)
def bisect(f, lo, hi):
# f is increasing with f(lo) < 0 < f(hi).
for _ in range(200):
mid = (lo + hi) / 2
if mid in (lo, hi):
break
if f(mid) < 0:
lo = mid
else:
hi = mid
return (lo + hi) / 2
def diode_voltage_by_bisection(e, r=1000.0):
return bisect(lambda v: IS * (safe_exp(v / VT) - 1) - (e - v) / r, 0.0, e)
def test_plain_newton_from_zero_overflows_and_source_stepping_does_not():
net = diode_circuit(20.0)
with pytest.raises(NewtonFailure) as info:
newton(net, 2, [0.0, 0.0, 0.0], 1.0, max_iter=1000)
assert isinstance(info.value.__cause__, OverflowError)
x, stats = source_stepping(net, 2)
v = diode_voltage_by_bisection(20.0)
assert abs(x[1] - v) < 1e-9
assert abs(x[2] + (20.0 - v) / 1000.0) < 1e-12 # the source current, from + through the source to -
assert stats["path"][-1][0] == 1
def test_plain_newton_from_zero_is_slow_at_five_volts():
net = diode_circuit(5.0)
with pytest.raises(NewtonFailure):
newton(net, 2, [0.0, 0.0, 0.0], 1.0, max_iter=100)
x_plain, its = newton(net, 2, [0.0, 0.0, 0.0], 1.0, max_iter=1000)
assert its > 150 # about (5 - 0.69) / VT steps of size VT down the exponential
x, stats = source_stepping(net, 2)
assert stats["iterations"] < its
v = diode_voltage_by_bisection(5.0)
assert abs(x[1] - v) < 1e-9 and abs(x_plain[1] - v) < 1e-9
assert abs(x[1] - 0.69254) < 1e-5
def test_homotopy_end_points():
net = diode_circuit(20.0) + [("I", 0, 2, 1e-3)]
# At lam = 0 every source is off and x = 0 solves the circuit exactly.
assert residual(net, 2, [0.0, 0.0, 0.0], 0) == [0.0, 0.0, 0.0]
x, stats = source_stepping(net, 2)
# At lam = 1 the circuit is the given one.
assert max(abs(v) for v in residual(net, 2, x, 1)) < 1e-12
lams = [lam for lam, _ in stats["path"]]
assert lams[0] == 0 and lams[-1] == 1 and lams == sorted(lams)
def test_linear_circuit_path_is_exact_and_proportional():
# 10 V at node 1, 2 ohm from 1 to 2, 8 ohm from 2 to ground: e = (10, 8), source current -1.
net = [("V", 1, 0, F(10)), ("R", 1, 2, F(2)), ("R", 2, 0, F(8))]
x, stats = source_stepping(net, 2, first_step=F(1, 4))
assert x == [10, 8, -1]
assert [lam for lam, _ in stats["path"]] == [0, F(1, 4), F(3, 4), 1]
for lam, xs in stats["path"]:
assert xs == [lam * 10, lam * 8, -lam]
def test_no_operating_point_is_reported():
# The source pulls 1 mA out of the anode, so the diode would need a reverse current of 1 mA.
net = [("I", 1, 0, 1e-3), ("D", 1, 0, IS, VT)]
with pytest.raises(NewtonFailure):
source_stepping(net, 1)
def random_diode_network(rng, n):
net = []
for k in range(1, n + 1):
net.append(("R", k, 0, rng.uniform(100.0, 10000.0)))
net.append(("I", 0, k, rng.uniform(0.0, 0.01)))
if k < n:
net.append(("R", k, k + 1, rng.uniform(100.0, 10000.0)))
p, q = (k, rng.randint(0, n)) if rng.random() < 0.5 else (rng.randint(0, n), k)
if p != q:
net.append(("D", p, q, IS, VT))
return net
def gauss_seidel(net, n):
# Nonlinear Gauss-Seidel: solve the KCL of one node at a time by bisection.
# Every element is monotone, so the current leaving node k increases with e_k.
e = [0.0] * (n + 1)
at = {k: [el for el in net if k in (el[1], el[2])] for k in range(1, n + 1)}
def leaving(k, ek):
old, e[k] = e[k], ek
s = 0.0
for el in at[k]:
kind, p, q = el[0], el[1], el[2]
if kind == "R":
i = (e[p] - e[q]) / el[3]
elif kind == "I":
i = el[3]
else:
i = el[3] * (safe_exp((e[p] - e[q]) / el[4]) - 1)
s += i if p == k else -i
e[k] = old
return s
for _ in range(5000):
change = 0.0
for k in range(1, n + 1):
lo, hi = -1.0, 1.0
while leaving(k, lo) > 0:
lo *= 2
while leaving(k, hi) < 0:
hi *= 2
v = bisect(lambda u: leaving(k, u), lo, hi)
change = max(change, abs(v - e[k]))
e[k] = v
if change < 1e-14:
break
return e[1:]
def test_random_monotone_circuits_against_gauss_seidel():
rng = random.Random(20240611)
hard = 0
for _ in range(8):
n = rng.randint(2, 4)
net = random_diode_network(rng, n)
try:
newton(net, n, [0.0] * n, 1.0, max_iter=50)
except NewtonFailure:
hard += 1
x, _ = source_stepping(net, n)
ref = gauss_seidel(net, n)
# Gauss-Seidel converges slowly when diodes couple the nodes strongly, so it only gives about 7 digits.
assert max(abs(a - b) for a, b in zip(x, ref)) < 1e-6
assert max(abs(v) for v in residual(net, n, x, 1)) < 1e-12
assert hard > 0 # some of these circuits defeat plain Newton from zero
Exercises
- For a source , a resistor and a diode, show that is increasing in and that the path is smooth, directly from the scalar KCL equation.
- Show that for a circuit of linear resistors and sources the solution is , and that source stepping with any steps takes one Newton iteration per step plus one for the convergence test.
- In the tunnel-diode example, find the value of at which a second turning point appears on the way back, and describe the three branches of the path.
- Derive the predictor and compute it at for the diode circuit.
References
- Farid N. Najm, Circuit Simulation, Wiley-IEEE Press, 2010, Chapter 4, Section 4.4.3 (source stepping) and Section 4.4.6 (the justification of the continuation methods)
- ngspice source, src/spicelib/analysis/cktop.c, the functions spice3_src (equal steps of the source factor CKTsrcFact) and gillespie_src (adaptive steps, after a gmin ramp at zero sources)
- Eugene L. Allgower and Kurt Georg, Introduction to Numerical Continuation Methods, SIAM Classics in Applied Mathematics 45, 2003 (first published 1990), the chapters on predictor-corrector methods and on step length control along a smooth solution curve
- James M. Ortega and Werner C. Rheinboldt, Iterative Solution of Nonlinear Equations in Several Variables, SIAM Classics in Applied Mathematics 30, 2000 (first published 1970), Section 6.4, the uniform monotonicity theorem
- Robert C. Melville, Ljiljana Trajković, San-Chin Fang and Layne T. Watson, Artificial parameter homotopy methods for the DC operating point problem, IEEE Transactions on Computer-Aided Design 12(6), 861 to 877, 1993, the discussion of natural parameter homotopies such as source stepping and their failure at turning points, which motivates artificial parameter homotopies
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 QF22WC Edit this page History Report an error Markdown