Algorithmadvanced
Immersed boundary method
Also called Peskin immersed boundary method.
Represents an elastic boundary by points that spread forces to a fixed grid through a smoothed delta function and move with the interpolated velocity.
- Solves
- Navier-Stokes equations
- Time
- Θ(N (M K + P)) worst
- Space
- Θ(M + P) extra
- Where
- K = the number of conjugate gradient iterations per pressure solve; M = the number of grid cells; N = the number of time steps; P = the number of membrane points
- Model
- Real RAM
- Properties
- deterministicdivergence free grid velocityexplicitfixed cartesian gridlagrangian boundaryneeds poisson solve
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles S. Peskin, 1972
The immersed boundary method computes the flow of a fluid that contains a moving elastic structure, such as a heart valve, a cell membrane or a flexible fiber, on a fixed Cartesian grid that does not follow the structure. The structure is a set of points with their own coordinates. In every time step the points compute their elastic forces, spread those forces onto nearby grid cells through a smoothed delta function, the fluid solver advances the velocity with this body force, and the points then move with the fluid velocity interpolated back from the same delta function. No grid has to be fitted to the boundary or regenerated as it moves. The price is a boundary that is smeared over a few grid cells and an accuracy near the boundary that is usually only first order in the grid spacing.
In plain words
Picture a rubber band floating in water on a sheet of graph paper. The band is drawn as a chain of beads, and the water is known only at the squares of the paper. When the band is stretched, each bead pulls on the water, and that pull is shared out among the squares near the bead, a little more to the nearest ones. The water then moves under these pulls while staying incompressible. Each bead then looks at the squares around it, takes a weighted average of their motion with the same weights, and moves by that amount. The beads and the squares always use the same weights, so the work the band does on the water is the same whether counted at the beads or at the squares.
The problem
A closed elastic curve is immersed in a fluid that fills the periodic box. The fluid obeys the incompressible Navier-Stokes equations with a body force from the curve,
with the pressure divided by the density and the kinematic viscosity. The curve moves with the fluid, , and its force density comes from its elasticity; for springs of zero rest length with stiffness , . The discrete method uses the periodic MAC grid with cells of size and points with parameter spacing , and replaces by with Peskin's four-point kernel , whose support is 4 cells wide. The cost is counted in real arithmetic operations.
The algorithm
IB-STEP(u, X, κ, Δs, ν, Δt)- 1
F_l ← κ (X_{l+1} - 2 X_l + X_{l-1}) / Δs² ▷ elastic force at each point - 2
f(x) ← Σ_l F_l δ_h(x - X_l) Δs ▷ spread to the grid - 3
u* ← u + Δt (-(u·∇)u + ν Δ_h u + f) ▷ explicit momentum step - 4
solve -D G q = -D u*; u ← u* - G q; p ← q / Δt ▷ projection - 5
U_l ← Σ_x u(x) δ_h(x - X_l) h² ▷ interpolate to the points - 6
X_l ← X_l + Δt U_l - 7
return (u, p, X)
Lines L2 and L5 use the same weights at the 16 grid points around each membrane point, separately for the and the lattice of the staggered grid. Line L4 is the projection of Chorin's method, solved here with conjugate gradients. Peskin's kernel is for , for , and 0 beyond. It is the unique function with this support for which, at every position , the weights sum to 1 separately over even and odd grid points (each half gets ), have zero first moment, and have squares summing to . The first two conditions make the interpolation exact for linear fields and keep total force and torque; the last one makes the coupling between two points almost independent of where they sit relative to the grid.
Example
A static circle. Put points on a circle of radius . The discrete spring force is with , normal to the circle and of equal size everywhere. This is a stretched band with tension , so by the Laplace law the pressure inside exceeds the pressure outside by the tension divided by the radius, , and the fluid stays at rest. On the unit box with , and a point spacing of about , the difference of the mean pressures inside and outside (cells more than from the circle) after one spreading and one projection:
| grid | points | measured jump | |
|---|---|---|---|
| 50 | 0.998556 | 0.998685 | |
| 101 | 0.999665 | 0.999678 | |
| 201 | 0.999925 | 0.999919 |
The pressure is flat inside to within . The jump is smeared over the support of , about on each side of the circle.
A relaxing ellipse. Start with 100 points on an ellipse with semi-axes 0.3 and 0.2 in fluid at rest, with , , a grid and . The tension pulls the ellipse toward a circle:
| time | width | height | relative area change |
|---|---|---|---|
| 0 | 0.6 | 0.4 | 0 |
| 0.1 | 0.5884 | 0.4064 | 3.05e-5 |
| 0.2 | 0.5686 | 0.4206 | 3.30e-5 |
| 0.3 | 0.5488 | 0.4367 | 2.88e-5 |
| 0.4 | 0.5320 | 0.4511 | 2.98e-5 |
The grid velocity has after every step (at most ). These are measurements from the implementation on this page.
Correctness
The proof is in proofs/correctness.md. It checks the four kernel conditions by direct algebra: on the four nonzero weights are , , and with , which gives the even and odd sums and the first moment at once, and the sum of squares is because is a root of . Spreading is the adjoint of interpolation, so the power on the grid equals at the points. The moment conditions show that spreading keeps the total force and the torque. The projection makes every grid velocity exactly divergence free. The pressure jump of the static circle and the stability of the explicit step are measured, not proved.
Proof: The four-point kernel meets Peskin's conditions, spreading is the adjoint of interpolation, and spreading keeps total force and torquefull
Setting. The grid and the operators are those of the main page. Each velocity component lives on its own lattice of spacing : the faces at and the faces at . Interpolation and spreading at a point use
each component on its own lattice. The kernel is for , for , and 0 otherwise.
Lemma 1 (kernel conditions). For every real ,
In particular .
Proof. Replacing by shifts the index by one, which swaps the even and odd sums and leaves the other two sums unchanged. So it is enough to take . Then only give nonzero terms, at the distances , , and . Let , which is real because on . Put the distances into the formulas:
- : here , so .
- .
- : here , so .
- : here , so .
The even indices are : . The odd indices are : . The first moment is . For the squares, write and :
since , and . The number is a root of , because the roots are and . So the sum of squares is .
The two formulas agree at (both give ) and the outer one is 0 at , so is continuous with support . The test file checks the four conditions at 205 values of to .
Corollary (moments of ). On each lattice and for every point , and , where runs over the lattice points near without wrapping.
Proof. The sum factors into a sum over and a sum over . A lattice offset ( in one direction) only shifts , and Lemma 1 holds for every real . For the first moment in , the factor is up to sign and the factor is 1.
Theorem 1 (spreading is the adjoint of interpolation). For all grid velocities , point forces and points ,
Proof. Both sides equal , component by component on each lattice; the two sides only sum in a different order. Periodic wrapping of the stencil does not matter, because both operators use the same wrapped indices and weights.
So the power that the membrane puts into the fluid, computed on the grid, equals the power computed at the points. This is the discrete form of the identity that gives energy balance for the continuous immersed boundary equations. The test file checks it with random data to , with points near the edges of the box.
Theorem 2 (total force and torque). If no stencil wraps around the box, then and , with summed over the lattice and over the lattice.
Proof. Swap the sums: by the corollary. For the torque, on the lattice by the two moment conditions, and the same for on the lattice.
Theorem 3 (incompressibility). After every step the grid velocity satisfies , for every membrane force.
Proof. Line L4 is the projection of the Chorin projection method, whose proof shows that is the periodic 5-point matrix, that the right side sums to zero, and that for the solution . The spread force enters only .
Termination. One step evaluates spring forces, spreads and interpolates over 16 grid points per component per membrane point, and solves one Poisson equation with conjugate gradients, which stops after at most its iteration limit. So each step ends after a bounded amount of work.
What is not proved. The discrete pressure jump of a static circle is measured, not proved: the spread force is not exactly a discrete gradient, so a small divergence-free part remains. The stability of the explicit step and the accuracy of the method near the membrane (first order in for the velocity in general, because the force is singular) are not proved here.
Complexity
The force, spreading and interpolation cost per step, with 16 grid points per point and component. The momentum step costs and the Poisson solve costs conjugate gradient iterations of each. So one step costs and steps cost , with memory. With an FFT Poisson solver on the periodic box the step costs . The explicit spring force makes the method stiff: the stable falls as grows and as shrinks, and this often dominates .
Properties
- The grid is fixed and Cartesian; the structure can move and deform freely without remeshing.
- Spreading and interpolation are adjoint, so energy is exchanged between structure and fluid without a numerical source in the coupling.
- Total force and torque pass unchanged from the points to the grid.
- The grid velocity is exactly divergence free; the interpolated velocity at the points is not, so enclosed areas can drift slowly.
- The interface is smeared over about four cells, and the velocity is usually first order accurate near it.
Variants and improvements
- Other kernels. Peskin's three-point and six-point kernels, and kernels built from B-splines, trade support width against smoothness and grid invariance.
- Implicit and semi-implicit time stepping removes the severe step limit of stiff structures, at the cost of a coupled solve.
- Direct forcing and discrete forcing methods compute the force that makes the velocity at the boundary equal a prescribed value, for rigid bodies; Mittal and Iaccarino (2005) survey these.
- The immersed interface method puts the jump conditions into the finite difference stencils instead of smoothing them, which gives second order accuracy.
- Adaptive and finite element versions refine the grid near the structure or describe the structure with finite elements.
- Related front methods: front tracking also carries Lagrangian points on a fixed grid for multiphase flow, and the ghost fluid method and level set method treat interfaces in an Eulerian way.
When to use it
Use the immersed boundary method when an elastic or moving structure interacts strongly with a viscous incompressible fluid and fitting a grid to the structure is hard: heart valves, swimming organisms, red blood cells, flexible fibers, insect flight. It suits low and moderate Reynolds numbers and problems where the coupling matters more than the sharpness of the boundary layer. For a rigid body at high Reynolds number, where the boundary layer must be resolved accurately, body-fitted grids, cut cells or sharp-interface direct forcing are usually better.
Pitfalls
- Stiffness and the explicit time step. On a grid with and , and run smoothly, already shows growth (maximum velocity 0.86 after 10 steps instead of about 0.1), and blows up. Stiffer springs need smaller steps.
- Points too far apart. If neighboring points are more than about apart, fluid leaks between them. A common rule of thumb is a spacing of about , which this page uses.
- Area and volume drift. The interpolated velocity is not exactly divergence free, so a closed membrane can slowly lose or gain area; here the drift stayed near of the area, but it grows with time and coarse grids.
- Smeared boundaries. The force and the pressure jump are spread over about four cells. Quantities at the boundary, such as wall shear stress, are only first order accurate.
- Stencils that cross the box. Spreading and interpolation must wrap around periodic edges, or be cut at walls with care; the moment conditions hold only for the full stencil.
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/immersed-boundary-method/. The authors are listed in prov/J7JVKP.jsonl.
"""Peskin's immersed boundary method for an elastic closed membrane in 2D flow.
Fluid: u_t + (u . grad) u = -grad p + nu Laplacian u + f, div u = 0, with p the pressure
divided by the density, on the periodic box [0, L)^2. Staggered (MAC) grid with n by n
cells of size h: p[k] at ((i + 1/2) h, (j + 1/2) h), u[k] at (i h, (j + 1/2) h) and
v[k] at ((i + 1/2) h, j h), k = i + n j.
Membrane: points X_l, l = 0..m-1, on a closed curve with parameter spacing ds. The force
of zero rest length springs is F_l = kappa (X_{l+1} - 2 X_l + X_{l-1}) / ds^2 per unit
parameter. The grid force density is f(x) = sum_l F_l delta_h(x - X_l) ds, and the
membrane velocity is U(X_l) = sum_x u(x) delta_h(x - X_l) h^2, with Peskin's four-point
delta function delta_h(x, y) = phi(x / h) phi(y / h) / h^2.
One time step: Chorin's projection method for the fluid with the spread force, then the
points move with the interpolated new velocity (forward Euler).
"""
import math
import scisparse
def phi(r):
"""Peskin's four-point kernel. For every real r: sum_j phi(r - j) = 1,
sum_j (r - j) phi(r - j) = 0, sum_j phi(r - j)^2 = 3/8, and the sums over even j
and over odd j are both 1/2 (proved on the page)."""
r = abs(r)
if r < 1:
return (3 - 2 * r + math.sqrt(1 + 4 * r - 4 * r * r)) / 8
if r < 2:
return (5 - 2 * r - math.sqrt(max(0.0, -7 + 12 * r - 4 * r * r))) / 8
return 0.0
class Grid:
def __init__(self, n, length=1.0):
self.n, self.L, self.h = n, length, length / n
self.N = n * n
self.e = [(k % n + 1) % n + n * (k // n) for k in range(self.N)]
self.w = [(k % n - 1) % n + n * (k // n) for k in range(self.N)]
self.nn = [k % n + n * ((k // n + 1) % n) for k in range(self.N)]
self.s = [k % n + n * ((k // n - 1) % n) for k in range(self.N)]
self.A = scisparse.poisson2d(n, n, self.h, self.h, bc="periodic")
def points(self, where):
sx = 0.0 if where == "u" else 0.5
sy = 0.0 if where == "v" else 0.5
return [((k % self.n + sx) * self.h, (k // self.n + sy) * self.h) for k in range(self.N)]
def _stencil(g, X, Y, sx, sy):
"""The 16 grid points (index, weight phi phi) of one component near (X, Y). The grid of
the component is shifted by (sx, sy) cells; sx, sy are 0 or 1/2."""
h, n = g.h, g.n
ax, ay = X / h - sx, Y / h - sy
i0, j0 = math.floor(ax) - 1, math.floor(ay) - 1
wx = [(i0 + a, phi(ax - (i0 + a))) for a in range(4)]
wy = [(j0 + b, phi(ay - (j0 + b))) for b in range(4)]
return [((i % n) + n * (j % n), cx * cy) for i, cx in wx for j, cy in wy]
def interpolate(g, u, v, X):
"""U(X_l) = sum_x u(x) delta_h(x - X_l) h^2 for each point; the h^2 cancels the 1/h^2."""
U = []
for x, y in X:
U.append((sum(c * u[k] for k, c in _stencil(g, x, y, 0.0, 0.5)), sum(c * v[k] for k, c in _stencil(g, x, y, 0.5, 0.0))))
return U
def spread(g, F, X, ds):
"""f(x) = sum_l F_l delta_h(x - X_l) ds on the u and v faces."""
fu, fv = [0.0] * g.N, [0.0] * g.N
s = ds / g.h**2
for (Fx, Fy), (x, y) in zip(F, X):
for k, c in _stencil(g, x, y, 0.0, 0.5):
fu[k] += c * Fx * s
for k, c in _stencil(g, x, y, 0.5, 0.0):
fv[k] += c * Fy * s
return fu, fv
def elastic_force(X, kappa, ds):
m = len(X)
return [tuple(kappa * (X[(l + 1) % m][a] - 2 * X[l][a] + X[l - 1][a]) / ds**2 for a in (0, 1)) for l in range(m)]
def divergence(g, u, v):
return [(u[g.e[k]] - u[k] + v[g.nn[k]] - v[k]) / g.h for k in range(g.N)]
def project(g, u, v):
"""Make (u, v) discretely divergence free: solve -D G q = -D u, u <- u - G q. Returns (u, v, q)."""
d = divergence(g, u, v)
mean = sum(d) / g.N
q, _ = scisparse.cg(g.A, [-(x - mean) for x in d], tol=1e-12)
u = [u[k] - (q[k] - q[g.w[k]]) / g.h for k in range(g.N)]
v = [v[k] - (q[k] - q[g.s[k]]) / g.h for k in range(g.N)]
return u, v, q
def _rhs(g, u, v, nu):
h = g.h
ru, rv = [], []
for k in range(g.N):
e, w, nn, s = g.e[k], g.w[k], g.nn[k], g.s[k]
vb = 0.25 * (v[k] + v[w] + v[nn] + v[g.w[nn]])
ru.append(nu * (u[e] + u[w] + u[nn] + u[s] - 4 * u[k]) / h**2 - (u[k] * (u[e] - u[w]) + vb * (u[nn] - u[s])) / (2 * h))
ub = 0.25 * (u[k] + u[e] + u[s] + u[g.e[s]])
rv.append(nu * (v[e] + v[w] + v[nn] + v[s] - 4 * v[k]) / h**2 - (ub * (v[e] - v[w]) + v[k] * (v[nn] - v[s])) / (2 * h))
return ru, rv
def ib_step(g, u, v, X, kappa, ds, nu, dt):
"""One immersed boundary time step. Returns (u, v, p, X) at the new time level."""
F = elastic_force(X, kappa, ds) # @line L1
fu, fv = spread(g, F, X, ds) # @line L2
ru, rv = _rhs(g, u, v, nu)
us = [u[k] + dt * (ru[k] + fu[k]) for k in range(g.N)] # @line L3
vs = [v[k] + dt * (rv[k] + fv[k]) for k in range(g.N)] # @line L3
un, vn, q = project(g, us, vs) # @line L4
U = interpolate(g, un, vn, X) # @line L5
Xn = [(x + dt * a, y + dt * b) for (x, y), (a, b) in zip(X, U)] # @line L6
return un, vn, [x / dt for x in q], Xn # @line L7
def circle(m, cx, cy, rx, ry=None):
ry = rx if ry is None else ry
return [(cx + rx * math.cos(2 * math.pi * l / m), cy + ry * math.sin(2 * math.pi * l / m)) for l in range(m)]
def polygon_area(X):
return 0.5 * sum(X[l - 1][0] * X[l][1] - X[l][0] * X[l - 1][1] for l in range(len(X)))
scisparse.py 189 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Tridiagonal solvers, sparse matrices and simple iterative solvers.
A vector is a list. A sparse matrix is a list of rows, and each row is a
dict that maps a column index to a value. Entries may be int, float or
fractions.Fraction. thomas, thomas_periodic, spmatvec, from_dense and
to_dense keep Fraction entries exact. cg takes square roots and works in
float.
API (fixed; other pages copy this file byte for byte):
thomas(a, b, c, d) solve a tridiagonal system. Row i reads
a[i] x[i-1] + b[i] x[i] + c[i] x[i+1] = d[i];
a[0] and c[n-1] are not used.
thomas_periodic(a, b, c, d) solve a cyclic tridiagonal system: as
thomas, but a[0] multiplies x[n-1] and
c[n-1] multiplies x[0]. Uses the
Sherman-Morrison formula. n >= 3.
from_dense(A) sparse copy of a dense matrix (drops zeros)
to_dense(A, ncols=None) dense copy of a sparse matrix
spmatvec(A, x) A times x
poisson2d(nx, ny, dx, dy, bc="dirichlet")
the matrix of MINUS the 5-point Laplacian
on nx by ny unknowns, numbered
k = i + nx * j (i along x, j along y).
bc = "dirichlet": unknowns at the interior
nodes ((i + 1) dx, (j + 1) dy) with zero
values outside; the matrix is symmetric
positive definite.
bc = "periodic": the grid wraps around in
both directions; the matrix is symmetric
positive semidefinite, and its null space
is the constant vectors.
bc = "neumann": unknowns at cell centers,
zero normal derivative at the walls (a
missing neighbor drops out of the
stencil); null space as for "periodic".
cg(A, b, tol=1e-10, maxit=None, x0=None)
conjugate gradient for a symmetric
positive (semi)definite A. Stops when
||b - A x||_2 <= tol * ||b||_2. Returns
(x, iterations). For a singular A, b must
be in the range of A (for the Poisson
matrices above: sum(b) = 0).
gauss_seidel(A, b, iters, x0=None)
iters forward Gauss-Seidel sweeps; every
row needs a nonzero diagonal entry.
"""
import math
def thomas(a, b, c, d):
n = len(d)
if n == 0:
return []
cp = [0] * n
dp = [0] * n
cp[0] = c[0] / b[0] if n > 1 else 0
dp[0] = d[0] / b[0]
for i in range(1, n):
m = b[i] - a[i] * cp[i - 1]
if i < n - 1:
cp[i] = c[i] / m
dp[i] = (d[i] - a[i] * dp[i - 1]) / m
x = [0] * n
x[n - 1] = dp[n - 1]
for i in range(n - 2, -1, -1):
x[i] = dp[i] - cp[i] * x[i + 1]
return x
def thomas_periodic(a, b, c, d):
"""Cyclic tridiagonal solve. A = T + u v^T with u = (gamma, 0, .., 0, c[n-1])
and v = (1, 0, .., 0, a[0] / gamma), so T is tridiagonal."""
n = len(d)
if n < 3:
raise ValueError("thomas_periodic needs n >= 3")
gamma = -b[0]
bb = list(b)
bb[0] = b[0] - gamma
bb[n - 1] = b[n - 1] - c[n - 1] * a[0] / gamma
y = thomas(a, bb, c, d)
u = [0] * n
u[0] = gamma
u[n - 1] = c[n - 1]
z = thomas(a, bb, c, u)
vy = y[0] + a[0] * y[n - 1] / gamma
vz = z[0] + a[0] * z[n - 1] / gamma
f = vy / (1 + vz)
return [y[i] - f * z[i] for i in range(n)]
def from_dense(A):
return [{j: v for j, v in enumerate(row) if v != 0} for row in A]
def to_dense(A, ncols=None):
if ncols is None:
ncols = len(A)
out = []
for row in A:
r = [0] * ncols
for j, v in row.items():
r[j] = v
out.append(r)
return out
def spmatvec(A, x):
return [sum(v * x[j] for j, v in row.items()) for row in A]
def poisson2d(nx, ny, dx, dy, bc="dirichlet"):
if bc not in ("dirichlet", "periodic", "neumann"):
raise ValueError("bc must be dirichlet, periodic or neumann")
cx = 1 / (dx * dx)
cy = 1 / (dy * dy)
A = []
for j in range(ny):
for i in range(nx):
row = {}
k = i + nx * j
for (ii, jj, w) in ((i - 1, j, cx), (i + 1, j, cx), (i, j - 1, cy), (i, j + 1, cy)):
inside = 0 <= ii < nx and 0 <= jj < ny
if bc == "periodic":
ii %= nx
jj %= ny
inside = True
if bc == "neumann" and not inside:
continue
row[k] = row.get(k, 0) + w
if inside:
m = ii + nx * jj
row[m] = row.get(m, 0) - w
A.append({m: v for m, v in row.items() if v != 0})
return A
def cg(A, b, tol=1e-10, maxit=None, x0=None):
n = len(b)
if maxit is None:
maxit = 10 * n
x = [0.0] * n if x0 is None else [float(v) for v in x0]
if x0 is None:
r = [float(v) for v in b]
else:
ax = spmatvec(A, x)
r = [b[i] - ax[i] for i in range(n)]
bnorm = math.sqrt(sum(float(v) * float(v) for v in b))
stop = tol * bnorm
rr = sum(v * v for v in r)
if math.sqrt(rr) <= stop:
return x, 0
p = list(r)
for it in range(1, maxit + 1):
ap = spmatvec(A, p)
pap = sum(p[i] * ap[i] for i in range(n))
if pap <= 0:
return x, it
alpha = rr / pap
for i in range(n):
x[i] += alpha * p[i]
r[i] -= alpha * ap[i]
rr_new = sum(v * v for v in r)
if math.sqrt(rr_new) <= stop:
return x, it
beta = rr_new / rr
rr = rr_new
p = [r[i] + beta * p[i] for i in range(n)]
return x, maxit
def gauss_seidel(A, b, iters, x0=None):
n = len(b)
x = [0] * n if x0 is None else list(x0)
for _ in range(iters):
for i in range(n):
row = A[i]
s = b[i]
diag = 0
for j, v in row.items():
if j == i:
diag = v
else:
s -= v * x[j]
x[i] = s / diag
return x
test_immersed_boundary_method.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/immersed-boundary-method/. The authors are listed in prov/J7JVKP.jsonl.
import math
import random
from immersed_boundary_method import (Grid, circle, divergence, elastic_force, ib_step, interpolate, phi,
polygon_area, project, spread)
def test_four_point_kernel_conditions():
rng = random.Random(1)
for r in [0.0, 0.5, 1.0, 1.5, 2.0] + [rng.uniform(-3, 3) for _ in range(200)]:
js = range(math.floor(r) - 3, math.floor(r) + 4)
w = [phi(r - j) for j in js]
assert abs(sum(w) - 1) < 1e-14
assert abs(sum((r - j) * phi(r - j) for j in js)) < 1e-14
assert abs(sum(x * x for x in w) - 3 / 8) < 1e-14
assert abs(sum(phi(r - j) for j in js if j % 2 == 0) - 0.5) < 1e-14
assert phi(2.0) == 0.0 and abs(phi(0.0) - 0.5) < 1e-15 # continuous, support of width 4
def test_spreading_is_the_adjoint_of_interpolation():
# sum_x f(x) . u(x) h^2 = sum_l F_l . U(X_l) ds: the power is the same on both sides.
rng = random.Random(2)
g = Grid(12)
u = [rng.uniform(-1, 1) for _ in range(g.N)]
v = [rng.uniform(-1, 1) for _ in range(g.N)]
X = [(rng.uniform(0, 1), rng.uniform(0, 1)) for _ in range(7)] # some near the edges, so wrapping is tested
F = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(7)]
ds = 0.3
fu, fv = spread(g, F, X, ds)
U = interpolate(g, u, v, X)
grid_power = sum(fu[k] * u[k] + fv[k] * v[k] for k in range(g.N)) * g.h**2
point_power = sum(a * c + b * d for (a, b), (c, d) in zip(F, U)) * ds
assert abs(grid_power - point_power) < 1e-12
def test_spreading_keeps_total_force_and_torque():
rng = random.Random(3)
g = Grid(16)
X = [(rng.uniform(0.3, 0.7), rng.uniform(0.3, 0.7)) for _ in range(5)] # support does not wrap
F = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(5)]
ds = 0.1
fu, fv = spread(g, F, X, ds)
h2 = g.h**2
assert abs(sum(fu) * h2 - sum(a for a, _ in F) * ds) < 1e-13
assert abs(sum(fv) * h2 - sum(b for _, b in F) * ds) < 1e-13
torque_grid = (sum(x * fv[k] for k, (x, _) in enumerate(g.points("v")))
- sum(y * fu[k] for k, (_, y) in enumerate(g.points("u")))) * h2
torque_points = sum(x * b - y * a for (x, y), (a, b) in zip(X, F)) * ds
assert abs(torque_grid - torque_points) < 1e-13
def test_static_circle_pressure_jump_is_the_laplace_value():
# Zero rest length springs on a circle: tension kappa R, so the jump is kappa (discrete:
# kappa (2 - 2 cos ds) / ds^2). The pressure balances the gradient part of the force.
kappa, R = 1.0, 0.25
g = Grid(16)
m = 50
ds = 2 * math.pi / m
X = circle(m, 0.5, 0.5, R)
fu, fv = spread(g, elastic_force(X, kappa, ds), X, ds)
_, _, p = project(g, fu, fv)
r = [math.hypot(x - 0.5, y - 0.5) for x, y in g.points("p")]
pin = [p[k] for k in range(g.N) if r[k] < R - 2 * g.h]
pout = [p[k] for k in range(g.N) if r[k] > R + 2 * g.h]
jump = sum(pin) / len(pin) - sum(pout) / len(pout)
exact = kappa * (2 - 2 * math.cos(ds)) / ds**2
assert abs(jump - exact) < 1e-3 # measured: 0.998556 against 0.998685
assert max(pin) - min(pin) < 1e-3 # flat inside
def test_ellipse_relaxes_toward_a_circle_and_keeps_its_area():
g = Grid(16)
m = 50
ds = 2 * math.pi / m
X = circle(m, 0.5, 0.5, 0.3, 0.2)
a0 = polygon_area(X)
u, v = [0.0] * g.N, [0.0] * g.N
for _ in range(20):
u, v, p, X = ib_step(g, u, v, X, 1.0, ds, 0.1, 0.005)
assert max(abs(x) for x in divergence(g, u, v)) < 1e-10
xs, ys = [x for x, _ in X], [y for _, y in X]
assert max(xs) - min(xs) < 0.595 and max(ys) - min(ys) > 0.403, (max(xs) - min(xs), max(ys) - min(ys))
assert abs(polygon_area(X) / a0 - 1) < 1e-3
def test_explicit_step_too_large_blows_up():
g = Grid(16)
m = 50
ds = 2 * math.pi / m
X = circle(m, 0.5, 0.5, 0.3, 0.2)
u, v = [0.0] * g.N, [0.0] * g.N
for _ in range(8):
u, v, p, X = ib_step(g, u, v, X, 1.0, ds, 0.1, 0.04) # 4 times the viscous limit h^2 / (4 nu)
assert max(map(abs, u)) > 10
History
Peskin (1972) introduced the method to compute blood flow around heart valves, with the valve leaflets as elastic fibers on a fixed grid. Over the next decades Peskin, McQueen and others developed it into a three-dimensional model of the heart, and Peskin's 2002 review in Acta Numerica set out the continuous equations, the conditions on the discrete delta function and the four-point kernel. Many related methods for rigid and elastic bodies on Cartesian grids followed under the same name, surveyed by Mittal and Iaccarino (2005).
References
- Charles S. Peskin, Flow patterns around heart valves, a numerical method, Journal of Computational Physics 10(2) (1972) 252-271, the original method for elastic boundaries in a fluid on a fixed grid
- Charles S. Peskin, The immersed boundary method, Acta Numerica 11 (2002) 479-517, the continuous equations, the conditions on the discrete delta function and the four-point kernel
- Rajat Mittal and Gianluca Iaccarino, Immersed boundary methods, Annual Review of Fluid Mechanics 37 (2005) 239-261, the survey of continuous forcing and discrete forcing variants
- Alexandre J. Chorin, Numerical solution of the Navier-Stokes equations, Mathematics of Computation 22(104) (1968) 745-762, the projection method used for the fluid step
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag J7JVKP Edit this page History Report an error Markdown