Exercise: the level set equation

Goal

By the end of this exercise you should be able to:

  • take one time step of the level set equation on a small grid by hand, with upwind differences,
  • choose the time step from the CFL condition, and recognise what happens when it is violated,
  • predict how a curve moves under constant speed and under curvature flow,
  • explain why the implicit description handles merging and splitting, and why \phi must be reinitialised,
  • (math) derive the level set equation and the stability limit, and solve curvature flow for a circle.

Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.

Background

Idea What it means
Level set equation \phi_t + F\,\lvert\nabla\phi\rvert = 0; F = speed along the outward normal
Forward Euler step \phi^{n+1} = \phi^n - \Delta t\,F\,\lvert\nabla\phi^n\rvert
One-sided differences D^-\phi = \phi_i - \phi_{i-1} (backward), D^+\phi = \phi_{i+1} - \phi_i (forward)
Upwind, F > 0 slope^2 = \max(D^-, 0)^2 + \min(D^+, 0)^2 (per direction)
Upwind, F < 0 slope^2 = \min(D^-, 0)^2 + \max(D^+, 0)^2
CFL condition \Delta t \le \Delta x/\lvert F\rvert in 1D, \Delta x/(\sqrt2\lvert F\rvert) in 2D
Curvature flow F = -\varepsilon\kappa; a circle has r(t)^2 = r_0^2 - 2\varepsilon t; needs \Delta t \le \Delta x^2/(4\varepsilon)
Reinitialisation replace \phi by the signed distance to its zero contour

At the border of a grid, a missing neighbour is replaced by the border value itself (so the difference across the border is 0).

By hand

The 1D grid x = -3, -2, \dots, 3 (\Delta x = 1) with \phi = |x| - 1: the values 2, 1, 0, -1, 0, 1, 2. The “curve” is the interval [-1, 1].

B1. One step outward. F = 1, \Delta t = 0.5. (a) For each pixel, write D^-\phi and D^+\phi and the upwind slope. (b) Compute the new values and the new zero crossings (linear interpolation). Compare with the exact answer \pm(1 + F\Delta t). (c) Which value did not change, and why is that right?

B2. Too large a step. Repeat B1 with \Delta t = 2. What is the CFL limit here? Describe the new values. What do you expect after another step?

B3. Shrinking. F = -1, \Delta t = 0.5, same start. (a) One upwind step: compute the new value at x = 0 and at x = \pm 1. Where is the zero crossing now? (Exact: \pm 0.5.) (b) A second step: is anything still inside? When does the exact interval vanish? (c) Do the first step with central differences, \tfrac12(\phi_{i+1} - \phi_{i-1}). What happens at x = 0, now and in every later step?

B4. Grass fire. A square of side 40 moves with F = 1 for t = 5. (a) Sketch the new curve. What happens at the corners? What is the enclosed area? (b) The same square with F = -1 for t = 5: the new shape and area?

B5. Curvature flow. A circle of radius 30, \varepsilon = 1. (a) When does it vanish? What is its radius at t = 200? (b) With \Delta x = 1, what is the largest stable time step? How many steps until it vanishes? (c) The area of any simple closed curve under this flow drops by 2\pi per unit time. Check this for the circle.

B6. Predict. Two disks of radius 18 whose centres are 48 pixels apart move with F = 1. When do they merge? A dumbbell whose bar is 12 pixels thick shrinks with F = -1: when does it split? What does each look like if you move the points of a polygon instead?

B7. Time steps. On a 2D grid with \Delta x = 1: (a) F = 0.5; (b) F = 1 together with a curvature term \varepsilon = 2. Give the largest stable \Delta t in each case.

B1. (a)

x −3 −2 −1 0 1 2 3
D^- 0 −1 −1 −1 1 1 1
D^+ −1 −1 −1 1 1 1 0
upwind slope 1 1 1 0 1 1 1

