Algorithm Search⌘K

Algorithmresearch

Vectorless power grid verification

Also called current-constraint power grid verification, Kouroussis-Najm verification.

Kouroussis and Najm's worst-case IR drop check that bounds block currents by constraints and solves one linear program per node, with no simulation vectors.

Time
O(F + K (Z + L)) worst
Space
O(Z + S^2) extra
Where
F = the time to factor the conductance matrix once; K = the number of nodes checked; L = the time of one linear program with S variables and the given constraints; S = the number of current sources; Z = the number of nonzeros of the factor
Properties
deterministicexactiterative
Origin
Dionysios Kouroussis, Farid N. Najm, 2003

Vectorless power grid verification checks that the voltage drop at every node of an on-chip power grid stays below a limit for every pattern of load currents that the design may draw, not only for the patterns that someone simulated. The currents are not known. What is known are bounds: each current source lies between 0 and a peak value, and groups of sources, such as the blocks that share a clock or a power budget, have a bound on their total. Since the drop x=G−1ix = G^{-1} i is linear in the currents, the worst drop at node kk over all currents that meet the bounds is a linear program in the currents. Kouroussis and Najm (2003) solved one such program per node. The answer is the exact worst case under the bounds, so it is safe when the bounds are right. When the only group bound is one bound on the total current, a greedy rule solves the program exactly, as a fractional knapsack.

In plain words

Early in a design you do not know which blocks of the chip will be busy at the same time. You only know limits: this block never draws more than 0.4 A, and the chip as a whole never draws more than 0.5 A.

You want to know the worst voltage drop at each point of the power grid under any mix of currents that keeps to these limits. Each current adds a fixed share to the drop at a point, so the worst mix puts as much current as allowed into the blocks with the largest share. Finding that mix for each point is a linear program, and with one total limit it is just "fill the biggest shares first".

The problem

The grid is in drop form, as on the power grid analysis page: Gx=iG x = i, where GG is a symmetric M-matrix and xkx_k is the drop at node kk. The loads are SS current sources at chosen nodes. The input is GG, the bounds, a set of nodes to check and a limit xmax⁡x_{\max}. The bounds are

0≤is≤us for every source s,Ui≤w,0 \le i_s \le u_s \text{ for every source } s, \qquad U i \le w,

where each row of UU has entries 0 and 1 and picks a group of sources with a bound wqw_q on their total. The set F\mathcal{F} of current vectors that meet the bounds is the feasible space. The output is, for each node kk to check,

zk=max⁡i∈Fxk(i)=max⁡i∈FrkTi,rk=(row k of G−1) on the sources,z_k = \max_{i \in \mathcal{F}} x_k(i) = \max_{i \in \mathcal{F}} r_k^T i, \qquad r_k = (\text{row } k \text{ of } G^{-1}) \text{ on the sources},

and the list of nodes with zk>xmax⁡z_k > x_{\max}. The power grid analysis page shows that G−1G^{-1} has no negative entries, so rk≥0r_k \ge 0: more current never lowers a drop. This page treats the DC case. The bounds usu_s and wqw_q come from the designers or from power estimates of the blocks, for example from Monte Carlo power estimation or a power budget, and they are only as good as those estimates. The conductances of GG come from layout extraction and foundry data, as on the power grid analysis page. The method fits no parameter of its own.

The algorithm

  1. VECTORLESS-VERIFY(G, sources, u, U, w, nodes, x_max)
  2. 1for each node k in nodes do
  3. 2r ← the solution of G r = e_k, kept at the sources ▷ row k of G⁻¹, since G is symmetric
  4. 3z_k ← max rᵀ i subject to 0 ≤ i ≤ u and U i ≤ w ▷ a linear program
  5. 4return the nodes k with z_k > x_max, and all z_k
  6. GREEDY-ONE-BOUND(r, u, W) ▷ when U i ≤ w is the one bound Σ i_s ≤ W
  7. 5sort the sources by r_s, largest first
  8. 6rest ← W
  9. 7for each source s in this order do i_s ← min(u_s, rest); rest ← rest − i_s
  10. 8return rᵀ i

