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)
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and 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 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 , the top , the left and the right , with common corners. Optional inputs are control functions , a relaxation factor , a tolerance and a maximum number of sweeps. The output is a grid 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 and the indices and seen as continuous variables, are
for both coordinates of . They are equivalent, where , to and . With this is Winslow's method. Thompson, Thames and Mastin introduced the control functions and .
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.
ELLIPTIC-GRID(B, T, L, R, P, Q, ω, tol, K)- 1
x ← TFI(B, T, L, R) ▷ the sides stay fixed from here on - 2
for k ← 1 to K do - 3
for i ← 1 to M − 1 do - 4
for j ← 1 to N − 1 do - 5
x_ξ ← (x_{i+1,j} − x_{i−1,j})/2; x_η ← (x_{i,j+1} − x_{i,j−1})/2 - 6
α ← |x_η|²; β ← x_ξ · x_η; γ ← |x_ξ|²; J ← det(x_ξ, x_η) - 7
X ← (x_{i+1,j+1} − x_{i+1,j−1} − x_{i−1,j+1} + x_{i−1,j−1})/4 - 8
G ← [α(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(α + γ)) - 9
x_ij ← x_ij + ω (G − x_ij) - 10
r ← max over inner points of |G_ij(x) − x_ij| ▷ L5 to L8 on the new grid - 11
if r < tol then return (x, converged) - 12
return (x, not converged) CHECK(x)- 13
for 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 - 14
if ORIENT2D(q_{k−1}, q_k, q_{k+1}) ≤ 0 for some k = 0..3 then return false - 15
return true
L5 to L7 are central differences with unit index spacing. L8 solves the discrete equation at for , with the neighbours and the coefficients fixed. With this is a nonlinear Gauss-Seidel method, and with 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 , on the grid after the sweep.
Example
One inner point. Take the trapezoid with corners , , , and , with the side midpoints , , and . TFI puts the inner point at . With one inner point, L5 to L8 use only boundary points, so one sweep with gives the solution.
| step | value |
|---|---|
| L5 | , |
| L6 | , , , |
| L7 | |
| L8 | |
| L10 | after the sweep, so L11 returns |
The point moves from to , a shift of to the left. The term is the whole difference: without it, the point would stay at .
A conformal map as an oracle. Take the sector of an annulus with the grid points on the sides, with and . The map is conformal, so and are harmonic and this map is the exact continuous solution. The largest distance of the converged grid from it is , , and for , 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 at every resolution.
A grid that converges and is still not valid. Take the unit square with the bottom side replaced by the hook , the domain of the folding example of the transfinite interpolation page, with and . The boundary angle at is about . The TFI start has two cells turned over. ELLIPTIC-GRID with converges to a residual below 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 and 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 sweeps. When it reports convergence, every discrete equation holds with a residual below 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 be a bounded convex domain whose boundary is a Jordan curve , and let be a homeomorphism of the unit circle onto . Then the harmonic extension of to the unit disk is a one-to-one map of the disk onto 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 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 and are independent everywhere.
Winslow's map goes from the physical domain to the rectangle of indices, and the theorem needs the target to be convex. is convex. A conformal map of the disk onto , which exists by the Riemann mapping theorem and extends to the boundary by Carathéodory's theorem, carries the theorem from the disk to . So for any domain bounded by a Jordan curve, convex or not, is one to one with nonvanishing Jacobian, and its inverse, the grid map, has grid lines that never cross. If instead and were made harmonic in and , the target would be , and the map could fold on a non-convex domain. Control functions 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 meet at common corners, let , and . Then ELLIPTIC-GRID:
- returns a grid whose boundary points are the input side points;
- stops after at most sweeps;
- returns "converged" only if every interior point satisfies for both coordinates , where is the value of L5 to L8 at for the returned grid;
- with and exact arithmetic, if the side points are evenly spaced samples of an affine map , returns the grid after one sweep.
Step 1 (the discrete equation). At an interior point, with unit index spacing, L5 to L7 compute , , , , , and the cross difference . None of these depend on . The discrete equation is
It is linear in with coefficient . If , its unique solution for with the neighbours fixed is the value of L8, and the left side equals . So is the residual of the equation divided by . If , then and , 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 and only, so no boundary point is written later. This is part 1. The loop of L2 runs at most times. Each sweep and each residual of L10 visits points with a constant number of operations, and every exit is a return. This is part 2.
Step 3 (part 3). L10 computes on the grid after the sweep, with the same formula as L5 to L8. L11 returns "converged" only if . By Step 1, this bounds the residual of every discrete equation by at that point. In floating point, the bound holds for the computed values of . 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 . Then and at every interior point, all second differences and the cross difference vanish, and the discrete equation with reads . So at every point, the first sweep changes nothing, , and the procedure returns after one sweep.
Part B: the continuous map
Theorem (Radó-Kneser-Choquet). Let be the open unit disk, let be a bounded convex domain whose boundary is a Jordan curve , and let be a homeomorphism. Let be the harmonic extension of to , the Poisson integral of each coordinate. Then is a one-to-one harmonic map of onto , and its Jacobian does not vanish in .
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 , the harmonic function 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 vanished at some point , the level set would leave in at least four arcs, which by the maximum principle reach the circle and separate regions where alternates in sign, so the boundary values of would change sign at least four times. So for all , which says that the rows of the Jacobian matrix are independent. A map with a nonvanishing Jacobian whose boundary map runs once around is one to one, by a degree argument.
Winslow's equations. If and are harmonic and the map has an inverse , then the inverse satisfies for both coordinates. This follows from the chain rule with , , and , as derived by Winslow and in Thompson, Warsi and Mastin. These are the equations that ELLIPTIC-GRID discretizes with .
Where convexity is needed. In the claim below, the convex set is the rectangle , the target of , and the physical domain can be any Jordan domain. If instead and are taken harmonic in , so that the map goes from onto , then the theorem needs convex, and on a non-convex that map can fold. With control functions , and 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 in on a compact set inside the domain, then for a fine enough grid the cells in have positive corner Jacobians, since the Jacobian of is bounded away from 0 on . Near the boundary, and especially at a reentrant corner, the Jacobian of 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 , the discrete grid converges to a residual below 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 be a bounded domain whose boundary is a Jordan curve, convex or not. Let be a homeomorphism onto the boundary of the rectangle that maps the four sides of the block to the four sides of . Let be the harmonic functions on with boundary values . Then is a one-to-one map of onto the interior of with nonvanishing Jacobian. Its inverse is smooth with nonvanishing Jacobian, so its grid lines, the level curves of and of , never cross or touch in .
Proof. By the Riemann mapping theorem there is a conformal map , and by Carathéodory's theorem it extends to a homeomorphism of onto , because is a Jordan curve. A harmonic function composed with a holomorphic map is harmonic, so is the harmonic extension to of the homeomorphism . The rectangle is convex, so by the theorem, is one to one onto the interior of with nonvanishing Jacobian. Since is one to one and conformal, with nonvanishing derivative, is one to one on with nonvanishing Jacobian. By the inverse function theorem its inverse is smooth with nonvanishing Jacobian. Two lines of the same family, and with , never meet because is a function. A line and a line meet in exactly one point, because the map is one to one, and they cross there at a nonzero angle, because the gradients of and are independent.
Complexity
Each sweep visits the inner points with a constant amount of work, so it costs time for grid points, and the grid needs 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 sweeps for a fixed reduction of the error, and SOR with the best needs , so the totals are and . The elliptic iteration behaves about the same in practice: 41 to 94 sweeps to a residual below for the random convex quadrilaterals above with . Multigrid reaches 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 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 and the start.
Variants and improvements
- Control functions. Thompson, Thames and Mastin chose and as sums of exponential attraction terms toward given lines and points. Later methods compute and 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 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 and in , instead of the inverted equations, gives a map that can fold on a non-convex domain.
- Strong control functions. Large or can push lines across each other; the theorem does not cover them.
- Over-relaxation too large. The iteration is nonlinear, and an near 2 can diverge or create a fold on the way. Start with 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 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.
# 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
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EEEWVA Edit this page History Report an error Markdown