Algorithm Search⌘K

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.

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
Properties
deterministicdivergence free grid velocityexplicitfixed cartesian gridlagrangian boundaryneeds poisson solve
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 X(s,t)\mathbf{X}(s, t) 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,

ut+(u⋅∇)u=−∇p+νΔu+f,∇⋅u=0,f(x)=∫F(s) δ(x−X(s)) ds,\mathbf{u}_t + (\mathbf{u}\cdot\nabla)\mathbf{u} = -\nabla p + \nu\Delta\mathbf{u} + \mathbf{f}, \qquad \nabla\cdot\mathbf{u} = 0, \qquad \mathbf{f}(\mathbf{x}) = \int \mathbf{F}(s)\,\delta(\mathbf{x} - \mathbf{X}(s))\,ds,

with pp the pressure divided by the density and ν\nu the kinematic viscosity. The curve moves with the fluid, Xt=u(X)\mathbf{X}_t = \mathbf{u}(\mathbf{X}), and its force density comes from its elasticity; for springs of zero rest length with stiffness κ\kappa, F=κ Xss\mathbf{F} = \kappa\,\mathbf{X}_{ss}. The discrete method uses the periodic MAC grid with MM cells of size hh and PP points Xl\mathbf{X}_l with parameter spacing Δs\Delta s, and replaces δ\delta by δh(x)=ϕ(x/h)ϕ(y/h)/h2\delta_h(\mathbf{x}) = \phi(x/h)\phi(y/h)/h^2 with Peskin's four-point kernel ϕ\phi, whose support is 4 cells wide. The cost is counted in real arithmetic operations.

The algorithm

  1. IB-STEP(u, X, κ, Δs, ν, Δt)
  2. 1F_l ← κ (X_{l+1} - 2 X_l + X_{l-1}) / Δs² ▷ elastic force at each point
  3. 2f(x) ← Σ_l F_l δ_h(x - X_l) Δs ▷ spread to the grid
  4. 3u* ← u + Δt (-(u·∇)u + ν Δ_h u + f) ▷ explicit momentum step
  5. 4solve -D G q = -D u*; u ← u* - G q; p ← q / Δt ▷ projection
  6. 5U_l ← Σ_x u(x) δ_h(x - X_l) h² ▷ interpolate to the points
  7. 6X_l ← X_l + Δt U_l
  8. 7return (u, p, X)

Lines L2 and L5 use the same weights ϕϕ\phi\phi at the 16 grid points around each membrane point, separately for the uu and the vv lattice of the staggered grid. Line L4 is the projection of Chorin's method, solved here with conjugate gradients. Peskin's kernel ϕ\phi is (3−2∣r∣+1+4∣r∣−4r2)/8(3 - 2|r| + \sqrt{1 + 4|r| - 4r^2})/8 for ∣r∣≤1|r| \le 1, (5−2∣r∣−−7+12∣r∣−4r2)/8(5 - 2|r| - \sqrt{-7 + 12|r| - 4r^2})/8 for 1≤∣r∣≤21 \le |r| \le 2, and 0 beyond. It is the unique function with this support for which, at every position rr, the weights sum to 1 separately over even and odd grid points (each half gets 1/21/2), have zero first moment, and have squares summing to 3/83/8. 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 PP points on a circle of radius RR. The discrete spring force is Fl=−κλ(Xl−c)\mathbf{F}_l = -\kappa\lambda(\mathbf{X}_l - \mathbf{c}) with λ=(2−2cos⁡Δs)/Δs2\lambda = (2 - 2\cos\Delta s)/\Delta s^2, normal to the circle and of equal size everywhere. This is a stretched band with tension κλR\kappa\lambda R, so by the Laplace law the pressure inside exceeds the pressure outside by the tension divided by the radius, κλ\kappa\lambda, and the fluid stays at rest. On the unit box with R=0.25R = 0.25, κ=1\kappa = 1 and a point spacing of about h/2h/2, the difference of the mean pressures inside and outside (cells more than 2h2h from the circle) after one spreading and one projection:

grid points measured jump κλ\kappa\lambda
16×1616 \times 16 50 0.998556 0.998685
32×3232 \times 32 101 0.999665 0.999678
64×6464 \times 64 201 0.999925 0.999919

