Algorithm Search⌘K

Algorithmadvanced

Multigrid-like power grid analysis

Also called Kozhaya-Nassif-Najm multigrid.

Kozhaya, Nassif and Najm's power grid solver that reduces the mesh to a coarse grid, solves it directly and maps the answer back once, with no smoothing, for DC and transient IR drop.

Time
O(N + M^3) worst
Space
O(N + M^2) extra
Where
M = the number of nodes of the coarsest grid; N = the number of grid nodes
Properties
deterministicnot exactrecursive
Origin
Joseph N. Kozhaya, Sani R. Nassif, Farid N. Najm, 2001

The multigrid-like power grid analysis of Kozhaya, Nassif and Najm is a fast approximate solver for power grid analysis, the problem of finding the voltage drop at every node of an on-chip supply mesh. The drop xx solves Gx=iG x = i, with GG the conductance matrix of the grid and ii the load currents. The method keeps every other row and every other column of the mesh, writes each dropped node as a weighted mean of its kept neighbors with the wire conductances as weights, and solves the much smaller coarse system with a direct method. It maps the coarse answer back to the fine grid once and stops. Unlike the multigrid method, it does no smoothing and no iteration, so its answer is not exact. This page proves what it does give: the best approximation in the energy norm among all vectors that the interpolation can produce.

In plain words

A power grid on a chip is a mesh of wires with millions of crossing points. You want the voltage at each point, which means solving millions of linked equations.

This method throws away every other row and every other column of the mesh, so about a quarter of the points stay. It works out how the removed points would follow the kept ones: a removed point sits between kept points, and it follows the one it is wired to more strongly. It folds the loads of the removed points onto the kept ones, solves the small mesh exactly, and fills in the removed points from their neighbors.

It does this once. The answer is close on smooth parts of the grid and less close at sharp local peaks.

The problem

The grid is an nx×nyn_x \times n_y mesh of nodes with wires of conductance gjkg_{jk} between neighbors, pads of conductance gkpadg^{\mathrm{pad}}_k to the ideal supply at some nodes, and a load current ik≥0i_k \ge 0 drawn at each node. The drop xk=VDD−vkx_k = V_{DD} - v_k solves

Ax=b,A=G=L+diag(gpad),b=i,A x = b, \qquad A = G = \mathcal{L} + \mathrm{diag}(g^{\mathrm{pad}}), \qquad b = i,

where L\mathcal{L} is the weighted Laplacian of the wires. The power grid analysis page shows that AA is a symmetric, positive definite M-matrix when every connected part has a pad. For a transient step with the backward Euler method and step hh, the same form holds with A=G+C/hA = G + C/h and b=i(t)+(C/h)x(t−h)b = i(t) + (C/h) x(t - h), by the companion model of each capacitor. The output is xx, or an approximation of it, at every node. The method fits no parameter of its own. The conductances, capacitances and loads come from layout extraction, foundry data and power estimates, as the power grid analysis page explains.

The energy norm of a vector ee is ∥e∥A=eTAe\|e\|_A = \sqrt{e^T A e}. For a drop error ee it is the power that the error currents would spend in the wires and pads.

The algorithm

Number the node in row rr and column cc as rnx+cr n_x + c. The kept lines are the even ones and the last one, in each direction. Each fine node is in one of four classes. A K node is on a kept row and a kept column, and it maps to itself. An H node is on a kept row between two K nodes, and its weights are its conductances to them, normalized to sum to 1. A V node is the same along a column. A C node is on two dropped lines, and it takes the normalized conductance weights of its four H and V neighbors, through their own rows of PP.

  1. KNN-SOLVE(A, b, mesh, levels)
  2. 1if levels = 0 or the mesh is small then return the direct solution of A x = b
  3. 2P ← the interpolation from the kept nodes to all nodes (K, H, V and C rules)
  4. 3A_c ← Pᵀ A P; b_c ← Pᵀ b
  5. 4x_c ← KNN-SOLVE(A_c, b_c, the coarse mesh, levels − 1)
  6. 5return P x_c ▷ no smoothing
  7. TWO-GRID-VARIANT(A, b, mesh, cycles) ▷ not in the paper
  8. 6x ← KNN-SOLVE(A, b, mesh, 1)
  9. 7repeat cycles times
  10. 8one Gauss-Seidel sweep on A x = b
  11. 9r ← b − A x
  12. 10x ← x + P A_c⁻¹ Pᵀ r
  13. 11one Gauss-Seidel sweep on A x = b

Lines L1 to L5 are the method of the paper, applied over several levels. Lines L6 to L11 are a variant of this page: a standard two-grid cycle with Gauss-Seidel smoothing, which turns the one-pass answer into an iteration that converges to the exact drop. It is here to show what the missing smoothing would add.

Example

