Algorithm Search⌘K

Algorithmadvanced

Asymptotic waveform evaluation

Also called AWE.

Pillage and Rohrer's reduced model of a linear circuit that matches 2q moments of its response by a q-pole Pade approximation.

Time
Θ(n³ + q n² + q³ + I q²) worst · average · best
Space
Θ(n² + q²) extra
Where
I = the number of sweeps of the root finder; n = the number of nodes of the circuit; q = the number of poles of the model
Properties
deterministicnot exactiterative
Origin
Lawrence T. Pillage, Ronald A. Rohrer, 1990

Asymptotic waveform evaluation (AWE) replaces a large linear RC or RLC circuit, such as an RC tree of an extracted wire, by a small model with qq poles. It computes the moments of the transfer function, the coefficients of its Taylor series at s=0s = 0, by repeated solves with the conductance matrix. From 2q2q moments it builds the Padé approximation P(s)/Q(s)P(s)/Q(s) with qq poles, then the poles, the residues and the response in closed form. Pillage and Rohrer published it in 1990. With q=1q = 1 it gives the Elmore delay. With q=nq = n it gives the exact transfer function. In between, the model can have unstable poles although the circuit is stable.

In plain words

A wire with many resistors and capacitors responds to a step at its input with a smooth rise at its output. The exact rise is a sum of many decaying exponentials, one per node. AWE keeps only a few of them.

It does not simulate the circuit in time. It solves for the voltages once at DC, and then again with the capacitors fed by the previous solution, a few times. Each solve gives one number, a moment. From 2q2q moments it fits a ratio of two polynomials that has qq poles and agrees with the first 2q2q moments. The poles and residues of this ratio give a formula for the response, from which the delay at 50 percent can be read.

The problem

The input is a linear circuit in nodal form,

(G+sC) x(s)=b u(s),y(s)=lTx(s),(G + sC) \, x(s) = b \, u(s), \qquad y(s) = l^T x(s),

with n×nn \times n real matrices GG (conductances, invertible) and CC (capacitances), an input vector bb, an output vector ll, and an order qq. The transfer function is H(s)=lT(G+sC)−1bH(s) = l^T (G + sC)^{-1} b, and its expansion at s=0s = 0 is

H(s)=∑k≥0mksk,mk=lT(−G−1C)kG−1b.H(s) = \sum_{k \ge 0} m_k s^k, \qquad m_k = l^T (-G^{-1} C)^k G^{-1} b.

The output is a rational function P(s)/Q(s)P(s)/Q(s) with deg⁡P≤q−1\deg P \le q - 1, deg⁡Q≤q\deg Q \le q and Q(0)=1Q(0) = 1 whose expansion agrees with m0,…,m2q−1m_0, \ldots, m_{2q-1}, together with its poles pip_i (the roots of QQ) and residues kik_i. This is a model order reduction problem: a model of order qq for a circuit of order nn.

The algorithm

  1. AWE(G, C, b, l, q)
  2. 1x_0 ← G⁻¹ b ▷ the DC solution, one LU of G
  3. 2for k ← 1 to 2q − 1 do x_k ← G⁻¹ (−C x_{k−1}) ▷ reuse the LU of G
  4. 3m_k ← lᵀ x_k for k = 0 .. 2q − 1 ▷ the moments
  5. 4b_0 ← 1; solve Σ_{j=1..q} b_j m_{k−j} = −m_k for k = q .. 2q − 1
  6. 5a_k ← Σ_{j=0..k} b_j m_{k−j} for k = 0 .. q − 1
  7. 6p_1 .. p_q ← the roots of Q(s) = Σ_{j=0..q} b_j s^j
  8. 7k_i ← P(p_i) / Q′(p_i) for i = 1 .. q, where P(s) = Σ_k a_k s^k
  9. 8return P, Q, the poles p_i and the residues k_i

Lines L1 to L3 compute the moments. Line L4 is the Hankel system of the Padé approximation: it makes the coefficients of sq,…,s2q−1s^q, \ldots, s^{2q-1} in Q(s)H(s)Q(s) H(s) vanish. Line L5 takes the low-order part of Q(s)H(s)Q(s) H(s) as the numerator. Line L6 finds the poles, for example by the Durand-Kerner method. Line L7 is the partial fraction decomposition P/Q=∑iki/(s−pi)P/Q = \sum_i k_i/(s - p_i) for simple poles. The response to a unit step is then

y(t)=m0+∑i=1qkipiepit.y(t) = m_0 + \sum_{i=1}^q \frac{k_i}{p_i} e^{p_i t}.

The implementation computes lines L1 to L5 in exact rational arithmetic and lines L6 and L7 in floating point. It checks the stability of QQ exactly by the Routh-Hurwitz criterion.

Example

A stable model. Take a ladder of three sections, with R=(1,1,1)R = (1, 1, 1), C=(1,2,1)C = (1, 2, 1) and a unit step source at its left end, and the output at the far end. The DC solution is all ones, so m0=1m_0 = 1, and the moments are 1,−8,56,−386,2656,−182721, -8, 56, -386, 2656, -18272. The Elmore delay is −m1=1⋅1+2⋅2+1⋅3=8-m_1 = 1 \cdot 1 + 2 \cdot 2 + 1 \cdot 3 = 8.

