Algorithm Search⌘K

Algorithmadvanced

Elliptic grid generation

Also called Winslow grid generation, Thompson-Thames-Mastin method.

Computes a structured grid by solving Laplace or Poisson equations for the computational coordinates; the continuous map never folds, and control functions set the spacing.

Time
O(n^2) gauss_seidel_modelO(n) per_sweepO(n^(3/2)) sor_model
Space
O(n) extra
Where
n = the number of grid points (M + 1)(N + 1)
Properties
deterministicnot exactiterative
Origin
Alan M. Winslow, Joe F. Thompson, Frank C. Thames, C. Wayne Mastin, 1966

Elliptic grid generation makes a structured grid inside a block by asking that the computational coordinates ξ\xi and η\eta be harmonic functions of the physical coordinates, or solutions of a Poisson equation with chosen right-hand sides. The equations are inverted, so that the unknowns are the physical positions x(ξ,η)x(\xi, \eta) of the grid points, and solved by finite differences and an iteration such as successive over-relaxation, starting from a transfinite interpolation grid. The grids are smooth. For the Laplace case, the continuous map is one to one on any domain bounded by a Jordan curve, by the Radó-Kneser-Choquet theorem. The discrete grid does not inherit this guarantee, so it must still be checked.

In plain words

Think of the grid lines of one family as lines of equal temperature in a metal plate. Hold one side of the plate at one temperature and the opposite side at another, and the heat spreads evenly between them. Lines of equal temperature never cross, and they bend smoothly around dents in the plate. Do the same with the other two sides, and the two families of lines form the grid.

To compute this, the program moves each inner grid point toward a weighted average of its neighbours. It does this again and again until the points stop moving. Extra terms can pull the lines closer to a wall, where a flow solver needs small cells.

The smooth lines of the exact solution never cross. The computed grid is only close to them, so a program still checks every cell.

The problem

This is structured grid generation for one block. The input is four sides given as point lists, as for transfinite interpolation: the bottom B0,…,BMB_0, \ldots, B_M, the top T0,…,TMT_0, \ldots, T_M, the left L0,…,LNL_0, \ldots, L_N and the right R0,…,RNR_0, \ldots, R_N, with common corners. Optional inputs are control functions Pij,QijP_{ij}, Q_{ij}, a relaxation factor 0<ω<20 < \omega < 2, a tolerance and a maximum number of sweeps. The output is a grid xijx_{ij} with the given boundary points that satisfies the discrete equations below to the tolerance, and a flag that says whether it converged. A grid is valid if every cell is a strictly convex counterclockwise quadrilateral.

The continuous equations, with ξ\xi and η\eta the indices ii and jj seen as continuous variables, are

α xξξ−2β xξη+γ xηη+J2(P xξ+Q xη)=0,\alpha\, x_{\xi\xi} - 2 \beta\, x_{\xi\eta} + \gamma\, x_{\eta\eta} + J^2 (P\, x_\xi + Q\, x_\eta) = 0,
α=∣xη∣2,β=xξ⋅xη,γ=∣xξ∣2,J=det⁡(xξ,xη),\alpha = |x_\eta|^2, \quad \beta = x_\xi \cdot x_\eta, \quad \gamma = |x_\xi|^2, \quad J = \det(x_\xi, x_\eta),

for both coordinates of x=(x,y)x = (x, y). They are equivalent, where J≠0J \ne 0, to ξxx+ξyy=P\xi_{xx} + \xi_{yy} = P and ηxx+ηyy=Q\eta_{xx} + \eta_{yy} = Q. With P=Q=0P = Q = 0 this is Winslow's method. Thompson, Thames and Mastin introduced the control functions PP and QQ.

The algorithm

ORIENT2D is the orientation test. CHECK converts each stored float to a Fraction without rounding, so its signs are exact for the points as stored.

  1. ELLIPTIC-GRID(B, T, L, R, P, Q, ω, tol, K)
  2. 1x ← TFI(B, T, L, R) ▷ the sides stay fixed from here on
  3. 2for k ← 1 to K do
  4. 3for i ← 1 to M − 1 do
  5. 4for j ← 1 to N − 1 do
  6. 5x_ξ ← (x_{i+1,j} − x_{i−1,j})/2; x_η ← (x_{i,j+1} − x_{i,j−1})/2
  7. 6α ← |x_η|²; β ← x_ξ · x_η; γ ← |x_ξ|²; J ← det(x_ξ, x_η)
  8. 7X ← (x_{i+1,j+1} − x_{i+1,j−1} − x_{i−1,j+1} + x_{i−1,j−1})/4
  9. 8G ← [α(x_{i+1,j} + x_{i−1,j}) + γ(x_{i,j+1} + x_{i,j−1}) − 2βX + J²(P_ij x_ξ + Q_ij x_η)] / (2(α + γ))
  10. 9x_ij ← x_ij + ω (G − x_ij)
  11. 10r ← max over inner points of |G_ij(x) − x_ij| ▷ L5 to L8 on the new grid
  12. 11if r < tol then return (x, converged)
  13. 12return (x, not converged)
  14. CHECK(x)
  15. 13for each cell with corners q_0 = x_ij, q_1 = x_{i+1,j}, q_2 = x_{i+1,j+1}, q_3 = x_{i,j+1} do
  16. 14if ORIENT2D(q_{k−1}, q_k, q_{k+1}) ≤ 0 for some k = 0..3 then return false
  17. 15return true

L5 to L7 are central differences with unit index spacing. L8 solves the discrete equation at (i,j)(i, j) for xijx_{ij}, with the neighbours and the coefficients fixed. With ω=1\omega = 1 this is a nonlinear Gauss-Seidel method, and with 1<ω<21 < \omega < 2 it is point SOR. The coefficients are recomputed at each point from the newest values, so the iteration is a Picard iteration on a nonlinear system. L10 measures the residual of every equation, divided by 2(α+γ)2(\alpha + \gamma), on the grid after the sweep.

Example

