Algorithm Search⌘K

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.

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
Properties
randomizednot exactiterative
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: Gx=iG x = i with G=L+diag(gpad)G = \mathcal{L} + \mathrm{diag}(g^{\mathrm{pad}}), where L\mathcal{L} is the Laplacian of the wire conductances gmjg_{mj}, gmpad≥0g^{\mathrm{pad}}_m \ge 0 is the conductance from node mm to the ideal supply, im≥0i_m \ge 0 is the load current at mm, and xm=VDD−vmx_m = V_{DD} - v_m is the drop. Every connected part of the grid has a pad. The input is the grid and one node kk, and the output is an estimate of xkx_k 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 Dm=∑jgmj+gmpadD_m = \sum_j g_{mj} + g^{\mathrm{pad}}_m be the total conductance at mm. Row mm of Gx=iG x = i, divided by DmD_m, reads

xm=imDm+∑jgmjDm xj+gmpadDm⋅0.x_m = \frac{i_m}{D_m} + \sum_j \frac{g_{mj}}{D_m}\, x_j + \frac{g^{\mathrm{pad}}_m}{D_m} \cdot 0 .

The weights gmj/Dmg_{mj}/D_m and gmpad/Dmg^{\mathrm{pad}}_m/D_m 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

  1. RANDOM-WALK-DROP(grid, k, W)
  2. 1s ← 0
  3. 2repeat W times
  4. 3m ← k; R ← 0
  5. 4loop
  6. 5R ← R + i_m / D_m ▷ the reward of this visit
  7. 6with probability g^pad_m / D_m stop the walk
  8. 7otherwise move to a neighbor j with probability g_mj / D_m
  9. 8s ← s + R
  10. 9return s / W, and the standard error from the sample variance of R

The tables of line L7, one cumulative list of gmj/Dmg_{mj}/D_m 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 D=(30,20,10)D = (30, 20, 10), and the rewards im/Dmi_m/D_m are (0,0.01,0.03)(0, 0.01, 0.03) V. By hand: all 0.5 A flows through the pad, so x0=0.5/20=0.025x_0 = 0.5/20 = 0.025 V. Wire 0 to 1 carries 0.5 A, so x1=0.025+0.05=0.075x_1 = 0.025 + 0.05 = 0.075 V. Wire 1 to 2 carries 0.3 A, so x2=0.075+0.03=0.105x_2 = 0.075 + 0.03 = 0.105 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 2,1,2,1,2,1,2,1,02, 1, 2, 1, 2, 1, 2, 1, 0 with reward 4⋅0.03+4⋅0.01=0.164 \cdot 0.03 + 4 \cdot 0.01 = 0.16, then 2,1,02, 1, 0 twice, with reward 0.040.04 each. The walks vary a lot, but their mean is right:

walks WW estimate of x2x_2 (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 0.006675≈0.0817\sqrt{0.006675} \approx 0.0817 V, and the standard errors follow 0.0817/W0.0817/\sqrt{W}. 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 kk is exactly xkx_k. The step matrix QQ with Qmj=gmj/DmQ_{mj} = g_{mj}/D_m has rows that sum to at most 1, and from every node some path reaches a node with a pad, so Qt→0Q^t \to 0 and the spectral radius of QQ is below 1. The expected reward is ∑t(Qtr)k=((I−Q)−1r)k\sum_t (Q^t r)_k = ((I - Q)^{-1} r)_k with rm=im/Dmr_m = i_m/D_m, and since D(I−Q)=GD (I - Q) = G, this is (G−1i)k=xk(G^{-1} i)_k = x_k. The number of visits has a geometric tail, so the reward has a finite variance. The estimate is therefore unbiased, it converges to xkx_k by the law of large numbers, and by the central limit theorem the interval of two standard errors on each side covers xkx_k about 95% of the time when WW 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 1,…,N1, \ldots, N, wire conductances gmj=gjm≥0g_{mj} = g_{jm} \ge 0, pad conductances gmpad≥0g^{\mathrm{pad}}_m \ge 0 and loads im≥0i_m \ge 0. Every connected part of the wire graph has a node with gmpad>0g^{\mathrm{pad}}_m > 0, and every node has Dm=∑jgmj+gmpad>0D_m = \sum_j g_{mj} + g^{\mathrm{pad}}_m > 0. The drop xx solves Gx=iG x = i with Gmm=DmG_{mm} = D_m and Gmj=−gmjG_{mj} = -g_{mj} for j≠mj \ne m; the power grid analysis page shows that GG is nonsingular. Let Qmj=gmj/DmQ_{mj} = g_{mj}/D_m, let rm=im/Dmr_m = i_m/D_m, and let Δ=diag(D)\Delta = \mathrm{diag}(D), so that G=Δ(I−Q)G = \Delta (I - Q).

The walk of lines L3 to L7 is a Markov chain on the nodes plus one stopping state ⋆\star. From node mm it moves to jj with probability QmjQ_{mj} and to ⋆\star with probability gmpad/Dm=1−∑jQmjg^{\mathrm{pad}}_m / D_m = 1 - \sum_j Q_{mj}. Let X0=k,X1,…X_0 = k, X_1, \ldots be the nodes visited and τ\tau the number of node visits before ⋆\star. The reward is R=∑t=0τ−1rXtR = \sum_{t=0}^{\tau - 1} r_{X_t}.

Lemma 1 (the walk stops). There are n0≤Nn_0 \le N and δ>0\delta > 0 such that from every node the walk reaches ⋆\star within n0n_0 steps with probability at least δ\delta. Hence P(τ>t n0)≤(1−δ)tP(\tau > t\, n_0) \le (1 - \delta)^t, the walk stops with probability 1, and τ\tau has finite moments of every order.

Proof. From node mm, take a shortest path of wires to a node with a pad, of length at most N−1N - 1, and then the step to ⋆\star. Each step of this path has positive probability, so the probability δm\delta_m of following it is positive. Let n0=Nn_0 = N and δ=min⁡mδm\delta = \min_m \delta_m. The bound on P(τ>tn0)P(\tau > t n_0) follows by the Markov property, applied at the times n0,2n0,…n_0, 2 n_0, \ldots. A geometric tail gives finite moments. □\square

Lemma 2 (spectral radius). Qt→0Q^t \to 0 as t→∞t \to \infty, so ρ(Q)<1\rho(Q) < 1, I−QI - Q is nonsingular, and (I−Q)−1=∑t≥0Qt(I - Q)^{-1} = \sum_{t \ge 0} Q^t with nonnegative entries.

Proof. (Qt)kj(Q^t)_{kj} is the probability that the walk from kk is at node jj at step tt without having stopped, which is at most P(τ>t)P(\tau > t), 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 (I−Q)−1(I - Q)^{-1}. □\square

Theorem 1 (unbiased). E[R]=xkE[R] = x_k.

Proof. All rewards are nonnegative, so we may exchange the sum and the expectation:

E[R]=∑t≥0E[rXt[τ>t]]=∑t≥0∑m(Qt)kmrm=((I−Q)−1r)k,E[R] = \sum_{t \ge 0} E\big[r_{X_t} [\tau > t]\big] = \sum_{t \ge 0} \sum_m (Q^t)_{km} r_m = \big((I - Q)^{-1} r\big)_k ,

by Lemma 2. Now (I−Q)−1r=(I−Q)−1Δ−1i=(Δ(I−Q))−1i=G−1i=x(I - Q)^{-1} r = (I - Q)^{-1} \Delta^{-1} i = (\Delta (I - Q))^{-1} i = G^{-1} i = x. □\square

Theorem 2 (discrete harmonic property). For every node mm, xm=rm+∑jQmjxjx_m = r_m + \sum_j Q_{mj} x_j, and xx is the only vector with this property.

Proof. The identity is row mm of Gx=iG x = i divided by DmD_m. It can be read as a first-step analysis: the walk from mm collects rmr_m and then, with probability QmjQ_{mj}, starts afresh at jj, or stops with payoff 0. The system (I−Q)z=r(I - Q) z = r has the unique solution z=xz = x by Lemma 2. □\square

Theorem 3 (finite variance). E[R2]<∞E[R^2] < \infty. So the mean of WW independent walks has variance Var(R)/W\mathrm{Var}(R)/W, it converges to xkx_k with probability 1, and W\sqrt{W} times its error tends in distribution to a normal law with variance Var(R)\mathrm{Var}(R).

Proof. 0≤R≤τmax⁡mrm0 \le R \le \tau \max_m r_m, and E[τ2]<∞E[\tau^2] < \infty by Lemma 1. The rest is the law of large numbers and the central limit theorem for independent copies of RR. □\square

Corollary (length of the walks). The expected number of visits from kk is E[τ]=ykE[\tau] = y_k, where yy solves Gy=DG y = D, with DD the vector of the DmD_m.

Proof. Apply Theorem 1 with the reward 1 at each visit, that is r=1r = \mathbf{1} and i=Δ1=Di = \Delta \mathbf{1} = D. □\square

In the example of the page, Gy=DG y = D gives y=(3,6,7)y = (3, 6, 7), 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 O(N+E)O(N + E) time and space, where NN is the number of nodes and EE the number of wires. Each step costs O(log⁡d)O(\log d) for the binary search. A run of WW walks with mean length SS steps costs O(WSlog⁡d)O(W S \log d) expected time beyond the tables. The mean length from node kk is yk−1y_k - 1, where yy solves Gy=D1G y = D \mathbf{1}, 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 WW walks is σ/W\sigma/\sqrt{W}, 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 1/W1/\sqrt{W}. 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 hh, each capacitor becomes a conductance C/hC/h 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 gmpad/Dmg^{\mathrm{pad}}_m/D_m 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.

pgrid.pyI0RawGitHub
# 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

  1. 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
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • 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