Take a 5×55 \times 5 mesh with every wire at 10 S, pads of 50 S at the four corners, and loads of 0.1 A at the center node 12 and 0.05 A at nodes 8 and 16. The kept lines are 0, 2 and 4 in each direction, so the coarse mesh is 3×33 \times 3 with the nodes 0, 2, 4, 10, 12, 14, 20, 22 and 24. All wires are equal, so node 1 (an H node) gets the weights (1/2,1/2)(1/2, 1/2) on nodes 0 and 2, and node 6 (a C node) gets 1/41/4 on each of the coarse nodes 0, 2, 10 and 12.

The drops in mV, exact on the left and after one pass on the right:

row exact one pass
0 0.919, 3.218, 4.250, 3.782, 1.081 0.900, 2.379, 3.857, 2.479, 1.100
1 3.218, 4.484, 5.750, 6.016, 3.782 2.379, 3.921, 5.464, 3.971, 2.479
2 4.250, 5.750, 8.250, 5.750, 4.250 3.857, 5.464, 7.071, 5.464, 3.857
3 3.782, 6.016, 5.750, 4.484, 3.218 2.479, 3.971, 5.464, 3.921, 2.379
4 1.081, 3.782, 4.250, 3.218, 0.919 1.100, 2.479, 3.857, 2.379, 0.900

The worst drop is 33/400033/4000 V =8.25= 8.25 mV at the center, and the one-pass answer gives 7.07 mV there. The largest error is at node 8, a C node with its own load: 3.97 mV against 6.02 mV, because line L3 spreads its load over four coarse nodes. The energy of the error is 3.22×10−43.22 \times 10^{-4} W against xTAx=1.43×10−3x^T A x = 1.43 \times 10^{-3} W. The total current through the pads is 0.2 A in both answers. On this tiny grid with point loads the one-pass error is large. The variant of lines L6 to L11 brings the largest residual down to 6.51×10−36.51 \times 10^{-3}, 3.94×10−43.94 \times 10^{-4}, 2.47×10−52.47 \times 10^{-5}, 3.81×10−63.81 \times 10^{-6}, 4.46×10−74.46 \times 10^{-7} and 6.02×10−86.02 \times 10^{-8} in six cycles. These are runs of the code of this page on this toy grid, not benchmark results.

Correctness

The proof file proves four facts. First, Ac=PTAPA_c = P^T A P is symmetric and positive definite, because PP has full column rank: each kept node maps to itself. So line L4 is well defined at every level. Second, the one-pass answer x^=Pxc\hat{x} = P x_c satisfies the Galerkin condition PTA(x−x^)=0P^T A (x - \hat{x}) = 0, so it is the vector of the form PyP y closest to the exact xx in the energy norm, and with several levels the same holds for the product of the interpolations. Third, since the error is AA-orthogonal to x^\hat{x}, the energies add up, xTAx=x^TAx^+∥x−x^∥A2x^T A x = \hat{x}^T A \hat{x} + \|x - \hat{x}\|_A^2, so the load-weighted drop bTx^b^T \hat{x} is never above the exact bTxb^T x. Fourth, the rows of PP sum to 1, so PTP^T keeps the total load, and the pad currents of the coarse answer add up to the total load, as in the example.

The proofs say nothing about the error at a single node. In the example the one-pass answer is too low at every node but two, and too high only at the corners 4 and 20. The small errors that Kozhaya, Nassif and Najm report on their grids are measured, not proved.

For the variant, each Gauss-Seidel sweep and each coarse correction never increases the energy norm of the error, and Gauss-Seidel converges for a symmetric positive definite matrix, so the variant converges to the exact drop. Its rate on a given grid is measured, not proved here.

Proof: The one-pass coarse solve is the energy-norm best approximation in the range of the interpolationfull

Setting. AA is an N×NN \times N symmetric positive definite matrix, as the conductance matrix of a power grid is when every connected part has a pad (see the power grid analysis page). The exact drop is x=A−1bx = A^{-1} b. PP is an N×NcN \times N_c matrix. The energy inner product is ⟨u,v⟩A=uTAv\langle u, v \rangle_A = u^T A v, with the norm ∥u∥A=uTAu\|u\|_A = \sqrt{u^T A u}.

Lemma 1 (PP has full column rank). The interpolation of line L2 has full column rank, and its rows sum to 1.

Proof. Each coarse node qq is a K node m(q)m(q) of the fine grid, and row m(q)m(q) of PP is the unit row eqTe_q^T. So the rows of the K nodes form the identity of size NcN_c, and Py=0P y = 0 forces y=0y = 0. For the sums: a K row sums to 1. An H or V row is a combination of K rows with nonnegative weights that sum to 1, so it sums to 1. A C row is a combination of H and V rows with weights that sum to 1, so it sums to 1. (When all weights of a node are 0, the code uses equal weights, which also sum to 1.) □\square

Lemma 2 (the coarse matrix). Ac=PTAPA_c = P^T A P is symmetric and positive definite.