One inner point. Take the trapezoid with corners (0,0)(0, 0), (4,0)(4, 0), (2,2)(2, 2), (0,2)(0, 2) and M=N=2M = N = 2, with the side midpoints (2,0)(2, 0), (1,2)(1, 2), (0,1)(0, 1) and (3,1)(3, 1). TFI puts the inner point at (3/2,1)(3/2, 1). With one inner point, L5 to L8 use only boundary points, so one sweep with ω=1\omega = 1 gives the solution.

step value
L5 xξ=((3,1)−(0,1))/2=(3/2,0)x_\xi = ((3, 1) - (0, 1))/2 = (3/2, 0), xη=((1,2)−(2,0))/2=(−1/2,1)x_\eta = ((1, 2) - (2, 0))/2 = (-1/2, 1)
L6 α=5/4\alpha = 5/4, β=−3/4\beta = -3/4, γ=9/4\gamma = 9/4, J=3/2J = 3/2
L7 X=((2,2)−(4,0)−(0,2)+(0,0))/4=(−1/2,0)X = ((2, 2) - (4, 0) - (0, 2) + (0, 0))/4 = (-1/2, 0)
L8 G=[54(3,2)+94(3,2)−2(−34)(−12,0)]/7=(39/28,1)G = \big[\tfrac54 (3, 2) + \tfrac94 (3, 2) - 2 (-\tfrac34)(-\tfrac12, 0)\big] / 7 = (39/28, 1)
L10 r=0r = 0 after the sweep, so L11 returns

The point moves from x=1.5x = 1.5 to x=39/28≈1.393x = 39/28 \approx 1.393, a shift of 3/283/28 to the left. The term −2βX-2\beta X is the whole difference: without it, the point would stay at (3/2,1)(3/2, 1).

A conformal map as an oracle. Take the sector of an annulus with the grid points xij=eκi(cos⁡κj,sin⁡κj)x_{ij} = e^{\kappa i} (\cos \kappa j, \sin \kappa j) on the sides, with κ=π/(2N)\kappa = \pi / (2N) and M=NM = N. The map (ξ,η)↦eκξ(cos⁡κη,sin⁡κη)(\xi, \eta) \mapsto e^{\kappa \xi} (\cos \kappa \eta, \sin \kappa \eta) is conformal, so ξ\xi and η\eta are harmonic and this map is the exact continuous solution. The largest distance of the converged grid from it is 0.03450.0345, 0.00880.0088, 0.00230.0023 and 0.000570.00057 for N=4,8,16,32N = 4, 8, 16, 32, so the error falls by a factor of about 4 when the grid is refined, as expected for central differences. The TFI start is wrong by about 0.210.21 at every resolution.

A grid that converges and is still not valid. Take the unit square with the bottom side replaced by the hook (0,0)→(3/5,1/5)→(2/5,2/5)→(1,0)(0, 0) \to (3/5, 1/5) \to (2/5, 2/5) \to (1, 0), the domain of the folding example of the transfinite interpolation page, with M=6M = 6 and N=4N = 4. The boundary angle at (2/5,2/5)(2/5, 2/5) is about 349°349°. The TFI start has two cells turned over. ELLIPTIC-GRID with ω=1.5\omega = 1.5 converges to a residual below 10−1210^{-12} in 43 sweeps. No cell is turned over anymore, but two cells next to the hook have one or two negative corner values, so CHECK returns false. Grids of 12×812 \times 8 and 24×1624 \times 16 cells on the same domain also fail CHECK near the hook.

Convex quadrilaterals. On 25 random convex quadrilaterals with random point spacing on the sides and 6 to 12 cells per direction, 5 of the TFI starts fail CHECK, and every converged elliptic grid passes it. This is what the tests observe, not a theorem.

Correctness

The procedure keeps the boundary points, because it writes only inner points, and it stops after at most KK sweeps. When it reports convergence, every discrete equation holds with a residual below 2(α+γ)2(\alpha + \gamma) times the tolerance. If the sides are evenly spaced samples of an affine map, the TFI start already solves the equations, so the method reproduces parallelograms.

The reason elliptic grids do not fold is a theorem about the continuous map.

Theorem (Radó-Kneser-Choquet). Let Ω\Omega be a bounded convex domain whose boundary is a Jordan curve Γ\Gamma, and let φ\varphi be a homeomorphism of the unit circle onto Γ\Gamma. Then the harmonic extension of φ\varphi to the unit disk is a one-to-one map of the disk onto Ω\Omega with nonvanishing Jacobian.

Duren proves it in the chapter "Harmonic Mappings onto Convex Regions" of his book. The idea of Kneser's proof is that a linear combination aF1+bF2−ca F_1 + b F_2 - c of the two coordinate functions changes sign at most twice on the circle, because a line cuts a convex curve at most twice. A critical point would need four sign changes, so the gradients of F1F_1 and F2F_2 are independent everywhere.

Winslow's map (ξ,η)(\xi, \eta) goes from the physical domain Ω\Omega to the rectangle RR of indices, and the theorem needs the target to be convex. RR is convex. A conformal map of the disk onto Ω\Omega, which exists by the Riemann mapping theorem and extends to the boundary by Carathéodory's theorem, carries the theorem from the disk to Ω\Omega. So for any domain bounded by a Jordan curve, convex or not, (ξ,η)(\xi, \eta) is one to one with nonvanishing Jacobian, and its inverse, the grid map, has grid lines that never cross. If instead xx and yy were made harmonic in ξ\xi and η\eta, the target would be Ω\Omega, and the map could fold on a non-convex domain. Control functions P,Q≠0P, Q \ne 0 also leave the theorem behind.

The discrete grid inherits only part of this. Its equations are a finite difference approximation with coefficients that depend on the solution, and they have no maximum principle of the kind the proof needs. If discrete solutions converge to the continuous map, cells away from the boundary are positive on fine enough grids. Near the boundary, and at a reentrant corner, nothing is guaranteed, and the hook example shows a converged grid that fails CHECK. The full proofs are below.

