Algorithm Search⌘K

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
Properties
deterministicexactiterative
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 p1,…,pPp_1, \ldots, p_P (resistances, conductances, gains of controlled sources, values of independent sources), its MNA system M(p) x=z(p)M(p)\, x = z(p) with MM nonsingular, and an output φ=cTx\varphi = c^{\mathsf T} x, compute φ\varphi and the gradient ∂φ/∂pk\partial \varphi / \partial p_k for every kk. For several outputs c1,…,cKc_1, \ldots, c_K, compute the KK gradients. The same problem arises at a DC operating point of a nonlinear circuit, with MM the Jacobian there, and at each time step of a transient analysis with companion models.

The algorithm

Differentiate Mx=zM x = z: M ∂x/∂pk=∂z/∂pk−(∂M/∂pk) xM\, \partial x / \partial p_k = \partial z / \partial p_k - (\partial M / \partial p_k)\, x. The direct method solves this for every kk, PP solves. The adjoint method moves the inverse onto the output instead:

∂φ∂pk=cTM−1(∂z∂pk−∂M∂pkx)=λT(∂z∂pk−∂M∂pkx),MTλ=c.\frac{\partial \varphi}{\partial p_k} = c^{\mathsf T} M^{-1}\Big(\frac{\partial z}{\partial p_k} - \frac{\partial M}{\partial p_k} x\Big) = \lambda^{\mathsf T}\Big(\frac{\partial z}{\partial p_k} - \frac{\partial M}{\partial p_k} x\Big), \qquad M^{\mathsf T} \lambda = c.
  1. ADJOINT-SENSITIVITY(netlist, c)
  2. 1(M, z) ← the MNA stamps of netlist
  3. 2LU ← FACTOR(M)
  4. 3x ← SOLVE(LU, z)
  5. 4λ ← SOLVE-TRANSPOSED(LU, c) ▷ Mᵀ λ = c: the adjoint circuit
  6. 5φ ← cᵀ x
  7. 6for each element k with parameter p_k do
  8. 7s_k ← λᵀ (∂z/∂p_k − (∂M/∂p_k) x) ▷ at most four entries, by the table below
  9. 8return φ, (s_1, ..., s_P)

Each element touches at most four entries of MM and two of zz, so line L7 is a short formula. Write xa−xbx_a - x_b for the difference of node voltages, with x0=0x_0 = 0 at ground, and the same for λ\lambda:

element (as on the MNA page) parameter ∂φ/∂p\partial \varphi / \partial p
conductance GG from pp to qq GG −(λp−λq)(xp−xq)-(\lambda_p - \lambda_q)(x_p - x_q)
resistor RR from pp to qq RR (λp−λq)(xp−xq)/R2(\lambda_p - \lambda_q)(x_p - x_q) / R^2
current source ss from pp to qq ss −(λp−λq)-(\lambda_p - \lambda_q)
voltage source ss with current row mm ss λm\lambda_m
VCCS g(ec−ed)g(e_c - e_d) from pp to qq gg −(λp−λq)(xc−xd)-(\lambda_p - \lambda_q)(x_c - x_d)

The adjoint network. The stamps of resistors, conductances and voltage sources are symmetric, and the transpose of the stamp of a VCCS from pp to qq controlled by ec−ede_c - e_d is the stamp of a VCCS from cc to dd controlled by ep−eqe_p - e_q, with the same gain. So MTM^{\mathsf T} 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 cc is its excitation: for φ=ek\varphi = e_k, a 1 A source driving current into node kk; for φ\varphi the current of a voltage source, a 1 V value of that source. The vector λ\lambda 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, R1=2 ΩR_1 = 2\ \Omega from node 1 to node 2, R2=3 ΩR_2 = 3\ \Omega from node 2 to ground, and a 1 A source into node 2, with output φ=e2\varphi = e_2. Its MNA system has

M=(1/2−1/21−1/25/60100),z=(016),x=(624/5−3/5).M = \begin{pmatrix} 1/2 & -1/2 & 1 \\ -1/2 & 5/6 & 0 \\ 1 & 0 & 0 \end{pmatrix}, \quad z = \begin{pmatrix} 0 \\ 1 \\ 6 \end{pmatrix}, \quad x = \begin{pmatrix} 6 \\ 24/5 \\ -3/5 \end{pmatrix}.