Line L2 uses one factorization of GG, for example a sparse Cholesky decomposition, and two triangular solves per node. Line L3 can use the simplex method or an interior point method. The code of this page uses a dense simplex in exact fractions with Bland's rule, which suits small tests.

Example

Take a chain of 4 nodes, 0−1−2−30 - 1 - 2 - 3, with wires of 10 S and pads of 20 S at nodes 0 and 3. Current sources sit at nodes 1 and 2, each with us=0.4u_s = 0.4 A, and the total is at most W=0.5W = 0.5 A. The limit is 40 mV.

Solving Gr=e1G r = e_1 gives row 1 of G−1G^{-1}, (1/32,3/32,9/160,3/160)(1/32, 3/32, 9/160, 3/160) in ohms. At the sources it is r=(3/32,9/160)=(0.09375,0.05625)r = (3/32, 9/160) = (0.09375, 0.05625). The greedy of lines L5 to L8 fills the source at node 1 first, up to 0.4 A, and the source at node 2 with the remaining 0.1 A:

z1=0.4⋅332+0.1⋅9160=691600≈43.1 mV.z_1 = 0.4 \cdot \tfrac{3}{32} + 0.1 \cdot \tfrac{9}{160} = \tfrac{69}{1600} \approx 43.1 \text{ mV}.

By the symmetry of the chain, z2=69/1600z_2 = 69/1600 with the worst vector (0.1,0.4)(0.1, 0.4), and z0=z3=23/1600≈14.4z_0 = z_3 = 23/1600 \approx 14.4 mV. So nodes 1 and 2 fail the limit of 40 mV. Note that the worst vector for node 1 and the worst vector for node 2 are different. A simulation of one current pattern would find the worst case of at most one of the two nodes. Without the total bound, the worst vector is (0.4,0.4)(0.4, 0.4) for every node and z1=0.4⋅(3/32+9/160)=3/50=60z_1 = 0.4 \cdot (3/32 + 9/160) = 3/50 = 60 mV, so the global bound lowers the reported worst drop at node 1 from 60 mV to 43.1 mV.

Correctness

The proof file proves three facts. First, x=G−1ix = G^{-1} i is linear in ii, so xk=rkTix_k = r_k^T i, and zkz_k is the optimum of the linear program of line L3. The feasible space holds i=0i = 0 and is bounded by 0≤i≤u0 \le i \le u, so the optimum exists and is attained at a vertex. Hence zkz_k is both a bound and the least bound: every feasible current gives a drop of at most zkz_k, and some feasible current gives exactly zkz_k. Second, since rk≥0r_k \ge 0, the worst case with local bounds only is rkTur_k^T u, all sources at their peaks. Third, with one bound on the total, the program is a fractional knapsack with values rsr_s per ampere and capacities usu_s, and filling the largest rsr_s first is optimal by the exchange argument.

What the method does not prove is that the real chip meets the bounds. If a block draws more than its usu_s, or if blocks that the bounds treat as unable to peak together do so, the check is not safe. If the bounds are loose, the check is safe but pessimistic.

Proof: The worst drop under current bounds is a linear program, and with one total bound the greedy solves itfull

Setting. GG is the N×NN \times N conductance matrix of a power grid in drop form, symmetric and nonsingular, with G−1≥0G^{-1} \ge 0 entrywise. The power grid analysis page proves both facts when every connected part has a pad. There are SS sources at nodes n1,…,nSn_1, \ldots, n_S, with currents i∈RSi \in \mathbb{R}^S, and the load vector of the grid is b(i)=∑sisensb(i) = \sum_s i_s e_{n_s}. The feasible space is F={i:0≤i≤u, Ui≤w}\mathcal{F} = \{ i : 0 \le i \le u, \ U i \le w \} with u≥0u \ge 0, w≥0w \ge 0 and UU a 0-1 matrix.

Lemma 1 (the drop is linear). For each node kk, xk(i)=rkTix_k(i) = r_k^T i with (rk)s=(G−1)kns≥0(r_k)_s = (G^{-1})_{k n_s} \ge 0. Line L2 computes rkr_k correctly.

