Algorithm Search⌘K

Algorithmresearch

Floating random walk capacitance extraction

Also called random walk capacitance extraction, FRW capacitance extraction.

Le Coz and Iverson's Monte Carlo method that estimates capacitance by random walks that jump between maximal empty cubes around conductors.

Time
O(N T (M + log G)) expected
Space
O(M + G) extra
Where
G = the size of the sampling table; M = the number of conductor boxes; N = the number of walks; T = the mean number of jumps per walk
Properties
randomizednot exactiterative
Origin
Yannick L. Le Coz, Ralph B. Iverson, 1992

Floating random walk capacitance extraction estimates the capacitance between the wires of a chip by random walks through the space between them. Each walk starts on a closed surface around one conductor and jumps, again and again, to a random point on the boundary of the largest empty cube around its position, with the probabilities given by the Green's function of the cube. It stops when it lands on a conductor, and the conductor where it stops, with a weight from the first jump, is one sample of the charge. Yannick Le Coz and Ralph Iverson published it in 1992. It needs no mesh, it gives an error bar with each result, and its cost per coefficient grows only slowly with the size of the layout, so it is used for reference-quality parasitic extraction on large structures.

In plain words

The voltage at a point of empty space is the average of the voltages on any box of empty space around it. So you can find the voltage at a point by a game: jump to a random point on the biggest empty box around you, then to a random point on the biggest empty box around that point, and so on, until you land on a wire. The voltage of that wire is your answer, and the average over many games is the true voltage.

The charge on a wire depends on how fast the voltage changes just next to it. The method starts each game on a ring around the wire, gives the first jump a weight that measures that change, and adds the weighted answers. The result is a sum of random numbers, so it carries an error bar. More games give a smaller error.

The problem

There are MM conductors in a uniform dielectric with permittivity ε\varepsilon, inside a grounded box, which is conductor 0. For a conductor jj let ϕj\phi_j be the potential that solves the Laplace equation (the Poisson equation with no charge) in the free space, equals 1 on conductor jj and 0 on every other conductor. The capacitance coefficient CijC_{ij} is the charge on conductor ii under ϕj\phi_j. With a closed surface Γ\Gamma around conductor ii only, with length (or area) LL and outward normal nn, Gauss's law gives

Cij=−ε∮Γ∇ϕj⋅n ds.C_{ij} = -\varepsilon \oint_\Gamma \nabla \phi_j \cdot n \, ds.

The diagonal coefficient CiiC_{ii} is positive, the coupling coefficients CijC_{ij} with i≠ji \ne j are negative, and each row sums to zero when the box is counted. The task is to estimate one row Ci0,Ci1,…,CiMC_{i0}, C_{i1}, \ldots, C_{iM} to a given relative error. This page works in two dimensions with squares, so that the code and the tests stay small. Le Coz and Iverson work in three dimensions with cubes, and every step below is the same there.

The algorithm

  1. FRW-ROW(conductors, i, Γ, N)
  2. C[0..M] ← 0
  3. 1for each of N walks do
  4. 2r, n ← a uniform point of Γ and the outward normal there
  5. 3h ← the distance from r to the nearest conductor ▷ the largest empty square around r has half width h
  6. 4q ← a point of that square's boundary drawn with the Green's function density K(r, ·)
  7. 5w ← (∇_r K(r, q) · n) / K(r, q) ▷ the weight of the first jump
  8. repeat
  9. 6h, k ← the distance from q to the nearest conductor, and that conductor
  10. 7if h ≤ δ then stop the walk at conductor k
  11. 8q ← a point of the boundary of the empty square of half width h around q, drawn with the density K
  12. 9C[k] ← C[k] − ε L w
  13. return C / N, with the standard error of each entry from the sample variance

The first jump estimates the gradient and the rest of the walk estimates the potential. Lines L6 to L8 are the floating random walk proper: the square "floats" with the walker and is always as large as the free space allows, so the walk takes long jumps far from the conductors and short jumps near them. The density KK is the same for every square up to scaling, so the code tabulates it once for the unit square: a side chosen uniformly, then a position on the side from a table of its cumulative distribution. In three dimensions the tables are for one face of the unit cube. The stopping layer δ\delta is one grid unit in the code, which works on integer coordinates.

Example

The conductor is the square [−1,1]2[-1, 1]^2 inside the grounded box [−3,3]2[-3, 3]^2, a square coaxial line, with ε=1\varepsilon = 1. The surface Γ\Gamma is the square [−1.5,1.5]2[-1.5, 1.5]^2, with L=12L = 12. The reference is a finite difference solution with the five-point stencil. Its discrete energy is that of a piecewise linear finite element field, so by the Dirichlet principle it is an upper bound on C11C_{11}, and it decreases as the grid gets finer: 6.305, 6.251 and 6.229 on grids of spacing 1/4, 1/8 and 1/16.

One walk with seed 2 of the code:

step point distance hh nearest
L2 (−0.595,−1.5)(-0.595, -1.5), normal (0,−1)(0, -1) 0.5 conductor 1
L4 (−0.898,−2.0)(-0.898, -2.0) on the bottom side, w=2.947w = 2.947 1.0 box and conductor 1, a tie
L8 (0.102,−1.703)(0.102, -1.703) 0.703 conductor 1
L8 (0.323,−1.0)(0.323, -1.0) 0 conductor 1, stop