Proof: Elliptic grid generation keeps the boundary, certifies its residual, and stops; the continuous Winslow map is a diffeomorphismfull

The page makes two kinds of claims. Part A is about the procedure ELLIPTIC-GRID as it runs. Part B is about the continuous map that the discrete equations approximate. It rests on the Radó-Kneser-Choquet theorem, which is cited with its proof, and it says what the discrete grid does not inherit.

Part A: the procedure

Claim A. Let the sides B,T,L,RB, T, L, R meet at common corners, let 0<ω<20 < \omega < 2, tol>0\mathrm{tol} > 0 and K≥1K \ge 1. Then ELLIPTIC-GRID:

  1. returns a grid whose boundary points are the input side points;
  2. stops after at most KK sweeps;
  3. returns "converged" only if every interior point satisfies ∣Gij(x)k−xij,k∣<tol\lvert G_{ij}(x)_k - x_{ij,k} \rvert < \mathrm{tol} for both coordinates kk, where Gij(x)G_{ij}(x) is the value of L5 to L8 at (i,j)(i, j) for the returned grid;
  4. with P=Q=0P = Q = 0 and exact arithmetic, if the side points are evenly spaced samples of an affine map A(u,v)=a+bu+cvA(u, v) = a + b u + c v, returns the grid xij=A(i/M,j/N)x_{ij} = A(i/M, j/N) after one sweep.

Step 1 (the discrete equation). At an interior point, with unit index spacing, L5 to L7 compute xξ=(xi+1,j−xi−1,j)/2x_\xi = (x_{i+1,j} - x_{i-1,j})/2, xη=(xi,j+1−xi,j−1)/2x_\eta = (x_{i,j+1} - x_{i,j-1})/2, α=∣xη∣2\alpha = |x_\eta|^2, β=xξ⋅xη\beta = x_\xi \cdot x_\eta, γ=∣xξ∣2\gamma = |x_\xi|^2, J=det⁡(xξ,xη)J = \det(x_\xi, x_\eta) and the cross difference X=(xi+1,j+1−xi+1,j−1−xi−1,j+1+xi−1,j−1)/4X = (x_{i+1,j+1} - x_{i+1,j-1} - x_{i-1,j+1} + x_{i-1,j-1})/4. None of these depend on xijx_{ij}. The discrete equation is

α(xi+1,j−2xij+xi−1,j)−2βX+γ(xi,j+1−2xij+xi,j−1)+J2(Pijxξ+Qijxη)=0.\alpha (x_{i+1,j} - 2 x_{ij} + x_{i-1,j}) - 2 \beta X + \gamma (x_{i,j+1} - 2 x_{ij} + x_{i,j-1}) + J^2 (P_{ij} x_\xi + Q_{ij} x_\eta) = 0.

It is linear in xijx_{ij} with coefficient −2(α+γ)-2(\alpha + \gamma). If α+γ>0\alpha + \gamma > 0, its unique solution for xijx_{ij} with the neighbours fixed is the value GijG_{ij} of L8, and the left side equals 2(α+γ)(Gij−xij)2(\alpha + \gamma)(G_{ij} - x_{ij}). So Gij−xijG_{ij} - x_{ij} is the residual of the equation divided by 2(α+γ)2(\alpha + \gamma). If α+γ=0\alpha + \gamma = 0, then xi+1,j=xi−1,jx_{i+1,j} = x_{i-1,j} and xi,j+1=xi,j−1x_{i,j+1} = x_{i,j-1}, the grid has collapsed there, and the code stops with an error.

Step 2 (parts 1 and 2). L1 builds the initial grid by transfinite interpolation, whose boundary points are the side points. The code copies them, so that float rounding cannot move them. The loops of L3 and L4 run over 1≤i≤M−11 \le i \le M - 1 and 1≤j≤N−11 \le j \le N - 1 only, so no boundary point is written later. This is part 1. The loop of L2 runs at most KK times. Each sweep and each residual of L10 visits (M−1)(N−1)(M - 1)(N - 1) points with a constant number of operations, and every exit is a return. This is part 2.

Step 3 (part 3). L10 computes r=max⁡ijmax⁡k∣Gij(x)k−xij,k∣r = \max_{ij} \max_k \lvert G_{ij}(x)_k - x_{ij,k} \rvert on the grid after the sweep, with the same formula as L5 to L8. L11 returns "converged" only if r<tolr < \mathrm{tol}. By Step 1, this bounds the residual of every discrete equation by 2(α+γ) tol2(\alpha + \gamma)\,\mathrm{tol} at that point. In floating point, the bound holds for the computed values of GijG_{ij}. The tests check it again with a separate formula for the discrete equation.

Step 4 (part 4). TFI reproduces data that are linear in each parameter, as proved on the transfinite interpolation page, so the initial grid is xij=A(i/M,j/N)x_{ij} = A(i/M, j/N). Then xξ=b/Mx_\xi = b/M and xη=c/Nx_\eta = c/N at every interior point, all second differences and the cross difference XX vanish, and the discrete equation with P=Q=0P = Q = 0 reads 0=00 = 0. So Gij=xijG_{ij} = x_{ij} at every point, the first sweep changes nothing, r=0<tolr = 0 < \mathrm{tol}, and the procedure returns after one sweep. ■\blacksquare

Part B: the continuous map

Theorem (Radó-Kneser-Choquet). Let D\mathbb{D} be the open unit disk, let Ω⊂R2\Omega \subset \mathbb{R}^2 be a bounded convex domain whose boundary is a Jordan curve Γ\Gamma, and let φ:∂D→Γ\varphi : \partial \mathbb{D} \to \Gamma be a homeomorphism. Let FF be the harmonic extension of φ\varphi to D\mathbb{D}, the Poisson integral of each coordinate. Then FF is a one-to-one harmonic map of D\mathbb{D} onto Ω\Omega, and its Jacobian does not vanish in D\mathbb{D}.