Proof. x=G−1b(i)=∑sisG−1ensx = G^{-1} b(i) = \sum_s i_s G^{-1} e_{n_s}, so xk=∑sis(G−1)knsx_k = \sum_s i_s (G^{-1})_{k n_s}. Since GG is symmetric, so is G−1G^{-1}, and row kk of G−1G^{-1} equals column kk, which is the solution of Gr=ekG r = e_k. Its entries are nonnegative because G−1≥0G^{-1} \ge 0. □\square

Theorem 1 (exact worst case). The maximum zk=max⁡i∈Fxk(i)z_k = \max_{i \in \mathcal{F}} x_k(i) exists, it equals the optimum of the linear program of line L3, it is attained at a vertex of F\mathcal{F}, and for every i∈Fi \in \mathcal{F}, xk(i)≤zkx_k(i) \le z_k. No smaller number has this property.

Proof. By Lemma 1 the objective is the linear function rkTir_k^T i. F\mathcal{F} is a polyhedron. It is not empty, since i=0i = 0 meets every bound because u,w≥0u, w \ge 0. It is bounded, since 0≤i≤u0 \le i \le u. A linear function on a nonempty bounded polyhedron attains its maximum, and it attains it at a vertex. The bound property is the definition of the maximum, and since some i∗∈Fi^* \in \mathcal{F} gives xk(i∗)=zkx_k(i^*) = z_k, no smaller number bounds all feasible drops. □\square

Corollary 1 (local bounds only). If there are no group bounds, zk=rkTuz_k = r_k^T u, attained at i=ui = u.

Proof. Every feasible ii has i≤ui \le u, and rk≥0r_k \ge 0, so rkTi≤rkTur_k^T i \le r_k^T u, and uu is feasible. □\square

Corollary 2 (monotone). If u≤u′u \le u' and w≤w′w \le w', the worst drops for (u′,w′)(u', w') are at least those for (u,w)(u, w).

Proof. The feasible space only grows. □\square

Theorem 2 (the greedy with one total bound). Let r≥0r \ge 0, u≥0u \ge 0 and W≥0W \ge 0, and let the only group bound be ∑sis≤W\sum_s i_s \le W. Then lines L5 to L8 return max⁡{rTi:0≤i≤u, ∑sis≤W}\max \{ r^T i : 0 \le i \le u, \ \sum_s i_s \le W \}.

Proof. The greedy output gg is feasible: each gsg_s lies in [0,us][0, u_s], since restrest never becomes negative, and the gsg_s add up to at most WW. Sort the sources so that r1≥r2≥⋯≥rSr_1 \ge r_2 \ge \cdots \ge r_S, the order of line L5. Then g=(u1,…,uj−1,θ,0,…,0)g = (u_1, \ldots, u_{j-1}, \theta, 0, \ldots, 0) with 0≤θ≤uj0 \le \theta \le u_j, where either all sources are full or the total is WW.

Take an optimal i∗i^* that agrees with gg on the longest possible prefix, and suppose i∗≠gi^* \ne g. Let tt be the first index with it∗≠gti^*_t \ne g_t. If it∗>gti^*_t > g_t, then gt<utg_t < u_t, so the greedy had rest=gtrest = g_t at step tt, which means ∑s≤tgs=W\sum_{s \le t} g_s = W. Then ∑s≤tis∗>W\sum_{s \le t} i^*_s > W, which is not feasible. So it∗<gti^*_t < g_t. Let ϵ=gt−it∗>0\epsilon = g_t - i^*_t > 0.

If ∑sis∗<W\sum_s i^*_s < W, raise it∗i^*_t by min⁡(ϵ,W−∑sis∗)\min(\epsilon, W - \sum_s i^*_s). This stays feasible and does not lower rTi∗r^T i^*, since rt≥0r_t \ge 0. Otherwise ∑sis∗=W≥∑sgs\sum_s i^*_s = W \ge \sum_s g_s, and the first t−1t - 1 entries agree, so some s>ts > t has is∗>gs≥0i^*_s > g_s \ge 0. Move min⁡(ϵ,is∗)\min(\epsilon, i^*_s) ampere from source ss to source tt. This stays feasible and changes rTi∗r^T i^* by a multiple of rt−rs≥0r_t - r_s \ge 0. Repeating these moves raises it∗i^*_t to gtg_t while keeping i∗i^* optimal, which gives an optimal vector that agrees with gg on a longer prefix, a contradiction. So gg is optimal. □\square