The walk ends on conductor 1, so it adds −εLw=−35.4-\varepsilon L w = -35.4 to C11C_{11} and 0 to C10C_{10}. A single sample is large and has either sign. Only the mean is meaningful:

walks NN C11C_{11} C10C_{10}
1000 5.83±0.785.83 \pm 0.78 −5.73±0.55-5.73 \pm 0.55
10000 6.36±0.256.36 \pm 0.25 −6.16±0.18-6.16 \pm 0.18
100000 6.33±0.086.33 \pm 0.08 −6.15±0.06-6.15 \pm 0.06

The error bar is one standard error, and it falls by 10\sqrt{10} for each factor of 10 in NN. With 100000 walks both estimates are within two standard errors of the finite difference values. The walks in this example took 5.0 jumps on average, with at most 41 in a sample of 5000 walks.

Correctness

The proof is in proofs/correctness.md. A harmonic function at the centre of an empty square equals the integral of its boundary values against the Poisson kernel KK, and its gradient equals the integral against ∇K\nabla K. So the potential at the walker is a martingale along the walk. The walk reaches the stopping layer with probability 1, because each jump halves the distance to the nearest conductor with a probability that does not depend on the scale, and the optional stopping theorem then says that the indicator "the walk ends on conductor jj" has mean ϕj(q)\phi_j(q). Weighting the first jump by ∇K⋅n/K\nabla K \cdot n / K is importance sampling of the gradient integral with the density KK, so each sample has mean CijC_{ij}, up to the stopping layer and the grid. The weight is bounded because Γ\Gamma stays away from the conductors, so the variance is finite and the error falls as σ/N\sigma / \sqrt{N}.

Proof: The floating random walk gives an unbiased estimate of each capacitance coefficient, with finite variancefull

We prove the claims for the two-dimensional version of the page, with squares. The three-dimensional version with cubes is the same proof with a cube in place of the square.

Setting. The free space Ω\Omega is the open region inside the grounded box minus the closed conductor rectangles D1,…,DMD_1, \ldots, D_M. The box is conductor D0D_0. The permittivity ε\varepsilon is constant. For a conductor jj, let ϕj\phi_j be the potential that is harmonic in Ω\Omega, continuous on Ω‾\overline{\Omega}, equal to 1 on DjD_j and 0 on every other conductor. The capacitance coefficient CijC_{ij} is the charge on conductor ii when the potentials are ϕj\phi_j. Let Γ\Gamma be a closed curve in Ω\Omega that surrounds DiD_i and no other conductor, with outward unit normal nn and length LL. Gauss's law gives

Cij=−ε∮Γ∇ϕj⋅n ds.(1)C_{ij} = -\varepsilon \oint_\Gamma \nabla \phi_j \cdot n \, ds. \qquad (1)

In the code Γ\Gamma is the boundary of DiD_i grown by the gap gg, and gg is less than the distance from DiD_i to every other conductor.

Lemma 1 (the square kernel). Let QQ be the closed square of half width hh centred at pp, with Q⊂Ω‾Q \subset \overline{\Omega}. If ϕ\phi is harmonic in Ω\Omega and continuous on Ω‾\overline{\Omega}, then

ϕ(p)=∮∂QK(q) ϕ(q) dq,∇ϕ(p)=∮∂Q∇pK(p,q) ϕ(q) dq,\phi(p) = \oint_{\partial Q} K(q) \, \phi(q) \, dq, \qquad \nabla \phi(p) = \oint_{\partial Q} \nabla_p K(p, q) \, \phi(q) \, dq,

where K(q)=K(p,q)K(q) = K(p, q) is the Poisson kernel of QQ at its centre. After scaling QQ to [0,π]2[0, \pi]^2, the kernel on the bottom side at abscissa uu is

K(u)=1π∑n odd(−1)(n−1)/2sin⁡nucosh⁡(nπ/2),K(u) = \frac{1}{\pi} \sum_{n \text{ odd}} (-1)^{(n-1)/2} \frac{\sin n u}{\cosh(n \pi / 2)},

the same on the other sides by symmetry, and its derivatives with respect to the centre, toward the side and along it, are the series of the functions normal_derivative and tangent_derivative.

Proof. The interior of QQ is in Ω\Omega, because hh is at most the distance from pp to every conductor in the L∞L^\infty norm. So ϕ\phi is harmonic inside QQ and continuous on QQ, and it is the Poisson integral of its boundary values. Separation of variables on [0,π]2[0, \pi]^2 gives the kernel of the bottom side at (x,y)(x, y) as 2π∑n≥1sin⁡(nu)sin⁡(nx)sinh⁡(n(π−y))/sinh⁡(nπ)\frac{2}{\pi} \sum_{n \ge 1} \sin(n u) \sin(n x) \sinh(n(\pi - y)) / \sinh(n \pi). At x=y=π/2x = y = \pi/2 the factor sin⁡(nπ/2)\sin(n \pi / 2) is 0 for even nn and (−1)(n−1)/2(-1)^{(n-1)/2} for odd nn, and sinh⁡(nπ/2)/sinh⁡(nπ)=1/(2cosh⁡(nπ/2))\sinh(n \pi / 2) / \sinh(n \pi) = 1 / (2 \cosh(n \pi / 2)), which gives the formula. Differentiating the series term by term in xx and in yy at the centre gives the two derivative series. The series converge geometrically, as e−nπ/2e^{-n \pi / 2}, so term-by-term differentiation is valid at the centre. The gradient formula is the derivative of the Poisson integral under the integral sign, which is valid at an interior point. □\square