The pressure is flat inside to within 10−310^{-3}. The jump is smeared over the support of δh\delta_h, about 2h2h 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 κ=1\kappa = 1, ν=0.1\nu = 0.1, a 32×3232 \times 32 grid and Δt=0.002\Delta t = 0.002. 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 max⁡∣Du∣<10−12\max|D\mathbf{u}| < 10^{-12} after every step (at most 7.2×10−137.2 \times 10^{-13}). 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 0≤r<10 \le r < 1 the four nonzero weights are tt, 12−t\tfrac12 - t, 1+2r4−t\tfrac{1 + 2r}{4} - t and 1−2r4+t\tfrac{1 - 2r}{4} + t with t=(1+2r−1+4r−4r2)/8t = (1 + 2r - \sqrt{1 + 4r - 4r^2})/8, which gives the even and odd sums and the first moment at once, and the sum of squares is 3/83/8 because tt is a root of 4t2−(1+2r)t+r2/2=04t^2 - (1 + 2r)t + r^2/2 = 0. Spreading is the adjoint of interpolation, so the power ∑f⋅u h2\sum\mathbf{f}\cdot\mathbf{u}\,h^2 on the grid equals ∑Fl⋅Ul Δs\sum\mathbf{F}_l\cdot\mathbf{U}_l\,\Delta s 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 hh: the uu faces at (ih,(j+12)h)(ih, (j + \tfrac12)h) and the vv faces at ((i+12)h,jh)((i + \tfrac12)h, jh). Interpolation and spreading at a point X\mathbf{X} use

δh(x−X)=1h2 ϕ ⁣(x−Xh)ϕ ⁣(y−Yh),\delta_h(\mathbf{x} - \mathbf{X}) = \frac{1}{h^2}\,\phi\!\left(\frac{x - X}{h}\right)\phi\!\left(\frac{y - Y}{h}\right),
U(Xl)=∑xu(x) δh(x−Xl) h2,f(x)=∑lFl δh(x−Xl) Δs,U(\mathbf{X}_l) = \sum_{\mathbf{x}} \mathbf{u}(\mathbf{x})\,\delta_h(\mathbf{x} - \mathbf{X}_l)\,h^2, \qquad \mathbf{f}(\mathbf{x}) = \sum_l \mathbf{F}_l\,\delta_h(\mathbf{x} - \mathbf{X}_l)\,\Delta s,

each component on its own lattice. The kernel is ϕ(r)=(3−2∣r∣+1+4∣r∣−4r2)/8\phi(r) = (3 - 2|r| + \sqrt{1 + 4|r| - 4r^2})/8 for ∣r∣≤1|r| \le 1, ϕ(r)=(5−2∣r∣−−7+12∣r∣−4r2)/8\phi(r) = (5 - 2|r| - \sqrt{-7 + 12|r| - 4r^2})/8 for 1≤∣r∣≤21 \le |r| \le 2, and 0 otherwise.

Lemma 1 (kernel conditions). For every real rr,

∑j evenϕ(r−j)=∑j oddϕ(r−j)=12,∑j(r−j) ϕ(r−j)=0,∑jϕ(r−j)2=38.\sum_{j\ \text{even}}\phi(r - j) = \sum_{j\ \text{odd}}\phi(r - j) = \tfrac12, \qquad \sum_j (r - j)\,\phi(r - j) = 0, \qquad \sum_j \phi(r - j)^2 = \tfrac38.

In particular ∑jϕ(r−j)=1\sum_j \phi(r - j) = 1.