This is the exchange argument of the fractional knapsack, with values rsr_s per ampere, item sizes usu_s and the capacity WW. For several group bounds that overlap, no such greedy is exact in general, and line L3 needs a full linear program.

The tests check the simplex of the code against an enumeration of all vertices of small feasible spaces, check that the worst vector is feasible and bounds random feasible currents, and check Theorem 2 against the simplex on random grids.

Complexity

One factorization of GG costs FF, and each node then needs two triangular solves, O(Z)O(Z) with ZZ the nonzeros of the factor, and one linear program with SS variables, at cost LL. The total is O(F+K(Z+L))O(F + K (Z + L)) for KK nodes. With one total bound, LL is O(Slog⁡S)O(S \log S) for the sort. With general bounds, interior point methods solve each program in polynomial time, and the simplex method is fast in practice but exponential in the worst case. The dense simplex of the code needs O(S2)O(S^2) space for the tableau. The cost of one program per node is what limits the method on large grids, and it is the target of most later work.

Properties

  • Exact under the bounds, proved. zkz_k is the largest drop at kk over all currents that meet the bounds, and it is attained.
  • Safe, if the bounds are right. No current pattern that meets the bounds gives a larger drop, so no pattern is missed, unlike a check by simulation of chosen patterns.
  • Monotone, proved. Raising any bound only enlarges the feasible set F\mathcal{F}, so it never lowers any zkz_k.
  • One program per node. Each node has its own worst current vector, so the programs cannot be merged into one.
  • Measured cost. The run times that Kouroussis and Najm report are measurements on their grids. This page does not repeat them.

Variants and improvements

  • Transient constraints. Kouroussis and Najm also treat currents that vary over time, with bounds at each time step and the grid discretized in time by the companion model. The worst drop at a node and a time is again a linear program, in the currents of all time steps.
  • Fewer programs. Later work bounds zkz_k cheaply for many nodes at once and solves the full program only for nodes whose bound is close to the limit. Other work uses an approximate row of G−1G^{-1} that keeps only its large entries, which makes each program smaller.
  • Duality. By LP duality, a feasible point of the dual program gives an upper bound on zkz_k without solving the primal. A bound below xmax⁡x_{\max} is already a proof that node kk passes.
  • Other solvers. The multigrid-like method and the random walk method solve the grid for one known current vector. Vectorless verification asks about all vectors that meet the bounds.

When to use it

Use it early in a design, when the floorplan and the power budgets of the blocks are known but the activity is not, and at sign-off as a check that does not depend on the choice of test patterns. It is the right tool when a missed worst case is costly. Use it with care when the bounds come from rough guesses, since a check is only as safe as its bounds.

Pitfalls

  • Treating one worst vector as the worst for all nodes. Each node has its own worst vector, as in the example. Running the worst vector of one node through a simulator does not check the others.
  • Missing global bounds. With local bounds only, every source sits at its peak, which gives a safe but very pessimistic answer. The group bounds carry most of the real knowledge.
  • Wrong sign conventions. In drop form the currents are drawn from the grid and G−1≥0G^{-1} \ge 0. With node voltages instead of drops, the program must minimize the voltage, not maximize it.
  • Rounding in large programs. A floating point simplex can stop at a slightly infeasible point and report a drop that is too low. Check the final point against the bounds, or use the dual bound.
  • A grid part with no pad. Then GG is singular, and no bound exists. Check the connectivity first.

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
vectorless_power_grid_verification.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vectorless-power-grid-verification/. The authors are listed in prov/H1QXN8.jsonl.
"""Vectorless power grid verification after Kouroussis and Najm (2003), DC case.

The grid is in drop form, G x = i. The currents are not known. Only bounds are:
0 <= i_s <= u_s for each source s (local bounds), and U i <= w for groups of
sources (global bounds, U has 0-1 rows). The worst drop at node k is

    z_k = max r^T i  subject to  0 <= i <= u, U i <= w,

with r the row k of G^{-1} restricted to the source nodes. This is a linear
program. It is solved here by a dense simplex in exact fractions with Bland's
rule. With one global bound sum i <= W and nothing else, a greedy that fills the
sources in decreasing order of r_s is exact (a fractional knapsack).
"""

