Algorithm Search⌘K

Techniqueintro

Modified nodal analysis

Also called MNA, MNA stamps.

Write a circuit as linear equations in the node voltages plus the currents of voltage sources and inductors, each element adding a fixed stamp to the matrix.

Modified nodal analysis (MNA) writes a lumped circuit as a square linear system Mx=zMx = z whose unknowns are the voltages of the nodes other than ground plus the currents of the elements whose current is not a function of node voltages, mainly voltage sources and inductors. Each element adds a small fixed pattern of entries, its stamp, to MM and zz, so a simulator builds the system in one pass over the netlist. MNA belongs to the circuit simulation half of the logic and circuit simulation sub-area. Ho, Ruehli and Brennan introduced it in 1975, and SPICE and almost every later circuit simulator use it as the base of DC, transient and AC analysis.

In plain words

A circuit simulator needs equations it can hand to a linear solver. Modified nodal analysis gets them from one rule: at each connection point, the current that flows in must flow out.

Give each connection point a voltage, measured against a chosen ground point. A resistor's current then follows from the two voltages at its ends. A current source's current is known. A voltage source is the odd one out: its current can be anything, so the method adds that current as one more unknown and adds one more equation, which fixes the voltage difference across the source.

Each part writes its own few numbers into the matrix at the rows and columns of the points it touches. Add the contributions of all parts, solve once, and you have every voltage and every source current.

When it applies

MNA applies to any lumped circuit, that is, any circuit that obeys Kirchhoff's laws. It gives a linear system when every element law is linear. The other analyses reduce to that case:

  • Nonlinear DC. Each Newton iteration of DC operating point analysis replaces a nonlinear device by its linearization, a conductance in parallel with a current source, and solves one MNA system.
  • Transient. Each time step replaces a capacitor or inductor by its companion model and solves one MNA system, or one Newton sequence of them, in transient circuit analysis.
  • AC. In small-signal AC analysis a capacitor is the complex admittance jωCj\omega C, and the system is complex.

The technique needs a ground node. The system is square and nonsingular for the circuits described in the theorem below; the Pitfalls section lists what breaks it.

The template

Notation. The nodes are 0,1,…,n0, 1, \ldots, n, with node 0 as ground. Element currents follow the associated reference direction of the circuit laws page: a current is counted from the first node of an element, through the element, to its second node. The unknown vector is x=(e1,…,en,j1,…,jm)x = (e_1, \ldots, e_n, j_1, \ldots, j_m): node voltages first, then one current for each element that needs one. Row k≤nk \le n of Mx=zMx = z is KCL at node kk: the currents that leave node kk through the elements sum to zero, with the known source currents moved to the right side. Row n+rn + r is the law of the rr-th element with a current unknown.

  1. MNA(netlist, n)
  2. 1m ← the number of elements of netlist that need a current unknown
  3. 2M ← (n + m) × (n + m) zero matrix; z ← zero vector of length n + m
  4. 3r ← 0
  5. 4for each element el of netlist do
  6. 5if el needs a current unknown then r ← r + 1; give el the index n + r
  7. 6ADD-STAMP(M, z, el) ▷ add the entries of el; skip every entry in row 0 or column 0
  8. 7x ← SOLVE(M, z) ▷ report "singular" if M has no inverse
  9. 8return e_k = x_k for k = 1, ..., n (e_0 = 0), and the currents x_(n+1), ..., x_(n+m)

The holes are ADD-STAMP, which holds the element laws, and SOLVE, which is Gaussian elimination with partial pivoting for small dense systems and sparse LU with a fill-reducing order, such as Markowitz pivoting or the KLU solver, in a production simulator. Line L6 drops the entries of ground because e0=0e_0 = 0 is known and the KCL row of ground is the negative sum of the other KCL rows.

The stamps. For an element between nodes pp and qq (pp is the first node):