qq P(s)P(s) Q(s)Q(s) poles 50 percent delay
1 11 1+8s1 + 8s −0.125-0.125 8ln⁡2=5.54528 \ln 2 = 5.5452
2 1−s/41 - s/4 1+314s+6s21 + \tfrac{31}{4} s + 6 s^2 −0.1454-0.1454, −1.1463-1.1463 5.9428
3 11 1+8s+8s2+2s31 + 8s + 8s^2 + 2s^3 −0.1454-0.1454, −1.4030-1.4030, −2.4516-2.4516 5.9404

For q=2q = 2, line L4 solves −8b1+b2=−56-8 b_1 + b_2 = -56 and 56b1−8b2=38656 b_1 - 8 b_2 = 386, so b1=31/4b_1 = 31/4 and b2=6b_2 = 6, and line L5 gives a0=1a_0 = 1 and a1=−8+31/4=−1/4a_1 = -8 + 31/4 = -1/4. The model with q=3q = 3 is the exact transfer function. The two-pole model has the right dominant pole to four digits and a 50 percent delay within 0.04 percent of the exact 5.9404. The one-pole model is 6.7 percent early here.

An unstable model. Take the same circuit with the output at the middle node. The moments are 1,−7,48,−3301, -7, 48, -330, and line L4 solves −7b1+b2=−48-7 b_1 + b_2 = -48 and 48b1−7b2=33048 b_1 - 7 b_2 = 330, so Q(s)=1+6s−6s2Q(s) = 1 + 6s - 6s^2. Its roots are −0.1455-0.1455 and +1.1455+1.1455. The model has a pole in the right half-plane, and its step response grows without bound, although every pole of the circuit is negative. The model with q=3q = 3 at this node is exact and stable.

Correctness

The proof shows the following.

  • Moments. Lines L1 to L3 give the Taylor coefficients of HH at 0, by the Neumann series of (I+sG−1C)−1(I + s G^{-1} C)^{-1}.
  • 2q moments are matched. If the Hankel matrix of line L4 is invertible, then H−P/Q=O(s2q)H - P/Q = O(s^{2q}), and P/QP/Q is the only rational function of that type with this property.
  • q = n is exact. By Cramer's rule, H=N/DH = N/D with D=det⁡(G+sC)D = \det(G + sC) of degree at most nn and deg⁡N≤n−1\deg N \le n - 1, so with q=nq = n the model is HH itself and Q=D/D(0)Q = D/D(0).
  • Residues and the step response. For simple poles, line L7 gives the partial fractions, the step response has the form above, and y(0)=0y(0) = 0.
  • Elmore delay. For an RC tree, m0=1m_0 = 1 and −m1-m_1 is the Elmore delay at the output.
  • Stability is not guaranteed. The unstable example above is a proof that AWE with q=2q = 2 can give a pole in the right half-plane for a stable RC tree.

What is proved is the matching of moments, not an error bound on the waveform or the delay for q<nq < n. The rest is measured. On 300 random RC trees with 3 to 6 nodes and integer RR and CC from 1 to 9 (Python random.Random(9)), at all 1296 outputs, the model with q=2q = 2 was unstable at 112 outputs (8.6 percent). At the other 1184, the mean relative error of the 50 percent delay against the exact model was 3.1 percent for q=2q = 2 and 46 percent for q=1q = 1. The error was more than 10 percent at 44 outputs for q=2q = 2 and at 541 for q=1q = 1. The worst cases were near the driver, where a slow pole with a small residue appears.

Proof: AWE computes the moments of the transfer function, its model matches the first 2q of them and is the unique such model, q = n gives the exact function, and stability is not guaranteedfull

Setting. A linear circuit has the nodal equations (G+sC)x(s)=b u(s)(G + sC) x(s) = b \, u(s) in the Laplace domain, where GG and CC are real n×nn \times n matrices, GG is invertible, bb is the input vector and uu the input. The output is y=lTxy = l^T x. So the transfer function is

H(s)=lT(G+sC)−1b.H(s) = l^T (G + sC)^{-1} b.

Write A=−G−1CA = -G^{-1} C and r=G−1br = G^{-1} b. All arithmetic in lines L1 to L5 is exact (rational numbers); lines L6 and L7 use floating point.

Theorem 1 (moments). For ∣s∣<1/ρ(A)|s| < 1 / \rho(A), where ρ\rho is the spectral radius (∣s∣|s| unrestricted if ρ(A)=0\rho(A) = 0),

H(s)=∑k≥0mksk,mk=lTAkr,H(s) = \sum_{k \ge 0} m_k s^k, \qquad m_k = l^T A^k r,

and lines L1 to L3 compute m0,…,m2q−1m_0, \ldots, m_{2q-1}.

Proof. G+sC=G(I−sA)G + sC = G (I - sA), so (G+sC)−1=(I−sA)−1G−1(G + sC)^{-1} = (I - sA)^{-1} G^{-1}. For ∣s∣ρ(A)<1|s| \rho(A) < 1 the Neumann series (I−sA)−1=∑kskAk(I - sA)^{-1} = \sum_k s^k A^k converges, which gives the expansion. Line L1 sets x0=rx_0 = r, and line L2 sets xk=G−1(−Cxk−1)=Axk−1x_k = G^{-1}(-C x_{k-1}) = A x_{k-1}, so xk=Akrx_k = A^k r by induction, and line L3 gives mk=lTxkm_k = l^T x_k. □\square

