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.
- Solves
- Parasitic extraction
- 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
- Model
- Real RAM
- Properties
- randomizednot exactiterative
- Evidence
- Full proofCode in 1 languages
- 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 conductors in a uniform dielectric with permittivity , inside a grounded box, which is conductor 0. For a conductor let be the potential that solves the Laplace equation (the Poisson equation with no charge) in the free space, equals 1 on conductor and 0 on every other conductor. The capacitance coefficient is the charge on conductor under . With a closed surface around conductor only, with length (or area) and outward normal , Gauss's law gives
The diagonal coefficient is positive, the coupling coefficients with are negative, and each row sums to zero when the box is counted. The task is to estimate one row 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
FRW-ROW(conductors, i, Γ, N)C[0..M] ← 0- 1
for each of N walks do - 2
r, n ← a uniform point of Γ and the outward normal there - 3
h ← the distance from r to the nearest conductor ▷ the largest empty square around r has half width h - 4
q ← a point of that square's boundary drawn with the Green's function density K(r, ·) - 5
w ← (∇_r K(r, q) · n) / K(r, q) ▷ the weight of the first jump repeat- 6
h, k ← the distance from q to the nearest conductor, and that conductor - 7
if h ≤ δ then stop the walk at conductor k - 8
q ← a point of the boundary of the empty square of half width h around q, drawn with the density K - 9
C[k] ← C[k] − ε L w 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 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 is one grid unit in the code, which works on integer coordinates.
Example
The conductor is the square inside the grounded box , a square coaxial line, with . The surface is the square , with . 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 , 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 | nearest |
|---|---|---|---|
| L2 | , normal | 0.5 | conductor 1 |
| L4 | on the bottom side, | 1.0 | box and conductor 1, a tie |
| L8 | 0.703 | conductor 1 | |
| L8 | 0 | conductor 1, stop |
The walk ends on conductor 1, so it adds to and 0 to . A single sample is large and has either sign. Only the mean is meaningful:
| walks | ||
|---|---|---|
| 1000 | ||
| 10000 | ||
| 100000 |
The error bar is one standard error, and it falls by for each factor of 10 in . 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 , and its gradient equals the integral against . 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 " has mean . Weighting the first jump by is importance sampling of the gradient integral with the density , so each sample has mean , up to the stopping layer and the grid. The weight is bounded because stays away from the conductors, so the variance is finite and the error falls as .
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 is the open region inside the grounded box minus the closed conductor rectangles . The box is conductor . The permittivity is constant. For a conductor , let be the potential that is harmonic in , continuous on , equal to 1 on and 0 on every other conductor. The capacitance coefficient is the charge on conductor when the potentials are . Let be a closed curve in that surrounds and no other conductor, with outward unit normal and length . Gauss's law gives
In the code is the boundary of grown by the gap , and is less than the distance from to every other conductor.
Lemma 1 (the square kernel). Let be the closed square of half width centred at , with . If is harmonic in and continuous on , then
where is the Poisson kernel of at its centre. After scaling to , the kernel on the bottom side at abscissa is
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 is in , because is at most the distance from to every conductor in the norm. So is harmonic inside and continuous on , and it is the Poisson integral of its boundary values. Separation of variables on gives the kernel of the bottom side at as . At the factor is 0 for even and for odd , and , which gives the formula. Differentiating the series term by term in and in at the centre gives the two derivative series. The series converge geometrically, as , 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.
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). , on , and on minus the corners for a constant that does not depend on .
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 . Integration of the series term by term gives , which the code checks. As functions of , and are the normal derivatives of and , where is the Green's function of . Near a corner both are harmonic in and zero on the two sides, and at a right angle such a function is in polar coordinates at the corner. So both normal derivatives vanish to first order in , with for because on the sides. So the quotient has a finite limit at each corner, and it is continuous on each side, hence bounded. The factor comes from the scaling.
Lemma 3 (the walk stops, and its end value is unbiased). Let and let be drawn from on the largest empty square around . Let be the first with within distance of a conductor, and let be that conductor. Then is finite with probability 1, and over the -layer, which tends to 0 with .
Proof. By Lemma 1, , so is a martingale, bounded because by the maximum principle. Let be a conductor point at distance from . It lies on . The points of within distance of form one or two pieces of side of total length at least , and each of them is within of the conductor. The kernel is positive and scales with , so the next point falls there with probability at least a constant that does not depend on or . So the distance to the conductors halves with probability at least at every step. Let be the size of the box and . From any point, halvings in a row reach the -layer, so each block of steps stops the walk with probability at least . Then , so is finite with probability 1 and . The optional stopping theorem for a bounded martingale and an almost surely finite stopping time gives . Replacing by its value at the nearest conductor point moves it by at most .
In the code the positions are integers and the walk stops when it stands on a conductor, so is one grid unit, 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 ). Let , where is uniform on , is the largest empty square around with half width , the first point is drawn from on , , and is the conductor at the end of the walk from . Then, in the limit , , and .
Proof. Condition on and . By Lemma 3, , since is the indicator of on the conductors. So
by Lemma 1, where the density of is , with total mass 1 on the four sides by Lemma 2. Averaging over , uniform on with density , gives by (1). For the variance, is at least the distance from to the conductors, which is positive, so is bounded by Lemma 2, is bounded, and its variance is finite.
Corollary 5 (the row sums to zero, and the error falls as ). The sum , where runs over the box and all conductors, because has zero gradient. The mean of independent samples has standard deviation with . By the Chebyshev inequality, for every , and by the central limit theorem the interval , with the sample standard deviation , holds with probability that tends to 0.95.
Complexity. One step of a walk finds the nearest conductor, which costs by a scan of the rectangles, and draws a side and a position, which costs for a table of points. With the mean number of steps per walk, walks cost time and space. With a spatial index the nearest conductor query is faster in practice. The expected number of steps 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 with a fixed confidence, grows as .
Complexity
Each jump finds the nearest conductor and draws a point. A scan of the conductor boxes costs , and the draw costs with a table of points, so walks of jumps on average cost time, with space. What is proved is that is finite and that the error after walks is , so grows as for an error . What is measured is the size of and : in the example was about 5 and the relative standard deviation 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 . 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 factor, and 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.
# 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
- 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)
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 0AP7M8 Edit this page History Report an error Markdown