Algorithm Search⌘K

Algorithmadvanced

Boundary layer mesh generation

Also called advancing layers method, prismatic layer meshing.

Grows thin layers of prisms or stretched tetrahedra out from walls along normals with geometric growth, to resolve boundary layers in flow simulation.

Time
O(k n^2) worst
Space
O(k n) extra
Where
k = the number of layers; n = the number of wall vertices
Properties
deterministicexactiterative
Origin
Shahyar Pirzadeh, Rao V. Garimella, Mark S. Shephard, 1996

Boundary layer mesh generation makes thin, stretched elements next to the walls of a body, for flow simulations. In a viscous flow the velocity changes very fast across a thin layer near the wall, and slowly along it, so the first cells must be very thin in the wall normal direction and can be long along the wall. The method moves the wall vertices outward along normal directions in steps, one layer at a time, with heights that grow by a fixed ratio, and joins each layer to the one before it. In 2D the cells are quads, in 3D prisms, which can be split into tetrahedra. Each layer is accepted only if its cells are valid, so the growth stops where layers would invert or collide. The rest of the domain is then filled by an isotropic mesher.

In plain words

Draw the outline of a wing. Draw a second outline a tiny step outside it, then a third one a slightly bigger step outside the second, and so on, each step a fixed factor bigger than the one before. Join each corner to the matching corner of the next outline. The strips between the outlines are thin cells that hug the wall.

On a round shape this always works, because the outlines get longer as they move out. In a dent the outlines get shorter, and at some point a strip has no length left, or two sides of the dent meet. Before that, the method stops adding layers. The space that is left is filled with ordinary triangles.

The problem

The input is a wall polygon in counterclockwise order, with the flow outside it, a first height h1h_1, a growth ratio r>1r > 1 and a number of layers kk. The output is a mesh of quads in up to kk layers. Layer jj has the thickness h1rj−1h_1 r^{j-1}, so the total height after jj layers is dj=h1(rj−1)/(r−1)d_j = h_1 (r^j - 1)/(r - 1). Every quad must be strictly convex, the layers must not overlap, and the outer front must be a simple polygon, so that a triangle mesher can fill the rest. The first height comes from the flow: for a turbulent flow it is chosen so that the first cell centre is inside the viscous sublayer.

The algorithm

Each wall vertex moves along its miter vector mim_i, which is the sum of the unit outward normals of its two edges, divided by one plus their dot product. The point xi+d mix_i + d\,m_i is at the distance dd from both edge lines, so every layer is a true offset of the wall.

  1. GROW-LAYERS(wall x_0..x_{n−1}, h1, r, k)
  2. 1n_i ← the unit outward normal of the edge x_i x_{i+1}
  3. 2m_i ← (n_{i−1} + n_i) / (1 + n_{i−1} · n_i)
  4. 3d_0 ← 0; d_j ← d_{j−1} + h1 · r^(j−1) for j = 1..k
  5. 4for j ← 1 to k do
  6. 5x_i^j ← x_i + d_j · m_i for every i
  7. 6Q_i^j ← (x_{i+1}^{j−1}, x_i^{j−1}, x_i^j, x_{i+1}^j) for every i
  8. 7if some Q_i^j is not strictly convex and counterclockwise then stop
  9. 8if the polygon x_0^j..x_{n−1}^j is not simple then stop
  10. 9accept layer j
  11. 10return the accepted quads and the number of layers

L7 uses exact orientation tests on the float coordinates, which convert to fractions without rounding. L8 tests every pair of front edges for a common point, which costs O(n2)O(n^2).

Example

Take the unit square as the wall, with h1=0.01h_1 = 0.01 and r=1.2r = 1.2. All corners turn by 90°90°, and the miter of each corner is (±1,±1)(\pm 1, \pm 1), so layer jj is the square [−dj,1+dj]2[-d_j, 1 + d_j]^2. After 10 layers, d10=0.2596d_{10} = 0.2596, all 40 quads are valid, and their total area 1.30791.3079 equals (1+2d10)2−1(1 + 2 d_{10})^2 - 1, as Theorem 5 of the proof says.

Now take the U-shaped wall (0,0)(0,0), (3,0)(3,0), (3,2)(3,2), (2,2)(2,2), (2,1)(2,1), (1,1)(1,1), (1,2)(1,2), (0,2)(0,2), with a slot of width 1 and depth 1, and h1=0.05h_1 = 0.05, r=1.2r = 1.2.