Proof. AcT=PTATP=AcA_c^T = P^T A^T P = A_c. For y≠0y \ne 0, Py≠0P y \ne 0 by Lemma 1, so yTAcy=(Py)TA(Py)>0y^T A_c y = (P y)^T A (P y) > 0. □\square

So line L4 solves a nonsingular system at every level, and by induction every coarse matrix of the recursion is symmetric positive definite.

Theorem 1 (Galerkin best approximation, one level). Let xc=Ac−1PTbx_c = A_c^{-1} P^T b and x^=Pxc\hat{x} = P x_c. Then PTA(x−x^)=0P^T A (x - \hat{x}) = 0, and for every y∈RNcy \in \mathbb{R}^{N_c},

∥x−x^∥A≤∥x−Py∥A,\|x - \hat{x}\|_A \le \|x - P y\|_A,

with equality only for y=xcy = x_c.

Proof. PTAx^=Acxc=PTb=PTAxP^T A \hat{x} = A_c x_c = P^T b = P^T A x, which is the first claim. So the error e=x−x^e = x - \hat{x} is AA-orthogonal to every PzP z. For any yy, write x−Py=e+P(xc−y)x - P y = e + P(x_c - y). Then

∥x−Py∥A2=∥e∥A2+2⟨e,P(xc−y)⟩A+∥P(xc−y)∥A2=∥e∥A2+∥P(xc−y)∥A2,\|x - P y\|_A^2 = \|e\|_A^2 + 2 \langle e, P(x_c - y) \rangle_A + \|P(x_c - y)\|_A^2 = \|e\|_A^2 + \|P(x_c - y)\|_A^2,

and the last term is positive unless y=xcy = x_c, by Lemma 1. □\square

Theorem 2 (several levels). Let the recursion use the interpolations P1,P2,…,PℓP_1, P_2, \ldots, P_\ell, end with an exact solve at line L1, and let Q=P1P2⋯PℓQ = P_1 P_2 \cdots P_\ell. Then the answer of line L5 at the top is x^=Q(QTAQ)−1QTb\hat{x} = Q (Q^T A Q)^{-1} Q^T b, and Theorem 1 holds with QQ in place of PP.

Proof. By induction on ℓ\ell. For ℓ=0\ell = 0, Q=IQ = I and the answer is A−1bA^{-1} b. For ℓ≥1\ell \ge 1, the call at line L4 works on A1=P1TAP1A_1 = P_1^T A P_1 and b1=P1Tbb_1 = P_1^T b with the interpolations P2,…,PℓP_2, \ldots, P_\ell, so by the induction hypothesis it returns Q′(Q′TA1Q′)−1Q′Tb1Q' (Q'^T A_1 Q')^{-1} Q'^T b_1 with Q′=P2⋯PℓQ' = P_2 \cdots P_\ell. Line L5 multiplies by P1P_1. Since Q=P1Q′Q = P_1 Q', we get Q′TA1Q′=QTAQQ'^T A_1 Q' = Q^T A Q and Q′Tb1=QTbQ'^T b_1 = Q^T b, so the answer is Q(QTAQ)−1QTbQ (Q^T A Q)^{-1} Q^T b. QQ has full column rank as a product of matrices with full column rank, so the proof of Theorem 1 applies with QQ. □\square

Corollary 1 (energy split and low average). xTAx=x^TAx^+∥x−x^∥A2x^T A x = \hat{x}^T A \hat{x} + \|x - \hat{x}\|_A^2, and bTx^≤bTxb^T \hat{x} \le b^T x, with equality only when x^=x\hat{x} = x.

Proof. x^=Qy\hat{x} = Q y for some yy, and x−x^x - \hat{x} is AA-orthogonal to it, so the first identity is the Pythagorean theorem in the energy inner product. From QTA(x−x^)=0Q^T A (x - \hat{x}) = 0 we get x^TAx^=x^TAx=x^Tb\hat{x}^T A \hat{x} = \hat{x}^T A x = \hat{x}^T b, and xTAx=xTbx^T A x = x^T b. So bTx−bTx^=∥x−x^∥A2≥0b^T x - b^T \hat{x} = \|x - \hat{x}\|_A^2 \ge 0. □\square

Corollary 2 (exact cases). x^=x\hat{x} = x if and only if xx is in the range of QQ.

Proof. If x=Qyx = Q y, then Theorem 1 gives ∥x−x^∥A≤∥x−Qy∥A=0\|x - \hat{x}\|_A \le \|x - Q y\|_A = 0. The converse is clear. □\square

Corollary 3 (the total load). The total coarse load equals the total fine load, 1TPTb=1Tb\mathbf{1}^T P^T b = \mathbf{1}^T b, and the pad currents of x^\hat{x} add up to the total load.