Theorem 2 (matching of 2q moments). Suppose the q×qq \times q Hankel matrix MqM_q with entries mk−jm_{k-j} (k=q,…,2q−1k = q, \ldots, 2q-1, j=1,…,qj = 1, \ldots, q) is invertible. Let b0=1b_0 = 1, let b1,…,bqb_1, \ldots, b_q solve line L4 and let a0,…,aq−1a_0, \ldots, a_{q-1} be given by line L5. With Q(s)=∑j=0qbjsjQ(s) = \sum_{j=0}^q b_j s^j and P(s)=∑k=0q−1akskP(s) = \sum_{k=0}^{q-1} a_k s^k,

Q(s)H(s)−P(s)=O(s2q),H(s)−P(s)Q(s)=O(s2q).Q(s) H(s) - P(s) = O(s^{2q}), \qquad H(s) - \frac{P(s)}{Q(s)} = O(s^{2q}).

So the Taylor coefficients of P/QP/Q at 0 are m0,…,m2q−1m_0, \ldots, m_{2q-1}.

Proof. The coefficient of sks^k in Q(s)H(s)Q(s) H(s) is ck=∑j=0min⁡(k,q)bjmk−jc_k = \sum_{j=0}^{\min(k, q)} b_j m_{k-j}. For k≤q−1k \le q - 1, ck=akc_k = a_k by line L5. For q≤k≤2q−1q \le k \le 2q - 1, ck=mk+∑j=1qbjmk−j=0c_k = m_k + \sum_{j=1}^q b_j m_{k-j} = 0 by line L4. So QH−PQH - P has no terms of degree below 2q2q. Since Q(0)=1Q(0) = 1, 1/Q1/Q is a power series, and H−P/Q=(QH−P)/Q=O(s2q)H - P/Q = (QH - P)/Q = O(s^{2q}). □\square

Theorem 3 (uniqueness). Under the hypothesis of Theorem 2, if P′P' and Q′Q' are polynomials with deg⁡P′≤q−1\deg P' \le q - 1, deg⁡Q′≤q\deg Q' \le q, Q′(0)=1Q'(0) = 1 and H−P′/Q′=O(s2q)H - P'/Q' = O(s^{2q}), then P′=PP' = P and Q′=QQ' = Q.

Proof. Q′H−P′=Q′(H−P′/Q′)=O(s2q)Q' H - P' = Q' (H - P'/Q') = O(s^{2q}). Since deg⁡P′≤q−1\deg P' \le q - 1, the coefficients of sq,…,s2q−1s^q, \ldots, s^{2q-1} in Q′HQ' H are 0, which says that the coefficients b1′,…,bq′b'_1, \ldots, b'_q of Q′Q' solve the system of line L4. As MqM_q is invertible, Q′=QQ' = Q. Then P′P' is the part of degree below qq of QHQ H, which is PP. □\square

Theorem 4 (q = n is exact). Let D(s)=det⁡(G+sC)D(s) = \det(G + sC) and suppose that line L4 succeeds for q=nq = n. Then Q=D/D(0)Q = D / D(0), and P/Q=HP / Q = H as rational functions.

Proof. By Cramer's rule, xi(s)=Di(s)/D(s)x_i(s) = D_i(s) / D(s), where DiD_i is the determinant of G+sCG + sC with column ii replaced by bb. Each term of DD is a product of nn entries of degree at most 1 in ss, so deg⁡D≤n\deg D \le n, and each term of DiD_i has one constant factor from bb, so deg⁡Di≤n−1\deg D_i \le n - 1. Hence H=N/DH = N / D with N=∑iliDiN = \sum_i l_i D_i and deg⁡N≤n−1\deg N \le n - 1. Also D(0)=det⁡G≠0D(0) = \det G \ne 0. The pair P′=N/D(0)P' = N / D(0), Q′=D/D(0)Q' = D / D(0) meets the conditions of Theorem 3 with q=nq = n, since H−P′/Q′=0H - P'/Q' = 0. So Q=Q′Q = Q' and P=P′P = P'. □\square

If MqM_q is singular, line L4 has no unique solution, and the implementation raises an error. This happens, for example, for q=2q = 2 on a circuit with one capacitor, whose moments mk=(−τ)km_k = (-\tau)^k give m12−m0m2=0m_1^2 - m_0 m_2 = 0.

Theorem 5 (residues and step response). Suppose bq≠0b_q \ne 0 and the roots p1,…,pqp_1, \ldots, p_q of QQ are simple. Then