MM is symmetric. Solve MTλ=(0,1,0)M^{\mathsf T} \lambda = (0, 1, 0): the last row gives λ1=0\lambda_1 = 0, the second 56λ2=1\tfrac56 \lambda_2 = 1, so λ2=6/5\lambda_2 = 6/5, and the first gives λ3=12λ2=3/5\lambda_3 = \tfrac12 \lambda_2 = 3/5. 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 2 Ω∥3 Ω=6/5 Ω2\ \Omega \parallel 3\ \Omega = 6/5\ \Omega. The table then gives

  • the source EE: λ3=3/5\lambda_3 = 3/5;
  • R1R_1: (λ1−λ2)(x1−x2)/R12=(−6/5)(6/5)/4=−9/25(\lambda_1 - \lambda_2)(x_1 - x_2)/R_1^2 = (-6/5)(6/5)/4 = -9/25;
  • R2R_2: λ2x2/R22=(6/5)(24/5)/9=16/25\lambda_2 x_2 / R_2^2 = (6/5)(24/5)/9 = 16/25;
  • the 1 A source, from ground into node 2: −(λ0−λ2)=6/5-(\lambda_0 - \lambda_2) = 6/5.

By hand, e2=R2(E+R1I)/(R1+R2)e_2 = R_2 (E + R_1 I)/(R_1 + R_2), whose partial derivatives are R2/(R1+R2)=3/5R_2/(R_1 + R_2) = 3/5, R2(IR2−E)/(R1+R2)2=−9/25R_2(I R_2 - E)/(R_1 + R_2)^2 = -9/25, R1(E+R1I)/(R1+R2)2=16/25R_1(E + R_1 I)/(R_1 + R_2)^2 = 16/25 and R1R2/(R1+R2)=6/5R_1 R_2/(R_1 + R_2) = 6/5. One transposed solve gave all four.

Correctness

The identity behind line L7 is exact: from Mx=zM x = z and MTλ=cM^{\mathsf T} \lambda = c, ∂φ/∂pk=cT∂x/∂pk=λTM ∂x/∂pk=λT(∂z/∂pk−(∂M/∂pk)x)\partial \varphi / \partial p_k = c^{\mathsf T} \partial x / \partial p_k = \lambda^{\mathsf T} M\, \partial x / \partial p_k = \lambda^{\mathsf T}(\partial z / \partial p_k - (\partial M / \partial p_k) x), where xx is differentiable in pp because MM is nonsingular and its entries are smooth in pp. 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 ∑b(δvb ı^b−v^b δib)=0\sum_b (\delta v_b\, \hat\imath_b - \hat v_b\, \delta i_b) = 0, 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 MTM^{\mathsf T} 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 0,…,n0, \ldots, n with ground 00, and let its modified nodal analysis system be M(p) x=z(p)M(p)\, x = z(p), where x=(e1,…,en,j1,…,jm)x = (e_1, \ldots, e_n, j_1, \ldots, j_m) and p=(p1,…,pP)p = (p_1, \ldots, p_P) are the parameters of the elements. The stamps are those of the MNA page: a conductance GG from aa to bb adds GG at (a,a)(a, a) and (b,b)(b, b) and −G-G at (a,b)(a, b) and (b,a)(b, a); a current source ss from aa to bb adds −s-s to zaz_a and ss to zbz_b; a voltage source with current row rr adds 11 at (a,r)(a, r) and (r,a)(r, a), −1-1 at (b,r)(b, r) and (r,b)(r, b), and ss to zrz_r; a VCCS of gain gg from aa to bb controlled by ec−ede_c - e_d adds gg at (a,c)(a, c) and (b,d)(b, d) and −g-g at (a,d)(a, d) and (b,c)(b, c). Entries in a row or column of ground are dropped, and x0=λ0=0x_0 = \lambda_0 = 0. Let φ=cTx\varphi = c^{\mathsf T} x be an output.

Lemma 1 (differentiability). If M(p0)M(p_0) is nonsingular, then on a neighbourhood of p0p_0 the solution x(p)=M(p)−1z(p)x(p) = M(p)^{-1} z(p) is continuously differentiable, and

M ∂x∂pk=∂z∂pk−∂M∂pk x.M\, \frac{\partial x}{\partial p_k} = \frac{\partial z}{\partial p_k} - \frac{\partial M}{\partial p_k}\, x.