Proof. P1=1P \mathbf{1} = \mathbf{1} by Lemma 1, so 1TPTb=(P1)Tb=1Tb\mathbf{1}^T P^T b = (P \mathbf{1})^T b = \mathbf{1}^T b. For the pad currents: A=L+diag(gpad)A = \mathcal{L} + \mathrm{diag}(g^{\mathrm{pad}}) with L1=0\mathcal{L} \mathbf{1} = 0, so the total pad current of a drop vector zz is ∑kgkpadzk=1TAz\sum_k g^{\mathrm{pad}}_k z_k = \mathbf{1}^T A z. Since 1=Q1\mathbf{1} = Q \mathbf{1} is in the range of QQ, the Galerkin condition gives 1TAx^=1TAx=1Tb\mathbf{1}^T A \hat{x} = \mathbf{1}^T A x = \mathbf{1}^T b. □\square

Theorem 3 (the variant never increases the energy error and converges). In lines L6 to L11, let e=x−xcurrente = x - x_{\text{current}}. Each Gauss-Seidel sweep and each coarse correction of line L10 gives ∥enew∥A≤∥e∥A\|e_{\text{new}}\|_A \le \|e\|_A, and the iterates converge to xx.

Proof. Coarse correction: the new error is e−PAc−1PTAe=(I−Π)ee - P A_c^{-1} P^T A e = (I - \Pi) e, where Π=PAc−1PTA\Pi = P A_c^{-1} P^T A is the AA-orthogonal projection onto the range of PP. By the Pythagorean theorem, ∥e∥A2=∥Πe∥A2+∥(I−Π)e∥A2\|e\|_A^2 = \|\Pi e\|_A^2 + \|(I - \Pi) e\|_A^2, so the norm does not grow.

Gauss-Seidel: one update of coordinate kk sets xkx_k so that equation kk holds. Among all changes of coordinate kk alone, this one minimizes ∥x−xcurrent∥A2\|x - x_{\text{current}}\|_A^2, because that quadratic in the new value of xkx_k has the derivative −2(Ae)k-2 (A e)_k, which vanishes exactly when equation kk holds. The old value is one of the candidates, so the norm does not grow. A sweep is NN such updates.

Convergence: for a symmetric positive definite AA, the forward Gauss-Seidel iteration matrix MM satisfies ∥M∥A<1\|M\|_A < 1, the classical theorem of Reich and Ostrowski on the Gauss-Seidel method. So each cycle multiplies ∥e∥A\|e\|_A by at most ∥M∥A2<1\|M\|_A^2 < 1, with the coarse correction in between not increasing it, and e→0e \to 0. □\square

The rate ∥M∥A2\|M\|_A^2 can be close to 1 on a large grid, and the coarse correction is what makes the measured rate fast. How fast it is on a given grid is measured, not proved here. The tests check Theorem 1 exactly in rational arithmetic for one and two levels, compare x^\hat{x} with random coarse vectors, check Corollary 2 on a uniform line, and check that the energy error of the variant never grows.

Complexity

Each row of PP has at most 4 nonzeros, and the coarse matrices keep a bounded number of nonzeros per row, so lines L2 and L3 cost O(N)O(N) on the fine grid, and each level has about a quarter of the nodes of the one above it. The total over all levels is O(N)O(N), plus the direct solve on the coarsest grid with MM nodes, O(M3)O(M^3) by dense elimination and less by a sparse Cholesky decomposition. The space is O(N)O(N) for the matrices and O(M2)O(M^2) for a dense coarse factor. The code of this page uses dense matrices for clarity, so it is slower than these bounds. A transient run factors the coarse matrix once, when hh is fixed, and pays O(N)O(N) plus two triangular solves per time step.

Properties

  • Approximate. The answer is exact only when the exact drop lies in the range of PP, as for a uniform line of nodes with loads and pads only at kept nodes, where each dropped node is the mean of its two neighbors.
  • Best in energy, proved. No vector of the form PyP y is closer to the exact drop in the energy norm.
  • Low on average, proved. The load-weighted drop of the answer is at most the exact one. A single node can be too high or too low.
  • Keeps the total current, proved. The rows of PP sum to 1, so the total load is the same on every level.
  • Direct. There is no iteration and no tolerance to set. The cost is fixed by the grid size and the number of levels.
  • Measured accuracy. Kozhaya, Nassif and Najm report, for their industrial design C1 in a 0.18 µm process at 1.8 V, a drop error with a mean of −0.0077%-0.0077\% and a standard deviation of 0.0333%0.0333\%, and a speedup of 16 to 20 times over their reference solver. These are measurements on their grids.

Variants and improvements

  • Smoothing and iteration. Lines L6 to L11 add Gauss-Seidel sweeps and repeated coarse corrections. With several levels this is the V-cycle of the multigrid method, and it converges to the exact answer, at the cost of several passes.
  • Algebraic coarsening. Algebraic multigrid chooses the coarse nodes and the weights from the matrix alone, with no mesh. It fits grids with irregular wires, vias between layers and missing segments, where the row and column rule fails.
  • Multigrid as a preconditioner. One V-cycle per step as a preconditioner of the conjugate gradient method gives an exact solver whose number of steps grows slowly with the grid size. Many later power grid solvers use this form.
  • Other fast solvers. The random walk method finds the drop at a few nodes without solving for the rest. Vectorless verification bounds the worst drop over a set of possible loads.