(For F > 0: keep D^- if positive, D^+ if negative.) (b) New values 1.5, 0.5, -0.5, -1, -0.5, 0.5, 1.5. Crossings halfway between x = \pm 1 and \pm 2: \pm 1.5, exactly 1 + 0.5. (c) The minimum at x = 0 stays -1. The front moves outward, away from the centre: nothing changes deep inside (the exact solution |x| - 1 - t does lower it, but every value inside stays negative, which is all that matters; reinitialisation fixes the values).

B2. CFL: \Delta t \le \Delta x/F = 1, so \Delta t = 2 is twice the limit. New values: 0, -1, -2, -1, -2, -1, 0. Instead of a V moved down, a zigzag: the front would have to jump 2 pixels, but each update only sees its neighbours. Another step gives -2, -3, -2, -3.83, -2, -3, -2: the zigzag grows, and in 2D such alternating errors explode.

B3. (a) At x = 0: \min(D^-, 0) = -1 and \max(D^+, 0) = 1: slope \sqrt 2, new value -1 + 0.5\sqrt2 = -0.29. At x = \pm 1: slope 1, new value 0 + 0.5 = 0.5. Crossing between 0 (-0.29) and \pm 1 (0.5): at \pm 0.37. The exact \pm 0.5 is resolved only to about a pixel; the grid is coarse. (b) Second step: the value at x = 0 becomes 0.27, every value is positive: the interval is gone. Exactly: it vanishes at t = 1, after two steps. (c) Central difference at x = 0: (0 - 0)/2 = 0, so the value stays -1 in this step and in every later one (the two neighbours stay equal by symmetry). The neighbours rise to 0.5, 1.13, 1.86, …: the curve shrinks around x = 0 but never disappears.

B4. (a) The straight sides move out by 5; the corners become quarter circles of radius 5 around the old corners (every point at distance 5 from the square). Area 40^2 + 4 \cdot 40 \cdot 5 + \pi 5^2 = 1600 + 800 + 78.5 = 2478.5. (b) The sides move in by 5: a square of side 30 with sharp corners, area 900. Shrinking keeps corners sharp; growing rounds them.

B5. (a) r^2 = 900 - 2t: vanishes at t = 450; at t = 200, r = \sqrt{500} = 22.4. (b) \Delta t \le 1/(4\varepsilon) = 0.25: at least 1800 steps. (c) Area \pi r^2 = \pi(900 - 2t) drops by 2\pi per unit time; initial area 2827, 2827/2\pi = 450.

B6. The gap between the disks is 48 - 36 = 12 pixels; each front moves 1 per unit time, so they touch at t = 6 and the contour becomes one. The bar is 12 thick, so its two sides meet after t = 6 and the shape splits in two. With polygons, the two circles simply overlap (two curves crossing each other, each still a circle), and the shrinking dumbbell’s two sides pass through each other: the polygon becomes self-intersecting, and both cases need explicit collision detection and re-connection.

B7. (a) \Delta t \le 1/(\sqrt2 \cdot 0.5) = 1.41. (b) Wave part: 1/\sqrt2 = 0.71; curvature part 1/(4 \cdot 2) = 0.125: the curvature limit wins, \Delta t \le 0.125.

Math questions

B8. (math) Derive \phi_t + F|\nabla\phi| = 0 from \phi(\mathbf x(t), t) = 0 with \mathbf x'(t) = F\,\nabla\phi/|\nabla\phi|. What changes if a point also slides along the curve?

B9. (math) In 1D with F > 0 and D^-\phi > 0, write the upwind step as \phi_i^{n+1} = (1 - a)\phi_i^n + a\,\phi_{i-1}^n. What is a? Show that an alternating error e_i = (-1)^i\epsilon is multiplied by 1 - 2a per step, and conclude the CFL condition.

B10. (math) Solve r' = -\varepsilon/r for a circle under curvature flow. Then show that for a signed distance function the curvature flow \phi_t = \varepsilon\kappa|\nabla\phi| becomes the heat equation \phi_t = \varepsilon\nabla^2\phi, and use the explicit 5-point scheme to explain the limit \Delta t \le \Delta x^2/(4\varepsilon).