layer jj djd_j length of the slot bottom, 1−2dj1 - 2 d_j result
1 0.0500 0.9000 accepted
3 0.1820 0.6360 accepted
5 0.3721 0.2558 accepted
6 0.4965 0.0070 accepted
7 0.6458 −0.2916-0.2916 stop: the quad inverts

Both ends of the slot bottom are reflex corners that turn by −90°-90°, so the offset of the bottom loses 2d2d of length, and it collapses at d=0.5d = 0.5. The method keeps 6 layers, 48 quads. On a horseshoe shaped wall whose two tips face each other across a gap of 0.4, the same parameters stop at layer 4, where d4=0.2684>0.2d_4 = 0.2684 > 0.2: the quads are still valid, but the two fronts cross.

Correctness

The proof file has the details. The heights are a geometric series, so the thickness ratio is exactly rr. The miter vector puts every layer vertex at the distance dd from both edge lines, so each offset edge is parallel to its wall edge, and its length is L+d(tan⁡(αa/2)+tan⁡(αb/2))L + d(\tan(\alpha_a/2) + \tan(\alpha_b/2)), where αa\alpha_a and αb\alpha_b are the signed turning angles at its ends. Each quad is a trapezoid, and it is strictly convex exactly while that length is positive, which gives an exact collapse height at reflex corners.

For a whole layer, the boundaries of the quads add up to the outer front minus the inner front, because each radial edge cancels with its neighbour. So the winding numbers add up the same way. If every quad is valid and the new front is simple, every point between the fronts is in exactly one quad, every point inside the inner front is inside the outer front, and the area of the layer is the difference of the two front areas. On a strictly convex wall the lengths only grow, so every layer is accepted.

What is not proved: the stop rule is safe but crude, nothing bounds the stretch of the quads, which is high on purpose, and the miter length is unbounded at sharp convex corners.

Proof: Accepted boundary layers are valid quad meshes with geometric heights, and on a convex wall every layer is acceptedfull

Setting. The wall is a simple polygon x0,…,xn−1x_0, \dots, x_{n-1} in counterclockwise order (indices mod nn). Edge ii goes from xix_i to xi+1x_{i+1}, with length Li>0L_i > 0, unit direction tit_i, and unit outward normal nin_i, which is tit_i turned by −90°-90°. The turning angle αi∈(−π,π)\alpha_i \in (-\pi, \pi) at xix_i is the signed angle from ti−1t_{i-1} to tit_i; it is positive at a convex corner and negative at a reflex one. The miter vector is mi=(ni−1+ni)/(1+ni−1⋅ni)m_i = (n_{i-1} + n_i) / (1 + n_{i-1}\cdot n_i). The layer-kk vertex is xik=xi+dkmix_i^k = x_i + d_k m_i, the front PkP_k is the polygon x0k,…,xn−1kx_0^k, \dots, x_{n-1}^k, and the layer-kk quad on edge ii is Qik=(xi+1k−1,xik−1,xik,xi+1k)Q_i^k = (x_{i+1}^{k-1}, x_i^{k-1}, x_i^k, x_{i+1}^k).

Lemma 1 (heights). dk=h1(rk−1)/(r−1)d_k = h_1 (r^k - 1)/(r - 1) for r≠1r \ne 1, and the thickness of layer kk is dk−dk−1=h1rk−1d_k - d_{k-1} = h_1 r^{k-1}, so consecutive thicknesses have the ratio rr.

Proof. L3 sets d0=0d_0 = 0 and dk=dk−1+h1rk−1d_k = d_{k-1} + h_1 r^{k-1}. The sum of the geometric series gives the formula. □\square

Lemma 2 (miter). mi⋅ni−1=mi⋅ni=1m_i \cdot n_{i-1} = m_i \cdot n_i = 1. So xikx_i^k is at the distance dkd_k from the lines of both edges at xix_i, on their outer sides.

Proof. With c=ni−1⋅nic = n_{i-1}\cdot n_i, (ni−1+ni)⋅ni=c+1(n_{i-1} + n_i)\cdot n_i = c + 1, and the same for ni−1n_{i-1}. The division is defined because c>−1c > -1 when ∣αi∣<π|\alpha_i| < \pi. The signed distance of xi+dmix_i + d m_i to the line of edge ii is (dmi)⋅ni=d(d m_i)\cdot n_i = d. □\square