The tests check the series against a direct sum of the kernel and against central differences, and check by quadrature that the kernel reproduces harmonic polynomials and their gradients.

Lemma 2 (each side has mass 1/4, and the weight is bounded). ∫0πK(u) du=1/4\int_0^\pi K(u) \, du = 1/4, K(u)>0K(u) > 0 on (0,π)(0, \pi), and ∣∇pK/K∣≤c/h|\nabla_p K / K| \le c / h on ∂Q\partial Q minus the corners for a constant cc that does not depend on hh.

Proof. The kernel of a domain is positive on the smooth part of the boundary, and the four sides are symmetric, so each has mass 1/41/4. Integration of the series term by term gives 4π∑n odd(−1)(n−1)/2/(ncosh⁡(nπ/2))=1/4\frac{4}{\pi} \sum_{n \text{ odd}} (-1)^{(n-1)/2} / (n \cosh(n \pi / 2)) = 1/4, which the code checks. As functions of qq, K(p,q)K(p, q) and ∇pK(p,q)\nabla_p K(p, q) are the normal derivatives of G(p,q)G(p, q) and ∇pG(p,q)\nabla_p G(p, q), where GG is the Green's function of QQ. Near a corner both are harmonic in qq and zero on the two sides, and at a right angle such a function is ar2sin⁡2θ+O(r4)a r^2 \sin 2\theta + O(r^4) in polar coordinates at the corner. So both normal derivatives vanish to first order in rr, with a>0a > 0 for GG because K>0K > 0 on the sides. So the quotient has a finite limit at each corner, and it is continuous on each side, hence bounded. The factor 1/h1/h comes from the scaling. □\square

Lemma 3 (the walk stops, and its end value is unbiased). Let X0=q∈ΩX_0 = q \in \Omega and let Xt+1X_{t+1} be drawn from KK on the largest empty square around XtX_t. Let τ\tau be the first tt with XtX_t within distance δ\delta of a conductor, and let kk be that conductor. Then τ\tau is finite with probability 1, and ∣E[ϕ(the point of Dk nearest Xτ)]−ϕ(q)∣≤δ⋅max⁡∣∇ϕ∣|E[\phi(\text{the point of } D_k \text{ nearest } X_\tau)] - \phi(q)| \le \delta \cdot \max |\nabla \phi| over the δ\delta-layer, which tends to 0 with δ\delta.

Proof. By Lemma 1, E[ϕ(Xt+1)∣Xt]=ϕ(Xt)E[\phi(X_{t+1}) \mid X_t] = \phi(X_t), so ϕ(Xt)\phi(X_t) is a martingale, bounded because ∣ϕ∣≤1|\phi| \le 1 by the maximum principle. Let zz be a conductor point at distance hh from XtX_t. It lies on ∂Q\partial Q. The points of ∂Q\partial Q within distance h/2h/2 of zz form one or two pieces of side of total length at least h/2h/2, and each of them is within h/2h/2 of the conductor. The kernel is positive and scales with hh, so the next point falls there with probability at least a constant β>0\beta > 0 that does not depend on hh or tt. So the distance to the conductors halves with probability at least β\beta at every step. Let RR be the size of the box and s=⌈log⁡2(R/δ)⌉s = \lceil \log_2(R / \delta) \rceil. From any point, ss halvings in a row reach the δ\delta-layer, so each block of ss steps stops the walk with probability at least βs\beta^s. Then P(τ>bs)≤(1−βs)bP(\tau > b s) \le (1 - \beta^s)^b, so τ\tau is finite with probability 1 and E[τ]≤s/βsE[\tau] \le s / \beta^s. The optional stopping theorem for a bounded martingale and an almost surely finite stopping time gives E[ϕ(Xτ)]=ϕ(q)E[\phi(X_\tau)] = \phi(q). Replacing ϕ(Xτ)\phi(X_\tau) by its value at the nearest conductor point moves it by at most δmax⁡∣∇ϕ∣\delta \max |\nabla \phi|. □\square

In the code the positions are integers and the walk stops when it stands on a conductor, so δ\delta is one grid unit, 2−242^{-24} of a length unit in the tests, and the only other error is the rounding of each jump to the grid. The bound on the expected number of steps above is weak. The measured number is small, as the page shows.

Theorem 4 (unbiased estimate of CijC_{ij}). Let Z=−εL w [k=j]Z = -\varepsilon L \, w \, [k = j], where rr is uniform on Γ\Gamma, QQ is the largest empty square around rr with half width hh, the first point qq is drawn from KK on ∂Q\partial Q, w=∇rK(r,q)⋅n/K(q)w = \nabla_r K(r, q) \cdot n / K(q), and kk is the conductor at the end of the walk from qq. Then, in the limit δ→0\delta \to 0, E[Z]=CijE[Z] = C_{ij}, and Var⁡(Z)<∞\operatorname{Var}(Z) < \infty.