from __future__ import annotations

from fractions import Fraction
from typing import List, Optional, Sequence, Tuple

from pgrid import solve


def inverse_row(g: Sequence[Sequence[Fraction]], k: int) -> List[Fraction]:
    """Row k of G^{-1}. G is symmetric, so it is the solution of G r = e_k."""
    n = len(g)
    e = [Fraction(0)] * n
    e[k] = Fraction(1)
    return solve(g, e)


def simplex_max(c: Sequence[Fraction], a: Sequence[Sequence[Fraction]], b: Sequence[Fraction]):
    """max c^T y subject to a y <= b, y >= 0, with b >= 0. Returns (value, y).

    Dense tableau with slack variables, Bland's rule, exact fractions. The
    origin is feasible because b >= 0, so no first phase is needed.
    """
    m, n = len(a), len(c)
    if any(bi < 0 for bi in b):
        raise ValueError("this small simplex needs b >= 0")
    t = [[Fraction(v) for v in a[i]] + [Fraction(int(i == j)) for j in range(m)] + [Fraction(b[i])] for i in range(m)]
    obj = [-Fraction(v) for v in c] + [Fraction(0)] * (m + 1)
    basis = [n + i for i in range(m)]
    while True:
        enter = next((j for j in range(n + m) if obj[j] < 0), None)
        if enter is None:
            break
        best: Optional[Tuple[Fraction, int, int]] = None
        for i in range(m):
            if t[i][enter] > 0:
                ratio = t[i][-1] / t[i][enter]
                key = (ratio, basis[i], i)
                if best is None or key < best:
                    best = key
        if best is None:
            raise ValueError("unbounded")
        r = best[2]
        piv = t[r][enter]
        t[r] = [v / piv for v in t[r]]
        for i in range(m):
            if i != r and t[i][enter] != 0:
                f = t[i][enter]
                t[i] = [u - f * v for u, v in zip(t[i], t[r])]
        f = obj[enter]
        obj = [u - f * v for u, v in zip(obj, t[r])]
        basis[r] = enter
    y = [Fraction(0)] * n
    for i, j in enumerate(basis):
        if j < n:
            y[j] = t[i][-1]
    return obj[-1], y


def worst_drop(g, sources: Sequence[int], k: int, u: Sequence[Fraction], groups: Sequence[Sequence[int]], w: Sequence[Fraction]):
    """z_k and a worst current vector, by the LP of line L3.

    groups[q] lists positions in `sources`, and the bound is the sum of their
    currents <= w[q].
    """
    r_full = inverse_row(g, k)  # @line L2
    r = [r_full[s] for s in sources]
    ns = len(sources)
    rows, rhs = [], []
    for s in range(ns):  # local bounds i_s <= u_s
        rows.append([Fraction(int(s == t)) for t in range(ns)])
        rhs.append(Fraction(u[s]))
    for q, grp in enumerate(groups):  # global bounds U i <= w
        rows.append([Fraction(int(t in grp)) for t in range(ns)])
        rhs.append(Fraction(w[q]))
    return simplex_max(r, rows, rhs)  # @line L3


def verify(g, sources, u, groups, w, nodes: Sequence[int], limit: Fraction):
    """Nodes whose worst drop exceeds the limit, with all the worst drops."""
    z = {}
    for k in nodes:  # @line L1
        z[k] = worst_drop(g, sources, k, u, groups, w)[0]
    return [k for k in nodes if z[k] > limit], z  # @line L4


def greedy_one_bound(r: Sequence[Fraction], u: Sequence[Fraction], total: Fraction):
    """max r^T i with 0 <= i <= u and sum i <= total, for r >= 0. Fractional knapsack."""
    order = sorted(range(len(r)), key=lambda s: -r[s])  # @line L5
    rest = Fraction(total)  # @line L6
    i = [Fraction(0)] * len(r)
    for s in order:  # @line L7
        i[s] = min(Fraction(u[s]), rest)
        rest -= i[s]
    return sum((r[s] * i[s] for s in range(len(r))), Fraction(0)), i  # @line L8