B11. (math) Show that every steady state of \phi_\tau = \operatorname{sign}(\phi_0)(1 - |\nabla\phi|) away from the zero level satisfies |\nabla\phi| = 1, and that the zero level does not move as long as \operatorname{sign}(0) = 0.

B8. Chain rule: \tfrac{d}{dt}\phi(\mathbf x(t), t) = \phi_t + \nabla\phi\cdot\mathbf x' = 0. With \mathbf x' = F\nabla\phi/|\nabla\phi|: \nabla\phi\cdot\mathbf x' = F|\nabla\phi|. Adding a tangential velocity \mathbf v with \nabla\phi\cdot\mathbf v = 0 adds nothing: the equation, and therefore the motion of the curve, is unchanged.

B9. \phi_i^{n+1} = \phi_i - \Delta t F(\phi_i - \phi_{i-1})/\Delta x: a = F\Delta t/\Delta x. With e_i = (-1)^i\epsilon: (1 - a)(-1)^i\epsilon + a(-1)^{i-1}\epsilon = (1 - 2a)(-1)^i\epsilon. Errors stay bounded iff |1 - 2a| \le 1, i.e. 0 \le a \le 1: \Delta t \le \Delta x/F. For a \le 1 the new value is also a convex combination of old ones, so no new extremes appear.

B10. r\,r' = -\varepsilon, so (r^2)' = -2\varepsilon and r^2 = r_0^2 - 2\varepsilon t. For a signed distance |\nabla\phi| = 1 and \kappa = \nabla^2\phi, so \phi_t = \varepsilon\nabla^2\phi. Explicit step: \phi_i^{n+1} = \phi_i + \tfrac{\varepsilon\Delta t}{\Delta x^2}(\phi_{\text{left}} + \phi_{\text{right}} + \phi_{\text{up}} + \phi_{\text{down}} - 4\phi_i). A checkerboard error (-1)^{i+j}\epsilon has all four neighbours of the opposite sign: it is multiplied by 1 - 8\varepsilon\Delta t/\Delta x^2, which stays in [-1, 1] iff \Delta t \le \Delta x^2/(4\varepsilon).

B11. Steady state: \operatorname{sign}(\phi_0)(1 - |\nabla\phi|) = 0; away from the zero level the sign is \pm 1, so |\nabla\phi| = 1. On the zero level \phi_0 = 0, the right-hand side is 0 and \phi stays 0 there. (With the smoothed sign S = \phi_0/\sqrt{\phi_0^2 + \Delta x^2}, pixels next to the front still move a little, which shifts the curve slightly.)

Explore: moving fronts

A 128 \times 128 grid. Left: \phi in colour (blue inside, red outside; grey level lines every 4 pixels) with the zero contour in black, or, with surface, as a 3D height field. The speed is F = c - \varepsilon\kappa; \Delta t is set as a fraction of the stability limit (shown in the readout). upwind / central chooses the differences for the c part; reinit every k steps restores a signed distance (exact method). Tick explicit polygon to move the points of the start contour with the same speed (green). Draw a closed curve on the image with the mouse to add it to the shape. The readout gives the number of contour pieces, the enclosed area, the length, and the mean |\nabla\phi| near the front.

E1. Preset two blobs merge (disks of radius 18, 48 pixels apart, F = 1). Press play. At which step and time does “pieces” drop to 1? Compare with B6. What does the green polygon do instead?

E2. Preset dumbbell splits (F = -1). When does the contour split? Watch the green polygon near the bar.

E3. Preset swallowtail (a star, F = 1, stops at t = 14). Where do loops appear in the green curve, and what does the black contour do there? Why do they appear at the dents and not at the tips?

E4. Preset Δt too large (\Delta t = 1.5 × the limit, one step per frame). Step through and read max |\phi| at steps 5, 15 and 20. Where does the noise start? Reset, set Δt/limit to 1.0 and play again.