This is the theorem as stated and proved in Duren, Harmonic Mappings in the Plane, in the chapter "Harmonic Mappings onto Convex Regions" (p. 29, with Choquet's proof on p. 31). Duren allows a more general boundary function, which only makes the theorem stronger. We use it without a full proof here. Its proof, in Kneser's form, goes as follows. For a line ax+by=ca x + b y = c, the harmonic function h=aF1+bF2−ch = a F_1 + b F_2 - c has boundary values that change sign at most twice on the circle, because a line meets the boundary of a convex domain in at most two points or in one segment. If ∇h\nabla h vanished at some point z0z_0, the level set {h=h(z0)}\{h = h(z_0)\} would leave z0z_0 in at least four arcs, which by the maximum principle reach the circle and separate regions where h−h(z0)h - h(z_0) alternates in sign, so the boundary values of h−h(z0)h - h(z_0) would change sign at least four times. So a∇F1+b∇F2≠0a \nabla F_1 + b \nabla F_2 \ne 0 for all (a,b)≠0(a, b) \ne 0, which says that the rows of the Jacobian matrix are independent. A map with a nonvanishing Jacobian whose boundary map runs once around Γ\Gamma is one to one, by a degree argument.

Winslow's equations. If ξ(x,y)\xi(x, y) and η(x,y)\eta(x, y) are harmonic and the map (ξ,η)(\xi, \eta) has an inverse x(ξ,η)x(\xi, \eta), then the inverse satisfies αxξξ−2βxξη+γxηη=0\alpha x_{\xi\xi} - 2 \beta x_{\xi\eta} + \gamma x_{\eta\eta} = 0 for both coordinates. This follows from the chain rule with ξx=yη/J\xi_x = y_\eta / J, ξy=−xη/J\xi_y = -x_\eta / J, ηx=−yξ/J\eta_x = -y_\xi / J and ηy=xξ/J\eta_y = x_\xi / J, as derived by Winslow and in Thompson, Warsi and Mastin. These are the equations that ELLIPTIC-GRID discretizes with P=Q=0P = Q = 0.

Where convexity is needed. In the claim below, the convex set is the rectangle RR, the target of (ξ,η)(\xi, \eta), and the physical domain can be any Jordan domain. If instead xx and yy are taken harmonic in (ξ,η)(\xi, \eta), so that the map goes from RR onto Ω\Omega, then the theorem needs Ω\Omega convex, and on a non-convex Ω\Omega that map can fold. With control functions P,Q≠0P, Q \ne 0, ξ\xi and η\eta are not harmonic and the theorem does not apply.

What the discrete grid does not inherit. The claim below is about the exact solution of a differential equation. ELLIPTIC-GRID solves a finite difference approximation of it on a fixed grid, and no theorem says that the discrete solution has positive cells. The discrete equations have no maximum principle of the kind the proof of the theorem needs, because their coefficients depend on the solution. What holds is a conditional statement: if the discrete solutions converge to the smooth map xx in C1C^1 on a compact set KK inside the domain, then for a fine enough grid the cells in KK have positive corner Jacobians, since the Jacobian of xx is bounded away from 0 on KK. Near the boundary, and especially at a reentrant corner, the Jacobian of xx tends to 0 or to infinity, and this argument gives nothing. The test file has such a case: on a domain with a boundary angle of about 349°349°, the discrete grid converges to a residual below 10−1010^{-10} and still has two cells that are not convex. So the grid must be checked with exact orientation signs, which is what CHECK does.

Claim B. Let Ω\Omega be a bounded domain whose boundary is a Jordan curve, convex or not. Let s:∂Ω→∂Rs : \partial \Omega \to \partial R be a homeomorphism onto the boundary of the rectangle R=[0,M]×[0,N]R = [0, M] \times [0, N] that maps the four sides of the block to the four sides of RR. Let ξ,η\xi, \eta be the harmonic functions on Ω\Omega with boundary values ss. Then (ξ,η)(\xi, \eta) is a one-to-one map of Ω\Omega onto the interior of RR with nonvanishing Jacobian. Its inverse x(ξ,η)x(\xi, \eta) is smooth with nonvanishing Jacobian, so its grid lines, the level curves of ξ\xi and of η\eta, never cross or touch in Ω\Omega.

Proof. By the Riemann mapping theorem there is a conformal map ψ:D→Ω\psi : \mathbb{D} \to \Omega, and by Carathéodory's theorem it extends to a homeomorphism of ∂D\partial \mathbb{D} onto ∂Ω\partial \Omega, because ∂Ω\partial \Omega is a Jordan curve. A harmonic function composed with a holomorphic map is harmonic, so (ξ,η)∘ψ(\xi, \eta) \circ \psi is the harmonic extension to D\mathbb{D} of the homeomorphism s∘ψ:∂D→∂Rs \circ \psi : \partial \mathbb{D} \to \partial R. The rectangle RR is convex, so by the theorem, (ξ,η)∘ψ(\xi, \eta) \circ \psi is one to one onto the interior of RR with nonvanishing Jacobian. Since ψ\psi is one to one and conformal, with nonvanishing derivative, (ξ,η)=((ξ,η)∘ψ)∘ψ−1(\xi, \eta) = ((\xi, \eta) \circ \psi) \circ \psi^{-1} is one to one on Ω\Omega with nonvanishing Jacobian. By the inverse function theorem its inverse is smooth with nonvanishing Jacobian. Two lines of the same family, ξ=a1\xi = a_1 and ξ=a2\xi = a_2 with a1≠a2a_1 \ne a_2, never meet because ξ\xi is a function. A line ξ=a\xi = a and a line η=b\eta = b meet in exactly one point, because the map is one to one, and they cross there at a nonzero angle, because the gradients of ξ\xi and η\eta are independent. ■\blacksquare

Complexity

Each sweep visits the (M−1)(N−1)(M - 1)(N - 1) inner points with a constant amount of work, so it costs O(n)O(n) time for nn grid points, and the grid needs O(n)O(n) space. The number of sweeps has no proved bound, because the iteration is nonlinear. For the linear model problem, the Laplace equation on a square, Gauss-Seidel needs O(n)O(n) sweeps for a fixed reduction of the error, and SOR with the best ω\omega needs O(n)O(\sqrt{n}), so the totals are O(n2)O(n^2) and O(n3/2)O(n^{3/2}). The elliptic iteration behaves about the same in practice: 41 to 94 sweeps to a residual below 10−1210^{-12} for the random convex quadrilaterals above with ω=1.5\omega = 1.5. Multigrid reaches O(n)O(n) work for the linear problem and is used for large grids.

Properties

  • Smooth. Grid lines are smooth inside the domain, and spacing changes smoothly even when the boundary spacing jumps.
  • No folding in the continuous limit. With P=Q=0P = Q = 0 the continuous map is one to one on every Jordan domain.
  • Boundary fixed. The boundary points never move. Orthogonality at the boundary is not enforced unless the control functions are chosen for it.
  • Lines crowd at convex sides and spread at concave sides. In the annulus sector, the circles of the exact solution have radii in geometric progression, so they are closer together near the inner circle, the convex side. A side that bends into the domain gets wider cells.
  • Reproduces affine grids. A parallelogram with evenly spaced sides is a fixed point.
  • Iterative. The result depends on the tolerance, and the run time on ω\omega and the start.

Variants and improvements

  • Control functions. Thompson, Thames and Mastin chose PP and QQ as sums of exponential attraction terms toward given lines and points. Later methods compute PP and QQ on the boundary from the wanted spacing and angle of the first line of cells, and interpolate them inside.
  • Three dimensions. The same idea with three harmonic coordinates gives grids of hexahedra. The Radó-Kneser-Choquet theorem has no analogue there: harmonic maps in 3D onto convex sets can fail to be one to one.
  • Other solvers. Line SOR, alternating direction methods, multigrid and Newton's method replace point SOR for large grids.
  • Variational methods. The elliptic system is close to the Euler-Lagrange equations of smoothness functionals. Brackbill and Saltzman combined smoothness, orthogonality and size terms, and the grid follows from an optimization.
  • Unstructured smoothing. On an unstructured mesh, Laplacian smoothing and the Tutte embedding are the discrete relatives. The Tutte embedding has a discrete guarantee of no folding, which the finite difference scheme lacks.

When to use it

Use it when a smooth structured grid is needed on a block with curved sides, for example around an airfoil or inside a duct, and the TFI grid is too skewed or folds. Start from TFI, use P=Q=0P = Q = 0 first, and add control functions only when spacing near a wall matters. Check the cells after convergence with exact orientation signs. On a block with a sharp reentrant corner, split the block at the corner first. For domains that do not split into four-sided blocks, use an unstructured method such as advancing front mesh generation.

Pitfalls

  • Trusting the theorem for the discrete grid. The continuous map does not fold, but a coarse discrete grid near a reentrant corner can. Check every cell.
  • The wrong direction. Solving Laplace equations for xx and yy in (ξ,η)(\xi, \eta), instead of the inverted equations, gives a map that can fold on a non-convex domain.
  • Strong control functions. Large PP or QQ can push lines across each other; the theorem does not cover them.
  • Over-relaxation too large. The iteration is nonlinear, and an ω\omega near 2 can diverge or create a fold on the way. Start with ω\omega between 1 and 1.5.
  • A folded start. In the hook example the iteration removed the turned-over cells of the TFI start, but nothing guarantees this, and α+γ\alpha + \gamma is zero where the start puts opposite neighbours of a point at the same place.

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.

elliptic_grid_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elliptic-grid-generation/. The authors are listed in prov/EEEWVA.jsonl.

"""Elliptic grid generation in the plane (Winslow, and Thompson, Thames and Mastin).

The grid map x(xi, eta) from the index rectangle [0, M] x [0, N] onto the
physical block solves the inverse form of the Laplace (or Poisson) equations
for xi and eta:

    alpha x_xixi - 2 beta x_xieta + gamma x_etaeta + J^2 (P x_xi + Q x_eta) = 0

with alpha = |x_eta|^2, beta = x_xi . x_eta, gamma = |x_xi|^2 and
J = det(x_xi, x_eta). The equations are discretized by central differences
with unit index spacing and solved by nonlinear successive over-relaxation,
starting from transfinite interpolation. Boundary points never move.
Coordinates are floats; the cell test converts them to Fraction without
rounding, so its signs are exact for the stored points.
"""

from fractions import Fraction
from typing import Callable, List, Optional, Sequence, Tuple

from mg1geom import exact, grid_cells, quad_corner_values

Point = Tuple[float, float]
Grid = List[List[Point]]
Control = Callable[[int, int], float]


def tfi_start(bottom: Sequence[Point], top: Sequence[Point], left: Sequence[Point], right: Sequence[Point]) -> Grid:
    """Initial grid by transfinite interpolation with uniform parameters. Cost O(M N)."""
    m, n = len(bottom) - 1, len(left) - 1
    if m < 1 or n < 1 or len(top) != m + 1 or len(right) != n + 1:
        raise ValueError("bottom and top need equal lengths, left and right too, each at least 2")
    if bottom[0] != left[0] or bottom[m] != right[0] or top[0] != left[n] or top[m] != right[n]:
        raise ValueError("the four sides do not meet at common corners")
    p00, p10, p01, p11 = bottom[0], bottom[m], top[0], top[m]
    grid = []
    for i in range(m + 1):
        u = i / m
        col = []
        for j in range(n + 1):
            v = j / n
            col.append(tuple(
                (1 - u) * left[j][k] + u * right[j][k] + (1 - v) * bottom[i][k] + v * top[i][k]
                - ((1 - u) * (1 - v) * p00[k] + u * (1 - v) * p10[k] + (1 - u) * v * p01[k] + u * v * p11[k])
                for k in range(2)
            ))
        grid.append(col)
    # TFI reproduces the sides exactly in exact arithmetic; copy them so that float rounding does not move them
    for i in range(m + 1):
        grid[i][0], grid[i][n] = tuple(bottom[i]), tuple(top[i])
    for j in range(n + 1):
        grid[0][j], grid[m][j] = tuple(left[j]), tuple(right[j])
    return grid


def _gs_target(x: Grid, i: int, j: int, p: float, q: float) -> Point:
    """The point that satisfies the discrete equation at (i, j) with the neighbours fixed."""
    e, w, nn, s = x[i + 1][j], x[i - 1][j], x[i][j + 1], x[i][j - 1]
    # x_xi = (xx, xy) and x_eta = (ex, ey)
    xx, xy = (e[0] - w[0]) / 2, (e[1] - w[1]) / 2  # @line L5
    ex, ey = (nn[0] - s[0]) / 2, (nn[1] - s[1]) / 2
    alpha = ex * ex + ey * ey  # @line L6
    beta = xx * ex + xy * ey
    gamma = xx * xx + xy * xy
    jac = xx * ey - xy * ex
    ne, se, nw, sw = x[i + 1][j + 1], x[i + 1][j - 1], x[i - 1][j + 1], x[i - 1][j - 1]
    cx = (ne[0] - se[0] - nw[0] + sw[0]) / 4  # @line L7
    cy = (ne[1] - se[1] - nw[1] + sw[1]) / 4
    den = 2 * (alpha + gamma)
    if den == 0:
        raise ZeroDivisionError("grid collapsed at an interior point")
    j2 = jac * jac
    gx = (alpha * (e[0] + w[0]) + gamma * (nn[0] + s[0]) - 2 * beta * cx + j2 * (p * xx + q * ex)) / den  # @line L8
    gy = (alpha * (e[1] + w[1]) + gamma * (nn[1] + s[1]) - 2 * beta * cy + j2 * (p * xy + q * ey)) / den
    return gx, gy


def residual(x: Grid, P: Optional[Control] = None, Q: Optional[Control] = None) -> float:
    """Max over interior points of |g - x_ij|: the discrete equation divided by 2 (alpha + gamma). Cost O(M N)."""
    r = 0.0
    for i in range(1, len(x) - 1):
        for j in range(1, len(x[0]) - 1):
            g = _gs_target(x, i, j, P(i, j) if P else 0.0, Q(i, j) if Q else 0.0)
            r = max(r, abs(g[0] - x[i][j][0]), abs(g[1] - x[i][j][1]))
    return r


def elliptic_grid(
    bottom: Sequence[Point],
    top: Sequence[Point],
    left: Sequence[Point],
    right: Sequence[Point],
    omega: float = 1.5,
    tol: float = 1e-12,
    max_sweeps: int = 20000,
    P: Optional[Control] = None,
    Q: Optional[Control] = None,
) -> Tuple[Grid, int, float, bool]:
    """Winslow (P = Q = 0) or Thompson-Thames-Mastin grid of a four-sided block.

    Precondition: sides as for transfinite interpolation (matching corners,
    opposite sides with equal point counts), 0 < omega < 2, and P(i, j),
    Q(i, j) control values in index units when given.
    Returns (grid, sweeps, residual after the last sweep, converged), where
    converged means residual < tol.
    Cost: O(M N) per sweep, at most max_sweeps sweeps. For the linear model
    problem the number of sweeps grows like max(M, N)^2 for Gauss-Seidel and
    like max(M, N) for the best omega; this iteration is nonlinear and has no
    proved bound.
    """
    x = tfi_start(bottom, top, left, right)  # @line L1
    x = [list(col) for col in x]
    m, n = len(x) - 1, len(x[0]) - 1
    r = float("inf")
    for k in range(1, max_sweeps + 1):  # @line L2
        for i in range(1, m):  # @line L3
            for j in range(1, n):  # @line L4
                g = _gs_target(x, i, j, P(i, j) if P else 0.0, Q(i, j) if Q else 0.0)
                old = x[i][j]
                x[i][j] = (old[0] + omega * (g[0] - old[0]), old[1] + omega * (g[1] - old[1]))  # @line L9
        r = residual(x, P, Q)  # @line L10
        if r < tol:  # @line L11
            return x, k, r, True
    return x, max_sweeps, r, False  # @line L12


def cell_corner_values_exact(x: Grid) -> dict:
    """Exact corner Jacobians of every cell, from the float points converted to Fraction. Cost O(M N)."""
    out = {}
    for key, q in grid_cells([[exact(p) for p in col] for col in x]):  # @line L13
        out[key] = quad_corner_values(q)  # @line L14
    return out


def is_unfolded(x: Grid) -> bool:
    """True if every cell has four positive corner Jacobians (exact signs)."""
    return all(s > 0 for vals in cell_corner_values_exact(x).values() for s in vals)  # @line L15


def side(a: Point, b: Point, ts: Sequence[float]) -> List[Point]:
    """Points a + t (b - a) for t in ts, with the ends set to a and b exactly."""
    pts = [(a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])) for t in ts]
    pts[0], pts[-1] = tuple(a), tuple(b)
    return pts