Element Entries of MM Entries of zz
conductance GG (resistor 1/G1/G) +G+G at (p,p)(p,p) and (q,q)(q,q); −G-G at (p,q)(p,q) and (q,p)(q,p) none
current source ss, from pp through it to qq none −s-s at pp; +s+s at qq
voltage source ep−eq=se_p - e_q = s, current jj at index kk +1+1 at (p,k)(p,k) and (k,p)(k,p); −1-1 at (q,k)(q,k) and (k,q)(k,q) ss at kk
voltage-controlled current source, current g(ec−ed)g(e_c - e_d) from pp to qq +g+g at (p,c)(p,c) and (q,d)(q,d); −g-g at (p,d)(p,d) and (q,c)(q,c) none
inductor LL at DC, current jj at index kk as a voltage source with s=0s = 0 none

A capacitor is an open circuit at DC and stamps nothing. In a transient step its companion model stamps a conductance and a current source.

Why the stamps are right. Row k≤nk \le n must say ∑(currents leaving node k)=0\sum (\text{currents leaving node } k) = 0. A conductance from pp to qq carries G(ep−eq)G(e_p - e_q) out of pp and the same amount into qq, that is −G(ep−eq)=G(eq−ep)-G(e_p - e_q) = G(e_q - e_p) out of qq: this is the entries +G,−G+G, -G in row pp and −G,+G-G, +G in row qq. A current source moves the known current ss out of pp and into qq; moved to the right side, this is −s-s in row pp and +s+s in row qq. The current jj of a voltage source leaves pp and enters qq, which is the column entries +1+1 in row pp and −1-1 in row qq; its own row is ep−eq=se_p - e_q = s. A controlled source carries g(ec−ed)g(e_c - e_d) out of pp and into qq, which gives the four entries. Every unknown voltage is a node voltage, so every branch voltage is a difference of node voltages and KVL holds by construction. Summing the contributions of all elements gives exactly KCL at every node plus one law for each current unknown, and nothing else, so a vector xx solves Mx=zMx = z if and only if the node voltages and the source currents it describes satisfy KCL, KVL and all element laws.

Block form. Order the branches as resistors (conductances G=diag⁡(g1,…)G = \operatorname{diag}(g_1, \ldots), all g>0g > 0), voltage sources and current sources, and split the reduced incidence matrix AA of the circuit laws page into ARA_R, AVA_V and AIA_I. Then

M=(ARGARTAVAVT0),z=(−AI sIsV).M = \begin{pmatrix} A_R G A_R^{\mathsf T} & A_V \\ A_V^{\mathsf T} & 0 \end{pmatrix}, \qquad z = \begin{pmatrix} -A_I\, s_I \\ s_V \end{pmatrix}.

The block ARGARTA_R G A_R^{\mathsf T} is the weighted Laplacian matrix of the resistor graph with the row and column of ground removed.

Theorem (when MNA is nonsingular). For a circuit of positive resistors, independent voltage sources and independent current sources, MM is nonsingular if and only if both of these hold:

  1. the voltage sources contain no loop (no cycle, no two sources in parallel and no source with both ends on one node), that is, the columns of AVA_V are independent;
  2. the resistors and the voltage sources together connect every node to ground, that is, there is no cut set made of current sources only and no floating node, which is the same as the rows of (AR  AV)(A_R \; A_V) being independent.

Lemma. Let ASA_S be the submatrix of AA made of the columns of a set SS of branches. The columns of ASA_S are independent if and only if SS has no cycle, and the rows of ASA_S are independent if and only if SS connects every node to ground. Proof. If SS has a cycle, add its columns with sign +1+1 for branches traversed along their direction and −1-1 against: each node of the cycle is entered once and left once, so the sum is zero. If SS is a forest, every tree of SS with at least one branch has at least two leaves, so some leaf kk is not ground; among the columns of SS, row kk has one nonzero, so a zero combination gives that column the coefficient 0; remove the leaf and repeat. For the rows: if SS connects every node to ground, it contains a spanning tree, whose nn columns are independent by the first part, so the rank is nn. If not, let CC be the set of nodes of a component of SS that does not contain ground, and let xx be its indicator vector. Each branch of SS has both ends in CC or both outside, so (ATx)j=xp−xq=0(A^{\mathsf T} x)_j = x_p - x_q = 0 (with x0=0x_0 = 0) on the columns of SS, and x≠0x \ne 0. □\square