Proof. Replacing rr by r+1r + 1 shifts the index jj by one, which swaps the even and odd sums and leaves the other two sums unchanged. So it is enough to take 0≤r<10 \le r < 1. Then only j=−1,0,1,2j = -1, 0, 1, 2 give nonzero terms, at the distances r+1r + 1, rr, 1−r1 - r and 2−r2 - r. Let σ=1+4r−4r2\sigma = \sqrt{1 + 4r - 4r^2}, which is real because 1+4r−4r2≥11 + 4r - 4r^2 \ge 1 on [0,1][0, 1]. Put the distances into the formulas:

  • ϕ(2−r)\phi(2 - r): here −7+12(2−r)−4(2−r)2=1+4r−4r2-7 + 12(2 - r) - 4(2 - r)^2 = 1 + 4r - 4r^2, so ϕ(2−r)=(1+2r−σ)/8=:t\phi(2 - r) = (1 + 2r - \sigma)/8 =: t.
  • ϕ(r)=(3−2r+σ)/8=12−t\phi(r) = (3 - 2r + \sigma)/8 = \tfrac12 - t.
  • ϕ(1−r)\phi(1 - r): here 1+4(1−r)−4(1−r)2=1+4r−4r21 + 4(1 - r) - 4(1 - r)^2 = 1 + 4r - 4r^2, so ϕ(1−r)=(1+2r+σ)/8=1+2r4−t\phi(1 - r) = (1 + 2r + \sigma)/8 = \tfrac{1 + 2r}{4} - t.
  • ϕ(1+r)\phi(1 + r): here −7+12(1+r)−4(1+r)2=1+4r−4r2-7 + 12(1 + r) - 4(1 + r)^2 = 1 + 4r - 4r^2, so ϕ(1+r)=(3−2r−σ)/8=1−2r4+t\phi(1 + r) = (3 - 2r - \sigma)/8 = \tfrac{1 - 2r}{4} + t.

The even indices are j=0,2j = 0, 2: (12−t)+t=12(\tfrac12 - t) + t = \tfrac12. The odd indices are j=−1,1j = -1, 1: 1−2r4+t+1+2r4−t=12\tfrac{1 - 2r}{4} + t + \tfrac{1 + 2r}{4} - t = \tfrac12. The first moment is (r+1)ϕ(1+r)+rϕ(r)+(r−1)ϕ(1−r)+(r−2)ϕ(2−r)=r⋅1+ϕ(1+r)−ϕ(1−r)−2t=r+1−2r4−1+2r4+2t−2t=0(r + 1)\phi(1 + r) + r\phi(r) + (r - 1)\phi(1 - r) + (r - 2)\phi(2 - r) = r \cdot 1 + \phi(1 + r) - \phi(1 - r) - 2t = r + \tfrac{1 - 2r}{4} - \tfrac{1 + 2r}{4} + 2t - 2t = 0. For the squares, write a=1−2r4a = \tfrac{1 - 2r}{4} and b=1+2r4b = \tfrac{1 + 2r}{4}:

(a+t)2+(12−t)2+(b−t)2+t2=4t2−(1+2r)t+a2+b2+14,(a + t)^2 + (\tfrac12 - t)^2 + (b - t)^2 + t^2 = 4t^2 - (1 + 2r)t + a^2 + b^2 + \tfrac14,

since 2a−2b−1=−(1+2r)2a - 2b - 1 = -(1 + 2r), and a2+b2=(1+4r2)/8a^2 + b^2 = (1 + 4r^2)/8. The number tt is a root of 4t2−(1+2r)t+r2/2=04t^2 - (1 + 2r)t + r^2/2 = 0, because the roots are ((1+2r)±(1+2r)2−8r2)/8((1 + 2r) \pm \sqrt{(1 + 2r)^2 - 8r^2})/8 and (1+2r)2−8r2=1+4r−4r2=σ2(1 + 2r)^2 - 8r^2 = 1 + 4r - 4r^2 = \sigma^2. So the sum of squares is −r2/2+(1+4r2)/8+14=38-r^2/2 + (1 + 4r^2)/8 + \tfrac14 = \tfrac38. □\square

The two formulas agree at ∣r∣=1|r| = 1 (both give 1/41/4) and the outer one is 0 at ∣r∣=2|r| = 2, so ϕ\phi is continuous with support [−2,2][-2, 2]. The test file checks the four conditions at 205 values of rr to 10−1410^{-14}.

Corollary (moments of δh\delta_h). On each lattice and for every point X\mathbf{X}, ∑xδh(x−X)h2=1\sum_{\mathbf{x}}\delta_h(\mathbf{x} - \mathbf{X})h^2 = 1 and ∑x(x−X) δh(x−X)h2=0\sum_{\mathbf{x}}(\mathbf{x} - \mathbf{X})\,\delta_h(\mathbf{x} - \mathbf{X})h^2 = 0, where x\mathbf{x} runs over the lattice points near X\mathbf{X} without wrapping.

Proof. The sum factors into a sum over ii and a sum over jj. A lattice offset (12\tfrac12 in one direction) only shifts rr, and Lemma 1 holds for every real rr. For the first moment in xx, the xx factor is h∑i(r−i)ϕ(r−i)=0h\sum_i (r - i)\phi(r - i) = 0 up to sign and the yy factor is 1. □\square

Theorem 1 (spreading is the adjoint of interpolation). For all grid velocities u\mathbf{u}, point forces Fl\mathbf{F}_l and points Xl\mathbf{X}_l,

∑xf(x)⋅u(x) h2=∑lFl⋅U(Xl) Δs.\sum_{\mathbf{x}} \mathbf{f}(\mathbf{x})\cdot\mathbf{u}(\mathbf{x})\,h^2 = \sum_l \mathbf{F}_l\cdot U(\mathbf{X}_l)\,\Delta s.

Proof. Both sides equal ∑l∑xFl⋅u(x) δh(x−Xl) h2Δs\sum_l\sum_{\mathbf{x}} \mathbf{F}_l\cdot\mathbf{u}(\mathbf{x})\,\delta_h(\mathbf{x} - \mathbf{X}_l)\,h^2\Delta s, 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. □\square

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 10−1210^{-12}, with points near the edges of the box.

Theorem 2 (total force and torque). If no stencil wraps around the box, then ∑xfh2=∑lFlΔs\sum_{\mathbf{x}}\mathbf{f}h^2 = \sum_l\mathbf{F}_l\Delta s and ∑x(xfv−yfu)h2=∑l(XlFy,l−YlFx,l)Δs\sum_{\mathbf{x}}(x f_v - y f_u)h^2 = \sum_l (X_l F_{y,l} - Y_l F_{x,l})\Delta s, with fuf_u summed over the uu lattice and fvf_v over the vv lattice.

Proof. Swap the sums: ∑xfh2=∑lFlΔs∑xδh(x−Xl)h2=∑lFlΔs\sum_{\mathbf{x}}\mathbf{f}h^2 = \sum_l \mathbf{F}_l\Delta s\sum_{\mathbf{x}}\delta_h(\mathbf{x} - \mathbf{X}_l)h^2 = \sum_l\mathbf{F}_l\Delta s by the corollary. For the torque, ∑xx δh(x−Xl)h2=Xl\sum_{\mathbf{x}} x\,\delta_h(\mathbf{x} - \mathbf{X}_l)h^2 = X_l on the vv lattice by the two moment conditions, and the same for yy on the uu lattice. □\square

Theorem 3 (incompressibility). After every step the grid velocity satisfies Du=0D\mathbf{u} = 0, for every membrane force.

Proof. Line L4 is the projection of the Chorin projection method, whose proof shows that −DG-DG is the periodic 5-point matrix, that the right side −Du∗-D\mathbf{u}^* sums to zero, and that D(u∗−Gq)=0D(\mathbf{u}^* - Gq) = 0 for the solution qq. The spread force enters only u∗\mathbf{u}^*. □\square

Termination. One step evaluates mm 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 hh for the velocity in general, because the force is singular) are not proved here.

Complexity

The force, spreading and interpolation cost Θ(P)\Theta(P) per step, with 16 grid points per point and component. The momentum step costs Θ(M)\Theta(M) and the Poisson solve costs KK conjugate gradient iterations of Θ(M)\Theta(M) each. So one step costs Θ(MK+P)\Theta(MK + P) and NN steps cost Θ(N(MK+P))\Theta(N(MK + P)), with Θ(M+P)\Theta(M + P) memory. With an FFT Poisson solver on the periodic box the step costs Θ(Mlog⁡M+P)\Theta(M\log M + P). The explicit spring force makes the method stiff: the stable Δt\Delta t falls as κ\kappa grows and as hh shrinks, and this often dominates NN.

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 16×1616 \times 16 grid with ν=0.1\nu = 0.1 and κ=1\kappa = 1, Δt=0.005\Delta t = 0.005 and 0.010.01 run smoothly, Δt=0.02\Delta t = 0.02 already shows growth (maximum velocity 0.86 after 10 steps instead of about 0.1), and Δt=0.04\Delta t = 0.04 blows up. Stiffer springs need smaller steps.
  • Points too far apart. If neighboring points are more than about hh apart, fluid leaks between them. A common rule of thumb is a spacing of about h/2h/2, 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 3×10−53 \times 10^{-5} 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.

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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example