mg1geom.py 77 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mg1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small exact tools for planar grids and triangulations, used by the mg1 pages.

Points are tuples of int, fractions.Fraction or float. Every predicate here is
exact when the coordinates are int or Fraction. A float coordinate converts to
a Fraction without rounding, so exact() followed by a predicate gives the exact
sign for the float points as they are stored.
"""

from fractions import Fraction
from typing import Iterable, Sequence, Tuple

Point = Tuple


def exact(p: Point) -> Tuple[Fraction, ...]:
    """The point p with each coordinate converted to Fraction, without rounding."""
    return tuple(Fraction(c) for c in p)


def orient2d(a: Point, b: Point, c: Point):
    """Twice the signed area of the triangle a, b, c; positive if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def twice_area(poly: Sequence[Point]):
    """Twice the signed area of a polygon by the shoelace formula."""
    n = len(poly)
    return sum(poly[i][0] * poly[(i + 1) % n][1] - poly[(i + 1) % n][0] * poly[i][1] for i in range(n))


def quad_corner_values(q: Sequence[Point]) -> list:
    """The four values ORIENT2D(q[k-1], q[k], q[k+1]) of a quadrilateral q[0..3].

    They are the Jacobian determinants of the bilinear map of the cell at its
    corners. All four are positive exactly when the quadrilateral is strictly
    convex and counterclockwise.
    """
    return [orient2d(q[k - 1], q[k], q[(k + 1) % 4]) for k in range(4)]