E5. Preset central differences (a circle of radius 30 shrinking with F = -1). Play. What happens to the contour around step 45? What remains at the end? Switch to upwind and reset: when does the circle vanish? What do you expect?

E6. Preset dumbbell, curvature flow (c = 0, \varepsilon = 1, reinitialised every 25 steps). Does the neck pinch off? Read the area at t = 0, 90 and 180 and compute the rate of loss. Compare with B5(c).

E7. Preset star: corners round off (curvature flow with the explicit polygon). Describe the shape over time. Read the area at t = 0 and t = 22.5: same rate as in E6?

E8. Preset no reinitialisation (the star, curvature flow, until t = 100). Watch the grey level lines and the mean |\nabla\phi| at the front. Then set “reinit every” to 10 and reset. Compare |\nabla\phi| and the area at the end.

E1. At step 17, t = 6.0 (\Delta t = 0.354): exactly when the 12-pixel gap is closed from both sides. The green polygons keep growing as two circles that overlap: an explicit method would have to detect the overlap and re-join the curves.

E2. At step 17, t = 6.0 the contour splits into 2 pieces: the bar is 12 pixels thick, each side moves in by 6. The green polygon’s two long sides pass through each other and the polygon crosses itself.

E3. Loops (swallowtails) form at the five dents of the star, where neighbouring points move outward along converging normals and overtake each other. The black contour forms a sharp corner there instead: the “entropy” solution, the set of points at distance t from the start. At the tips the normals spread apart: points move apart (the polygon gets sparse) but no loops form.

E4. max |\phi| = 55 at step 5, 109 at step 15, 568 at step 20. The checkerboard starts in the middle of the circle, far from the front, at the kink of \phi, and grows by a large factor every step; around step 32 it reaches the contour, which falls apart into pieces, and soon the demo stops because \phi has exploded. With Δt/limit = 1.0 (\Delta t = 0.707) the run stays stable (max |\phi| about 32 after 40 steps; it decreases because the growing circle fills the grid).

E5. Around step 45 (t \approx 16) the contour breaks into dozens of small pieces: the central scheme is unstable and the kink in the middle has no slope. At the end one pixel in the middle stays inside forever while \phi grows without bound around it; the demo stops when it explodes. With upwind the circle shrinks smoothly and vanishes at step 82, t = 29.0; expected t = 30 (radius 30), the last pixel goes slightly early because the contour lies between pixels.

E6. It does not pinch: the neck widens, the shape becomes convex and rounder, and shrinks as one piece. Area 3239, 2665 and 2091 at t = 0, 90, 180: a loss of 574/90 = 6.4 per unit time in both intervals, close to 2\pi = 6.28. (Most of the area is gone around t \approx 510; the demo stops when the last inside pixel disappears, at t = 624.)

E7. The sharp tips move in fastest (large \kappa), the dents move out, and the star becomes a rounded pentagon and then a disk. Area 3480 → 3339: 141/22.5 = 6.3 per unit time, again 2\pi, independent of the shape. The green polygon behaves similarly here, but its vertices drift unevenly along the curve.

E8. Without reinitialisation, mean |\nabla\phi| at the front falls from 1.00 to 0.56 at t = 100; the grey level lines inside spread apart (deeper levels move faster, because they are more curved). With reinitialisation every 10 steps it stays 1.00. The area at the end is 2853 without and 2830 with reinitialisation: the curve itself barely changes, but derivatives and the time-step rule rely on |\nabla\phi| \approx 1.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in levelsets/src/levelset_eq/exercise.rs. The 1D grid of the exercises is an image one pixel high.

C1. upwind_gradient(phi, x, y, outward): the upwind |\nabla\phi| at one pixel:

D−x = φ(x, y) − φ(x−1, y)        D+x = φ(x+1, y) − φ(x, y)        (outside: copy the edge)
D−y, D+y likewise
if outward (F > 0):  s = max(D−x, 0)² + min(D+x, 0)² + max(D−y, 0)² + min(D+y, 0)²
else:                s = min(D−x, 0)² + max(D+x, 0)² + min(D−y, 0)² + max(D+y, 0)²
return √s

