Algorithmcore
Adjoint sensitivity analysis
Also called Director-Rohrer adjoint network, adjoint network method.
Director and Rohrer's method that gets the sensitivity of one output to every circuit parameter from a single solve of the adjoint network built by Tellegen's theorem.
- Time
- O(N^3 + K (N^2 + P)) worst
- Space
- O(N^2 + P) extra
- Where
- K = the number of outputs; N = the number of MNA unknowns; P = the number of parameters
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stephen W. Director, Ronald A. Rohrer, 1969
Adjoint sensitivity analysis computes the derivatives of one circuit output, such as a node voltage, with respect to every parameter of the circuit, such as every resistance and every source value, at the cost of one extra linear solve. The extra solve is with the transposed MNA matrix, which is the MNA matrix of the adjoint network, and it reuses the LU factors of the original analysis. It is an algorithm of the circuit simulation half of the logic and circuit simulation sub-area, given by Director and Rohrer in 1969 from Tellegen's theorem.
In plain words
Suppose you want to know how much an output voltage moves if you change each resistor a little. The obvious way is to change one resistor, solve the circuit again, and repeat for every resistor. With a thousand resistors that is a thousand solves.
The adjoint method needs only one more solve. It builds a second circuit, the adjoint, on the same wires: it removes the original sources, drives the output point with a unit current, and swaps the input and output of each controlled source. The voltages of this circuit say how strongly each place in the circuit influences the output. The sensitivity to each resistor then comes from a product of two numbers: the voltage across it in the original circuit and the voltage across it in the adjoint.
The problem
Given a linear resistive circuit with parameters (resistances, conductances, gains of controlled sources, values of independent sources), its MNA system with nonsingular, and an output , compute and the gradient for every . For several outputs , compute the gradients. The same problem arises at a DC operating point of a nonlinear circuit, with the Jacobian there, and at each time step of a transient analysis with companion models.
The algorithm
Differentiate : . The direct method solves this for every , solves. The adjoint method moves the inverse onto the output instead:
ADJOINT-SENSITIVITY(netlist, c)- 1
(M, z) ← the MNA stamps of netlist - 2
LU ← FACTOR(M) - 3
x ← SOLVE(LU, z) - 4
λ ← SOLVE-TRANSPOSED(LU, c) ▷ Mᵀ λ = c: the adjoint circuit - 5
φ ← cᵀ x - 6
for each element k with parameter p_k do - 7
s_k ← λᵀ (∂z/∂p_k − (∂M/∂p_k) x) ▷ at most four entries, by the table below - 8
return φ, (s_1, ..., s_P)
Each element touches at most four entries of and two of , so line L7 is a short formula. Write for the difference of node voltages, with at ground, and the same for :
| element (as on the MNA page) | parameter | |
|---|---|---|
| conductance from to | ||
| resistor from to | ||
| current source from to | ||
| voltage source with current row | ||
| VCCS from to |
The adjoint network. The stamps of resistors, conductances and voltage sources are symmetric, and the transpose of the stamp of a VCCS from to controlled by is the stamp of a VCCS from to controlled by , with the same gain. So is the MNA matrix of the adjoint network: the same circuit with every controlled source turned around and every independent source set to zero. The right side is its excitation: for , a 1 A source driving current into node ; for the current of a voltage source, a 1 V value of that source. The vector is the solution of this circuit, its node voltages and source currents. For a reciprocal circuit, one without controlled sources, the adjoint network is the circuit itself.
Example
Take the circuit of the MNA page: a 6 V source at node 1, from node 1 to node 2, from node 2 to ground, and a 1 A source into node 2, with output . Its MNA system has
is symmetric. Solve : the last row gives , the second , so , and the first gives . In circuit terms, the adjoint is the circuit with the 6 V source shorted and the 1 A source removed, driven by 1 A into node 2: node 2 sees . The table then gives
- the source : ;
- : ;
- : ;
- the 1 A source, from ground into node 2: .
By hand, , whose partial derivatives are , , and . One transposed solve gave all four.
Correctness
The identity behind line L7 is exact: from and , , where is differentiable in because is nonsingular and its entries are smooth in . The table follows by reading off the entries of each stamp. Director and Rohrer's form of the same result uses only Kirchhoff's laws: Tellegen's theorem applied to the perturbed original circuit and the adjoint network, which share one graph, gives , and the adjoint element laws are chosen so that every unperturbed element drops out of this sum. The full proof gives both forms, the table, and the identification of with the adjoint network.
Proof: One adjoint solve gives the derivative of an output with respect to every parameterfull
Let a linear resistive circuit have nodes with ground , and let its modified nodal analysis system be , where and are the parameters of the elements. The stamps are those of the MNA page: a conductance from to adds at and and at and ; a current source from to adds to and to ; a voltage source with current row adds at and , at and , and to ; a VCCS of gain from to controlled by adds at and and at and . Entries in a row or column of ground are dropped, and . Let be an output.
Lemma 1 (differentiability). If is nonsingular, then on a neighbourhood of the solution is continuously differentiable, and
Proof. Every entry of and is a polynomial in a conductance, a gain or a source value, or for a resistance , so it is continuously differentiable in . The determinant is continuous, so stays nonsingular near , and the entries of are rational functions of the entries of with nonzero denominator (Cramer's rule). So is continuously differentiable. Differentiating the identity with the product rule gives the displayed equation.
Theorem 1 (the adjoint identity). Let solve . Then for every parameter ,
So one solve with for each output gives the derivative with respect to all parameters.
Proof. , and Lemma 1 replaces . The vector does not depend on .
Lemma 2 (the table). With , Theorem 1 gives:
- conductance from to : ;
- resistor from to : ;
- current source from to : ;
- voltage source with current row : ;
- VCCS of gain from to controlled by : .
Proof. (1) , and is the stamp with replaced by . So has in row and in row , and of it is ; dropping a ground row or column agrees with . (2) and , so the chain rule applied to (1) gives the formula. (3) and has in row and in row , so the product is . (4) and is the unit vector of row . (5) , and has in row and in row , so of it is .
Lemma 3 (the adjoint network). is the MNA matrix of the adjoint network, the same netlist with every independent source set to zero and every VCCS from to controlled by replaced by a VCCS of the same gain from to controlled by . The right side is the excitation of that network by independent sources: (the unit vector of node ) is a current source of 1 A from ground into node , and for the current row of a voltage source is the value 1 V of that source.
Proof. is the sum of the stamps of the elements, and the transpose of a sum is the sum of the transposes. The stamp of a conductance and the stamp of a voltage source are symmetric matrices. The VCCS stamp has at and and at and ; its transpose has at and and at and , which is the stamp of a VCCS from to controlled by . Independent sources do not enter . A current source of 1 A from ground to node adds to row of the right side, and a voltage source of value 1 V adds to its own row.
Theorem 2 (Tellegen form). Let be the branch voltages and currents of the original circuit, those of the adjoint network of Lemma 3 written as a circuit on the same graph, and let a parameter change from to change the original solution by . Then
Proof. The perturbed circuit and the original circuit have the same graph, so satisfies Kirchhoff's voltage law and satisfies Kirchhoff's current law, because both laws are linear. The adjoint network has the same graph as well, so satisfies KVL and satisfies KCL. Tellegen's theorem, which needs only KCL for one vector and KVL for the other on the same graph, gives and . Subtracting gives the claim.
The terms of this sum for an element that was not changed vanish by the choice of the adjoint element. For a resistor with and adjoint , the term is . For a changed conductance, to first order, so its term is , which is the first row of Lemma 2 with and . The other rows follow in the same way. This is the form in which Director and Rohrer stated the method; Theorem 1 is the same statement in matrix form.
Theorem 3 (cost). For a circuit with unknowns, parameters and outputs, the algorithm uses one LU factorization of , one solve for and solves with , and further operations per parameter and output.
Proof. Lines L2 and L3 run once. For each output, line L4 runs once. If with a permutation , then , so is solved by a forward substitution with the lower triangular , a back substitution with the upper triangular , and the permutation , with no new factorization. Each row of Lemma 2 reads at most four entries of and and does a fixed number of arithmetic operations.
Theorem 4 (correctness of the algorithm). If is nonsingular, ADJOINT-SENSITIVITY returns and, for every element , . If is singular, the factorization of line L2 fails and the code reports it.
Proof. Lines L1 to L3 compute the solution of the MNA system, since the stamps are those of the MNA page and LU with partial pivoting solves a nonsingular system exactly in exact arithmetic. Line L4 computes with by Theorem 3. Line L5 is the definition of . Line L7 evaluates the formula of Lemma 2 for the kind of element , which equals by Theorem 1. If is singular, Gaussian elimination with partial pivoting meets a column with no nonzero pivot candidate, and the factorization raises the error.
Complexity
With dense LU, line L2 costs and each of lines L3 and L4 costs ; lines L6 and L7 cost per parameter, in all. For outputs the total is , against for the direct method, which solves once per parameter. So the adjoint method wins when there are fewer outputs than parameters, the usual case in circuit optimization, where one cost function depends on many element values. With a sparse LU, as in SPICE, the same counts hold with the costs of a sparse factorization and sparse triangular solves. The extra space is the factors, dense, and the gradient, . The code of this page counts the operations, and its tests check that outputs use one factorization, one forward solve and transposed solves.
Properties
- Exact. In exact arithmetic the result is the true gradient, not an estimate; the tests check equality with exact fractions against the direct method.
- One solve per output. The work for all derivatives of one output is one transposed solve plus , whatever is.
- Reuses the factors. for , so the transposed solve uses the same LU factors; no new factorization is needed.
- Local in the circuit. Each derivative needs only the original and adjoint voltages at the element's own nodes and, for a controlled source, at its control nodes.
- Linear in the output. For a weighted sum of outputs, the adjoint vector is the same weighted sum of their adjoint vectors.
Variants and improvements
- Nonlinear DC. At an operating point of a nonlinear circuit, use the Jacobian of the last Newton iteration as and the partial derivatives of the device equations in place of and ; the identity is the implicit function theorem.
- AC sensitivity. In small-signal AC analysis the matrix is complex, ; the adjoint uses , not the conjugate transpose, and gives the derivatives of a complex transfer function.
- Transient sensitivity. For a time-domain output, the adjoint system runs backward in time, with the transposed companion models of each step; it needs the forward solution at every time point, which is stored or recomputed, as in gradient checkpointing.
- Noise analysis. Circuit noise analysis uses the same adjoint solve: the transfer from every noise source to one output is one adjoint solution.
- Second derivatives. The derivatives of the gradient follow from one more forward solve per direction, as in second-order automatic differentiation.
- Tableau form. In sparse tableau analysis the adjoint is the transposed tableau, and Hachtel, Brayton and Gustavson used it with the same LU factors.
When to use it
Use it when there are many parameters and few outputs: gradients of a cost function for circuit optimization and sizing, the sensitivity of a delay or a gain to every element, worst-case and statistical analysis that needs the derivative of one output with respect to every device. When there are many outputs and few parameters, use the direct method, one forward solve per parameter. For a check of a few derivatives, finite differences are simpler, but each costs a full analysis and gives only a few correct digits.
Pitfalls
- Transpose, not the same matrix. With controlled sources is not symmetric, and solving with instead of gives wrong results that still look reasonable. The controlled sources of the adjoint network must be turned around.
- Signs of the excitation. The sign of fixes the direction of the unit source of the adjoint network; mixing the conventions of the current direction for sources and outputs flips signs in the table.
- Resistance or conductance. The derivative with respect to is times the derivative with respect to ; using one formula for the other is a common error.
- AC conjugation. In complex analysis the adjoint uses the plain transpose; the conjugate transpose gives the derivatives of the wrong function.
- Singular matrix. If the circuit has a voltage-source loop or a current-source cut set, is singular and the output has no derivative; the code reports this as an error.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adjoint-sensitivity-analysis/. The authors are listed in prov/XP8WTV.jsonl.
"""Adjoint sensitivity analysis of a linear resistive circuit at DC.
Nodes are the integers 0 to n, and node 0 is ground. A netlist is a list of
tuples, one for each element, as on the modified nodal analysis page:
- ("R", p, q, r): a resistor of resistance r between p and q;
- ("G", p, q, g): a conductance g between p and q;
- ("I", p, q, s): a current source; the current s flows from p through the
source to q;
- ("V", p, q, s): a voltage source with e_p - e_q = s, whose current from p
through the source to q is an extra unknown;
- ("VCCS", p, q, c, d, g): the current g (e_c - e_d) flows from p through the
element to q.
The parameter of each element is its last value (r, g, s or g). An output is
a linear function phi = c . x of the MNA unknowns x = (e_1..e_n, j_1..j_m).
Values are Fraction (exact) or float.
"""
from densela import SingularMatrixError, lu_factor, lu_solve, lu_solve_transpose
__all__ = ["SingularMatrixError", "stamp", "node_output", "source_current_output", "sensitivities"]
def _add(a, i, j, v):
if i > 0 and j > 0:
a[i - 1][j - 1] += v
def stamp(netlist, n):
"""Return (M, z, rows): the MNA system M x = z and the row of each voltage source."""
rows, size = {}, n
for k, el in enumerate(netlist):
if el[0] == "V":
rows[k] = size
size += 1
a = [[0] * size for _ in range(size)]
z = [0] * size
for k, el in enumerate(netlist):
kind = el[0]
if kind in ("R", "G"):
_, p, q, value = el
g = 1 / value if kind == "R" else value
for r, c, s in ((p, p, 1), (q, q, 1), (p, q, -1), (q, p, -1)):
_add(a, r, c, s * g)
elif kind == "I":
_, p, q, s = el
if p > 0:
z[p - 1] -= s
if q > 0:
z[q - 1] += s
elif kind == "V":
_, p, q, s = el
m = rows[k]
for node, sign in ((p, 1), (q, -1)):
if node > 0:
a[node - 1][m] += sign
a[m][node - 1] += sign
z[m] += s
elif kind == "VCCS":
_, p, q, c, d, g = el
for r, col, s in ((p, c, 1), (p, d, -1), (q, c, -1), (q, d, 1)):
_add(a, r, col, s * g)
else:
raise ValueError(f"unknown element {kind!r}")
return a, z, rows
def node_output(netlist, n, node):
"""The vector c with c . x = e_node."""
_, _, rows = stamp(netlist, n)
c = [0] * (n + len(rows))
c[node - 1] = 1
return c
def source_current_output(netlist, n, k):
"""The vector c with c . x = the current of the voltage source netlist[k]."""
_, _, rows = stamp(netlist, n)
c = [0] * (n + len(rows))
c[rows[k]] = 1
return c
def _diff(vec, p, q):
# vec_p - vec_q, with the ground entry 0.
return (vec[p - 1] if p > 0 else 0) - (vec[q - 1] if q > 0 else 0)
def sensitivities(netlist, n, outputs, stats=None):
"""Return [(phi, grad)] for each output vector c in outputs.
grad[k] is d phi / d (parameter of netlist[k]). The work is one LU
factorization of M, one solve for x, and one transposed solve for the
adjoint vector of each output, whatever the number of parameters.
Raise SingularMatrixError when M is singular. If stats is a dict, it
receives the counts of these operations.
"""
a, z, rows = stamp(netlist, n) # @line L1
factors = lu_factor(a) # @line L2
x = lu_solve(factors, z) # @line L3
if stats is not None:
stats.update(factorizations=1, solves=1, transposed_solves=0)
result = []
for c in outputs:
lam = lu_solve_transpose(factors, c) # @line L4
if stats is not None:
stats["transposed_solves"] += 1
phi = sum(ci * xi for ci, xi in zip(c, x)) # @line L5
grad = []
for k, el in enumerate(netlist): # @line L6
kind, p, q = el[0], el[1], el[2]
# @line L7: grad = lam . (dz/dp - (dM/dp) x), which touches at most four entries
if kind == "G":
grad.append(-_diff(lam, p, q) * _diff(x, p, q))
elif kind == "R":
grad.append(_diff(lam, p, q) * _diff(x, p, q) / (el[3] * el[3]))
elif kind == "I":
grad.append(-_diff(lam, p, q))
elif kind == "V":
grad.append(lam[rows[k]])
else:
c_node, d_node = el[3], el[4]
grad.append(-_diff(lam, p, q) * _diff(x, c_node, d_node))
result.append((phi, grad))
return result # @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_adjoint_sensitivity_analysis.py 183 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adjoint-sensitivity-analysis/. The authors are listed in prov/XP8WTV.jsonl.
import random
from fractions import Fraction as F
import pytest
from adjoint_sensitivity_analysis import (
SingularMatrixError,
node_output,
sensitivities,
source_current_output,
stamp,
)
from densela import lu_factor, lu_solve, matvec, solve
def output_value(netlist, n, c):
a, z, _ = stamp(netlist, n)
x = solve(a, z)
return sum(ci * xi for ci, xi in zip(c, x))
def with_parameter(netlist, k, value):
el = list(netlist[k])
el[-1] = value
return netlist[:k] + [tuple(el)] + netlist[k + 1 :]
def direct_sensitivity(netlist, n, k):
"""The direct method: solve M dx = dz - dM x for one parameter, exactly."""
if netlist[k][0] == "R":
# dx/dR = dx/dG * dG/dR with G = 1/R, so work with a conductance.
el = netlist[k]
r = el[-1]
g_net = netlist[:k] + [("G", el[1], el[2], 1 / r)] + netlist[k + 1 :]
return [d * (-1 / (r * r)) for d in direct_sensitivity(g_net, n, k)]
a, z, _ = stamp(netlist, n)
x = solve(a, z)
a1, z1, _ = stamp(with_parameter(netlist, k, netlist[k][-1] + 1), n)
# M and z are affine in a conductance, a gain or a source value, so a unit step gives dM and dz exactly.
da = [[u - v for u, v in zip(r1, r)] for r1, r in zip(a1, a)]
dz = [u - v for u, v in zip(z1, z)]
rhs = [d - m for d, m in zip(dz, matvec(da, x))]
return solve(a, rhs)
# The circuit of the page: 6 V at node 1, 2 ohm from 1 to 2, 3 ohm from 2 to 0, 1 A into node 2.
PAGE = [("V", 1, 0, F(6)), ("R", 1, 2, F(2)), ("R", 2, 0, F(3)), ("I", 0, 2, F(1))]
def test_page_example():
stats = {}
[(phi, grad)] = sensitivities(PAGE, 2, [node_output(PAGE, 2, 2)], stats)
assert phi == F(24, 5)
# e2 = R2 (E + R1 I) / (R1 + R2); its partial derivatives by hand are
# R2 / (R1 + R2), R2 (I R2 - E) / (R1 + R2)^2, R1 (E + R1 I) / (R1 + R2)^2 and R1 R2 / (R1 + R2).
assert grad == [F(3, 5), F(-9, 25), F(16, 25), F(6, 5)]
assert stats == {"factorizations": 1, "solves": 1, "transposed_solves": 1}
def test_divider_formula():
e, r1, r2 = F(10), F(2), F(8)
net = [("V", 1, 0, e), ("R", 1, 2, r1), ("R", 2, 0, r2)]
[(phi, grad)] = sensitivities(net, 2, [node_output(net, 2, 2)])
assert phi == e * r2 / (r1 + r2)
assert grad[0] == r2 / (r1 + r2)
assert grad[1] == -e * r2 / (r1 + r2) ** 2
assert grad[2] == e * r1 / (r1 + r2) ** 2
def random_circuit(rng, n, exact):
def val(lo, hi):
if exact:
return F(rng.randint(lo * 4, hi * 4), 4)
return rng.uniform(lo, hi)
net = []
for k in range(1, n + 1): # a spanning tree keeps every node connected to ground
net.append(("R", k, rng.randint(0, k - 1), val(1, 5)))
for _ in range(n):
p, q = rng.sample(range(n + 1), 2)
net.append(("G", p, q, val(1, 3)))
for _ in range(2):
p, q = rng.sample(range(n + 1), 2)
net.append(("I", p, q, val(-2, 2)))
net.append(("V", rng.randint(1, n), 0, val(1, 5)))
p, q, c, d = (rng.randint(0, n) for _ in range(4))
if p != q and c != d:
net.append(("VCCS", p, q, c, d, val(-1, 1)))
return net
def nonsingular_circuits(seed, count, exact):
rng = random.Random(seed)
out = []
while len(out) < count:
n = rng.randint(2, 5)
net = random_circuit(rng, n, exact)
try:
lu_factor(stamp(net, n)[0])
except SingularMatrixError:
continue
out.append((net, n))
return out
def test_adjoint_equals_exact_direct_sensitivities():
for net, n in nonsingular_circuits(7, 12, exact=True):
outputs = [node_output(net, n, k) for k in range(1, n + 1)]
outputs.append(source_current_output(net, n, next(k for k, el in enumerate(net) if el[0] == "V")))
results = sensitivities(net, n, outputs)
for k in range(len(net)):
dx = direct_sensitivity(net, n, k)
for c, (_, grad) in zip(outputs, results):
assert grad[k] == sum(ci * di for ci, di in zip(c, dx))
def test_adjoint_equals_exact_difference_quotient_limit():
# phi is a rational function of each parameter; the central difference with exact
# fractions differs from the derivative by O(t^2), checked over three values of t.
curved = 0
for net, n in nonsingular_circuits(11, 4, exact=True):
# The current of the voltage source depends on every element of these circuits.
c = source_current_output(net, n, next(k for k, el in enumerate(net) if el[0] == "V"))
[(_, grad)] = sensitivities(net, n, [c])
for k in range(len(net)):
p = net[k][-1]
errs = []
for t in (F(1, 10**4), F(1, 10**5), F(1, 10**6)):
hi = output_value(with_parameter(net, k, p + t), n, c)
lo = output_value(with_parameter(net, k, p - t), n, c)
errs.append(abs((hi - lo) / (2 * t) - grad[k]))
if errs[0] == 0:
assert errs == [0, 0, 0] # phi is affine in this parameter
else:
curved += 1
assert all(90 < a / b < 110 for a, b in zip(errs, errs[1:])), errs
assert curved >= 20
def test_adjoint_against_float_central_differences():
for net, n in nonsingular_circuits(2024, 20, exact=False):
outputs = [node_output(net, n, n), source_current_output(net, n, next(k for k, el in enumerate(net) if el[0] == "V"))]
for c, (phi, grad) in zip(outputs, sensitivities(net, n, outputs)):
check_against_differences(net, n, c, phi, grad)
def check_against_differences(net, n, c, phi, grad):
assert abs(phi - output_value(net, n, c)) < 1e-12 * max(1.0, abs(phi))
for k in range(len(net)):
p = net[k][-1]
t = 1e-6 * max(1.0, abs(p))
hi = output_value(with_parameter(net, k, p + t), n, c)
lo = output_value(with_parameter(net, k, p - t), n, c)
assert abs((hi - lo) / (2 * t) - grad[k]) < 1e-6 * max(1.0, abs(grad[k]))
def test_one_factorization_and_one_adjoint_solve_per_output():
net, n = nonsingular_circuits(5, 1, exact=True)[0]
outputs = [node_output(net, n, k) for k in range(1, n + 1)]
stats = {}
results = sensitivities(net, n, outputs, stats)
assert stats == {"factorizations": 1, "solves": 1, "transposed_solves": n}
assert all(len(grad) == len(net) for _, grad in results)
def test_reciprocal_circuit_has_adjoint_equal_to_a_forward_solve():
# Without controlled sources M is symmetric, so the adjoint circuit is the circuit itself.
net = [("V", 1, 0, F(6)), ("R", 1, 2, F(2)), ("R", 2, 3, F(3)), ("R", 3, 0, F(1)), ("R", 2, 0, F(4))]
a, _, _ = stamp(net, 3)
assert all(a[i][j] == a[j][i] for i in range(4) for j in range(4))
c = node_output(net, 3, 3)
lam = lu_solve(lu_factor(a), c)
[(_, grad)] = sensitivities(net, 3, [c])
assert grad[0] == lam[3] # d e3 / dE is the adjoint value at the source row
def test_singular_circuit_is_reported():
net = [("V", 1, 0, F(1)), ("V", 1, 0, F(1)), ("R", 1, 0, F(1))] # a loop of voltage sources
with pytest.raises(SingularMatrixError):
sensitivities(net, 1, [[1, 0, 0]])
History
Bode studied the sensitivity of feedback amplifiers in the 1940s, one parameter at a time. Director and Rohrer (1969) defined the adjoint network element by element and used Tellegen's theorem to show that one analysis of it gives the sensitivities to all elements; they applied it to the automated design of networks in the same years. Hachtel, Brayton and Gustavson (1971) gave the matrix form with the transposed sparse tableau and its LU factors. The same idea, under the name of the reverse mode, became the core of automatic differentiation and of backpropagation in neural networks.
References
- Stephen W. Director and Ronald A. Rohrer, The generalized adjoint network and network sensitivities, IEEE Transactions on Circuit Theory 16(3), 318 to 323, 1969, the adjoint network defined element by element through Tellegen's theorem, and the sensitivity formulas for resistors, sources and controlled sources
- Gary D. Hachtel, Robert K. Brayton and Fred G. Gustavson, The sparse tableau approach to network analysis and design, IEEE Transactions on Circuit Theory 18(1), 101 to 113, 1971, the sensitivity computation with the transposed tableau, which reuses the LU factors of the analysis
- Jiří Vlach and Kishore Singhal, Computer Methods for Circuit Analysis and Design, second edition, Van Nostrand Reinhold, 1994, the chapter on sensitivities (adjoint system and the transposed matrix); the chapter number was not checked
- Andreas Griewank and Andrea Walther, Evaluating Derivatives, Principles and Techniques of Algorithmic Differentiation, second edition, SIAM, 2008, the reverse mode and its cost bound (a gradient for a small multiple of the cost of the function), of which the adjoint method is the linear-solve case
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag XP8WTV Edit this page History Report an error Markdown