Lemma 3 (offset edge). For every d≥0d \ge 0, the segment from xi+dmix_i + d m_i to xi+1+dmi+1x_{i+1} + d m_{i+1} is parallel to edge ii, at the distance dd on its outer side, has the direction tit_i when its length is positive, and its signed length is ℓi(d)=Li+d (τi+τi+1)\ell_i(d) = L_i + d\,(\tau_i + \tau_{i+1}) with τj=tan⁡(αj/2)\tau_j = \tan(\alpha_j / 2).

Proof. Put the frame at xix_i with ti=(1,0)t_i = (1, 0), so ni=(0,−1)n_i = (0, -1). Then ti−1t_{i-1} is tit_i turned by −αi-\alpha_i and ni−1=(−sin⁡αi,−cos⁡αi)n_{i-1} = (-\sin\alpha_i, -\cos\alpha_i), so mi⋅ti=−sin⁡αi/(1+cos⁡αi)=−τim_i \cdot t_i = -\sin\alpha_i / (1 + \cos\alpha_i) = -\tau_i. In the same way ti+1t_{i+1} is tit_i turned by αi+1\alpha_{i+1}, ni+1=(sin⁡αi+1,−cos⁡αi+1)n_{i+1} = (\sin\alpha_{i+1}, -\cos\alpha_{i+1}), and mi+1⋅ti=τi+1m_{i+1} \cdot t_i = \tau_{i+1}. By Lemma 2 both end points have the normal component dd. So the segment runs from (−dτi,−d)(-d\tau_i, -d) to (Li+dτi+1,−d)(L_i + d\tau_{i+1}, -d). □\square

Theorem 4 (one quad). QikQ_i^k is strictly convex and counterclockwise if and only if ℓi(dk)>0\ell_i(d_k) > 0. Since ℓi\ell_i is affine with ℓi(0)=Li>0\ell_i(0) = L_i > 0, this holds for every kk if τi+τi+1≥0\tau_i + \tau_{i+1} \ge 0, and otherwise exactly while dk<Li/(−(τi+τi+1))d_k < L_i / (-(\tau_i + \tau_{i+1})), the collapse height.

Proof. Let h=dk−1h = d_{k-1}, h′=dkh' = d_k, Δ=h′−h>0\Delta = h' - h > 0 by Lemma 1, ℓ=ℓi(h)\ell = \ell_i(h) and ℓ′=ℓi(h′)\ell' = \ell_i(h'). By induction on kk (layer k−1k - 1 was accepted), ℓ>0\ell > 0. Use the frame of Lemma 3, which is a rotation and a translation of the plane, so it keeps orientations. The quad has the vertices (Li+hτi+1,−h)(L_i + h\tau_{i+1}, -h), (−hτi,−h)(-h\tau_i, -h), (−h′τi,−h′)(-h'\tau_i, -h') and (Li+h′τi+1,−h′)(L_i + h'\tau_{i+1}, -h'). The four orientation values at its corners, in order, are ℓΔ\ell\Delta, ℓ′Δ\ell'\Delta, ℓ′Δ\ell'\Delta and ℓΔ\ell\Delta. All four are positive exactly when ℓ′>0\ell' > 0. □\square

Theorem 5 (one layer). Suppose Pk−1P_{k-1} is a simple counterclockwise polygon, every quad of layer kk is strictly convex and counterclockwise, and PkP_k is simple. Then PkP_k is counterclockwise, the region Rk−1R_{k-1} bounded by Pk−1P_{k-1} lies in the region RkR_k bounded by PkP_k, and the quads of layer kk have pairwise disjoint interiors whose union is the closure of Rk∖Rk−1R_k \setminus R_{k-1}. Also ∑iarea⁡(Qik)=area⁡(Rk)−area⁡(Rk−1)\sum_i \operatorname{area}(Q_i^k) = \operatorname{area}(R_k) - \operatorname{area}(R_{k-1}).

Proof. As 1-chains, the boundary of QikQ_i^k is the reversed edge xi+1k−1xik−1x_{i+1}^{k-1} x_i^{k-1}, the edge xikxi+1kx_i^k x_{i+1}^k, and two radial edges xik−1xikx_i^{k-1} x_i^k and xi+1kxi+1k−1x_{i+1}^k x_{i+1}^{k-1}. Each radial edge appears once in each direction in the two neighbouring quads, so they cancel, and ∑i∂Qik=∂Pk−∂Pk−1\sum_i \partial Q_i^k = \partial P_k - \partial P_{k-1}. The winding number w(γ,x)w(\gamma, x) of a closed chain about a point xx off it is additive in the chain, so for every xx off all edges