Proof of the theorem. Assume 1 and 2, and let M(x,y)=0M (x, y) = 0, that is, ARGARTx+AVy=0A_R G A_R^{\mathsf T} x + A_V y = 0 and AVTx=0A_V^{\mathsf T} x = 0. Multiply the first equation by xTx^{\mathsf T} and use the second:

0=xTARGARTx+(AVTx)Ty=∑rgr((ARTx)r)2.0 = x^{\mathsf T} A_R G A_R^{\mathsf T} x + (A_V^{\mathsf T} x)^{\mathsf T} y = \sum_{r} g_r \big((A_R^{\mathsf T} x)_r\big)^2.

All gr>0g_r > 0, so ARTx=0A_R^{\mathsf T} x = 0. With AVTx=0A_V^{\mathsf T} x = 0 this says (AR  AV)Tx=0(A_R \; A_V)^{\mathsf T} x = 0, so x=0x = 0 by condition 2. Then the first equation gives AVy=0A_V y = 0, so y=0y = 0 by condition 1. The kernel is zero, and MM is nonsingular.

Conversely, if condition 1 fails, the lemma gives y≠0y \ne 0 with AVy=0A_V y = 0, and M(0,y)=(AVy,0)=0M(0, y) = (A_V y, 0) = 0: a current can circulate around the loop of sources. If condition 2 fails, the lemma gives x≠0x \ne 0 with ARTx=0A_R^{\mathsf T} x = 0 and AVTx=0A_V^{\mathsf T} x = 0, and M(x,0)=(ARGARTx,AVTx)=0M(x, 0) = (A_R G A_R^{\mathsf T} x, A_V^{\mathsf T} x) = 0: the voltage of the cut-off part can shift by any constant. In both cases MM is singular. ■\blacksquare

The same argument with a monotone nonlinearity in place of GG is the uniqueness result of Tellegen's theorem. With controlled sources or negative resistances the graph conditions are neither necessary nor sufficient: a resistor of 1 Ω1\ \Omega in parallel with one of −1 Ω-1\ \Omega gives a zero conductance and a singular MM, and a controlled source that draws gekg e_k out of node kk acts as a conductance and can make a node with no resistor nonsingular.

Worked example. Node 1 has a 6 V source to ground, a 2 Ω2\ \Omega resistor joins nodes 1 and 2, a 3 Ω3\ \Omega resistor joins node 2 to ground, and a 1 A source drives current from ground into node 2. With x=(e1,e2,j)x = (e_1, e_2, j):

(1/2−1/21−1/25/60100)(e1e2j)=(016).\begin{pmatrix} 1/2 & -1/2 & 1 \\ -1/2 & 5/6 & 0 \\ 1 & 0 & 0 \end{pmatrix} \begin{pmatrix} e_1 \\ e_2 \\ j \end{pmatrix} = \begin{pmatrix} 0 \\ 1 \\ 6 \end{pmatrix}.

Row 3 gives e1=6e_1 = 6. Row 2 gives −3+56e2=1-3 + \tfrac{5}{6} e_2 = 1, so e2=24/5e_2 = 24/5. Row 1 gives 3−125+j=03 - \tfrac{12}{5} + j = 0, so j=−3/5j = -3/5: the current of the source from its plus node through it to ground is −3/5-3/5 A, so the source delivers 3/53/5 A to the circuit. The conditions of the theorem hold: one source, no loop, and the resistors and the source connect both nodes to ground. A second source between node 1 and ground, or deleting the 2 Ω2\ \Omega and 3 Ω3\ \Omega resistors so that node 2 meets only the current source, makes MM singular, and the code reports it.

Cost. Let the netlist have EE elements and let N=n+mN = n + m. Lines L1 to L6 take Θ(E)\Theta(E) time, and each element of the table adds at most 4 entries to MM, so MM has at most 4E4E nonzeros before summing. Line L7 with dense elimination takes Θ(N3)\Theta(N^3) time and Θ(N2)\Theta(N^2) space. With sparse LU the cost depends on the fill-in that the pivot order creates, and no bound below the dense one holds for every circuit graph. Small fill on real circuit matrices is a measured property, not a theorem. The code of this page uses a dense exact solver over fractions, so it detects singularity exactly.