def grid_cells(grid: Sequence[Sequence[Point]]) -> Iterable:
    """Yield ((i, j), corners) for each cell of a grid x[i][j], corners counterclockwise for u right, v up."""
    for i in range(len(grid) - 1):
        for j in range(len(grid[0]) - 1):
            yield (i, j), (grid[i][j], grid[i + 1][j], grid[i + 1][j + 1], grid[i][j + 1])


def in_closed_triangle(p: Point, a: Point, b: Point, c: Point) -> bool:
    """True if p lies in the closed counterclockwise triangle a, b, c."""
    return orient2d(a, b, p) >= 0 and orient2d(b, c, p) >= 0 and orient2d(c, a, p) >= 0


def segments_cross(a: Point, b: Point, c: Point, d: Point) -> bool:
    """True if the closed segments ab and cd share a point other than a common endpoint.

    Segments that share exactly one endpoint and are not collinear return False.
    Cost O(1); exact for int and Fraction.
    """
    shared = {a, b} & {c, d}
    o1, o2 = orient2d(a, b, c), orient2d(a, b, d)
    o3, o4 = orient2d(c, d, a), orient2d(c, d, b)
    if o1 == 0 and o2 == 0:
        # collinear: overlap in more than a shared endpoint?
        k = 0 if a[0] != b[0] else 1
        lo1, hi1 = sorted((a[k], b[k]))
        lo2, hi2 = sorted((c[k], d[k]))
        lo, hi = max(lo1, lo2), min(hi1, hi2)
        if lo < hi:
            return True
        return lo == hi and not shared
    if shared:
        # two segments that are not collinear meet in at most one point
        return False
    return o1 * o2 <= 0 and o3 * o4 <= 0