When to use it

Use it for a fast first look at the IR drop of a large, regular mesh, in early design or inside a loop that tries many grid sizes, where an error of a few percent of the drop is fine. Use a direct sparse solver or a preconditioned iterative solver for sign-off, and add the smoothing of the variant when the point loads matter.

Pitfalls

  • Loads at dropped nodes. Line L3 spreads the load of a dropped node over its kept neighbors, and line L5 cannot bring back the local peak. In the example the error is worst at the loaded C nodes. Keep nodes with large loads in the coarse grid, or smooth.
  • Irregular grids. The rule of every other row and column assumes a full mesh. A missing wire or a via stack breaks it, and a node can end up with no kept neighbor. The code falls back to equal weights when the weights sum to 0, which is not a physical choice.
  • A part with no pad. Then AA is singular, and so is AcA_c. Check that every connected part of the grid reaches a pad.
  • Taking the energy bound for a node bound. The proofs bound an average error. The worst node, which is what sign-off needs, can be off by much more.

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.

multigrid_power_grid_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multigrid-power-grid-analysis/. The authors are listed in prov/C6B46K.jsonl.
"""Multigrid-like power grid analysis after Kozhaya, Nassif and Najm (2002).

The fine grid is a mesh of nx by ny nodes with the matrix A = G of the drop
equations A x = b. One reduction keeps every other row and every other column
(and the last ones). A dropped node takes its value from its kept neighbors,
with weights that are the conductances to them. This gives the interpolation
matrix P. The coarse system is A_c = P^T A P, b_c = P^T b. The reduction is
applied again to the coarse system, a dense direct solve ends the recursion,
and x = P x_c maps the answer back. There is no smoothing in this one-pass
method.

two_grid_iterate is NOT the method of the paper. It is a variant of this page
that adds Gauss-Seidel sweeps and repeats the coarse correction, so that the
answer converges to the exact solution.
"""

from __future__ import annotations

from typing import Dict, List, Optional, Sequence, Tuple

from pgrid import matmul, matvec, solve, transpose


def kept_lines(n: int) -> List[int]:
    """Indices of the lines that stay: every other one, and the last one."""
    return sorted(set(range(0, n, 2)) | {n - 1})


def prolongation(a: Sequence[Sequence[object]], shape: Tuple[int, int]):
    """Interpolation matrix P (fine by coarse) and the coarse shape.

    Classes of fine nodes: K is on a kept row and a kept column; H is on a
    kept row between two K nodes; V is on a kept column between two K nodes;
    C is on two dropped lines and takes its value from its four H and V
    neighbors. The weight of neighbor j of node m is the conductance -a[m][j].
    """
    nx, ny = shape
    kc, kr = kept_lines(nx), kept_lines(ny)
    col_of = {c: i for i, c in enumerate(kc)}
    row_of = {r: i for i, r in enumerate(kr)}
    ncx = len(kc)
    zero = a[0][0] * 0
    one = zero + 1
    rows: Dict[int, Dict[int, object]] = {}

    def at(r: int, c: int) -> int:
        return r * nx + c

    def blend(m: int, nbrs: List[int]) -> Dict[int, object]:
        ws = [max(-a[m][j], zero) for j in nbrs]
        tot = sum(ws, zero)
        if tot == 0:
            ws, tot = [one] * len(nbrs), one * len(nbrs)
        out: Dict[int, object] = {}
        for j, w in zip(nbrs, ws):
            for q, p in rows[j].items():
                out[q] = out.get(q, zero) + w * p / tot
        return out

    for r in kr:  # @line L2: kept nodes map to themselves
        for c in kc:
            rows[at(r, c)] = {row_of[r] * ncx + col_of[c]: one}
    for r in kr:  # H nodes: v_m = (g_mA v_A + g_mB v_B) / (g_mA + g_mB)
        for c in range(nx):
            if c not in col_of:
                rows[at(r, c)] = blend(at(r, c), [at(r, c - 1), at(r, c + 1)])
    for r in range(ny):  # V nodes, the same rule along the column
        if r not in row_of:
            for c in kc:
                rows[at(r, c)] = blend(at(r, c), [at(r - 1, c), at(r + 1, c)])
    for r in range(ny):  # C nodes, from their four H and V neighbors
        if r not in row_of:
            for c in range(nx):
                if c not in col_of:
                    nb = [at(r, c - 1), at(r, c + 1), at(r - 1, c), at(r + 1, c)]
                    rows[at(r, c)] = blend(at(r, c), nb)
    nc = ncx * len(kr)
    p = [[zero] * nc for _ in range(nx * ny)]
    for m, row in rows.items():
        for q, w in row.items():
            p[m][q] = w
    return p, (ncx, len(kr))


def knn_solve_with_basis(a, b, shape: Tuple[int, int], levels: int, min_size: int = 4):
    """One-pass multigrid-like solve. Returns x and the composite P of all levels."""
    n = len(b)
    nx, ny = shape
    if levels == 0 or n <= min_size or (len(kept_lines(nx)) == nx and len(kept_lines(ny)) == ny):
        zero = a[0][0] * 0
        ident = [[zero + (1 if i == j else 0) for j in range(n)] for i in range(n)]
        return solve(a, b), ident  # @line L1: a direct solve ends the recursion
    p, cshape = prolongation(a, shape)  # @line L2
    pt = transpose(p)
    ac = matmul(matmul(pt, a), p)  # @line L3: A_c = P^T A P
    bc = matvec(pt, b)  # @line L3: b_c = P^T b
    xc, pc = knn_solve_with_basis(ac, bc, cshape, levels - 1, min_size)  # @line L4
    return matvec(p, xc), matmul(p, pc)  # @line L5: x = P x_c, no smoothing


def knn_solve(a, b, shape: Tuple[int, int], levels: int, min_size: int = 4):
    """The one-pass answer x = P x_c."""
    return knn_solve_with_basis(a, b, shape, levels, min_size)[0]


def energy_error(a, x_exact, x) -> object:
    """||x_exact - x||_A squared, that is e^T A e."""
    e = [u - v for u, v in zip(x_exact, x)]
    ae = matvec(a, e)
    return sum((u * v for u, v in zip(e, ae)), e[0] * 0)


def gauss_seidel(a, b, x, sweeps: int):
    """Forward Gauss-Seidel sweeps, in place."""
    n = len(b)
    for _ in range(sweeps):
        for k in range(n):
            s = b[k]
            for j in range(n):
                if j != k and a[k][j] != 0:
                    s = s - a[k][j] * x[j]
            x[k] = s / a[k][k]
    return x


def two_grid_iterate(a, b, shape, cycles: int, sweeps: int = 1, x0: Optional[list] = None):
    """VARIANT, not in the paper: smoothing plus repeated coarse correction.

    Returns x and the list of residual norms max |b - A x| after each cycle.
    """
    p, _ = prolongation(a, shape)
    pt = transpose(p)
    ac = matmul(matmul(pt, a), p)
    x = list(x0) if x0 is not None else knn_solve(a, b, shape, 1)  # @line L6
    hist = []
    for _ in range(cycles):  # @line L7
        gauss_seidel(a, b, x, sweeps)  # @line L8
        r = [bi - ai for bi, ai in zip(b, matvec(a, x))]  # @line L9
        ec = solve(ac, matvec(pt, r))  # @line L10
        x = [xi + di for xi, di in zip(x, matvec(p, ec))]  # @line L10
        gauss_seidel(a, b, x, sweeps)  # @line L11
        hist.append(max(abs(bi - ai) for bi, ai in zip(b, matvec(a, x))))
    return x, hist
pgrid.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pr2 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Resistive power grids in drop form, and a dense direct solver.

A grid has nodes 0 .. N-1. Each wire between nodes a and b has a conductance
g > 0. A node k can have a pad conductance gpad[k] > 0 to the ideal supply,
and a load current cur[k] >= 0 that it draws to ground. With the drop
x = VDD - v, Kirchhoff's current law gives G x = cur with G = L + diag(gpad),
where L is the weighted Laplacian of the wires.

This module builds grids and matrices and solves dense systems by Gaussian
elimination. It works with float or with fractions.Fraction. It holds no
power grid analysis method of the pr2 pages.
"""

from __future__ import annotations

import random
from fractions import Fraction
from typing import Callable, Dict, List, Optional, Sequence, Tuple


class Grid:
    """Wires as adjacency lists, pad conductances and load currents."""

    def __init__(self, n: int):
        self.n = n
        self.adj: List[Dict[int, object]] = [dict() for _ in range(n)]
        self.gpad: List[object] = [0] * n
        self.cur: List[object] = [0] * n
        self.shape: Optional[Tuple[int, int]] = None

    def add_wire(self, a: int, b: int, g) -> None:
        if a == b or g <= 0:
            raise ValueError("a wire joins two different nodes with g > 0")
        self.adj[a][b] = self.adj[a].get(b, 0) + g
        self.adj[b][a] = self.adj[b].get(a, 0) + g

    def degree(self, k: int):
        """D_k: the sum of all conductances at node k, pad included."""
        return sum(self.adj[k].values()) + self.gpad[k]

    def matrix(self) -> List[List[object]]:
        """The dense matrix G = L + diag(gpad)."""
        zero = self.gpad[0] * 0
        a = [[zero] * self.n for _ in range(self.n)]
        for k in range(self.n):
            a[k][k] = self.degree(k)
            for j, g in self.adj[k].items():
                a[k][j] = a[k][j] - g
        return a

    def every_part_has_a_pad(self) -> bool:
        """True when each connected part of the wire graph holds a pad."""
        seen = [False] * self.n
        for s in range(self.n):
            if seen[s]:
                continue
            stack, part = [s], []
            seen[s] = True
            while stack:
                k = stack.pop()
                part.append(k)
                for j in self.adj[k]:
                    if not seen[j]:
                        seen[j] = True
                        stack.append(j)
            if not any(self.gpad[k] > 0 for k in part):
                return False
        return True


def mesh(
    nx: int,
    ny: int,
    g_h: Callable[[int, int], object],
    g_v: Callable[[int, int], object],
    pads: Dict[int, object],
    cur: Sequence[object],
) -> Grid:
    """An nx by ny mesh. Node (r, c) has the index r * nx + c.

    g_h(r, c) is the wire from (r, c) to (r, c + 1), and g_v(r, c) the wire
    from (r, c) to (r + 1, c).
    """
    grid = Grid(nx * ny)
    grid.shape = (nx, ny)
    for r in range(ny):
        for c in range(nx):
            k = r * nx + c
            if c + 1 < nx:
                grid.add_wire(k, k + 1, g_h(r, c))
            if r + 1 < ny:
                grid.add_wire(k, k + nx, g_v(r, c))
    for k, g in pads.items():
        grid.gpad[k] = g
    grid.cur = list(cur)
    return grid


def random_mesh(nx: int, ny: int, rng: random.Random, exact: bool = True, n_pads: int = 2) -> Grid:
    """A mesh with conductances in {1, ..., 5}, a few pads and loads in {0, ..., 4}."""
    num = Fraction if exact else float
    gh = {(r, c): num(rng.randint(1, 5)) for r in range(ny) for c in range(nx)}
    gv = {(r, c): num(rng.randint(1, 5)) for r in range(ny) for c in range(nx)}
    n = nx * ny
    pads = {k: num(rng.randint(2, 8)) for k in rng.sample(range(n), min(n_pads, n))}
    cur = [num(rng.randint(0, 4)) for _ in range(n)]
    return mesh(nx, ny, lambda r, c: gh[(r, c)], lambda r, c: gv[(r, c)], pads, cur)


def solve(a: Sequence[Sequence[object]], b: Sequence[object]) -> List[object]:
    """Solve a x = b by Gaussian elimination with partial pivoting."""
    n = len(b)
    m = [list(row) + [b[i]] for i, row in enumerate(a)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(m[r][col]))
        if m[piv][col] == 0:
            raise ZeroDivisionError("singular matrix")
        m[col], m[piv] = m[piv], m[col]
        p = m[col][col]
        for r in range(col + 1, n):
            f = m[r][col] / p
            if f != 0:
                row, top = m[r], m[col]
                for c in range(col, n + 1):
                    row[c] = row[c] - f * top[c]
    x = [m[0][0] * 0] * n
    for r in range(n - 1, -1, -1):
        s = m[r][n]
        for c in range(r + 1, n):
            s = s - m[r][c] * x[c]
        x[r] = s / m[r][r]
    return x


def matvec(a: Sequence[Sequence[object]], x: Sequence[object]) -> List[object]:
    return [sum((row[j] * x[j] for j in range(len(x))), x[0] * 0) for row in a]


def transpose(a: Sequence[Sequence[object]]) -> List[List[object]]:
    return [list(col) for col in zip(*a)]


def matmul(a: Sequence[Sequence[object]], b: Sequence[Sequence[object]]) -> List[List[object]]:
    bt = transpose(b)
    zero = a[0][0] * 0
    out = []
    for row in a:
        nz = [(j, v) for j, v in enumerate(row) if v != 0]
        out.append([sum((v * col[j] for j, v in nz), zero) for col in bt])
    return out
test_multigrid_power_grid_analysis.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multigrid-power-grid-analysis/. The authors are listed in prov/C6B46K.jsonl.

import random
from fractions import Fraction

from multigrid_power_grid_analysis import (
    energy_error,
    kept_lines,
    knn_solve,
    knn_solve_with_basis,
    prolongation,
    two_grid_iterate,
)
from pgrid import matmul, matvec, mesh, random_mesh, solve, transpose


def test_kept_lines():
    assert kept_lines(5) == [0, 2, 4]
    assert kept_lines(4) == [0, 2, 3]
    assert kept_lines(1) == [0]


def test_rows_of_p_sum_to_one_and_are_nonnegative():
    rng = random.Random(1)
    for nx, ny in [(5, 5), (4, 6), (7, 3)]:
        g = random_mesh(nx, ny, rng)
        p, cshape = prolongation(g.matrix(), (nx, ny))
        assert len(p[0]) == cshape[0] * cshape[1]
        for row in p:
            assert sum(row) == 1
            assert all(w >= 0 for w in row)


def test_h_node_weights_are_conductance_ratios():
    # 3 by 1 line: node 1 sits between the kept nodes 0 and 2.
    g = mesh(3, 1, lambda r, c: Fraction([2, 6][c]), lambda r, c: Fraction(1), {0: Fraction(5)}, [0, 0, 0])
    p, _ = prolongation(g.matrix(), (3, 1))
    assert p[1] == [Fraction(2, 8), Fraction(6, 8)]


def test_galerkin_orthogonality_exact():
    # P^T A (x - P x_c) = 0 exactly, for one level and for several levels.
    rng = random.Random(2)
    for nx, ny, levels in [(5, 5, 1), (5, 5, 2), (7, 5, 2), (4, 4, 1)]:
        g = random_mesh(nx, ny, rng)
        a, b = g.matrix(), g.cur
        x = solve(a, b)
        y, p = knn_solve_with_basis(a, b, (nx, ny), levels)
        e = [u - v for u, v in zip(x, y)]
        assert matvec(transpose(p), matvec(a, e)) == [0] * len(p[0])


def test_one_pass_is_the_best_coarse_answer_in_energy_norm():
    rng = random.Random(3)
    for _ in range(6):
        g = random_mesh(5, 5, rng)
        a, b = g.matrix(), g.cur
        x = solve(a, b)
        y, p = knn_solve_with_basis(a, b, (5, 5), 1)
        best = energy_error(a, x, y)
        for _ in range(20):
            z = [Fraction(rng.randint(-20, 20), 4) for _ in range(len(p[0]))]
            pz = matvec(p, z)
            assert energy_error(a, x, pz) >= best
        # The coarse nodes are only part of the fine nodes, so the answer is not exact in general.
        assert energy_error(a, x, y) >= 0


def test_exact_when_the_solution_is_in_the_range_of_p():
    # A uniform line with a pad at node 0 and a load only at the far end:
    # the drop is linear in the distance, and linear interpolation is exact.
    n = 9
    cur = [Fraction(0)] * n
    cur[-1] = Fraction(3)
    g = mesh(n, 1, lambda r, c: Fraction(2), lambda r, c: Fraction(1), {0: Fraction(4)}, cur)
    a = g.matrix()
    assert knn_solve(a, cur, (n, 1), 3) == solve(a, cur)


def test_float_mesh_close_to_direct():
    rng = random.Random(4)
    g = random_mesh(9, 9, rng, exact=False, n_pads=4)
    a, b = g.matrix(), g.cur
    x = solve(a, b)
    y = knn_solve(a, b, (9, 9), 2)
    assert max(abs(u - v) for u, v in zip(x, y)) < max(x)


def test_variant_converges_to_the_direct_solution():
    rng = random.Random(5)
    g = random_mesh(9, 9, rng, exact=False, n_pads=3)
    a, b = g.matrix(), g.cur
    x = solve(a, b)
    y, hist = two_grid_iterate(a, b, (9, 9), cycles=20, sweeps=1)
    assert max(abs(u - v) for u, v in zip(x, y)) < 1e-8
    assert all(h2 <= h1 * 1.0000001 for h1, h2 in zip(hist, hist[1:]))


def test_variant_energy_error_never_grows():
    rng = random.Random(6)
    g = random_mesh(7, 7, rng)
    a, b = g.matrix(), g.cur
    x = solve(a, b)
    y = knn_solve(a, b, (7, 7), 1)
    prev = energy_error(a, x, y)
    for _ in range(3):
        y, _ = two_grid_iterate(a, b, (7, 7), cycles=1, sweeps=1, x0=y)
        cur = energy_error(a, x, y)
        assert cur <= prev
        prev = cur

History

Power grids grew to millions of nodes around 2000, and direct solvers ran out of memory. Kozhaya, Nassif and Najm (2001, 2002) borrowed the coarse grid and the interpolation of geometric multigrid, used one coarse solve without the smoothing loop, and showed small errors on industrial grids, both for DC and for transient analysis. Other fast methods followed within two years: the random walk solver of Qian, Nassif and Sapatnekar (2003), the vectorless bounds of Kouroussis and Najm (2003), and algebraic multigrid and preconditioned solvers for grids with irregular structure.

References

  1. Joseph N. Kozhaya, Sani R. Nassif and Farid N. Najm, A multigrid-like technique for power grid analysis, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 21(10), 1148 to 1160, October 2002, the grid reduction, the interpolation of the dropped nodes by their conductances, the coarse solve, the mapping back, the transient form, and the measured accuracy and speed on industrial grids
  2. Joseph N. Kozhaya, Sani R. Nassif and Farid N. Najm, Multigrid-like technique for power grid analysis, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design, 480 to 487, November 2001, the conference version of the method
  3. William L. Briggs, Van Emden Henson and Steve F. McCormick, A Multigrid Tutorial, 2nd edition, SIAM, 2000, the chapters on the two-grid correction scheme, the variational properties of the Galerkin coarse operator, and the energy norm

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