Classic examples

Variations

  • Nodal analysis. Without voltage sources and inductors, m=0m = 0 and M=ARGARTM = A_R G A_R^{\mathsf T}, the grounded Laplacian. It is symmetric, and positive definite exactly when the resistors connect every node to ground, so Cholesky decomposition or the conjugate gradient method applies. A voltage source with a series resistor can be replaced by a current source with a parallel conductance (a Norton equivalent) to stay in this form.
  • More stamps. A voltage-controlled voltage source ep−eq=μ(ec−ed)e_p - e_q = \mu (e_c - e_d) has a current unknown jj at index kk, the entries +1+1 at (p,k)(p,k) and (k,p)(k,p), −1-1 at (q,k)(q,k) and (k,q)(k,q), −μ-\mu at (k,c)(k,c) and +μ+\mu at (k,d)(k,d). Current-controlled sources use the current unknown of the branch that controls them. An inductor in a transient step has the row ep−eq−L dj/dt=0e_p - e_q - L\, dj/dt = 0, discretized by the companion model.
  • Dynamic form. With capacitors and inductors, MNA gives Gx+Cx˙=u(t)G x + C \dot x = u(t), or f(x)+ddtq(x)=u(t)f(x) + \frac{d}{dt} q(x) = u(t) for nonlinear devices with charges qq. This is a system of differential-algebraic equations, because CC is singular in general; its index is 1 or 2 for the usual elements.
  • Sparse tableau analysis. Sparse tableau analysis keeps all branch voltages and branch currents as unknowns. Its system is larger and sparser, and MNA is what remains after the branch unknowns of the voltage-defined elements are eliminated.
  • Reduced MNA. A voltage source to ground fixes its node voltage, so the node and the current unknown can be removed before the solve, and a symmetric conductance block remains. Simulators do this to keep the matrix small and to avoid the zero diagonal.

Pitfalls

  • A zero diagonal. The row of a voltage source has a zero on the diagonal, so elimination in the natural order fails even when MM is nonsingular. Use pivoting, or order each source current next to a node of the source.
  • Loops of voltage sources and cut sets of current sources. The theorem shows that they make MM singular. At DC an inductor is a zero-volt source, so a loop of inductors and voltage sources is singular. A capacitor is an open circuit, so a node that meets only capacitors and current sources floats. SPICE adds a tiny conductance gmin from such nodes to ground, see gmin stepping, and many simulators check the topology first and report the faulty node.
  • Sign conventions. A current source "from pp to qq" means the current flows through the source from pp to qq, so it leaves the circuit at pp and enters at qq. Mixing this with the opposite convention flips all the source currents in the answer. The current unknown of a voltage source is negative when the source delivers power.
  • Bad scaling. Conductances of 10−1210^{-12} next to 10310^{3} and rows of ±1\pm 1 next to rows of conductances make MM badly scaled, and partial pivoting on the raw matrix can pick poor pivots. Simulators scale rows or use threshold pivoting.
  • Floating subcircuits that are not errors. A transformer winding or an isolated logic block that has no DC path to ground is a valid design, but its MNA matrix at DC is singular. The usual fix is a large resistor to ground from one node of each floating part.
  • Asymmetry. MM is symmetric for resistors and independent sources, but controlled sources and linearized transistors make it nonsymmetric, so solvers for symmetric matrices do not apply in general.

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.

densela.pyI0RawGitHub
# 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]
modified_nodal_analysis.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modified-nodal-analysis/. The authors are listed in prov/CCJ8NY.jsonl.
"""Modified nodal 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:

- ("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. Its 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.

Values are Fraction (exact) or float. The unknowns are e_1, ..., e_n and then
one current for each voltage source, in netlist order. Row k of the system,
for k <= n, is Kirchhoff's current law at node k: the currents that leave node
k through the elements sum to zero, with the known source currents moved to the
right-hand side.
"""

from densela import SingularMatrixError, lu_factor, lu_solve

__all__ = ["SingularMatrixError", "stamp_mna", "solve_mna"]