test_vectorless_power_grid_verification.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vectorless-power-grid-verification/. The authors are listed in prov/H1QXN8.jsonl.

import itertools
import random
from fractions import Fraction

from pgrid import Grid, matvec, random_mesh, solve
from vectorless_power_grid_verification import greedy_one_bound, inverse_row, simplex_max, verify, worst_drop


def vertex_max(c, a, b):
    """Brute force: the best vertex of {y >= 0, a y <= b}, by trying every set of tight constraints."""
    n = len(c)
    rows = [[Fraction(int(i == j)) for j in range(n)] for i in range(n)] + [list(r) for r in a]
    rhs = [Fraction(0)] * n + [Fraction(v) for v in b]
    sign = [-1] * n + [1] * len(a)  # -y <= 0 written as y >= 0
    best = None
    for tight in itertools.combinations(range(len(rows)), n):
        try:
            y = solve([rows[t] for t in tight], [rhs[t] for t in tight])
        except ZeroDivisionError:
            continue
        ok = all(v >= 0 for v in y) and all(sum(r[j] * y[j] for j in range(n)) <= bb for r, bb in zip(a, b))
        if ok:
            val = sum(c[j] * y[j] for j in range(n))
            if best is None or val > best:
                best = val
    return best


def small_case(rng, nx=3, ny=3, ns=4, n_groups=2):
    g = random_mesh(nx, ny, rng, n_pads=2)
    a = g.matrix()
    sources = rng.sample(range(g.n), ns)
    u = [Fraction(rng.randint(1, 6)) for _ in range(ns)]
    groups = [rng.sample(range(ns), rng.randint(2, ns)) for _ in range(n_groups)]
    w = [Fraction(rng.randint(2, 10)) for _ in range(n_groups)]
    return g, a, sources, u, groups, w


def test_simplex_matches_vertex_enumeration():
    rng = random.Random(21)
    for _ in range(40):
        n = rng.randint(1, 4)
        m = rng.randint(1, 5)
        c = [Fraction(rng.randint(-3, 6)) for _ in range(n)]
        a = [[Fraction(rng.randint(0, 4)) for _ in range(n)] for _ in range(m)]
        for j in range(n):  # keep the region bounded: a row with every coefficient positive
            a[0][j] = Fraction(rng.randint(1, 4))
        b = [Fraction(rng.randint(0, 12)) for _ in range(m)]
        val, y = simplex_max(c, a, b)
        assert val == vertex_max(c, a, b)
        assert all(v >= 0 for v in y)
        assert all(sum(r[j] * y[j] for j in range(n)) <= bb for r, bb in zip(a, b))
        assert sum(c[j] * y[j] for j in range(n)) == val


def test_inverse_rows_are_nonnegative_and_symmetric():
    rng = random.Random(22)
    g = random_mesh(3, 3, rng)
    a = g.matrix()
    rows = [inverse_row(a, k) for k in range(g.n)]
    for k in range(g.n):
        assert all(v >= 0 for v in rows[k])
        for j in range(g.n):
            assert rows[k][j] == rows[j][k]


def test_worst_drop_is_attained_and_bounds_every_feasible_current():
    rng = random.Random(23)
    for _ in range(6):
        g, a, sources, u, groups, w = small_case(rng)
        for k in range(g.n):
            z, iw = worst_drop(a, sources, k, u, groups, w)
            full = [Fraction(0)] * g.n
            for s, v in zip(sources, iw):
                full[s] = v
            assert solve(a, full)[k] == z  # the worst currents give the drop z_k
            for _ in range(15):  # random feasible currents never do worse
                i = [Fraction(rng.randint(0, int(us) * 4), 4) for us in u]
                if all(sum(i[t] for t in grp) <= wq for grp, wq in zip(groups, w)):
                    full = [Fraction(0)] * g.n
                    for s, v in zip(sources, i):
                        full[s] = v
                    assert solve(a, full)[k] <= z