∑iw(∂Qik,x)=w(Pk,x)−w(Pk−1,x).\sum_i w(\partial Q_i^k, x) = w(P_k, x) - w(P_{k-1}, x).

The shoelace sums are additive in the same way, which gives the area identity, and its left side is positive, so the signed area of PkP_k is larger than that of Pk−1P_{k-1}, hence positive: the simple polygon PkP_k is counterclockwise, and w(Pk,⋅)w(P_k, \cdot) is 1 inside and 0 outside, as is w(Pk−1,⋅)w(P_{k-1}, \cdot). A strictly convex counterclockwise quad has winding number 1 inside and 0 outside. So the left side is a sum of terms in {0,1}\{0, 1\}, and the right side is in {−1,0,1}\{-1, 0, 1\}. It cannot be −1-1, so x∈Rk−1x \in R_{k-1} implies x∈Rkx \in R_k. Where it is 1, exactly one quad contains xx; where it is 0, none does. Points on edges are a set of measure zero, so the interiors are disjoint and the union is the closure of Rk∖Rk−1R_k \setminus R_{k-1}. □\square

Corollary 6 (the output). Every accepted layer satisfies Theorem 5, by the exact tests in L7 and L8 and by induction from the wall P0P_0, which is simple and counterclockwise. The regions Rk∖Rk−1R_k \setminus R_{k-1} are disjoint for different kk, because the RkR_k are nested. Neighbouring quads share whole edges, by construction, and no directed edge is used twice (L7). So the output is a conforming mesh of strictly convex quads without inverted cells, which covers the region between the wall and the last front, with layer heights as in Lemma 1. The tests check all of this exactly, and they check the absence of overlap again by counting, for 3000 random points, the quads that contain each point.

Theorem 7 (convex walls). If the wall is strictly convex, that is, every αi∈(0,π)\alpha_i \in (0, \pi), every layer is accepted.

Proof. Every τi>0\tau_i > 0, so every ℓi(d)\ell_i(d) is positive and Theorem 4 makes every quad valid. The front PkP_k has edges with the directions t0,…,tn−1t_0, \dots, t_{n-1} (Lemma 3), so its turning angles are the αi\alpha_i, all in (0,π)(0, \pi), with sum 2π2\pi. A closed polygon with that property is convex and simple. □\square

Termination. The loop L4 runs at most nlayers times, and each pass does O(n2)O(n^2) exact tests. So the procedure stops.

What is not proved. For a wall with reflex corners, the collapse height of Theorem 4 is exact, but the front can also hit itself before any quad degenerates, for example across a narrow gap, and the code finds that only by the simplicity test. The method stops the whole layer at the first failure; it does not prove that a better local rule exists. Nothing is proved about the shape of the quads, which are stretched on purpose, or about the miter length 1/cos⁡(αi/2)1/\cos(\alpha_i/2), which grows without bound at sharp convex corners. Multiple bodies, normal smoothing and the 3D prism case are not covered.

Complexity

One layer costs O(n)O(n) for the new points and the quad tests and O(n2)O(n^2) for the simplicity test of the front, so kk layers cost O(kn2)O(k n^2). A sweep line or a grid of buckets makes the front test O(nlog⁡n)O(n \log n) for most inputs, and production codes test only nearby fronts with a search tree. The space is O(kn)O(k n) for the points and quads.

Properties

  • Exact heights. The distance of each layer vertex from both of its wall edges is exactly the planned height in exact arithmetic.
  • Valid by test. No inverted or overlapping cell is ever accepted.
  • Convex walls always work. On a strictly convex wall, every requested layer is accepted.
  • Anisotropic by design. The cells are long along the wall and thin across it, with aspect ratios of 100 or more in practice.
  • Structured in the normal direction. The layers form a structured grid in the wall normal direction, which flow solvers like.