Proof. Condition on rr and qq. By Lemma 3, E[[k=j]∣q]=ϕj(q)E[[k = j] \mid q] = \phi_j(q), since ϕj\phi_j is the indicator of jj on the conductors. So

E[w [k=j]∣r]=∮∂QK(q)∇rK(r,q)⋅nK(q)ϕj(q) dq=∇ϕj(r)⋅nE[w \, [k = j] \mid r] = \oint_{\partial Q} K(q) \frac{\nabla_r K(r, q) \cdot n}{K(q)} \phi_j(q) \, dq = \nabla \phi_j(r) \cdot n

by Lemma 1, where the density of qq is KK, with total mass 1 on the four sides by Lemma 2. Averaging over rr, uniform on Γ\Gamma with density 1/L1/L, gives E[Z]=−ε∮Γ∇ϕj⋅n ds=CijE[Z] = -\varepsilon \oint_\Gamma \nabla \phi_j \cdot n \, ds = C_{ij} by (1). For the variance, hh is at least the distance from Γ\Gamma to the conductors, which is positive, so ∣w∣≤c/h|w| \le c / h is bounded by Lemma 2, ∣Z∣|Z| is bounded, and its variance is finite. □\square

Corollary 5 (the row sums to zero, and the error falls as 1/N1/\sqrt{N}). The sum ∑jE[Zj]=∑jCij=0\sum_j E[Z_j] = \sum_j C_{ij} = 0, where jj runs over the box and all conductors, because ∑jϕj≡1\sum_j \phi_j \equiv 1 has zero gradient. The mean Zˉ\bar Z of NN independent samples has standard deviation σ/N\sigma / \sqrt{N} with σ2=Var⁡(Z)\sigma^2 = \operatorname{Var}(Z). By the Chebyshev inequality, P(∣Zˉ−Cij∣≥aσ/N)≤1/a2P(|\bar Z - C_{ij}| \ge a \sigma / \sqrt{N}) \le 1 / a^2 for every NN, and by the central limit theorem the interval Zˉ±1.96 σ^/N\bar Z \pm 1.96 \, \hat\sigma / \sqrt{N}, with the sample standard deviation σ^\hat\sigma, holds CijC_{ij} with probability that tends to 0.95. □\square

Complexity. One step of a walk finds the nearest conductor, which costs O(M)O(M) by a scan of the MM rectangles, and draws a side and a position, which costs O(log⁡G)O(\log G) for a table of GG points. With TT the mean number of steps per walk, NN walks cost O(NT(M+log⁡G))O(N T (M + \log G)) time and O(M+G)O(M + G) space. With a spatial index the nearest conductor query is faster in practice. The expected number of steps TT is finite by Lemma 3, but this proof gives no useful bound on it in terms of the geometry. It is a measured quantity. For an error of η\eta with a fixed confidence, NN grows as σ2/η2\sigma^2 / \eta^2.

Complexity

Each jump finds the nearest conductor and draws a point. A scan of the MM conductor boxes costs O(M)O(M), and the draw costs O(log⁡G)O(\log G) with a table of GG points, so NN walks of TT jumps on average cost O(NT(M+log⁡G))O(N T (M + \log G)) time, with O(M+G)O(M + G) space. What is proved is that TT is finite and that the error after NN walks is σ/N\sigma / \sqrt{N}, so NN grows as σ2/η2\sigma^2 / \eta^2 for an error η\eta. What is measured is the size of TT and σ\sigma: in the example TT was about 5 and the relative standard deviation σ/C\sigma / C of one sample was about 4. Production tools replace the scan with a spatial index over the conductor boxes, so the cost of a jump grows only slowly with MM. Unlike a quadtree or uniform grid that stores a solid in mechanical CAD, this index only has to answer one query: the distance from a point to the nearest box.

Properties

  • Randomized and unbiased up to the stopping layer. Each estimate comes with a standard error, so the user can stop when the error is small enough.
  • No mesh and no linear system. The memory is the geometry plus the tables.
  • Local. The cost of one row depends on the region the walks visit, not on the total size of the layout, so the method suits a few critical nets in a large chip.
  • Each walk is independent, so the walks run in parallel with no communication.
  • The estimated matrix is not exactly symmetric, and the coupling coefficients of far conductors have a large relative error, because few walks reach them.

Variants and improvements

  • Three dimensions. The original method uses cubes and the surface Green's function of a cube, tabulated once.
  • Layered dielectrics. The jump domain may cross the interface of two dielectrics if the transition table is computed for that case. RWCap uses tables for cubes cut by a planar interface.
  • Variance reduction. The sample variance of the gradient weight is large. Importance sampling of the first jump, stratified sampling of the start point, and antithetic pairs of walks reduce it.
  • Non-Manhattan conductors. Jump domains then need the distance to slanted or curved shapes. Xu, Zhang and Yu extended the walks to conductors of general shape in 2017.
  • Walk on spheres. Muller's method uses spheres instead of cubes, with the uniform distribution on the sphere as the transition density, which needs no table. Cubes fit Manhattan wiring better, because a face of the cube can lie flat against a wire.

When to use it

Use it for a few nets with high accuracy, for checking a fast rule-based or table-based extractor, and for structures too large for a boundary element solver such as FastCap. For the full chip, extractors use precomputed capacitance tables per pattern, which are faster but less accurate. Use a deterministic solver when the result must be repeatable to all digits, or when the whole matrix of a small structure is needed, since the walk costs grow with the number of rows.