def _add(a, i, j, v):
    # Row or column 0 is ground: its equation and its voltage are dropped.
    if i > 0 and j > 0:
        a[i - 1][j - 1] += v


def stamp_mna(netlist, n):
    """Return (A, b, names) of the MNA system A x = b."""
    nv = sum(1 for el in netlist if el[0] == "V")  # @line L1
    size = n + nv
    a = [[0] * size for _ in range(size)]  # @line L2
    b = [0] * size
    names = [f"e{k}" for k in range(1, n + 1)]
    m = n  # @line L3: index of the next source-current unknown, 0-based
    for el in netlist:  # @line L4
        kind = el[0]
        nodes = el[1:-1]
        for node in nodes:
            if not 0 <= node <= n:
                raise ValueError(f"node {node} is out of range in {el}")
        if kind in ("R", "G"):  # @line L6: the stamps follow, one branch for each kind
            _, p, q, value = el
            g = 1 / value if kind == "R" else value
            _add(a, p, p, g)
            _add(a, q, q, g)
            _add(a, p, q, -g)
            _add(a, q, p, -g)
        elif kind == "I":
            _, p, q, s = el
            if p > 0:
                b[p - 1] -= s
            if q > 0:
                b[q - 1] += s
        elif kind == "V":
            _, p, q, s = el
            row = m  # @line L5
            names.append(f"j{len(names) - n}")
            if p > 0:
                a[p - 1][row] += 1
                a[row][p - 1] += 1
            if q > 0:
                a[q - 1][row] -= 1
                a[row][q - 1] -= 1
            b[row] += s
            m += 1
        elif kind == "VCCS":
            _, p, q, c, d, g = el
            _add(a, p, c, g)
            _add(a, p, d, -g)
            _add(a, q, c, -g)
            _add(a, q, d, g)
        else:
            raise ValueError(f"unknown element {kind!r}")
    return a, b, names


def solve_mna(netlist, n, tol=0):
    """Solve the circuit.

    Return (e, j): e[k] is the voltage of node k with e[0] = 0, and j[i] is the
    current of the i-th voltage source. Raise SingularMatrixError when the MNA
    matrix is singular, for example with a loop of voltage sources or a cut set
    of current sources.
    """
    a, b, _ = stamp_mna(netlist, n)
    if not a:
        return [0], []
    x = lu_solve(lu_factor(a, tol), b)  # @line L7
    return [0] + x[:n], x[n:]  # @line L8
test_modified_nodal_analysis.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modified-nodal-analysis/. The authors are listed in prov/CCJ8NY.jsonl.

import random
from fractions import Fraction as F

import pytest

from modified_nodal_analysis import SingularMatrixError, solve_mna, stamp_mna


def branch_currents(netlist, e, j):
    """Current of each element from its first node to its second node, from the element laws alone."""
    out = []
    k = 0
    for el in netlist:
        kind = el[0]
        if kind == "R":
            out.append((el[1], el[2], (e[el[1]] - e[el[2]]) / el[3]))
        elif kind == "G":
            out.append((el[1], el[2], el[3] * (e[el[1]] - e[el[2]])))
        elif kind == "I":
            out.append((el[1], el[2], el[3]))
        elif kind == "V":
            out.append((el[1], el[2], j[k]))
            k += 1
        elif kind == "VCCS":
            _, p, q, c, d, g = el
            out.append((p, q, g * (e[c] - e[d])))
    return out


def assert_solution(netlist, n, e, j):
    """Check KCL at every node and the law of every voltage source, exactly."""
    leaving = [0] * (n + 1)
    for p, q, cur in branch_currents(netlist, e, j):
        leaving[p] += cur
        leaving[q] -= cur
    assert all(x == 0 for x in leaving[1:]), leaving
    assert sum(leaving) == 0
    for el in netlist:
        if el[0] == "V":
            assert e[el[1]] - e[el[2]] == el[3]


class DSU:
    def __init__(self, n):
        self.parent = list(range(n))

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, x, y):
        rx, ry = self.find(x), self.find(y)
        if rx == ry:
            return False
        self.parent[rx] = ry
        return True