Variants and improvements

  • Local stop. Instead of stopping the whole layer, real codes freeze single vertices where a quad would invert or fronts come close, and close the gap with triangles or pyramids. This keeps more layers where the wall is smooth.
  • Normal smoothing. Pirzadeh's advancing layers method smooths the march directions over many layers, so that the layers open up in concave regions instead of collapsing.
  • Fans at sharp corners. At a sharp convex corner, such as a trailing edge, several directions spread out from one wall vertex, which avoids the long miter.
  • 3D prisms and tetrahedra. In 3D the wall is a triangle mesh, each layer gives prisms, and each prism can be split into three tetrahedra. Garimella and Shephard handle curved walls and the transition to the isotropic mesh.
  • Metric view. A boundary layer mesh is an anisotropic mesh whose metric is stretched in the normal direction near the wall.

When to use it

Use it for viscous flow simulations with the finite volume method or a finite element method, where the solver needs thin, wall aligned cells to resolve the velocity gradient at the wall. Use it before the isotropic mesher, which then meshes the region outside the last front, for example by advancing front mesh generation or Delaunay methods. For inviscid flow or for structures, there is no thin layer to resolve, and an isotropic mesh is enough.

Pitfalls

  • Reflex corners. The offset edges next to a reflex corner shrink and invert at the collapse height. Test each layer, and stop or smooth the directions there.
  • Narrow gaps. Two parts of the wall that face each other across a gap smaller than twice the total height make the fronts cross, even when every quad is valid. Test the front for self intersection.
  • Sharp convex corners. The miter length is 1/cos⁡(α/2)1/\cos(\alpha/2) and is unbounded as the turning angle α\alpha approaches 180°180°. Use a fan of directions there.
  • Bad transition. If the last layer is much thinner than the size of the outer mesh, the jump in size spoils the solution. Choose rr and kk so that the last thickness is close to the outer size.
  • Float tests. A float orientation test can accept a quad that is slightly inverted, which a solver later rejects. Use exact tests.

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.

boundary_layer_mesh_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-layer-mesh-generation/. The authors are listed in prov/H3T7WW.jsonl.

"""Boundary layer meshing in the plane by advancing layers of quads.

The wall is a simple polygon with counterclockwise vertices (a body), and the
layers grow outward into the flow. Each wall vertex moves along a miter
vector: the sum of the unit outward normals of its two edges, scaled so that
the point at height d is at distance d from both edge lines. The heights grow
geometrically: d_k = h1 (r^k - 1) / (r - 1), so layer k has thickness h1 r^(k-1).

A layer is accepted only if every new quad is strictly convex and
counterclockwise and the new front is a simple polygon, tested exactly on the
float coordinates (each float converts to a Fraction without rounding). The
growth stops at the first layer that fails. Positions are floats.
"""

import math
from fractions import Fraction
from typing import List, Sequence, Tuple

from mg3geom import exact, is_valid_planar_mesh, orient2d

Vec = Tuple[float, float]


def outward_normal(a: Vec, b: Vec) -> Vec:
    """Unit normal of the edge ab of a counterclockwise polygon, pointing out."""
    dx, dy = b[0] - a[0], b[1] - a[1]
    n = math.hypot(dx, dy)
    return (dy / n, -dx / n)


def miter(na: Vec, nb: Vec) -> Vec:
    """The vector m with m . na = m . nb = 1."""
    s = 1.0 + na[0] * nb[0] + na[1] * nb[1]
    if s < 1e-9:
        raise ValueError("a corner of nearly 360 degrees has no miter vector")
    return ((na[0] + nb[0]) / s, (na[1] + nb[1]) / s)


def layer_heights(h1, r, n: int) -> List:
    """d_0 = 0 and d_k = h1 (1 + r + ... + r^(k-1)); exact for Fraction input."""
    d = [h1 * 0]
    for k in range(n):
        d.append(d[-1] + h1 * r ** k)
    return d


def segments_meet(a, b, c, d) -> bool:
    """Exact test whether the closed segments ab and cd have a common point."""
    def on(p, q, x):
        return (min(p[0], q[0]) <= x[0] <= max(p[0], q[0]) and min(p[1], q[1]) <= x[1] <= max(p[1], q[1]))
    o1, o2, o3, o4 = orient2d(a, b, c), orient2d(a, b, d), orient2d(c, d, a), orient2d(c, d, b)
    if o1 * o2 < 0 and o3 * o4 < 0:
        return True
    return ((o1 == 0 and on(a, b, c)) or (o2 == 0 and on(a, b, d))
            or (o3 == 0 and on(c, d, a)) or (o4 == 0 and on(c, d, b)))