test_elliptic_grid_generation.py 150 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elliptic-grid-generation/. The authors are listed in prov/EEEWVA.jsonl.

import math
import random

import pytest

from elliptic_grid_generation import cell_corner_values_exact, elliptic_grid, is_unfolded, residual, side, tfi_start

RESIDUAL_TOL = 1e-10


def discrete_equation(x, i, j):
    """alpha x_xixi - 2 beta x_xieta + gamma x_etaeta at (i, j), written out on its own (an independent oracle)."""
    def d(a, b):
        return (a[0] - b[0], a[1] - b[1])

    xi = [c / 2 for c in d(x[i + 1][j], x[i - 1][j])]
    eta = [c / 2 for c in d(x[i][j + 1], x[i][j - 1])]
    alpha = eta[0] ** 2 + eta[1] ** 2
    beta = xi[0] * eta[0] + xi[1] * eta[1]
    gamma = xi[0] ** 2 + xi[1] ** 2
    out = []
    for k in range(2):
        xx = x[i + 1][j][k] - 2 * x[i][j][k] + x[i - 1][j][k]
        yy = x[i][j + 1][k] - 2 * x[i][j][k] + x[i][j - 1][k]
        xy = (x[i + 1][j + 1][k] - x[i + 1][j - 1][k] - x[i - 1][j + 1][k] + x[i - 1][j - 1][k]) / 4
        out.append((alpha * xx - 2 * beta * xy + gamma * yy) / (2 * (alpha + gamma)))
    return out


def test_example_of_the_page() -> None:
    b = [(0, 0), (2, 0), (4, 0)]
    t = [(0, 2), (1, 2), (2, 2)]
    l = [(0, 0), (0, 1), (0, 2)]
    r = [(4, 0), (3, 1), (2, 2)]
    assert tfi_start(b, t, l, r)[1][1] == (1.5, 1.0)
    x, sweeps, res, ok = elliptic_grid(b, t, l, r, omega=1.0)
    assert ok and sweeps == 1 and res == 0.0
    assert abs(x[1][1][0] - 39 / 28) < 1e-15 and abs(x[1][1][1] - 1) < 1e-15
    assert is_unfolded(x)


def test_parallelogram_is_a_fixed_point() -> None:
    m, n = 5, 3
    b = side((0, 0), (4, 1), [i / m for i in range(m + 1)])
    t = side((1, 3), (5, 4), [i / m for i in range(m + 1)])
    l = side((0, 0), (1, 3), [j / n for j in range(n + 1)])
    r = side((4, 1), (5, 4), [j / n for j in range(n + 1)])
    x0 = tfi_start(b, t, l, r)
    assert residual(x0) < 1e-14
    x, sweeps, res, ok = elliptic_grid(b, t, l, r)
    assert ok and sweeps <= 2
    assert max(math.dist(x[i][j], x0[i][j]) for i in range(m + 1) for j in range(n + 1)) < 1e-13


def random_convex_quad(rng):
    return [(rng.uniform(-1, 0), rng.uniform(-1, 0)), (rng.uniform(1, 2), rng.uniform(-1, 0)),
            (rng.uniform(1, 2), rng.uniform(1, 2)), (rng.uniform(-1, 0), rng.uniform(1, 2))]


def random_params(rng, k):
    inner = sorted(rng.uniform(0.02, 0.98) for _ in range(k - 1))
    return [0.0] + inner + [1.0]