Pitfalls

  • Do not start walks on the conductor itself. The weight has a 1/h1/h factor, and hh near 0 gives an unbounded variance. The Gaussian surface must keep a positive distance from every conductor.
  • A sample is large and of either sign. Report the standard error, and do not trust a few hundred walks.
  • The fixed seed in a test gives a repeatable result, but the tolerance must come from the standard error, not from one lucky run.
  • A coupling coefficient smaller than its standard error is not resolved. Report it as such and do not round it to zero without saying so.
  • The stopping layer and the rounding of jumps add a small bias. Keep the layer far below the smallest feature.

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.

floating_random_walk_capacitance.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/floating-random-walk-capacitance/. The authors are listed in prov/0AP7M8.jsonl.
"""Floating random walk capacitance extraction, in two dimensions.

The geometry is Manhattan. Conductors are closed axis-parallel rectangles
(x0, y0, x1, y1) with integer corners, inside a grounded box whose inner
side is the open rectangle (X0, X1) x (Y0, Y1). The box is conductor 0 and
the rectangles are conductors 1, 2, ... in the order given. Conductors must
not touch. The dielectric is uniform with permittivity eps.

Each step of a walk jumps from a point p to the boundary of the largest
square centred at p that holds no conductor, at a point drawn from the
surface Green's function (the Poisson kernel) of the square at its centre.
The square in 2D plays the part of the cube of Le Coz and Iverson in 3D.
Positions are integers, so the test "the walk stands on a conductor" is an
exact integer test, and the integer grid is the stopping layer. The only
rounding is the offset of each jump along a side of the square, which is
rounded to the grid; use coordinates large enough (for example 2**24 per
length unit) that this is negligible. The estimates are floats with a
standard error.
"""

import bisect
import math

TERMS = 30
_COSH = [math.cosh(n * math.pi / 2) for n in range(TERMS + 1)]
_SINH = [math.sinh(n * math.pi / 2) if n else 1.0 for n in range(TERMS + 1)]