def is_simple_polygon(poly: Sequence) -> bool:
    """Exact test: non-adjacent edges do not meet and adjacent edges do not fold back."""
    n = len(poly)
    for i in range(n):
        a, b, c = poly[i], poly[(i + 1) % n], poly[(i + 2) % n]
        if orient2d(a, b, c) == 0 and (a[0] - b[0]) * (c[0] - b[0]) + (a[1] - b[1]) * (c[1] - b[1]) > 0:
            return False
        for j in range(i + 2, n):
            if i == 0 and j == n - 1:
                continue
            if segments_meet(poly[i], poly[(i + 1) % n], poly[j], poly[(j + 1) % n]):
                return False
    return True


def grow_layers(wall: Sequence[Vec], h1: float, r: float, nlayers: int):
    """Returns (points, quads, layers, reason). points[k * n + i] is wall vertex i
    at height d_k; quads are counterclockwise index 4-tuples; layers is the
    number of accepted layers; reason is None or why the growth stopped."""
    n = len(wall)
    normals = [outward_normal(wall[i], wall[(i + 1) % n]) for i in range(n)]  # @line L1
    m = [miter(normals[i - 1], normals[i]) for i in range(n)]  # @line L2
    d = layer_heights(h1, r, nlayers)  # @line L3
    points: List[Vec] = list(wall)
    quads: List[Tuple[int, int, int, int]] = []
    E = [exact(p) for p in points]
    for k in range(1, nlayers + 1):  # @line L4
        new = [(wall[i][0] + d[k] * m[i][0], wall[i][1] + d[k] * m[i][1]) for i in range(n)]  # @line L5
        lo, hi = (k - 1) * n, k * n
        layer = [(lo + (i + 1) % n, lo + i, hi + i, hi + (i + 1) % n) for i in range(n)]  # @line L6
        En = E + [exact(p) for p in new]
        if not is_valid_planar_mesh(En, layer):  # @line L7
            return points, quads, k - 1, "a quad of layer %d is not strictly convex" % k
        if not is_simple_polygon(En[hi:]):  # @line L8
            return points, quads, k - 1, "the front of layer %d is not simple" % k
        points += new  # @line L9
        E = En
        quads += layer
    return points, quads, nlayers, None  # @line L10


def collapse_height(wall: Sequence[Vec], i: int) -> float:
    """The height at which the offset of edge i reaches length zero, from the
    formula length(d) = L + d (tan(a/2) + tan(b/2)), with a, b the signed turning
    angles at its two ends; infinity if the length does not shrink."""
    n = len(wall)
    a, b = wall[i], wall[(i + 1) % n]
    L = math.hypot(b[0] - a[0], b[1] - a[1])

    def turn(j):
        p, q, s = wall[j - 1], wall[j], wall[(j + 1) % n]
        u = (q[0] - p[0], q[1] - p[1])
        v = (s[0] - q[0], s[1] - q[1])
        return math.atan2(u[0] * v[1] - u[1] * v[0], u[0] * v[0] + u[1] * v[1])
    rate = math.tan(turn(i) / 2) + math.tan(turn((i + 1) % n) / 2)
    return math.inf if rate >= 0 else L / -rate


def area2(points, quads) -> Fraction:
    """Twice the total signed area of the quads, exact."""
    total = Fraction(0)
    for q in quads:
        P = [exact(points[i]) for i in q]
        total += orient2d(P[0], P[1], P[2]) + orient2d(P[0], P[2], P[3])
    return total
mg3geom.py 114 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mg3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small exact tools for triangle and tetrahedral meshes, used by the mg3 pages.

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

import math
from fractions import Fraction
from typing import Dict, Iterable, List, 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 to_grid(x: float, bits: int = 20) -> Fraction:
    """The nearest multiple of 2**-bits to x, as a Fraction."""
    return Fraction(round(x * (1 << bits)), 1 << bits)


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 incircle(a: Point, b: Point, c: Point, d: Point):
    """Positive if d is inside the circle through a, b, c (a, b, c counterclockwise),
    zero if on it, negative if outside."""
    rows = []
    for p in (a, b, c):
        dx, dy = p[0] - d[0], p[1] - d[1]
        rows.append((dx, dy, dx * dx + dy * dy))
    (a0, a1, a2), (b0, b1, b2), (c0, c1, c2) = rows
    return a0 * (b1 * c2 - b2 * c1) - a1 * (b0 * c2 - b2 * c0) + a2 * (b0 * c1 - b1 * c0)