def test_lp_against_vertex_enumeration_on_grids():
    rng = random.Random(24)
    for _ in range(5):
        g, a, sources, u, groups, w = small_case(rng)
        k = rng.randrange(g.n)
        r_full = inverse_row(a, k)
        r = [r_full[s] for s in sources]
        rows = [[Fraction(int(s == t)) for t in range(len(sources))] for s in range(len(sources))]
        rows += [[Fraction(int(t in grp)) for t in range(len(sources))] for grp in groups]
        z, _ = worst_drop(a, sources, k, u, groups, w)
        assert z == vertex_max(r, rows, list(u) + list(w))


def test_greedy_equals_lp_with_one_global_bound():
    rng = random.Random(25)
    for _ in range(25):
        g = random_mesh(3, 3, rng)
        a = g.matrix()
        ns = rng.randint(1, 5)
        sources = rng.sample(range(g.n), ns)
        u = [Fraction(rng.randint(1, 6)) for _ in range(ns)]
        total = Fraction(rng.randint(1, 20))
        k = rng.randrange(g.n)
        r_full = inverse_row(a, k)
        r = [r_full[s] for s in sources]
        gz, gi = greedy_one_bound(r, u, total)
        lz, _ = worst_drop(a, sources, k, u, [list(range(ns))], [total])
        assert gz == lz
        assert sum(gi) <= total and all(0 <= v <= us for v, us in zip(gi, u))


def test_no_global_bound_means_all_currents_at_their_maximum():
    rng = random.Random(26)
    g = random_mesh(3, 3, rng)
    a = g.matrix()
    sources = [0, 4, 8]
    u = [Fraction(2), Fraction(3), Fraction(1)]
    full = [Fraction(0)] * g.n
    for s, v in zip(sources, u):
        full[s] = v
    x = solve(a, full)
    for k in range(g.n):
        assert worst_drop(a, sources, k, u, [], [])[0] == x[k]


def test_page_example():
    # Pads of 20 S at nodes 0 and 3, wires of 10 S: 0 - 1 - 2 - 3. Sources at nodes 1 and 2.
    g = Grid(4)
    for x, y in [(0, 1), (1, 2), (2, 3)]:
        g.add_wire(x, y, Fraction(10))
    g.gpad[0] = g.gpad[3] = Fraction(20)
    g.cur = [Fraction(0)] * 4
    a = g.matrix()
    assert inverse_row(a, 1) == [Fraction(1, 32), Fraction(3, 32), Fraction(9, 160), Fraction(3, 160)]
    u = [Fraction(4, 10), Fraction(4, 10)]
    bad, z = verify(a, [1, 2], u, [[0, 1]], [Fraction(5, 10)], [0, 1, 2, 3], Fraction(4, 100))
    assert z == {0: Fraction(23, 1600), 1: Fraction(69, 1600), 2: Fraction(69, 1600), 3: Fraction(23, 1600)}
    assert bad == [1, 2]
    assert worst_drop(a, [1, 2], 1, u, [[0, 1]], [Fraction(5, 10)])[1] == [Fraction(2, 5), Fraction(1, 10)]
    assert worst_drop(a, [1, 2], 2, u, [[0, 1]], [Fraction(5, 10)])[1] == [Fraction(1, 10), Fraction(2, 5)]
    assert worst_drop(a, [1, 2], 1, u, [], [])[0] == Fraction(3, 50)

History

Before 2003, power grids were checked by simulating a few current patterns, often the peak current of every block at once, which is pessimistic, or patterns from logic simulation, which can miss the worst case. Kouroussis and Najm (2003) proposed to describe the unknown currents by constraints and to find the worst drop by linear programming, both for DC and for transient analysis. Najm and his students then worked for several years on making the per-node programs cheaper, with early bounds, sparse approximations of the inverse and better handling of the transient case.

References

  1. Dionysios Kouroussis and Farid N. Najm, A static pattern-independent technique for power grid voltage integrity verification, Proceedings of the 40th Design Automation Conference, 99 to 104, 2003, the current constraints (local bounds per source and global bounds on groups), the worst drop at a node as a linear program, the DC and the transient form

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
  • at least three sources
  • a scene preset for the example