The checks are the slopes of B1(a), and \sqrt2 at x = 0 for a shrinking front (B3a).

C2. level_set_step(phi, speed, dt): one forward-Euler step, \phi - \Delta t\,F\,|\nabla\phi| at every pixel, with the upwind gradient for the sign of F there. The checks are B1(b), B2 and B3(a, b).

C3. curvature_step(phi, eps, dt): one step of curvature flow, \phi + \Delta t\,\varepsilon\,\kappa|\nabla\phi|, with central differences as in the previous unit and \kappa|\nabla\phi| = (\phi_{xx}\phi_y^2 - 2\phi_x\phi_y\phi_{xy} + \phi_{yy}\phi_x^2)/(\phi_x^2 + \phi_y^2). The check is B5: a circle of radius 20 shrinks to radius \sqrt{200} at t = 100.

C4. reinitialise(phi): replace \phi by the signed distance to its zero level:

points = every crossing of the zero level on an edge between two neighbouring pixels
         (linear interpolation)
for every pixel p:
    d = distance from p to the nearest point in points
    new φ(p) = −d if φ(p) < 0, else d

The check gives it three times a distance and expects the distance back (to within the gaps between the crossing points).

Then cargo run -p levelsets -- levelset-eq and open the pictures in out/levelset-eq/. fronts.png shows two growing disks (radius 18, centres 48 apart, F = 1), a shrinking dumbbell (bar 12 pixels thick, F = -1) and a growing square, at a few times; \Delta t = 0.5, reinitialised every 10 steps. cfl-curvature.png shows a circle after 30 steps of 1.5 times the CFL limit (black: |\phi| > 1000; red: the contour), and a star under curvature flow at t = 0, 30, 100 and 250.

C5. When do the disks merge and the dumbbell split, according to the printed times? Compare with B6. What happens at the corners of the growing square?

C6. Follow the printed largest |\phi| for the too large step, and compare with the step at the limit. Where in the picture has \phi exploded first: at the front, or elsewhere? Why does stability matter at pixels far from the front?

C7. The star under curvature flow: how many pieces does it have at each time, and how much area does it lose per unit time? Compare with the slide “The math: curvature flow”.

The model solution is levelsets/src/levelset_eq/solution.rs in the download.

C5. The disks become one piece at t = 6.0 and the dumbbell splits into two at t = 6.0, as B6 predicts: the gap of 12 pixels closes from both sides at speed 1, and the bar, 12 thick, is eaten from both sides. Nothing in the code looks for collisions: the number of pieces is only counted afterwards. The growing square keeps straight sides, and its corners become quarter circles (every point at distance t from the square, B4).

C6. At 1.5 times the limit the largest |\phi| is 55 after 5 steps, 109 after 15, 568 after 20, 3696 after 25 and 25 902 after 30: it grows several times every 5 steps. At the limit it is 39 after 30 steps (the far corners of the image, at their true distance). In the picture the exploded pixels (black) fill a region in the middle of the circle, far from the front, while the contour is still roughly round but ragged. Every pixel is updated by the same rule, and every level line moves with speed F, not only the zero one: an error that grows anywhere spreads and reaches the front sooner or later.

C7. One piece at every time (Grayson: curvature flow never splits a curve); the arms pull in, the dents fill, and by t = 250 it is nearly a circle. Area lost per unit time: 6.40 (up to t = 30), 6.20 (up to 100), 6.28 (up to 250), close to 2\pi = 6.28, as for any simple closed curve: A' = -\varepsilon\oint\kappa\,ds = -2\pi\varepsilon.

Where this leads

The speed F was a number or the curvature. The next unit lets the image choose it: fast in flat regions, almost zero on edges. Then the moving front stops on the boundary of the objects: an active contour that can split and merge. A front that only ever grows can be computed much faster by fast marching (dynamic programming day).