def orient3d(a: Point, b: Point, c: Point, d: Point):
    """Six times the signed volume of the tetrahedron a, b, c, d.

    Positive if d lies on the side of the plane abc toward which (b - a) x (c - a)
    points, that is, if a, b, c look clockwise from d."""
    u = (b[0] - a[0], b[1] - a[1], b[2] - a[2])
    v = (c[0] - a[0], c[1] - a[1], c[2] - a[2])
    w = (d[0] - a[0], d[1] - a[1], d[2] - a[2])
    return (u[0] * (v[1] * w[2] - v[2] * w[1])
            - u[1] * (v[0] * w[2] - v[2] * w[0])
            + u[2] * (v[0] * w[1] - v[1] * w[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 segments_cross(a: Point, b: Point, c: Point, d: Point) -> bool:
    """True if the open segments ab and cd cross at one point inside both."""
    return (orient2d(a, b, c) * orient2d(a, b, d) < 0
            and orient2d(c, d, a) * orient2d(c, d, b) < 0)


def edge_map(cells: Iterable[Sequence[int]]) -> Dict[Tuple[int, int], int]:
    """Map each directed edge (i, j) of a list of counterclockwise polygons
    (triangles or quads, given by vertex indices) to the index of its cell.
    Raises ValueError if a directed edge is used twice."""
    m: Dict[Tuple[int, int], int] = {}
    for k, cell in enumerate(cells):
        n = len(cell)
        for s in range(n):
            e = (cell[s], cell[(s + 1) % n])
            if e in m:
                raise ValueError("directed edge %r used twice" % (e,))
            m[e] = k
    return m


def boundary_edges(cells: Iterable[Sequence[int]]) -> List[Tuple[int, int]]:
    """The directed edges whose reverse is not an edge of any cell."""
    m = edge_map(cells)
    return [e for e in m if (e[1], e[0]) not in m]


def is_valid_planar_mesh(points: Sequence[Point], cells: Sequence[Sequence[int]]) -> bool:
    """Exact check that every cell is a strictly convex counterclockwise polygon
    and that no directed edge is used twice. With the area sum of the caller,
    this shows a conforming mesh of a simply covered region."""
    try:
        edge_map(cells)
    except ValueError:
        return False
    for cell in cells:
        n = len(cell)
        for s in range(n):
            a, b, c = points[cell[s]], points[cell[(s + 1) % n]], points[cell[(s + 2) % n]]
            if orient2d(a, b, c) <= 0:
                return False
    return True


def mean_ratio(a: Point, b: Point, c: Point) -> float:
    """The mean ratio 4 sqrt(3) A / (sum of squared edge lengths) of a triangle,
    in floats; 1 for the equilateral triangle, 0 for a flat one, negative if the
    triangle is clockwise."""
    s = sum(float((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2) for p, q in ((a, b), (b, c), (c, a)))
    return 2.0 * math.sqrt(3.0) * float(orient2d(a, b, c)) / s
test_boundary_layer_mesh_generation.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boundary-layer-mesh-generation/. The authors are listed in prov/H3T7WW.jsonl.

import math
import random
from fractions import Fraction as F

from boundary_layer_mesh_generation import area2, collapse_height, grow_layers, is_simple_polygon, layer_heights
from mg3geom import boundary_edges, exact, is_valid_planar_mesh, orient2d, twice_area

U = [(0.0, 0.0), (3.0, 0.0), (3.0, 2.0), (2.0, 2.0), (2.0, 1.0), (1.0, 1.0), (1.0, 2.0), (0.0, 2.0)]
HORSESHOE = [(0.0, 0.0), (4.0, 0.0), (4.0, 3.0), (2.2, 3.0), (2.2, 2.5), (3.5, 2.5), (3.5, 0.5), (0.5, 0.5),
             (0.5, 2.5), (1.8, 2.5), (1.8, 3.0), (0.0, 3.0)]


def convex_polygon(rng, n):
    """A convex polygon with n vertices on an ellipse, counterclockwise."""
    angles = sorted(rng.uniform(0, 2 * math.pi) for _ in range(n))
    a, b = rng.uniform(1, 3), rng.uniform(1, 3)
    return [(a * math.cos(t), b * math.sin(t)) for t in angles]


def line_distance(p, a, b):
    return abs((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])) / math.dist(a, b)


def inside_quad(q, x):
    return all(orient2d(q[s], q[(s + 1) % 4], x) > 0 for s in range(4))


def test_heights_follow_the_growth_ratio_exactly():
    d = layer_heights(F(1, 100), F(6, 5), 12)
    assert d[0] == 0 and d[1] == F(1, 100)
    for k in range(1, 12):
        assert (d[k + 1] - d[k]) / (d[k] - d[k - 1]) == F(6, 5)
        assert d[k] == F(1, 100) * (F(6, 5) ** k - 1) / (F(6, 5) - 1)


def test_layer_vertices_sit_at_the_layer_height_from_both_wall_edges():
    rng = random.Random(1)
    wall = convex_polygon(rng, 9)
    n = len(wall)
    pts, quads, k, why = grow_layers(wall, 0.01, 1.25, 10)
    d = layer_heights(0.01, 1.25, 10)
    assert k == 10 and why is None
    for layer in range(1, 11):
        for i in range(n):
            p = pts[layer * n + i]
            for a, b in ((wall[i - 1], wall[i]), (wall[i], wall[(i + 1) % n])):
                assert abs(line_distance(p, a, b) - d[layer]) < 1e-9 * (1 + d[layer])


def test_convex_walls_never_stop_and_the_quads_tile_the_layers():
    rng = random.Random(2)
    for _ in range(8):
        wall = convex_polygon(rng, rng.randint(3, 12))
        if min(math.dist(wall[i], wall[i - 1]) for i in range(len(wall))) < 1e-3:
            continue
        n = len(wall)
        pts, quads, k, why = grow_layers(wall, 0.02, 1.3, 12)
        assert k == 12 and why is None
        E = [exact(p) for p in pts]
        assert is_valid_planar_mesh(E, quads)                      # no inverted quad, conforming
        outer = E[12 * n:]
        assert area2(pts, quads) == twice_area(outer) - twice_area(E[:n])
        bnd = set(boundary_edges(quads))
        assert bnd == {(i, (i - 1) % n) for i in range(n)} | {(12 * n + i, 12 * n + (i + 1) % n) for i in range(n)}


def test_concave_corners_stop_at_the_collapse_height():
    d = layer_heights(0.05, 1.2, 10)
    h = min(collapse_height(U, i) for i in range(len(U)))
    assert abs(h - 0.5) < 1e-12
    expected = max(k for k in range(11) if d[k] < h)
    pts, quads, k, why = grow_layers(U, 0.05, 1.2, 10)
    assert k == expected == 6 and "not strictly convex" in why
    E = [exact(p) for p in pts]
    assert is_valid_planar_mesh(E, quads)
    # brute force: no point lies inside two quads
    rng = random.Random(3)
    for _ in range(3000):
        x = (F(rng.randint(-2000, 5000), 1000), F(rng.randint(-2000, 4000), 1000))
        assert sum(inside_quad([E[i] for i in q], x) for q in quads) <= 1


def test_colliding_fronts_stop_on_the_simplicity_test():
    pts, quads, k, why = grow_layers(HORSESHOE, 0.05, 1.2, 10)
    d = layer_heights(0.05, 1.2, 10)
    # the two tips face each other across a gap of 0.4, so the fronts meet at height 0.2
    assert d[3] < 0.2 < d[4]
    assert k == 3 and "not simple" in why
    assert min(collapse_height(HORSESHOE, i) for i in range(len(HORSESHOE))) > d[4]
    n = len(HORSESHOE)
    E = [exact(p) for p in pts]
    assert is_valid_planar_mesh(E, quads) and is_simple_polygon(E[3 * n:])
    assert area2(pts, quads) == twice_area(E[3 * n:]) - twice_area(E[:n])

History

Meshes for viscous flows were first made with structured grids. With the move to unstructured tetrahedral meshes for complex shapes in the 1990s, several groups made layers of thin cells next to the walls before filling the rest. Shahyar Pirzadeh described the advancing layers method in the AIAA Journal in 1996: it marches the wall triangles outward layer by layer along smoothed normals and stops locally where layers would collide. Rao Garimella and Mark Shephard described the generation of layers of prisms and stretched tetrahedra on curved walls in 2000.

References

  1. Shahyar Pirzadeh, Three-dimensional unstructured viscous grids by the advancing-layers method, AIAA Journal 34(1), 1996, 43 to 49, the march of layers along wall normals, the growth of the layer thickness, normal smoothing and the local stop of layers where fronts approach each other (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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