def graph_says_nonsingular(netlist, n):
    """The theorem of the page for circuits of positive resistors and independent sources."""
    dsu = DSU(n + 1)
    for el in netlist:
        if el[0] == "V" and not dsu.union(el[1], el[2]):
            return False  # a loop of voltage sources
    for el in netlist:
        if el[0] in ("R", "G"):
            dsu.union(el[1], el[2])
    root = dsu.find(0)
    return all(dsu.find(k) == root for k in range(n + 1))  # else a cut set of current sources


def test_page_example():
    # 6 V source at node 1, 2 ohm from 1 to 2, 3 ohm from 2 to ground, 1 A into node 2.
    net = [("V", 1, 0, F(6)), ("R", 1, 2, F(2)), ("R", 2, 0, F(3)), ("I", 0, 2, F(1))]
    a, b, names = stamp_mna(net, 2)
    assert names == ["e1", "e2", "j0"]
    assert a == [[F(1, 2), F(-1, 2), 1], [F(-1, 2), F(5, 6), 0], [1, 0, 0]]
    assert b == [0, 1, 6]
    e, j = solve_mna(net, 2)
    assert e == [0, 6, F(24, 5)]
    assert j == [F(-3, 5)]
    assert_solution(net, 2, e, j)


def test_divider_and_transconductance():
    e, j = solve_mna([("V", 1, 0, F(10)), ("R", 1, 2, F(1)), ("R", 2, 0, F(4))], 2)
    assert e == [0, 10, 8] and j == [-2]
    # Input 1 V, current 2 e1 drawn from node 2 to ground, load 5 ohm: gain -10.
    net = [("V", 1, 0, F(1)), ("VCCS", 2, 0, 1, 0, F(2)), ("R", 2, 0, F(5))]
    e, j = solve_mna(net, 2)
    assert e == [0, 1, -10] and j == [0]


def test_wheatstone_bridge():
    # 1 A in at node 1, out at ground (node 0); unit resistors except 1-3 = 2 and 2-0 = 2.
    net = [("I", 0, 1, F(1)), ("R", 1, 2, F(1)), ("R", 1, 3, F(2)), ("R", 2, 3, F(1)), ("R", 2, 0, F(2)), ("R", 3, 0, F(1))]
    e, j = solve_mna(net, 3)
    assert e == [0, F(7, 5), F(4, 5), F(3, 5)]
    assert_solution(net, 3, e, j)


@pytest.mark.parametrize(
    "net, n",
    [
        ([("V", 1, 0, F(1)), ("V", 1, 0, F(2)), ("R", 1, 0, F(1))], 1),  # two sources in parallel: a loop
        ([("V", 1, 0, F(1)), ("V", 1, 2, F(1)), ("V", 2, 0, F(1))], 2),  # a loop of three sources
        ([("V", 1, 1, F(1)), ("R", 1, 0, F(1))], 1),  # a source with both ends on one node
        ([("R", 1, 0, F(1)), ("I", 1, 2, F(1))], 2),  # node 2 meets only a current source
        ([("R", 1, 2, F(1)), ("I", 0, 1, F(1))], 2),  # nodes 1 and 2 float together
        ([("R", 1, 0, F(1))], 2),  # node 2 meets nothing, as a node with only capacitors at DC
        ([("R", 1, 0, F(1)), ("R", 1, 0, F(-1)), ("I", 0, 1, F(1))], 1),  # a negative resistor cancels
    ],
)
def test_singular_cases_are_reported(net, n):
    with pytest.raises(SingularMatrixError):
        solve_mna(net, n)


def random_circuit(rng, n, with_vccs):
    net = []
    for _ in range(rng.randint(1, 3 * n + 2)):
        p, q = rng.randint(0, n), rng.randint(0, n)
        r = rng.random()
        if r < 0.55:
            if p != q:
                net.append(("R", p, q, F(rng.randint(1, 9), rng.randint(1, 4))))
        elif r < 0.75:
            net.append(("I", p, q, F(rng.randint(-5, 5))))
        elif r < 0.9 or not with_vccs:
            net.append(("V", p, q, F(rng.randint(-5, 5))))
        else:
            c, d = rng.randint(0, n), rng.randint(0, n)
            net.append(("VCCS", p, q, c, d, F(rng.randint(-3, 3), 2)))
    return net


