Algorithmadvanced
Random walk power grid analysis
Also called Qian-Nassif-Sapatnekar random walk.
Qian, Nassif and Sapatnekar's solver that estimates the drop at one node as the mean reward of random walks on the grid's conductance graph, an unbiased estimate that is fast for local queries.
- Solves
- Power grid analysis
- Time
- O(N + E + W S log d) expected
- Space
- O(N + E) extra
- Where
- E = the number of wires; N = the number of grid nodes; S = the mean number of steps of a walk; W = the number of walks; d = the largest number of wires at a node
- Model
- Word RAM
- Properties
- randomizednot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Haifeng Qian, Sani R. Nassif, Sachin S. Sapatnekar, 2003
Random walk power grid analysis estimates the voltage drop at one node of an on-chip power grid by the mean payoff of random walks. A walker starts at the node. At each node it collects a reward equal to the load current there divided by the total conductance at the node, and then it either moves along a wire, with probability proportional to the wire's conductance, or stops at the supply through a pad. The expected total reward of a walk is exactly the drop at the start node, so the mean over many walks is an unbiased estimate whose error shrinks as one over the square root of the number of walks. Qian, Nassif and Sapatnekar (2003, 2005) used it to answer queries about a few nodes of a grid with millions of nodes, without solving for all of them. It is the power grid analysis form of a Monte Carlo method, close in spirit to the floating random walk of capacitance extraction.
In plain words
Picture a walker on the grid of wires. It starts at the node you care about. At each node it picks up a coin worth the load current there, scaled down by how well that node is wired. Then it picks a wire at random, a thick wire more often than a thin one, and walks along it. Sometimes it picks the pad instead, which leads to the supply, and then the walk ends.
Add up the coins of one walk. Do this for many walks and take the mean. That mean is the voltage drop at the start node. A node close to a pad has short walks and a small drop. A node far from the pads, among heavy loads, has long walks with many coins.
The problem
The grid is in drop form, as on the power grid analysis page: with , where is the Laplacian of the wire conductances , is the conductance from node to the ideal supply, is the load current at , and is the drop. Every connected part of the grid has a pad. The input is the grid and one node , and the output is an estimate of with a measure of its error. The method fits no parameter of its own. The conductances and loads come from layout extraction, foundry data and power estimates, as the power grid analysis page explains, and the estimate is only as good as they are.
Let be the total conductance at . Row of , divided by , reads
The weights and are nonnegative and sum to 1, so they are the step probabilities of a walk, and the supply is a stopping state with drop 0. This identity is the discrete harmonic property of the grid with sources.
The algorithm
RANDOM-WALK-DROP(grid, k, W)- 1
s ← 0 - 2
repeat W times - 3
m ← k; R ← 0 - 4
loop - 5
R ← R + i_m / D_m ▷ the reward of this visit - 6
with probability g^pad_m / D_m stop the walk - 7
otherwise move to a neighbor j with probability g_mj / D_m - 8
s ← s + R - 9
return s / W, and the standard error from the sample variance of R
The tables of line L7, one cumulative list of per node, are built once, and each step picks a neighbor by a binary search on a uniform number. A walk that starts at a node of a part with no pad would never stop, so the code checks that every part has a pad before it starts.
Example
Take a chain of 3 nodes: node 0 has a pad of 20 S, the wires 0 to 1 and 1 to 2 have 10 S each, and the loads are 0.2 A at node 1 and 0.3 A at node 2. Then , and the rewards are V. By hand: all 0.5 A flows through the pad, so V. Wire 0 to 1 carries 0.5 A, so V. Wire 1 to 2 carries 0.3 A, so V.
From node 2 the walker always moves to node 1. From node 1 it moves to node 0 or node 2 with probability 1/2 each. From node 0 it moves to node 1 with probability 1/3 and stops with probability 2/3. With the seed 2024, the first three walks from node 2 are with reward , then twice, with reward each. The walks vary a lot, but their mean is right:
| walks | estimate of (V) | standard error (V) |
|---|---|---|
| 100 | 0.1188 | 0.0093 |
| 1000 | 0.10832 | 0.00272 |
| 10 000 | 0.104211 | 0.000814 |
| 100 000 | 0.104914 | 0.000259 |
The exact value is 0.105. The exact standard deviation of one walk's reward is V, and the standard errors follow . A walk from node 2 makes 7 visits and 6 steps on average. The table comes from the code of this page with Python's generator and the seed 1. It is a toy grid, and these are not benchmark results.
Correctness
The proof file proves that the walk stops with probability 1 and that the expected reward of a walk from is exactly . The step matrix with has rows that sum to at most 1, and from every node some path reaches a node with a pad, so and the spectral radius of is below 1. The expected reward is with , and since , this is . The number of visits has a geometric tail, so the reward has a finite variance. The estimate is therefore unbiased, it converges to by the law of large numbers, and by the central limit theorem the interval of two standard errors on each side covers about 95% of the time when is large.
What is not proved is the number of walks a real grid needs for a given error. It depends on the variance of the reward, which grows with the length of the walks, and it is measured.
Proof: The expected reward of a walk is the drop at its start nodefull
Setting. The grid has nodes , wire conductances , pad conductances and loads . Every connected part of the wire graph has a node with , and every node has . The drop solves with and for ; the power grid analysis page shows that is nonsingular. Let , let , and let , so that .
The walk of lines L3 to L7 is a Markov chain on the nodes plus one stopping state . From node it moves to with probability and to with probability . Let be the nodes visited and the number of node visits before . The reward is .
Lemma 1 (the walk stops). There are and such that from every node the walk reaches within steps with probability at least . Hence , the walk stops with probability 1, and has finite moments of every order.
Proof. From node , take a shortest path of wires to a node with a pad, of length at most , and then the step to . Each step of this path has positive probability, so the probability of following it is positive. Let and . The bound on follows by the Markov property, applied at the times . A geometric tail gives finite moments.
Lemma 2 (spectral radius). as , so , is nonsingular, and with nonnegative entries.
Proof. is the probability that the walk from is at node at step without having stopped, which is at most , and this tends to 0 by Lemma 1. A matrix whose powers tend to 0 has spectral radius below 1, and then the Neumann series converges to .
Theorem 1 (unbiased). .
Proof. All rewards are nonnegative, so we may exchange the sum and the expectation:
by Lemma 2. Now .
Theorem 2 (discrete harmonic property). For every node , , and is the only vector with this property.
Proof. The identity is row of divided by . It can be read as a first-step analysis: the walk from collects and then, with probability , starts afresh at , or stops with payoff 0. The system has the unique solution by Lemma 2.
Theorem 3 (finite variance). . So the mean of independent walks has variance , it converges to with probability 1, and times its error tends in distribution to a normal law with variance .
Proof. , and by Lemma 1. The rest is the law of large numbers and the central limit theorem for independent copies of .
Corollary (length of the walks). The expected number of visits from is , where solves , with the vector of the .
Proof. Apply Theorem 1 with the reward 1 at each visit, that is and .
In the example of the page, gives , so a walk from node 2 makes 7 visits and 6 steps on average. The tests check Theorem 1 within 5 standard errors on a chain and on random meshes, Theorem 2 exactly in rational arithmetic, and the corollary against the mean length of the walks.
Complexity
Building the tables takes time and space, where is the number of nodes and the number of wires. Each step costs for the binary search. A run of walks with mean length steps costs expected time beyond the tables. The mean length from node is , where solves , the expected number of visits. It grows with the distance to the pads, and on a mesh with pads far apart it can be large. The error after walks is , so a tenfold smaller error costs a hundredfold more walks. The method does not need the whole grid in memory at once, only the parts that the walks visit, which is its main point for local queries.
Properties
- Unbiased, proved. The expected reward of one walk is the exact drop. So the estimate has no systematic error, only a random one.
- Local. One query touches only the nodes that its walks visit. Nodes near pads are cheap. A full solve of the grid is not needed for one node.
- Error from the sample. The sample variance gives a confidence interval at no extra cost.
- Slow convergence. The error falls as . For many nodes or a tight error, a direct or iterative solver of the whole grid is cheaper.
- Parallel. The walks are independent, so they run in parallel with no communication.
Variants and improvements
- Transient analysis. With the backward Euler method and step , each capacitor becomes a conductance to a source that holds the drop of the last time step, by the companion model. The walk then also stops at that source, with the old drop as its payoff.
- Known nodes as stops. Once the drop at some nodes is known, a walk that reaches one of them can stop there and take that drop as its payoff. The walks get shorter, and work done for one query helps the next.
- Many nodes at once. One walk visits many nodes, and the rewards of its tail from each node give samples for those nodes too, which lowers the cost per node when many nodes are queried.
- Other solvers. The multigrid-like method solves for every node at once, approximately. Vectorless verification bounds the worst drop over a set of possible loads instead of one load vector.
When to use it
Use it when you need the drop at a few nodes of a very large grid, for example after a local change of the grid near some cells, or to check a few hot spots. It also fits incremental analysis, since a local change affects only the walks that pass through it. Use a direct or preconditioned iterative solver when you need the drop everywhere, or a tight error at many nodes.
Pitfalls
- A part with no pad. A walk there never stops. Check the connectivity before the walks start.
- Floating rounding in the tables. The cumulative list of line L7 must leave exactly the pad probability for the stop. At a node with no pad, rounding can leave a tiny stop probability or none, so build the tables in the same order in which they are summed.
- Too few walks. With few walks the sample variance itself is noisy. Report the standard error, and use more walks near nodes with long walks.
- Treating one walk's payoff as a bound. Single walks can pay much more or much less than the drop, as the example shows. Only the mean is right.
- Nonlinear loads. The identity needs fixed load currents. Loads that depend on the local voltage need an outer loop that updates the currents.
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
# 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
random_walk_power_grid_analysis.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-walk-power-grid-analysis/. The authors are listed in prov/4F39NW.jsonl.
"""Random walk power grid analysis after Qian, Nassif and Sapatnekar (2003, 2005).
The grid is in drop form: G x = cur, with G = L + diag(gpad). At node m let
D_m = sum of the wire conductances at m plus gpad[m]. A walk at m pays the
reward cur[m] / D_m, then stops at the pad with probability gpad[m] / D_m, or
moves to the neighbor j with probability g_mj / D_m. The expected total reward
of a walk that starts at k is the drop x_k. The estimate is the mean of
independent walks.
"""
from __future__ import annotations
import bisect
import math
import random
from typing import List, Tuple
from pgrid import Grid
class WalkTables:
"""For each node: the reward, the cumulative step table and its targets."""
def __init__(self, grid: Grid):
if not grid.every_part_has_a_pad():
raise ValueError("a part of the grid has no pad: the drop is not defined")
self.reward: List[float] = []
self.cum: List[List[float]] = []
self.target: List[List[int]] = []
for m in range(grid.n):
d = float(grid.degree(m))
self.reward.append(float(grid.cur[m]) / d)
acc, cum, tgt = 0.0, [], []
for j, g in sorted(grid.adj[m].items()):
acc += float(g) / d
cum.append(acc)
tgt.append(j)
self.cum.append(cum)
self.target.append(tgt)
# The rest of each table, 1 - cum[-1], is the probability gpad / D of stopping.
def one_walk(t: WalkTables, k: int, rng: random.Random) -> Tuple[float, int]:
"""One walk from k: its total reward and its number of steps."""
m, total, steps = k, 0.0, 0 # @line L3
while True: # @line L4
total += t.reward[m] # @line L5: pay cur[m] / D_m at each visit
u = rng.random() # @line L6
cum = t.cum[m]
i = bisect.bisect_right(cum, u)
if i == len(cum): # @line L6: u fell in the pad part, the walk stops
return total, steps
m = t.target[m][i] # @line L7: move to neighbor j with probability g_mj / D_m
steps += 1
def estimate_drop(grid: Grid, k: int, walks: int, rng: random.Random):
"""Mean drop at k over the walks, its standard error, and the mean walk length."""
t = WalkTables(grid)
s = s2 = 0.0 # @line L1
steps = 0
for _ in range(walks): # @line L2
r, n = one_walk(t, k, rng)
s += r # @line L8
s2 += r * r
steps += n
mean = s / walks # @line L9
var = max(s2 / walks - mean * mean, 0.0) * walks / max(walks - 1, 1)
return mean, math.sqrt(var / walks), steps / walks
def first_step_identity(grid: Grid, x) -> List[object]:
"""x_m - (cur[m] + sum_j g_mj x_j) / D_m for every node m.
It is zero for every m exactly when G x = cur (the discrete harmonic property
with sources).
"""
out = []
for m in range(grid.n):
d = grid.degree(m)
s = grid.cur[m]
for j, g in grid.adj[m].items():
s = s + g * x[j]
out.append(x[m] - s / d)
return out
test_random_walk_power_grid_analysis.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/random-walk-power-grid-analysis/. The authors are listed in prov/4F39NW.jsonl.
import random
from fractions import Fraction
import pytest
from pgrid import Grid, mesh, random_mesh, solve
from random_walk_power_grid_analysis import WalkTables, estimate_drop, first_step_identity
def chain():
"""Pad (20 S) at node 0, wires of 10 S, loads 0.2 A at node 1 and 0.3 A at node 2."""
g = Grid(3)
g.add_wire(0, 1, Fraction(10))
g.add_wire(1, 2, Fraction(10))
g.gpad[0] = Fraction(20)
g.cur = [Fraction(0), Fraction(2, 10), Fraction(3, 10)]
return g
def test_chain_exact_drops():
g = chain()
x = solve(g.matrix(), g.cur)
assert x == [Fraction(25, 1000), Fraction(75, 1000), Fraction(105, 1000)]
assert first_step_identity(g, x) == [0, 0, 0]
def test_first_step_identity_holds_exactly_on_random_meshes():
rng = random.Random(11)
for _ in range(5):
g = random_mesh(4, 4, rng)
x = solve(g.matrix(), g.cur)
assert all(v == 0 for v in first_step_identity(g, x))
# and fails for a vector that is not the solution
y = list(x)
y[0] += 1
assert any(v != 0 for v in first_step_identity(g, y))
def test_drops_are_nonnegative_and_the_inverse_is_nonnegative():
rng = random.Random(12)
g = random_mesh(4, 3, rng)
a = g.matrix()
for j in range(g.n):
e = [Fraction(0)] * g.n
e[j] = Fraction(1)
assert all(v >= 0 for v in solve(a, e))
def test_estimate_on_chain_within_five_standard_errors():
g = chain()
rng = random.Random(1)
for k, exact in [(0, 0.025), (1, 0.075), (2, 0.105)]:
mean, se, _ = estimate_drop(g, k, 4000, rng)
assert abs(mean - exact) <= 5 * se + 1e-12
def test_estimate_on_random_meshes():
rng = random.Random(2)
for _ in range(3):
g = random_mesh(4, 4, rng, n_pads=3)
x = solve(g.matrix(), g.cur)
for k in rng.sample(range(g.n), 3):
mean, se, _ = estimate_drop(g, k, 3000, rng)
assert abs(mean - float(x[k])) <= 5 * se + 1e-12
def test_mean_walk_length():
# Expected visits y solve G y = D 1, and steps = visits - 1.
rng = random.Random(3)
g = random_mesh(3, 3, rng, n_pads=2)
d = [g.degree(m) for m in range(g.n)]
y = solve(g.matrix(), d)
k = 4
_, _, steps = estimate_drop(g, k, 6000, rng)
assert abs(steps - float(y[k] - 1)) < 0.08 * float(y[k])
def test_same_seed_same_answer():
g = chain()
a = estimate_drop(g, 2, 500, random.Random(7))
b = estimate_drop(g, 2, 500, random.Random(7))
assert a == b
def test_grid_without_pad_is_rejected():
g = Grid(2)
g.add_wire(0, 1, Fraction(1))
with pytest.raises(ValueError):
WalkTables(g)
History
The link between random walks and electric networks goes back to Kakutani's 1944 solution of the Dirichlet problem by Brownian motion and was made popular for networks by Doyle and Snell's book of 1984. In EDA it was first used in capacitance extraction, in the floating random walk of Le Coz and Iverson (1992). Qian, Nassif and Sapatnekar (2003) gave it to power grid analysis as a game in which the walker pays the load costs and is paid the supply voltage at the pads, and in 2005 they extended it to transient analysis. Later work used the same walks to build preconditioners for iterative grid solvers.
References
- Haifeng Qian, Sani R. Nassif and Sachin S. Sapatnekar, Random walks in a supply network, Proceedings of the 40th Design Automation Conference, 93 to 98, 2003, the game in which a walker pays a cost at each node and is paid at the pads, its equality with the node voltage, and the solver for single nodes
- Haifeng Qian, Sani R. Nassif and Sachin S. Sapatnekar, Power grid analysis using random walks, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 24(8), 1204 to 1224, August 2005, the journal version, with DC and transient analysis, the error and the number of walks, and the measured results on industrial grids
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 4F39NW Edit this page History Report an error Markdown