Proof. Every entry of MM and zz is a polynomial in a conductance, a gain or a source value, or 1/R1/R for a resistance R>0R > 0, so it is continuously differentiable in pp. The determinant is continuous, so M(p)M(p) stays nonsingular near p0p_0, and the entries of M−1M^{-1} are rational functions of the entries of MM with nonzero denominator det⁡M\det M (Cramer's rule). So xx is continuously differentiable. Differentiating the identity M(p) x(p)=z(p)M(p)\, x(p) = z(p) with the product rule gives the displayed equation. □\square

Theorem 1 (the adjoint identity). Let λ\lambda solve MTλ=cM^{\mathsf T} \lambda = c. Then for every parameter pkp_k,

∂φ∂pk=λT(∂z∂pk−∂M∂pk x).\frac{\partial \varphi}{\partial p_k} = \lambda^{\mathsf T}\Big(\frac{\partial z}{\partial p_k} - \frac{\partial M}{\partial p_k}\, x\Big).

So one solve with MTM^{\mathsf T} for each output gives the derivative with respect to all parameters.

Proof. ∂φ/∂pk=cT∂x/∂pk=(MTλ)T∂x/∂pk=λTM ∂x/∂pk\partial \varphi / \partial p_k = c^{\mathsf T} \partial x / \partial p_k = (M^{\mathsf T} \lambda)^{\mathsf T} \partial x / \partial p_k = \lambda^{\mathsf T} M\, \partial x / \partial p_k, and Lemma 1 replaces M ∂x/∂pkM\, \partial x / \partial p_k. The vector λ\lambda does not depend on kk. □\square

Lemma 2 (the table). With x0=λ0=0x_0 = \lambda_0 = 0, Theorem 1 gives:

  1. conductance GG from aa to bb: ∂φ/∂G=−(λa−λb)(xa−xb)\partial \varphi / \partial G = -(\lambda_a - \lambda_b)(x_a - x_b);
  2. resistor RR from aa to bb: ∂φ/∂R=(λa−λb)(xa−xb)/R2\partial \varphi / \partial R = (\lambda_a - \lambda_b)(x_a - x_b)/R^2;
  3. current source ss from aa to bb: ∂φ/∂s=−(λa−λb)\partial \varphi / \partial s = -(\lambda_a - \lambda_b);
  4. voltage source ss with current row rr: ∂φ/∂s=λr\partial \varphi / \partial s = \lambda_r;
  5. VCCS of gain gg from aa to bb controlled by ec−ede_c - e_d: ∂φ/∂g=−(λa−λb)(xc−xd)\partial \varphi / \partial g = -(\lambda_a - \lambda_b)(x_c - x_d).

Proof. (1) ∂z/∂G=0\partial z / \partial G = 0, and ∂M/∂G\partial M / \partial G is the stamp with GG replaced by 11. So (∂M/∂G) x(\partial M / \partial G)\, x has xa−xbx_a - x_b in row aa and −(xa−xb)-(x_a - x_b) in row bb, and λT\lambda^{\mathsf T} of it is (λa−λb)(xa−xb)(\lambda_a - \lambda_b)(x_a - x_b); dropping a ground row or column agrees with x0=λ0=0x_0 = \lambda_0 = 0. (2) G=1/RG = 1/R and dG/dR=−1/R2dG/dR = -1/R^2, so the chain rule applied to (1) gives the formula. (3) ∂M/∂s=0\partial M / \partial s = 0 and ∂z/∂s\partial z / \partial s has −1-1 in row aa and 11 in row bb, so the product is −λa+λb-\lambda_a + \lambda_b. (4) ∂M/∂s=0\partial M / \partial s = 0 and ∂z/∂s\partial z / \partial s is the unit vector of row rr. (5) ∂z/∂g=0\partial z / \partial g = 0, and (∂M/∂g) x(\partial M / \partial g)\, x has xc−xdx_c - x_d in row aa and −(xc−xd)-(x_c - x_d) in row bb, so λT\lambda^{\mathsf T} of it is (λa−λb)(xc−xd)(\lambda_a - \lambda_b)(x_c - x_d). □\square

Lemma 3 (the adjoint network). MTM^{\mathsf T} is the MNA matrix of the adjoint network, the same netlist with every independent source set to zero and every VCCS from aa to bb controlled by ec−ede_c - e_d replaced by a VCCS of the same gain from cc to dd controlled by ea−ebe_a - e_b. The right side cc is the excitation of that network by independent sources: c=ukc = u_k (the unit vector of node kk) is a current source of 1 A from ground into node kk, and c=urc = u_r for the current row rr of a voltage source is the value 1 V of that source.

Proof. MM 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 gg at (a,c)(a, c) and (b,d)(b, d) and −g-g at (a,d)(a, d) and (b,c)(b, c); its transpose has gg at (c,a)(c, a) and (d,b)(d, b) and −g-g at (d,a)(d, a) and (c,b)(c, b), which is the stamp of a VCCS from cc to dd controlled by ea−ebe_a - e_b. Independent sources do not enter MM. A current source of 1 A from ground to node kk adds 11 to row kk of the right side, and a voltage source of value 1 V adds 11 to its own row. □\square

Theorem 2 (Tellegen form). Let (v,i)(v, i) be the branch voltages and currents of the original circuit, (v^,ı^)(\hat v, \hat\imath) those of the adjoint network of Lemma 3 written as a circuit on the same graph, and let a parameter change from pkp_k to pk+δpkp_k + \delta p_k change the original solution by (δv,δi)(\delta v, \delta i). Then

∑b(δvb ı^b−v^b δib)=0.\sum_b \big(\delta v_b\, \hat\imath_b - \hat v_b\, \delta i_b\big) = 0.

Proof. The perturbed circuit and the original circuit have the same graph, so δv\delta v satisfies Kirchhoff's voltage law and δi\delta i satisfies Kirchhoff's current law, because both laws are linear. The adjoint network has the same graph as well, so v^\hat v satisfies KVL and ı^\hat\imath satisfies KCL. Tellegen's theorem, which needs only KCL for one vector and KVL for the other on the same graph, gives ∑bδvb ı^b=0\sum_b \delta v_b\, \hat\imath_b = 0 and ∑bv^b δib=0\sum_b \hat v_b\, \delta i_b = 0. Subtracting gives the claim. □\square

The terms of this sum for an element that was not changed vanish by the choice of the adjoint element. For a resistor with i=Gvi = G v and adjoint ı^=Gv^\hat\imath = G \hat v, the term is δv Gv^−v^ Gδv=0\delta v\, G \hat v - \hat v\, G \delta v = 0. For a changed conductance, δi=Gδv+δG v\delta i = G \delta v + \delta G\, v to first order, so its term is −v^ v δG-\hat v\, v\, \delta G, which is the first row of Lemma 2 with v^=λa−λb\hat v = \lambda_a - \lambda_b and v=xa−xbv = x_a - x_b. 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 N=n+mN = n + m unknowns, PP parameters and KK outputs, the algorithm uses one LU factorization of MM, one solve for xx and KK solves with MTM^{\mathsf T}, and O(1)O(1) further operations per parameter and output.

Proof. Lines L2 and L3 run once. For each output, line L4 runs once. If PrM=LUP_r M = L U with a permutation PrP_r, then MT=UTLTPrM^{\mathsf T} = U^{\mathsf T} L^{\mathsf T} P_r, so MTλ=cM^{\mathsf T} \lambda = c is solved by a forward substitution with the lower triangular UTU^{\mathsf T}, a back substitution with the upper triangular LTL^{\mathsf T}, and the permutation PrTP_r^{\mathsf T}, with no new factorization. Each row of Lemma 2 reads at most four entries of xx and λ\lambda and does a fixed number of arithmetic operations. □\square

Theorem 4 (correctness of the algorithm). If MM is nonsingular, ADJOINT-SENSITIVITY returns φ=cTx\varphi = c^{\mathsf T} x and, for every element kk, sk=∂φ/∂pks_k = \partial \varphi / \partial p_k. If MM is singular, the factorization of line L2 fails and the code reports it.

Proof. Lines L1 to L3 compute the solution xx 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 λ\lambda with MTλ=cM^{\mathsf T} \lambda = c by Theorem 3. Line L5 is the definition of φ\varphi. Line L7 evaluates the formula of Lemma 2 for the kind of element kk, which equals ∂φ/∂pk\partial \varphi / \partial p_k by Theorem 1. If MM is singular, Gaussian elimination with partial pivoting meets a column with no nonzero pivot candidate, and the factorization raises the error. ■\blacksquare

Complexity

With dense LU, line L2 costs Θ(N3)\Theta(N^3) and each of lines L3 and L4 costs Θ(N2)\Theta(N^2); lines L6 and L7 cost O(1)O(1) per parameter, O(P)O(P) in all. For KK outputs the total is O(N3+K(N2+P))O(N^3 + K(N^2 + P)), against O(N3+P(N2+K))O(N^3 + P(N^2 + K)) 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, O(N2)O(N^2) dense, and the gradient, O(P)O(P). The code of this page counts the operations, and its tests check that KK outputs use one factorization, one forward solve and KK 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 PP derivatives of one output is one transposed solve plus O(P)O(P), whatever PP is.
  • Reuses the factors. MT=UTLTPrM^{\mathsf T} = U^{\mathsf T} L^{\mathsf T} P_r for PrM=LUP_r M = L U, 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 MM and the partial derivatives of the device equations in place of ∂M/∂p\partial M/\partial p and ∂z/∂p\partial z/\partial p; the identity is the implicit function theorem.
  • AC sensitivity. In small-signal AC analysis the matrix is complex, M=G+jωCM = G + j\omega C; the adjoint uses MTM^{\mathsf T}, 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 MM is not symmetric, and solving with MM instead of MTM^{\mathsf T} 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 cc 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 RR is −1/R2-1/R^2 times the derivative with respect to G=1/RG = 1/R; 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, MM 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.

adjoint_sensitivity_analysis.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example