def test_random_circuits_match_the_graph_theorem():
    rng = random.Random(20250101)
    counts = [0, 0]
    for _ in range(1500):
        n = rng.randint(1, 6)
        net = random_circuit(rng, n, with_vccs=False)
        expected = graph_says_nonsingular(net, n)
        try:
            e, j = solve_mna(net, n)
        except SingularMatrixError:
            assert not expected, net
            counts[0] += 1
            continue
        assert expected, net
        assert_solution(net, n, e, j)
        counts[1] += 1
    assert min(counts) > 200


def test_random_circuits_with_controlled_sources_satisfy_the_laws():
    rng = random.Random(7)
    solved = 0
    for _ in range(800):
        n = rng.randint(1, 5)
        net = random_circuit(rng, n, with_vccs=True)
        try:
            e, j = solve_mna(net, n)
        except SingularMatrixError:
            continue
        assert_solution(net, n, e, j)
        solved += 1
    assert solved > 100


def test_float_agrees_with_fraction():
    rng = random.Random(99)
    checked = 0
    for _ in range(400):
        n = rng.randint(1, 6)
        net = random_circuit(rng, n, with_vccs=False)
        if not graph_says_nonsingular(net, n):
            continue
        e, j = solve_mna(net, n)
        fnet = [tuple(float(x) if isinstance(x, F) else x for x in el) for el in net]
        fe, fj = solve_mna(fnet, n, tol=1e-12)
        for exact, approx in zip(e + j, fe + fj):
            assert abs(float(exact) - approx) <= 1e-9 * (1 + abs(float(exact)))
        checked += 1
    assert checked > 50

Exercises

  1. Write the MNA system of a 1010 V source at node 1, a 1 Ω1\ \Omega resistor from node 1 to node 2 and a 4 Ω4\ \Omega resistor from node 2 to ground, and solve it by hand. (Answer: e=(10,8)e = (10, 8), j=−2j = -2.)
  2. Show that for a circuit of positive resistors and current sources only, MM is symmetric positive definite if and only if the resistors connect every node to ground.
  3. A voltage-controlled current source draws 2e12 e_1 from node 2 to ground, a 1 V source sets e1e_1, and a 5 Ω5\ \Omega resistor joins node 2 to ground. Find the gain e2/e1e_2 / e_1. (Answer: −10-10.)
  4. Prove the VCVS stamp of the Variations section, and give a circuit with one VCVS and positive resistors whose MM is singular although the graph conditions of the theorem hold.
  5. Show that the number of nonzeros of MM is at most 4E4E before summing, and give a circuit where summing makes some of them cancel.

References

  1. Chung-Wen Ho, Albert E. Ruehli and Pierce A. Brennan, The modified nodal approach to network analysis, IEEE Transactions on Circuits and Systems 22(6), 504 to 509, 1975, the formulation with node voltages plus the currents of voltage sources and current-defined branches, and the element stamps
  2. Farid N. Najm, Circuit Simulation, Wiley-IEEE Press, 2010, Chapter 2, Section 2.4.2 (nodal analysis), Section 2.4.3 (unique solvability), Section 2.4.4 (modified nodal analysis) and Section 2.5.1 (dynamic element stamps)
  3. Jiri Vlach and Kishore Singhal, Computer Methods for Circuit Analysis and Design, second edition, Van Nostrand Reinhold, 1994, the chapters on the formulation of network equations (nodal and modified nodal formulation, element stamps)
  4. Lawrence T. Pillage, Ronald A. Rohrer and Chandramouli Visweswariah, Electronic Circuit and System Simulation Methods, McGraw-Hill, 1994, the early chapters on nodal and modified nodal formulation and element stamps
  5. Laurence W. Nagel, SPICE2, A Computer Program to Simulate Semiconductor Circuits, Memorandum UCB/ERL M520, University of California, Berkeley, May 1975, the chapter on the formulation of the circuit equations

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises