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.
- Solves
- Power grid analysis
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactrecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 solves , with the conductance matrix of the grid and 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 mesh of nodes with wires of conductance between neighbors, pads of conductance to the ideal supply at some nodes, and a load current drawn at each node. The drop solves
where is the weighted Laplacian of the wires. The power grid analysis page shows that 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 , the same form holds with and , by the companion model of each capacitor. The output is , 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 is . For a drop error it is the power that the error currents would spend in the wires and pads.
The algorithm
Number the node in row and column as . 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 .
KNN-SOLVE(A, b, mesh, levels)- 1
if levels = 0 or the mesh is small then return the direct solution of A x = b - 2
P ← the interpolation from the kept nodes to all nodes (K, H, V and C rules) - 3
A_c ← Pᵀ A P; b_c ← Pᵀ b - 4
x_c ← KNN-SOLVE(A_c, b_c, the coarse mesh, levels − 1) - 5
return P x_c ▷ no smoothing TWO-GRID-VARIANT(A, b, mesh, cycles) ▷ not in the paper- 6
x ← KNN-SOLVE(A, b, mesh, 1) - 7
repeat cycles times - 8
one Gauss-Seidel sweep on A x = b - 9
r ← b − A x - 10
x ← x + P A_c⁻¹ Pᵀ r - 11
one 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 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 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 on nodes 0 and 2, and node 6 (a C node) gets 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 V 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 W against 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 , , , , and 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, is symmetric and positive definite, because has full column rank: each kept node maps to itself. So line L4 is well defined at every level. Second, the one-pass answer satisfies the Galerkin condition , so it is the vector of the form closest to the exact in the energy norm, and with several levels the same holds for the product of the interpolations. Third, since the error is -orthogonal to , the energies add up, , so the load-weighted drop is never above the exact . Fourth, the rows of sum to 1, so 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. is an 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 . is an matrix. The energy inner product is , with the norm .
Lemma 1 ( has full column rank). The interpolation of line L2 has full column rank, and its rows sum to 1.
Proof. Each coarse node is a K node of the fine grid, and row of is the unit row . So the rows of the K nodes form the identity of size , and forces . 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.)
Lemma 2 (the coarse matrix). is symmetric and positive definite.
Proof. . For , by Lemma 1, so .
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 and . Then , and for every ,
with equality only for .
Proof. , which is the first claim. So the error is -orthogonal to every . For any , write . Then
and the last term is positive unless , by Lemma 1.
Theorem 2 (several levels). Let the recursion use the interpolations , end with an exact solve at line L1, and let . Then the answer of line L5 at the top is , and Theorem 1 holds with in place of .
Proof. By induction on . For , and the answer is . For , the call at line L4 works on and with the interpolations , so by the induction hypothesis it returns with . Line L5 multiplies by . Since , we get and , so the answer is . has full column rank as a product of matrices with full column rank, so the proof of Theorem 1 applies with .
Corollary 1 (energy split and low average). , and , with equality only when .
Proof. for some , and is -orthogonal to it, so the first identity is the Pythagorean theorem in the energy inner product. From we get , and . So .
Corollary 2 (exact cases). if and only if is in the range of .
Proof. If , then Theorem 1 gives . The converse is clear.
Corollary 3 (the total load). The total coarse load equals the total fine load, , and the pad currents of add up to the total load.
Proof. by Lemma 1, so . For the pad currents: with , so the total pad current of a drop vector is . Since is in the range of , the Galerkin condition gives .
Theorem 3 (the variant never increases the energy error and converges). In lines L6 to L11, let . Each Gauss-Seidel sweep and each coarse correction of line L10 gives , and the iterates converge to .
Proof. Coarse correction: the new error is , where is the -orthogonal projection onto the range of . By the Pythagorean theorem, , so the norm does not grow.
Gauss-Seidel: one update of coordinate sets so that equation holds. Among all changes of coordinate alone, this one minimizes , because that quadratic in the new value of has the derivative , which vanishes exactly when equation holds. The old value is one of the candidates, so the norm does not grow. A sweep is such updates.
Convergence: for a symmetric positive definite , the forward Gauss-Seidel iteration matrix satisfies , the classical theorem of Reich and Ostrowski on the Gauss-Seidel method. So each cycle multiplies by at most , with the coarse correction in between not increasing it, and .
The rate 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 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 has at most 4 nonzeros, and the coarse matrices keep a bounded number of nonzeros per row, so lines L2 and L3 cost 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 , plus the direct solve on the coarsest grid with nodes, by dense elimination and less by a sparse Cholesky decomposition. The space is for the matrices and 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 is fixed, and pays plus two triangular solves per time step.
Properties
- Approximate. The answer is exact only when the exact drop lies in the range of , 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 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 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 and a standard deviation of , 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 is singular, and so is . 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag C6B46K Edit this page History Report an error Markdown