P(s)Q(s)=∑i=1qkis−pi,ki=P(pi)Q′(pi),\frac{P(s)}{Q(s)} = \sum_{i=1}^q \frac{k_i}{s - p_i}, \qquad k_i = \frac{P(p_i)}{Q'(p_i)},

and the inverse Laplace transform of P(s)/(sQ(s))P(s) / (s Q(s)), the response of the model to a unit step, is

y(t)=m0+∑i=1qkipiepit(t≥0),y(0)=0.y(t) = m_0 + \sum_{i=1}^q \frac{k_i}{p_i} e^{p_i t} \quad (t \ge 0), \qquad y(0) = 0.

Proof. deg⁡P<deg⁡Q\deg P < \deg Q and the roots are simple, so the partial fraction decomposition has the stated form, with ki=lim⁡s→pi(s−pi)P(s)/Q(s)=P(pi)/Q′(pi)k_i = \lim_{s \to p_i} (s - p_i) P(s) / Q(s) = P(p_i) / Q'(p_i), since Q(pi)=0Q(p_i) = 0 and Q′(pi)≠0Q'(p_i) \ne 0. No root is 0 because Q(0)=1Q(0) = 1. Then

kis(s−pi)=kipi(1s−pi−1s),\frac{k_i}{s (s - p_i)} = \frac{k_i}{p_i} \left( \frac{1}{s - p_i} - \frac{1}{s} \right),

whose inverse transform is (ki/pi)(epit−1)(k_i / p_i)(e^{p_i t} - 1). Summing over ii gives y(t)=∑i(ki/pi)epit−∑iki/piy(t) = \sum_i (k_i/p_i) e^{p_i t} - \sum_i k_i / p_i. At s=0s = 0 the decomposition gives P(0)/Q(0)=−∑iki/piP(0)/Q(0) = -\sum_i k_i / p_i, and P(0)/Q(0)=a0=m0P(0)/Q(0) = a_0 = m_0. So the constant is m0m_0, and y(0)=m0+∑iki/pi=0y(0) = m_0 + \sum_i k_i / p_i = 0. □\square

Lines L6 and L7 compute the roots and the residues in floating point by an iteration, so the poles and residues of the implementation are approximations of these exact values. The coefficients of PP and QQ are exact.

Theorem 6 (the first moment is minus the Elmore delay). For an RC tree driven at its root through the resistor RrootR_{\text{root}} by a source of value 1, with a capacitor CkC_k from node kk to ground, and output at node ii (l=eil = e_i), m0=1m_0 = 1 and −m1=∑kRikCk-m_1 = \sum_k R_{ik} C_k, the Elmore delay, where RikR_{ik} is the resistance of the common part of the paths from the source to ii and to kk.

Proof. At s=0s = 0 no current flows in the capacitors, so no current flows in the resistors, and every node has voltage 1: r=G−1b=1r = G^{-1} b = \mathbf 1, and m0=1m_0 = 1. Then m1=eiTG−1(−C1)=−∑k(G−1)ikCkm_1 = e_i^T G^{-1}(-C \mathbf 1) = -\sum_k (G^{-1})_{ik} C_k. Here (G−1)ik(G^{-1})_{ik} is the voltage at node ii when the source is set to 0 and a unit current is injected at node kk. That current flows to ground along the unique path from kk to the source, so the voltage at a node on that path is the resistance between the node and the source, and every node off the path has the voltage of the node where its path to the source meets the path from kk. The voltage at ii is therefore the resistance of the common part of the two paths, RikR_{ik}. □\square

Proposition 7 (stability is not guaranteed). There is an RC tree, whose poles all lie in the open left half-plane, for which the AWE model with q=2q = 2 has a pole in the right half-plane.

Proof. Take the ladder with R=(1,1,1)R = (1, 1, 1) and C=(1,2,1)C = (1, 2, 1) and the output at the middle node. Exact computation by lines L1 to L3 gives m=(1,−7,48,−330)m = (1, -7, 48, -330). Line L4 solves −7b1+b2=−48-7 b_1 + b_2 = -48 and 48b1−7b2=33048 b_1 - 7 b_2 = 330, so b1=6b_1 = 6 and b2=−6b_2 = -6, and Q(s)=1+6s−6s2Q(s) = 1 + 6s - 6s^2. Its roots are (6±60)/12(6 \pm \sqrt{60})/12, and (6+60)/12>0(6 + \sqrt{60})/12 > 0. The circuit itself has det⁡(G+sC)/det⁡G=1+8s+8s2+2s3\det(G + sC) / \det G = 1 + 8s + 8s^2 + 2s^3. All its coefficients are positive and 8⋅8>2⋅18 \cdot 8 > 2 \cdot 1, so by the Routh-Hurwitz condition for degree 3 all its roots have negative real parts. □\square

The function is_stable of the implementation decides with the Routh test in exact arithmetic whether all roots of QQ lie in the open left half-plane. Its correctness is the Routh-Hurwitz theorem, which is not proved here.

Theorem 8 (running time). With dense matrices of order nn, lines L1 to L3 take Θ(n3+qn2)\Theta(n^3 + q n^2) arithmetic operations: one LU factorization of GG and 2q2q triangular solves and products with CC. Lines L4 and L5 take Θ(q3)\Theta(q^3) and Θ(q2)\Theta(q^2). Each iteration of the root finder in line L6 takes Θ(q2)\Theta(q^2), and line L7 takes Θ(q2)\Theta(q^2).

Proof. The LU factorization of a dense n×nn \times n matrix takes Θ(n3)\Theta(n^3) operations, each pair of triangular solves Θ(n2)\Theta(n^2), and each product CxC x and each inner product lTxl^T x at most Θ(n2)\Theta(n^2). The Hankel system is a dense q×qq \times q system. Line L5 sums at most qq products for each of qq coefficients. One Durand-Kerner sweep evaluates QQ and a product of q−1q - 1 differences at each of qq points. Line L7 evaluates two polynomials of degree below qq at qq points. □\square

No bound on the number of iterations of the root finder is proved here. For an RC tree, GG is sparse and the moments take Θ(n)\Theta(n) operations each by two passes over the tree, as for the Elmore delay.

■\blacksquare

Complexity

  • Moments. With dense matrices, one LU factorization of GG costs Θ(n3)\Theta(n^3), and each of the 2q2q moments costs Θ(n2)\Theta(n^2) for a product with CC and two triangular solves. For an RC tree, GG is a tree Laplacian plus a diagonal, and each moment takes Θ(n)\Theta(n) time by two passes over the tree, as in the Elmore delay.
  • Padé and residues. The Hankel system costs Θ(q3)\Theta(q^3), the numerator Θ(q2)\Theta(q^2), and each sweep of the root finder Θ(q2)\Theta(q^2). No bound on the number of sweeps is proved here. In practice qq is 2 to 4, so this part is small.
  • Space. The LU factors take Θ(n2)\Theta(n^2) for dense matrices, and only two moment vectors are needed at a time.
  • Compared with simulation. A time-domain simulation solves one linear system per time step, and needs many steps to resolve the fastest and the slowest time constants. AWE needs 2q2q solves with one matrix.

Properties

  • Not exact for q<nq < n. It is an approximation of the transfer function near s=0s = 0, so it is good for the slow parts of the response and less good for the start of the step response.
  • The moments are exact. In exact arithmetic, the first 2q2q moments of the model equal those of the circuit.
  • Not stable in general. The Padé approximation does not keep the stability of the circuit, as the example shows. The model also need not be passive, so it can make a larger circuit unstable when it is connected to other parts.
  • Ill-conditioned in floating point. The moments grow or shrink like powers of the time constants, so the Hankel matrix becomes nearly singular as qq grows. In floating point, AWE is useful only for small qq. The implementation here avoids this problem by exact arithmetic, which costs more time.

Variants and improvements

  • Moment shifting and frequency scaling. Expand at a point s0≠0s_0 \ne 0, or scale ss, to reduce the spread of the moments.
  • Complex frequency hopping. Expand at several points and combine the poles found near each of them.
  • Krylov methods. The moments span the Krylov subspace of −G−1C-G^{-1}C and G−1bG^{-1}b. Padé via Lanczos (PVL) of Feldmann and Freund computes the same Padé model from a Lanczos process without forming the moments. PRIMA uses an Arnoldi basis and a congruence transform, matches qq block moments instead of 2q2q, and keeps the model passive.
  • Closed-form delay metrics. Formulas in the first two or three moments of an RC tree give fast delay estimates that are always defined, with no poles to compute.

When to use it

  • To get a delay and a slew of an RC or RLC interconnect that is more accurate than the Elmore delay, with a cost of a few linear solves.
  • For a few low-order models where the result is checked for stability, and where a lower order is used if it is not stable.
  • Not when the reduced model is connected back to a simulator and must be passive. Use PRIMA or a similar projection method.

Pitfalls

  • Unstable poles. Always check the poles. A model with a pole in the right half-plane, as in the example, has a response that grows without bound. The usual fix is to use a lower order, or to drop the unstable poles and refit the residues.
  • Singular Hankel matrix. With one capacitor, the moments are (−τ)k(-\tau)^k and the Hankel matrix for q=2q = 2 is singular. A circuit with fewer distinct poles than qq has no model with qq poles.
  • Rounding of the moments. In floating point, the moments must be scaled, or the Hankel matrix is singular to working precision already for small qq.
  • Multiple poles. Line L7 assumes simple poles. For a double pole the response has a term teptt e^{pt}, and the residue formula divides by Q′(p)=0Q'(p) = 0.

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.

asymptotic_waveform_evaluation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/asymptotic-waveform-evaluation/. The authors are listed in prov/5A3DBS.jsonl.

import cmath
from fractions import Fraction
from typing import NamedTuple, Sequence


class AweModel(NamedTuple):
    moments: list      # m_0 .. m_{2q-1}, exact
    numerator: list    # a_0 .. a_{q-1} of P(s), exact
    denominator: list  # b_0 = 1, b_1 .. b_q of Q(s), exact
    poles: list        # roots of Q, complex floats
    residues: list     # P(p) / Q'(p) for each pole, complex floats


def lu_factor(A: Sequence[Sequence]) -> tuple:
    """LU factorization with row pivoting on the first non-zero entry (exact for Fractions)."""
    n = len(A)
    M = [[Fraction(x) for x in row] for row in A]
    perm = list(range(n))
    for c in range(n):
        p = next((r for r in range(c, n) if M[r][c] != 0), None)
        if p is None:
            raise ValueError("singular matrix")
        M[c], M[p] = M[p], M[c]
        perm[c], perm[p] = perm[p], perm[c]
        for r in range(c + 1, n):
            if M[r][c] != 0:
                f = M[r][c] / M[c][c]
                M[r][c] = f
                for k in range(c + 1, n):
                    M[r][k] -= f * M[c][k]
    return M, perm


def lu_solve(factor: tuple, rhs: Sequence) -> list:
    M, perm = factor
    n = len(M)
    y = [Fraction(rhs[perm[i]]) for i in range(n)]
    for i in range(n):
        for k in range(i):
            y[i] -= M[i][k] * y[k]
    for i in range(n - 1, -1, -1):
        for k in range(i + 1, n):
            y[i] -= M[i][k] * y[k]
        y[i] /= M[i][i]
    return y


def polyval(c: Sequence, s):
    """c[k] is the coefficient of s^k."""
    v = 0
    for x in reversed(c):
        v = v * s + x
    return v


def durand_kerner(c: Sequence, iterations: int = 2000) -> list:
    """All complex roots of the polynomial with coefficients c (c[k] of s^k)."""
    c = [complex(x) for x in c]
    while c and c[-1] == 0:
        c.pop()
    deg = len(c) - 1
    if deg < 1:
        return []
    monic = [x / c[-1] for x in c]
    radius = 1.0 + max(abs(x) for x in monic[:-1])  # Cauchy bound on the roots
    z = [radius * (0.4 + 0.9j) ** k for k in range(deg)]
    for _ in range(iterations):
        change = 0.0
        for i in range(deg):
            den = 1.0
            for j in range(deg):
                if j != i:
                    den *= z[i] - z[j]
            step = polyval(monic, z[i]) / den
            z[i] -= step
            change = max(change, abs(step))
        if change <= 1e-15 * radius:
            break
    return z


def moments(G, C, b, l, count: int) -> list:
    """m_k = l^T (-G^{-1} C)^k G^{-1} b for k = 0 .. count-1, exactly."""
    n = len(G)
    factor = lu_factor(G)
    x = lu_solve(factor, b)  # @line L1
    out = [sum(Fraction(l[i]) * x[i] for i in range(n))]  # @line L3
    for _ in range(count - 1):
        cx = [-sum(Fraction(C[i][j]) * x[j] for j in range(n)) for i in range(n)]
        x = lu_solve(factor, cx)  # @line L2
        out.append(sum(Fraction(l[i]) * x[i] for i in range(n)))  # @line L3
    return out


def asymptotic_waveform_evaluation(G, C, b, l, q: int) -> AweModel:
    """The q-pole AWE model of H(s) = l^T (G + sC)^{-1} b.

    G, C are n x n matrices and b, l vectors of ints or Fractions. The model
    P(s)/Q(s) with deg P <= q-1 and deg Q <= q matches the moments m_0 ..
    m_{2q-1}. Raises ValueError if the Hankel matrix of the moments is singular.
    """
    if q < 1:
        raise ValueError("q must be at least 1")
    m = moments(G, C, b, l, 2 * q)
    hankel = [[m[k - j] for j in range(1, q + 1)] for k in range(q, 2 * q)]
    rhs = [-m[k] for k in range(q, 2 * q)]
    den = [Fraction(1)] + lu_solve(lu_factor(hankel), rhs)  # @line L4
    num = [sum(den[j] * m[k - j] for j in range(k + 1)) for k in range(q)]  # @line L5
    poles = durand_kerner(den)  # @line L6
    dden = [k * den[k] for k in range(1, len(den))]
    residues = [polyval(num, p) / polyval(dden, p) for p in poles]  # @line L7
    return AweModel(m, num, den, poles, residues)  # @line L8


def is_stable(den: Sequence) -> bool:
    """Exact Routh test: True if and only if every root of Q lies in the open left half-plane."""
    c = [Fraction(x) for x in den]
    while c and c[-1] == 0:
        c.pop()
    if len(c) <= 1:
        return True
    hi = c[::-1]  # coefficients from the highest power down
    rows = [hi[0::2], hi[1::2]]
    while len(rows[-1]) > 0 and any(x != 0 for x in rows[-1]):
        a, b = rows[-2], rows[-1]
        if b[0] == 0:
            return False  # a zero pivot: some root is on or right of the imaginary axis
        nxt = []
        for j in range(len(a) - 1):
            right = b[j + 1] if j + 1 < len(b) else 0
            nxt.append((b[0] * a[j + 1] - a[0] * right) / b[0])
        rows.append(nxt)
    rows = [r for r in rows if r]
    if len(rows) != len(c):
        return False  # a row of zeros: roots symmetric about the origin
    first = [r[0] for r in rows]
    return all(x != 0 for x in first) and all((x > 0) == (first[0] > 0) for x in first)


def step_response(model: AweModel, t: float) -> float:
    """y(t) = m_0 + sum_i (k_i / p_i) exp(p_i t), the response to a unit step at t = 0."""
    y = complex(model.moments[0])
    for p, k in zip(model.poles, model.residues):
        y += k / p * cmath.exp(p * t)
    return y.real
test_asymptotic_waveform_evaluation.py 283 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/asymptotic-waveform-evaluation/. The authors are listed in prov/5A3DBS.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from asymptotic_waveform_evaluation import (
    asymptotic_waveform_evaluation,
    durand_kerner,
    is_stable,
    moments,
    polyval,
    step_response,
)


def rc_tree(parent, R, C):
    """Nodal equations (G + sC) v = b for an RC tree driven by a unit source through R[root]."""
    n = len(parent)
    G = [[Fraction(0)] * n for _ in range(n)]
    Cm = [[Fraction(0)] * n for _ in range(n)]
    b = [Fraction(0)] * n
    for i in range(n):
        g = 1 / Fraction(R[i])
        Cm[i][i] = Fraction(C[i])
        G[i][i] += g
        if parent[i] < 0:
            b[i] += g
        else:
            p = parent[i]
            G[p][p] += g
            G[i][p] -= g
            G[p][i] -= g
    return G, Cm, b


def unit(n, i):
    return [1 if k == i else 0 for k in range(n)]


def random_tree(rng, n):
    parent = [-1] + [rng.randrange(i) for i in range(1, n)]
    R = [rng.randint(1, 9) for _ in range(n)]
    C = [rng.randint(1, 9) for _ in range(n)]
    return parent, R, C


def polymul(a, b):
    out = [Fraction(0)] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            out[i + j] += x * y
    return out


def polyadd(a, b):
    k = max(len(a), len(b))
    return [(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0) for i in range(k)]


def det_poly(M):
    """det of a matrix of polynomials by the Leibniz formula."""
    n = len(M)
    total = [Fraction(0)]
    for perm in itertools.permutations(range(n)):
        sign = 1
        for i in range(n):
            for j in range(i + 1, n):
                if perm[i] > perm[j]:
                    sign = -sign
        p = [Fraction(sign)]
        for i in range(n):
            p = polymul(p, M[i][perm[i]])
        total = polyadd(total, p)
    return total


def exact_transfer(G, C, b, l):
    """H(s) = N(s) / D(s) by Cramer's rule, with no moments involved."""
    n = len(G)
    M = [[[G[i][j], C[i][j]] for j in range(n)] for i in range(n)]
    D = det_poly(M)
    N = [Fraction(0)]
    for i in range(n):
        if l[i] != 0:
            Mi = [[[b[r], 0] if c == i else M[r][c] for c in range(n)] for r in range(n)]
            N = polyadd(N, [l[i] * x for x in det_poly(Mi)])
    return N, D


def series(N, D, count):
    """The first count Taylor coefficients of N(s) / D(s) at s = 0."""
    out = []
    for k in range(count):
        v = N[k] if k < len(N) else Fraction(0)
        for j in range(1, min(k, len(D) - 1) + 1):
            v -= D[j] * out[k - j]
        out.append(v / D[0])
    return out


def elmore(parent, R, C, i):
    def path(v):
        out = set()
        while v >= 0:
            out.add(v)
            v = parent[v]
        return out

    pi = path(i)
    return sum(C[k] * sum(R[e] for e in pi & path(k)) for k in range(len(parent)))


def test_moments_against_cramer_expansion():
    rng = random.Random(1)
    for _ in range(40):
        n = rng.randint(1, 5)
        parent, R, C = random_tree(rng, n)
        G, Cm, b = rc_tree(parent, R, C)
        l = [rng.randint(-2, 2) for _ in range(n)]
        N, D = exact_transfer(G, Cm, b, l)
        assert moments(G, Cm, b, l, 7) == series(N, D, 7)


def test_ladders_of_three_to_six_sections():
    rng = random.Random(6)
    for n in range(3, 7):
        R = [rng.randint(1, 9) for _ in range(n)]
        C = [rng.randint(1, 9) for _ in range(n)]
        G, Cm, b = rc_tree([-1] + list(range(n - 1)), R, C)
        l = unit(n, n - 1)
        N, D = exact_transfer(G, Cm, b, l)
        exact = series(N, D, 2 * n)
        assert moments(G, Cm, b, l, 2 * n) == exact
        for q in range(1, n + 1):
            model = asymptotic_waveform_evaluation(G, Cm, b, l, q)
            assert series(model.numerator, model.denominator, 2 * q) == exact[:2 * q]


def test_minus_first_moment_is_the_elmore_delay():
    rng = random.Random(2)
    for _ in range(60):
        n = rng.randint(1, 7)
        parent, R, C = random_tree(rng, n)
        G, Cm, b = rc_tree(parent, R, C)
        for i in range(n):
            m = moments(G, Cm, b, unit(n, i), 2)
            assert m[0] == 1
            assert -m[1] == elmore(parent, R, C, i)


def test_model_matches_two_q_moments():
    rng = random.Random(3)
    checked = 0
    for _ in range(80):
        n = rng.randint(2, 6)
        parent, R, C = random_tree(rng, n)
        G, Cm, b = rc_tree(parent, R, C)
        i = rng.randrange(n)
        for q in range(1, n + 1):
            try:
                model = asymptotic_waveform_evaluation(G, Cm, b, unit(n, i), q)
            except ValueError:
                continue  # singular Hankel matrix: no q-pole model exists
            exact = moments(G, Cm, b, unit(n, i), 2 * q + 1)
            assert series(model.numerator, model.denominator, 2 * q) == exact[:2 * q]
            checked += 1
    assert checked > 200


def test_q_equal_n_gives_the_exact_transfer_function():
    rng = random.Random(4)
    for _ in range(25):
        n = rng.randint(1, 5)
        _, R, C = random_tree(rng, n)
        # Far end of a chain: the numerator is a constant, so no pole cancels.
        G, Cm, b = rc_tree([-1] + list(range(n - 1)), R, C)
        l = unit(n, n - 1)
        N, D = exact_transfer(G, Cm, b, l)
        model = asymptotic_waveform_evaluation(G, Cm, b, l, n)
        assert model.denominator == [x / D[0] for x in D]
        assert polymul(model.numerator, D) == polymul(N, model.denominator)[:len(model.numerator) + len(D) - 1]
        assert is_stable(model.denominator)
        assert all(p.real < 0 and abs(p.imag) < 1e-6 * abs(p) for p in model.poles)


def test_one_pole_model_is_the_elmore_exponential():
    G, Cm, b = rc_tree([-1, 0, 1], [1, 2, 3], [3, 1, 2])
    model = asymptotic_waveform_evaluation(G, Cm, b, unit(3, 2), 1)
    td = elmore([-1, 0, 1], [1, 2, 3], [3, 1, 2], 2)
    assert model.denominator == [1, td]
    assert model.poles[0] == pytest.approx(-1 / td)
    assert step_response(model, float(td)) == pytest.approx(1 - 1 / 2.718281828459045)


def test_unstable_two_pole_model():
    # Ladder R = (1, 1, 1), C = (1, 2, 1), output at the middle node.
    G, Cm, b = rc_tree([-1, 0, 1], [1, 1, 1], [1, 2, 1])
    model = asymptotic_waveform_evaluation(G, Cm, b, unit(3, 1), 2)
    assert model.moments == [1, -7, 48, -330]
    assert model.denominator == [1, 6, -6]
    assert not is_stable(model.denominator)
    assert max(p.real for p in model.poles) == pytest.approx((6 + 60 ** 0.5) / 12, abs=1e-12)
    # The circuit itself is stable, and so is the exact model q = 3.
    exact = asymptotic_waveform_evaluation(G, Cm, b, unit(3, 1), 3)
    assert is_stable(exact.denominator)
    assert all(p.real < 0 for p in exact.poles)


def test_exact_stability_test_agrees_with_the_roots():
    rng = random.Random(5)
    for _ in range(400):
        deg = rng.randint(1, 5)
        roots = []
        while len(roots) < deg:
            re = rng.choice([-1, 1]) * rng.randint(1, 5) / 2
            if deg - len(roots) >= 2 and rng.random() < 0.5:
                im = rng.randint(1, 4) / 2
                roots += [complex(re, im), complex(re, -im)]
            else:
                roots.append(complex(re, 0))
        poly = [Fraction(1)]
        for r in roots:
            if r.imag > 0:
                poly = polymul(poly, [Fraction(r.real ** 2 + r.imag ** 2), Fraction(-2 * r.real), Fraction(1)])
            elif r.imag == 0:
                poly = polymul(poly, [Fraction(-r.real), Fraction(1)])
        assert is_stable(poly) == all(r.real < 0 for r in roots)
        if len(set(roots)) == len(roots):  # a multiple root is found to about sqrt(eps) only
            found = durand_kerner(poly)
            for r in roots:
                assert min(abs(r - z) for z in found) < 1e-8
    assert not is_stable([1, 0, 1])  # roots +i and -i
    assert not is_stable([0, 1])     # root 0
    assert is_stable([5])


def simulate(G, C, b, l, t_end, steps):
    """Brute force: RK4 on C v' = b - G v from v = 0, for a diagonal C."""
    n = len(G)
    Gf = [[float(x) for x in row] for row in G]
    cf = [float(C[i][i]) for i in range(n)]
    bf = [float(x) for x in b]

    def f(v):
        return [(bf[i] - sum(Gf[i][j] * v[j] for j in range(n))) / cf[i] for i in range(n)]

    h = t_end / steps
    v = [0.0] * n
    for _ in range(steps):
        k1 = f(v)
        k2 = f([v[i] + h / 2 * k1[i] for i in range(n)])
        k3 = f([v[i] + h / 2 * k2[i] for i in range(n)])
        k4 = f([v[i] + h * k3[i] for i in range(n)])
        v = [v[i] + h / 6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(n)]
    return sum(l[i] * v[i] for i in range(n))


def test_step_response_against_simulation():
    G, Cm, b = rc_tree([-1, 0, 1, 1], [1, 2, 1, 3], [1, 1, 2, 1])
    l = unit(4, 3)
    exact = asymptotic_waveform_evaluation(G, Cm, b, l, 4)
    two = asymptotic_waveform_evaluation(G, Cm, b, l, 2)
    assert step_response(exact, 0.0) == pytest.approx(0.0, abs=1e-9)
    assert step_response(two, 0.0) == pytest.approx(0.0, abs=1e-9)
    worst = 0.0
    for t in (0.5, 2.0, 5.0, 10.0, 20.0):
        y = simulate(G, Cm, b, l, t, 4000)
        assert step_response(exact, t) == pytest.approx(y, abs=1e-8)
        worst = max(worst, abs(step_response(two, t) - y))
    assert worst < 0.02  # measured for this circuit, not a bound


def test_errors():
    G, Cm, b = rc_tree([-1], [2], [3])
    with pytest.raises(ValueError):
        asymptotic_waveform_evaluation(G, Cm, b, [1], 0)
    with pytest.raises(ValueError):
        asymptotic_waveform_evaluation(G, Cm, b, [1], 2)  # one pole only: singular Hankel matrix
    assert polyval([1, 2, 3], 2) == 17

History

Elmore (1948) used the first moment of the impulse response as the delay of an amplifier, which is the case q=1q = 1. Padé approximation of a series is much older. Pillage and Rohrer (1990) used the moments of the circuit equations to build models with qq poles for the timing analysis of interconnect, and AWE was widely used for RC and RLC delay calculation in the 1990s. The problems with stability and with conditioning led to Krylov-subspace methods such as PVL (1995) and PRIMA (1998).

References

  1. Lawrence T. Pillage and Ronald A. Rohrer, Asymptotic waveform evaluation for timing analysis, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 9(4), 352 to 366, 1990, the moment recurrence, the Padé approximation with q poles from 2q moments, the residues and the step response
  2. W. C. Elmore, The transient response of damped linear networks with particular regard to wideband amplifiers, Journal of Applied Physics 19(1), 55 to 63, 1948, the first moment of the impulse response as a delay, the one-pole case of AWE

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 correctness
  • a full proof of time.average
  • a full proof of time.best
  • 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
  • at least three sources
  • a scene preset for the example