def density(u):
    """Poisson kernel of the square [0, pi]^2 at its centre, for a point at
    abscissa u of one side. Each side carries total mass 1/4."""
    s = 0.0
    for n in range(1, TERMS, 2):
        s += (-1) ** ((n - 1) // 2) * math.sin(n * u) / _COSH[n]
    return s / math.pi


def normal_derivative(u):
    """Derivative of the kernel when the centre moves toward that side."""
    s = 0.0
    for n in range(1, TERMS, 2):
        s += (-1) ** ((n - 1) // 2) * n * math.sin(n * u) / _SINH[n]
    return s / math.pi


def tangent_derivative(u):
    """Derivative of the kernel when the centre moves along the side, in the
    direction of growing u."""
    s = 0.0
    for n in range(2, TERMS, 2):
        s += (-1) ** (n // 2) * n * math.sin(n * u) / _COSH[n]
    return s / math.pi


def side_cdf(u):
    """Mass of [0, u] on one side, divided by 1/4, so side_cdf(pi) = 1."""
    s = 0.0
    for n in range(1, TERMS, 2):
        s += (-1) ** ((n - 1) // 2) * (1 - math.cos(n * u)) / (n * _COSH[n])
    return 4 * s / math.pi


_GRID = 4096
_U = [math.pi * i / _GRID for i in range(_GRID + 1)]
_F = [side_cdf(u) for u in _U]
_F[-1] = 1.0


def sample_side_position(rng):
    """Draw u in [0, pi] with the density of one side, by inverting a table."""
    r = rng.random()
    i = min(bisect.bisect_right(_F, r), _GRID) - 1
    f0, f1 = _F[i], _F[i + 1]
    t = 0.0 if f1 == f0 else (r - f0) / (f1 - f0)
    return _U[i] + t * (_U[i + 1] - _U[i])


# The four sides in counterclockwise order: start corner, tangent, outward normal.
_SIDES = (
    ((-1, -1), (1, 0), (0, -1)),  # bottom
    ((1, -1), (0, 1), (1, 0)),  # right
    ((1, 1), (-1, 0), (0, 1)),  # top
    ((-1, 1), (0, -1), (-1, 0)),  # left
)


def jump(p, h, rng):
    """One jump from the centre p of an empty square of half width h.
    Returns the new point, the side and u."""
    side = rng.randrange(4)
    (sx, sy), (tx, ty), _ = _SIDES[side]
    u = sample_side_position(rng)
    off = round(2 * h * u / math.pi)
    return (p[0] + sx * h + tx * off, p[1] + sy * h + ty * off), side, u


def gradient_weight(h, side, u, normal):
    """(grad of the kernel at the centre, dotted with normal) / kernel, for a
    square of half width h; the mean of weight * phi(q) is grad(phi) . normal."""
    _, tangent, outward = _SIDES[side]
    dot = (normal_derivative(u) * (outward[0] * normal[0] + outward[1] * normal[1])
           + tangent_derivative(u) * (tangent[0] * normal[0] + tangent[1] * normal[1]))
    return math.pi / (2 * h) * dot / density(u)


class Geometry:
    def __init__(self, box, conductors):
        self.box = box
        self.rects = list(conductors)
        X0, Y0, X1, Y1 = box
        for (x0, y0, x1, y1) in self.rects:
            if not (X0 < x0 <= x1 < X1 and Y0 < y0 <= y1 < Y1):
                raise ValueError("conductor outside the box")

    def nearest(self, p):
        """(L-infinity distance to the nearest conductor, its number)."""
        x, y = p
        X0, Y0, X1, Y1 = self.box
        best, k = min(x - X0, X1 - x, y - Y0, Y1 - y), 0
        for i, (x0, y0, x1, y1) in enumerate(self.rects, 1):
            d = max(x0 - x, x - x1, y0 - y, y - y1, 0)
            if d < best:
                best, k = d, i
        return best, k


def gaussian_point(rect, gap, rng):
    """A uniform point on the rectangle rect grown by gap, with its outward normal."""
    x0, y0, x1, y1 = rect[0] - gap, rect[1] - gap, rect[2] + gap, rect[3] + gap
    w, h = x1 - x0, y1 - y0
    t = rng.randrange(2 * (w + h))
    if t < w:
        return (x0 + t, y0), (0, -1)
    t -= w
    if t < h:
        return (x1, y0 + t), (1, 0)
    t -= h
    if t < w:
        return (x1 - t, y1), (0, 1)
    t -= w
    return (x0, y1 - t), (-1, 0)


def walks(geom, i, gap, n_walks, rng, eps=1.0, max_steps=10**6):
    """Yield n_walks triples (value, conductor, end point). If phi is harmonic
    in the free space and phi = score(k, point) on conductor k, the mean of
    value * score(conductor, end) is -eps times the flux of grad(phi) out of
    the Gaussian rectangle at distance gap around conductor i. With
    score = [k == j] that mean is the capacitance coefficient C_ij."""
    rect = geom.rects[i - 1]
    length = 2 * ((rect[2] - rect[0]) + (rect[3] - rect[1]) + 4 * gap)
    for _ in range(n_walks):  # @line L1
        r, normal = gaussian_point(rect, gap, rng)  # @line L2
        h, _ = geom.nearest(r)  # @line L3
        q, side, u = jump(r, h, rng)  # @line L4
        w = gradient_weight(h, side, u, normal)  # @line L5
        for _ in range(max_steps):
            h, k = geom.nearest(q)  # @line L6
            if h == 0:  # @line L7
                break
            q, _, _ = jump(q, h, rng)  # @line L8
        else:
            raise RuntimeError("walk too long")
        yield -eps * length * w, k, q  # @line L9


def flux_estimate(geom, i, gap, n_walks, rng, score, eps=1.0):
    """Mean and standard error of the flux functional of walks()."""
    return mean_and_error([v * score(k, q) for v, k, q in walks(geom, i, gap, n_walks, rng, eps)])


def capacitance_row(geom, i, gap, n_walks, rng, eps=1.0):
    """Estimates (mean, standard error) of C_ij for j = 0 (the box), 1, 2, ...,
    all from the same walks."""
    m = len(geom.rects) + 1
    cols = [[] for _ in range(m)]
    for v, k, _ in walks(geom, i, gap, n_walks, rng, eps):
        for j in range(m):
            cols[j].append(v if j == k else 0.0)
    return [mean_and_error(c) for c in cols]


def mean_and_error(xs):
    n = len(xs)
    mu = sum(xs) / n
    var = sum((x - mu) ** 2 for x in xs) / (n - 1)
    return mu, math.sqrt(var / n)
test_floating_random_walk_capacitance.py 203 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/floating-random-walk-capacitance/. The authors are listed in prov/0AP7M8.jsonl.
"""Tests for the floating random walk. The brute force is a finite
difference solution of the Laplace equation on a grid, whose discrete
energy is an upper bound on the capacitance. Monte Carlo checks use a fixed
seed and a tolerance of 4 standard errors computed from the samples."""

import math
import random
import unittest

import floating_random_walk_capacitance as F

S = 1 << 24  # grid points per length unit
Z = 4.0  # tolerance in standard errors


def kernel(x, y, u, terms=80):
    """Poisson kernel of [0, pi]^2 at (x, y) for the point (u, 0) of the bottom side."""
    return (2 / math.pi) * sum(
        math.sin(n * u) * math.sin(n * x) * math.sinh(n * (math.pi - y)) / math.sinh(n * math.pi)
        for n in range(1, terms))


def fd_energy(box, rects, volts, cells):
    """Brute force: 5-point successive over-relaxation with `cells` cells per
    unit. Returns the sum of squared differences over grid edges, which is
    2 W / eps for the discrete field and is never below the exact value."""
    X0, Y0, X1, Y1 = box
    nx, ny = (X1 - X0) * cells, (Y1 - Y0) * cells
    phi = [[None] * (ny + 1) for _ in range(nx + 1)]
    for i in range(nx + 1):
        for j in range(ny + 1):
            if i in (0, nx) or j in (0, ny):
                phi[i][j] = float(volts[0])
    for k, (x0, y0, x1, y1) in enumerate(rects, 1):
        for i in range((x0 - X0) * cells, (x1 - X0) * cells + 1):
            for j in range((y0 - Y0) * cells, (y1 - Y0) * cells + 1):
                phi[i][j] = float(volts[k])
    free = [(i, j) for i in range(nx + 1) for j in range(ny + 1) if phi[i][j] is None]
    for i, j in free:
        phi[i][j] = 0.0
    w = 2 / (1 + math.sin(math.pi / max(nx, ny)))
    for _ in range(100000):
        delta = 0.0
        for i, j in free:
            d = w * (0.25 * (phi[i - 1][j] + phi[i + 1][j] + phi[i][j - 1] + phi[i][j + 1]) - phi[i][j])
            phi[i][j] += d
            delta = max(delta, abs(d))
        if delta < 1e-10:
            break
    e = 0.0
    for i in range(nx + 1):
        for j in range(ny + 1):
            if i < nx:
                e += (phi[i + 1][j] - phi[i][j]) ** 2
            if j < ny:
                e += (phi[i][j + 1] - phi[i][j]) ** 2
    return e


def scaled(box, rects):
    return F.Geometry(tuple(c * S for c in box), [tuple(c * S for c in r) for r in rects])


def simpson(f, a, b, n=400):
    h = (b - a) / n
    s = f(a) + f(b) + sum((4 if i % 2 else 2) * f(a + i * h) for i in range(1, n))
    return s * h / 3


class TestKernel(unittest.TestCase):
    def test_density_matches_full_kernel(self):
        c = math.pi / 2
        for u in (0.1, 0.7, 1.3, 2.2, 3.0):
            self.assertAlmostEqual(F.density(u), kernel(c, c, u), places=12)

    def test_derivatives_match_finite_differences(self):
        c, d = math.pi / 2, 1e-5
        for u in (0.2, 1.0, 1.9, 2.8):
            dx = (kernel(c + d, c, u) - kernel(c - d, c, u)) / (2 * d)
            dy = (kernel(c, c + d, u) - kernel(c, c - d, u)) / (2 * d)
            self.assertAlmostEqual(F.tangent_derivative(u), dx, places=8)
            self.assertAlmostEqual(F.normal_derivative(u), -dy, places=8)

    def test_each_side_has_mass_one_quarter(self):
        self.assertAlmostEqual(F.side_cdf(math.pi), 1.0, places=12)
        self.assertAlmostEqual(simpson(F.density, 0, math.pi), 0.25, places=9)

    def test_mean_value_for_harmonic_polynomials(self):
        # Integrate phi against the kernel over the four sides of the square
        # [-1, 1]^2; it must give phi(0, 0), and the gradient weights must
        # give grad phi(0, 0).
        polys = [
            (lambda x, y: 1.0, (0.0, 0.0)),
            (lambda x, y: x + 2 * y + 3, (1.0, 2.0)),
            (lambda x, y: x * x - y * y + 0.5, (0.0, 0.0)),
            (lambda x, y: x * y + x, (1.0, 0.0)),
            (lambda x, y: x ** 3 - 3 * x * y * y + y, (0.0, 1.0)),
        ]
        h = 1.0
        for phi, grad in polys:
            for normal in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                val = gx = 0.0
                for side, ((sx, sy), (tx, ty), _) in enumerate(F._SIDES):
                    def point(u):
                        off = 2 * h * u / math.pi
                        return sx * h + tx * off, sy * h + ty * off
                    val += simpson(lambda u: F.density(u) * phi(*point(u)), 0, math.pi)
                    gx += simpson(lambda u: F.density(u) * F.gradient_weight(h, side, u, normal) * phi(*point(u)),
                                  1e-9, math.pi - 1e-9)
                self.assertAlmostEqual(val, phi(0, 0), places=7)
                self.assertAlmostEqual(gx, grad[0] * normal[0] + grad[1] * normal[1], places=5)

    def test_sampler_follows_the_cdf(self):
        rng = random.Random(5)
        n = 20000
        xs = sorted(F.sample_side_position(rng) for _ in range(n))
        ks = max(abs((i + 1) / n - F.side_cdf(x)) for i, x in enumerate(xs))
        self.assertLess(ks, 1.63 / math.sqrt(n))  # 1 percent level of Kolmogorov-Smirnov


class TestWalk(unittest.TestCase):
    def test_conductor_outside_box_is_rejected(self):
        with self.assertRaises(ValueError):
            F.Geometry((0, 0, 10, 10), [(0, 2, 3, 4)])

    def test_nearest_is_the_linf_distance(self):
        g = F.Geometry((0, 0, 100, 60), [(10, 10, 20, 20), (50, 30, 70, 40)])
        rng = random.Random(7)
        for _ in range(500):
            p = (rng.randrange(1, 100), rng.randrange(1, 60))
            d, k = g.nearest(p)
            cand = [(min(p[0], 100 - p[0], p[1], 60 - p[1]), 0)]
            for i, r in enumerate(g.rects, 1):
                cand.append((max(r[0] - p[0], p[0] - r[2], r[1] - p[1], p[1] - r[3], 0), i))
            self.assertEqual(d, min(c[0] for c in cand))
            self.assertIn((d, k), cand)

    def test_jumps_stay_in_the_empty_square_boundary(self):
        g = scaled((-3, -3, 3, 3), [(-1, -1, 1, 1)])
        rng = random.Random(11)
        for _ in range(2000):
            p = (rng.randrange(-3 * S + 1, 3 * S), rng.randrange(-3 * S + 1, 3 * S))
            h, _ = g.nearest(p)
            if h == 0:
                continue
            q, _, _ = F.jump(p, h, rng)
            self.assertEqual(max(abs(q[0] - p[0]), abs(q[1] - p[1])), h)
            self.assertGreaterEqual(g.nearest(q)[0], 0)

    def test_every_walk_ends_on_a_conductor(self):
        g = scaled((-4, -3, 4, 3), [(-3, -1, -1, 1), (1, -1, 3, 1)])
        for v, k, q in F.walks(g, 1, S // 2, 2000, random.Random(13)):
            self.assertEqual(g.nearest(q), (0, k))

    def test_same_seed_same_result(self):
        g = scaled((-3, -3, 3, 3), [(-1, -1, 1, 1)])
        a = F.capacitance_row(g, 1, S, 300, random.Random(17))
        b = F.capacitance_row(g, 1, S, 300, random.Random(17))
        self.assertEqual(a, b)


class TestEstimates(unittest.TestCase):
    def test_flux_of_log_r_is_two_pi(self):
        # phi = log r is harmonic outside the origin, which lies inside the
        # conductor, so -flux(grad phi) = -2 pi exactly.
        g = scaled((-3, -3, 3, 3), [(-1, -1, 1, 1)])
        mu, se = F.flux_estimate(g, 1, S, 12000, random.Random(1),
                                 lambda k, p: math.log(math.hypot(p[0], p[1]) / S))
        self.assertLess(abs(mu + 2 * math.pi), Z * se)

    def test_flux_of_linear_field_is_zero(self):
        g = scaled((-3, -3, 3, 3), [(-1, -1, 1, 1)])
        mu, se = F.flux_estimate(g, 1, S, 12000, random.Random(3), lambda k, p: (p[0] + 2 * p[1]) / S)
        self.assertLess(abs(mu), Z * se)

    def test_square_coax_matches_finite_differences(self):
        box, rects = (-3, -3, 3, 3), [(-1, -1, 1, 1)]
        c_fd = fd_energy(box, rects, [0, 1], 8)
        c_fd_fine_gap = c_fd - fd_energy(box, rects, [0, 1], 4)  # negative, about 3 times the bias
        row = F.capacitance_row(scaled(box, rects), 1, S // 2, 25000, random.Random(2))
        (c10, se0), (c11, se1) = row
        self.assertLess(abs(c11 - c_fd), Z * se1 + abs(c_fd_fine_gap))
        self.assertLess(abs(c10 + c_fd), Z * se0 + abs(c_fd_fine_gap))

    def test_two_conductors_reciprocity_and_brute_force(self):
        box, rects = (-4, -3, 4, 3), [(-3, -1, -1, 1), (1, -1, 3, 1)]
        e1 = fd_energy(box, rects, [0, 1, 0], 4)
        e2 = fd_energy(box, rects, [0, 0, 1], 4)
        e12 = fd_energy(box, rects, [0, 1, 1], 4)
        c12_fd = (e12 - e1 - e2) / 2
        g = scaled(box, rects)
        r1 = F.capacitance_row(g, 1, S // 2, 15000, random.Random(19))
        r2 = F.capacitance_row(g, 2, S // 2, 15000, random.Random(23))
        self.assertLess(r1[2][0], 0)  # coupling coefficients are negative
        self.assertLess(abs(r1[2][0] - r2[1][0]), Z * math.hypot(r1[2][1], r2[1][1]))
        self.assertLess(abs(r1[2][0] - c12_fd), Z * r1[2][1] + 0.05 * abs(c12_fd))
        self.assertLess(abs(r1[1][0] - e1), Z * r1[1][1] + 0.05 * e1)


if __name__ == "__main__":
    unittest.main()

History

Muller introduced the walk on spheres for the Dirichlet problem in 1956. Le Coz and Iverson adapted it to integrated circuit capacitance in 1992, with cubes that fit Manhattan wiring and a weighted first jump for the charge. Yu and his group made it fast for layered dielectrics and parallel machines with RWCap in 2013, and later extended it to conductors of general shape.

References

  1. Y. L. Le Coz and R. B. Iverson, A stochastic algorithm for high speed capacitance extraction in integrated circuits, Solid-State Electronics 35(7), 1005 to 1012, 1992, the floating random walk on the largest empty cubes, with the surface Green's function of the cube as the transition density, applied to the capacitance of integrated circuit conductors (general locator)
  2. Mervin E. Muller, Some continuous Monte Carlo methods for the Dirichlet problem, Annals of Mathematical Statistics 27(3), 569 to 589, 1956, the walk on spheres, the jump to the boundary of the largest empty sphere, and the stopping layer of width epsilon
  3. Wenjian Yu, Hao Zhuang, Chao Zhang, Gang Hu and Zhi Liu, RWCap, a floating random walk solver for 3-D capacitance extraction of very-large-scale integration interconnects, IEEE Transactions on Computer-Aided Design 32(3), 353 to 366, 2013, the precomputed transition and weight tables for cubes in layered dielectrics, the variance reduction, and the parallel walks
  4. K. Nabors and J. White, FastCap, a multipole accelerated 3-D capacitance extraction program, IEEE Transactions on Computer-Aided Design 10(11), 1447 to 1459, 1991, the boundary element method with which floating random walk results are usually compared

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 proofH2 full proof
  • correctness: no review record reviews/0AP7M8/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example