def test_convex_quadrilaterals_give_positive_jacobians() -> None:
    rng = random.Random(5)
    tfi_failures = 0
    for _ in range(25):
        q = random_convex_quad(rng)
        m, n = rng.randint(6, 12), rng.randint(6, 12)
        b = side(q[0], q[1], random_params(rng, m))
        t = side(q[3], q[2], random_params(rng, m))
        l = side(q[0], q[3], random_params(rng, n))
        r = side(q[1], q[2], random_params(rng, n))
        tfi_failures += not is_unfolded(tfi_start(b, t, l, r))
        x, sweeps, res, ok = elliptic_grid(b, t, l, r, omega=1.5, tol=1e-12)
        assert ok
        assert residual(x) < RESIDUAL_TOL
        assert max(abs(c) for i in range(1, m) for j in range(1, n) for c in discrete_equation(x, i, j)) < RESIDUAL_TOL
        assert [x[i][0] for i in range(m + 1)] == b and [x[i][n] for i in range(m + 1)] == t
        assert x[0] == l and x[m] == r
        vals = cell_corner_values_exact(x)
        assert all(s > 0 for v in vals.values() for s in v)
    assert tfi_failures > 0  # random spacing on the sides makes some TFI starts fail CHECK


def test_converges_to_the_conformal_map_of_an_annular_sector() -> None:
    errors = []
    for n in (4, 8, 16):
        k = (math.pi / 2) / n

        def f(i, j):
            return (math.exp(k * i) * math.cos(k * j), math.exp(k * i) * math.sin(k * j))

        b = [f(i, 0) for i in range(n + 1)]
        t = [f(i, n) for i in range(n + 1)]
        l = [f(0, j) for j in range(n + 1)]
        r = [f(n, j) for j in range(n + 1)]
        x, sweeps, res, ok = elliptic_grid(b, t, l, r, omega=1.8, tol=1e-13)
        assert ok and is_unfolded(x)
        errors.append(max(math.dist(x[i][j], f(i, j)) for i in range(n + 1) for j in range(n + 1)))
    assert errors[0] < 0.04
    assert 3.5 < errors[0] / errors[1] < 4.5 and 3.5 < errors[1] / errors[2] < 4.5


def hook_sides(m, n):
    hook = [(0.0, 0.0), (0.6, 0.2), (0.4, 0.4), (1.0, 0.0)]
    b = []
    for i in range(m + 1):
        s = 3 * i / m
        seg = min(int(s), 2)
        f = s - seg
        a, c = hook[seg], hook[seg + 1]
        b.append((a[0] + f * (c[0] - a[0]), a[1] + f * (c[1] - a[1])))
    t = [(i / m, 1.0) for i in range(m + 1)]
    l = [(0.0, j / n) for j in range(n + 1)]
    r = [(1.0, j / n) for j in range(n + 1)]
    return b, t, l, r


def test_hook_domain_converges_but_the_grid_is_not_valid() -> None:
    b, t, l, r = hook_sides(6, 4)
    start = cell_corner_values_exact(tfi_start(b, t, l, r))
    assert all(s < 0 for s in start[(2, 0)])
    x, sweeps, res, ok = elliptic_grid(b, t, l, r, omega=1.5)
    assert ok and residual(x) < RESIDUAL_TOL
    vals = cell_corner_values_exact(x)
    bad = {key for key, v in vals.items() if min(v) <= 0}
    assert bad == {(2, 0), (3, 0)}
    # no cell is turned over, but two cells are not convex
    assert sum(s > 0 for s in vals[(2, 0)]) == 3 and sum(s > 0 for s in vals[(3, 0)]) == 2


def test_control_functions_and_bad_input() -> None:
    q = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)]
    m, n = 8, 6
    b = side(q[0], q[1], [i / m for i in range(m + 1)])
    t = side(q[3], q[2], [i / m for i in range(m + 1)])
    l = side(q[0], q[3], [j / n for j in range(n + 1)])
    r = side(q[1], q[2], [j / n for j in range(n + 1)])
    P = lambda i, j: 0.0
    Q = lambda i, j: -0.5
    x, sweeps, res, ok = elliptic_grid(b, t, l, r, P=P, Q=Q)
    assert ok and residual(x, P, Q) < RESIDUAL_TOL and is_unfolded(x)
    assert x[0] == l and x[m] == r
    with pytest.raises(ValueError):
        elliptic_grid(b, t, l, [(5.0, 5.0)] + r[1:])

History

Alan Winslow proposed in 1966 to make meshes whose lines are equipotentials, by solving the inverted Laplace equations for the coordinates of the mesh points. In 1974 Joe Thompson, Frank Thames and Wayne Mastin built a general method on this, with Poisson equations, control functions that attract lines toward chosen curves and points, and fields with several bodies, and it became known as the TTM method. The book by Thompson, Warsi and Mastin in 1985 made elliptic generation the standard way to smooth structured grids. The univalence of planar harmonic maps onto convex regions, the theorem that explains why the grids do not fold, was posed by Radó in 1926, proved by Kneser the same year, and proved again by Choquet in 1945.

References

  1. Alan M. Winslow, Numerical solution of the quasilinear Poisson equation in a nonuniform triangle mesh, Journal of Computational Physics 1(2), 1966, 149 to 172, the mesh whose lines are equipotentials, obtained by solving the inverted Laplace equations for the coordinates (general locator)
  2. Joe F. Thompson, Frank C. Thames and C. Wayne Mastin, Automatic numerical generation of body-fitted curvilinear coordinate system for field containing any number of arbitrary two-dimensional bodies, Journal of Computational Physics 15(3), 1974, 299 to 319, the Poisson system with control functions for the computational coordinates, its transformed form, and its solution by point successive over-relaxation (general locator)
  3. Joe F. Thompson, Z. U. A. Warsi and C. Wayne Mastin, Numerical Grid Generation, Foundations and Applications, North-Holland, 1985, the chapters on elliptic generation systems (general locator)
  4. Peter Duren, Harmonic Mappings in the Plane, Cambridge Tracts in Mathematics 156, Cambridge University Press, 2004, the chapter Harmonic Mappings onto Convex Regions, the Radó-Kneser-Choquet theorem on p. 29 and Choquet's proof on p. 31

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.gauss_seidel_model
  • a full proof of time.per_sweep
  • a full proof of time.sor_model
  • 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