Algorithm Search⌘K

Algorithmadvanced

DistMesh

Also called Persson-Strang mesh generator.

Persson and Strang's mesher that treats edges as springs, moves points to force balance, projects them back with a signed distance function and retriangulates.

Time
O(k n^2) worst
Space
O(n) extra
Where
k = the number of iterations; n = the number of points
Properties
deterministicnot exactiterative
Origin
Per Olof Persson, Gilbert Strang, 2004

DistMesh is a mesh generator by Per-Olof Persson and Gilbert Strang. It describes the domain by a signed distance function, which is negative inside and positive outside. It treats the edges of a triangle mesh as springs that push their two end points apart, moves the points a small step along the net force, pulls back every point that left the domain onto the boundary, and rebuilds the Delaunay triangulation when the points have moved enough. It repeats until the points stop moving. The code is short, the triangles are close to equilateral in practice, and the method works for any shape that has a distance function. There is no proof that the iteration converges, and no proved bound on the angles.

In plain words

Scatter dots evenly over a box and throw away those outside the shape. Join the dots into triangles. Now think of every edge as a small spring that is a bit too short, so it pushes its two dots apart. The dots spread out until the pushes balance.

The shape acts as a wall. A dot that is pushed through the wall is put back on it. When the dots have moved far enough, join them into triangles again in the best way. When no dot moves more than a tiny amount, stop.

The result is a mesh with triangles close to equilateral and dots spread out evenly along the wall. Nothing proves that the dots settle, so a program sets a limit on the number of steps.

The problem

The input is a domain Ω={x:fd(x)≤0}\Omega = \{x : f_d(x) \le 0\} given by a function fdf_d that is the signed distance to the boundary, or close to it, a target edge length h0h_0, a box that contains Ω\Omega, and a list of fixed points such as corners. The output is a triangle mesh of a polygon close to Ω\Omega, with all vertices in Ω\Omega, the fixed points among them, boundary vertices on the boundary, and edges of length close to h0h_0. This page treats a uniform size; the original method also takes a relative size function h(x)h(x).

The algorithm

The parameters are the ones of Persson and Strang: Fscale=1.2F_\text{scale} = 1.2, Δt=0.2\Delta t = 0.2, geps=0.001h0g_\text{eps} = 0.001 h_0, ttol=0.1t_\text{tol} = 0.1 and dtol=0.001d_\text{tol} = 0.001.

  1. DISTMESH(f_d, h0, box, fixed, cap)
  2. 1p ← the points of an equilateral grid of spacing h0 in the box
  3. 2keep the points with f_d < g_eps, and put the fixed points first
  4. 3for it ← 1 to cap do
  5. 4if some point moved more than t_tol · h0 since the last triangulation then
  6. 5T ← Delaunay(p); drop the triangles whose centroid has f_d ≥ −g_eps; bars ← the edges of T
  7. 6ℓ ← the bar lengths; L0 ← F_scale · sqrt(Σ ℓ² / number of bars)
  8. 7for each bar ij: push i and j apart by max(L0 − ℓ_ij, 0)
  9. 8p ← p + Δt · F, with no force on the fixed points
  10. 9for each moved point with f_d(p) > 0: p ← p − f_d(p) ∇f_d(p)
  11. 10if every interior point moved less than d_tol · h0 then break
  12. 11T ← Delaunay(p) without the outside triangles
  13. 12return p, T

L6 to L8 are one explicit Euler step of the truss equation dp/dt=F(p)dp/dt = F(p); see the Euler method. The force of a bar is linear in the compression and zero for a stretched bar, so bars only push. L0L_0 is 20 percent longer than the mean bar, so most bars push, which drives the points out to the boundary. L9 is a projection: for an exact distance function, ∇fd\nabla f_d is a unit vector and the step lands on the nearest boundary point. The gradient is a forward difference. L5 and L11 use the Bowyer-Watson algorithm with exact integer predicates on the points rounded to the grid of step 2−242^{-24}; the in-circle test decides which triangles to remove.

Example

Take the unit disk with fd(x)=∣x∣−1f_d(x) = |x| - 1, h0=0.2h_0 = 0.2 and no fixed points. L1 and L2 keep 88 points. The table shows the state after some numbers of iterations. The quality is the mean ratio 43A/∑ℓ24\sqrt3 A / \sum \ell^2 from the mesh quality measures, where 1 means equilateral.

iterations triangles smallest mean ratio points on the circle
1 151 0.255 1
2 155 0.002 3
10 149 0.555 21
40 145 0.342 29
90 (stopped by L10) 143 0.815 31

The worst triangle is not monotone. In the first steps the outer points move to the circle and leave near flat triangles behind, and the retriangulation repairs them later. At the end, the mean of the mean ratio is 0.969, the angles are between 40.6°40.6° and 96.4°96.4°, and the area of the mesh is 3.1200, just under π\pi because the boundary edges are chords.

On the square [−1,1]2[-1,1]^2 with the four corners fixed and h0=0.25h_0 = 0.25, the run stops after 51 iterations with 87 points and 137 triangles. The smallest mean ratio is 0.852, the angles are between 42.0°42.0° and 91.5°91.5°, and the triangles cover the square exactly, with area 4. With h0=0.1h_0 = 0.1 on the disk, it stops after 197 iterations with 362 points, 661 triangles and smallest mean ratio 0.839. These numbers are measured, not proved.

Correctness

The proof file proves what can be proved. Each call of the Delaunay step gives triangles that are counterclockwise, conforming and have empty circumcircles, exactly, for the rounded points. The core is the classic argument for Bowyer-Watson: the triangles whose circumcircle contains the new point form a region that is connected and star shaped from that point, and the circles through an edge form a pencil, so each new circle lies inside the union of two old empty circles. Dropping the outside triangles keeps a subset, which keeps all three properties. For a convex domain and an exact distance function, every point stays in the domain to rounding, so every triangle does too.

What is not proved is the force iteration. Persson and Strang give no convergence proof, and the run above shows that the worst triangle can get worse for many steps before it gets better. The loop stops because of the iteration cap in L3. The tests check that the output on a disk and on a square is an exact Delaunay mesh with every triangle inside the domain, and that the Delaunay step equals a brute force over all triples on small random sets.

Proof: Every triangulation that DistMesh returns is an exact Delaunay mesh, and the loop stops only because of its capfull

What is proved and what is not. The proof below covers the parts of DistMesh that have a proof: each retriangulation (L5 and L11) gives triangles that are counterclockwise, conforming and Delaunay for the rounded points, and for a convex domain with a true signed distance function every returned triangle lies in the domain. It does not cover the force iteration L3 to L10. There is no proof that the points converge, and no proof that the final triangles have a bounded angle. Persson and Strang give no such proof either. The implementation stops because L3 has an iteration cap, and that is the whole termination argument.

Notation. The points are distinct integer points PP (the float positions times 2242^{24}, rounded). For a triangle tt, DtD_t is its open circumdisk and CtC_t its circle. ORIENT2D and INCIRCLE are exact on integers.

Lemma 1 (pencil of circles). Let x≠yx \ne y, let H+H^+ and H−H^- be the two open half planes of the line xyxy, and let nn be the unit normal pointing into H+H^+. Every circle through xx and yy has its centre at m+snm + s n with m=(x+y)/2m = (x + y)/2 and one real ss. Let D(s)D(s) be its open disk. If s<s′s < s', then D(s)∩H+⊊D(s′)∩H+D(s) \cap H^+ \subsetneq D(s') \cap H^+ and D(s′)∩H−⊊D(s)∩H−D(s') \cap H^- \subsetneq D(s) \cap H^-, and the circle of D(s)D(s) in H+H^+ lies inside D(s′)D(s'). Every D(s)D(s) meets the line xyxy in the open segment between xx and yy.

Proof. The power of a point qq with respect to the circle with parameter ss is ∣q−m−sn∣2−r(s)2|q - m - s n|^2 - r(s)^2 with r(s)2=∣x−m∣2+s2r(s)^2 = |x - m|^2 + s^2. It equals ∣q−m∣2−∣x−m∣2−2s (q−m)⋅n|q - m|^2 - |x - m|^2 - 2 s\,(q - m)\cdot n, which is affine in ss. For q∈H+q \in H^+, (q−m)⋅n>0(q - m)\cdot n > 0, so the power strictly decreases as ss grows: a point of H+H^+ inside or on the circle for ss is strictly inside for s′s'. For q∈H−q \in H^- the power strictly increases with ss. On the line, (q−m)⋅n=0(q - m)\cdot n = 0, so the power does not depend on ss, and it is negative exactly on the open segment xyxy. □\square

Lemma 2 (adjacent triangles). Suppose every triangle of a triangulation has an empty open circumdisk. Let tt and uu share the edge xyxy, with tt in H+H^+ and uu in H−H^-, and parameters sts_t, sus_u. Then su≤sts_u \le s_t, so Dt∩H−⊆Du∩H−D_t \cap H^- \subseteq D_u \cap H^-.

Proof. Let ww be the third vertex of uu; it lies on CuC_u and in H−H^-. If st<sus_t < s_u, Lemma 1 for H−H^- puts the points of CuC_u in H−H^- inside DtD_t, so w∈Dtw \in D_t, which is not empty. □\square

Theorem 3 (Bowyer-Watson in DELAUNAY). After each insertion, the triangles form a triangulation of the super triangle, every triangle is counterclockwise, and every open circumdisk contains none of the inserted points.

Proof. By induction on the insertions. At the start there is one counterclockwise triangle and no inserted point. Let pp be the next point. It is strictly inside the super triangle, because the super triangle is 64 times larger than the box of the points.

The start triangle is bad. The first loop of DELAUNAY finds a closed triangle t0t_0 that contains pp. The points are distinct, so pp is not a vertex, and a closed triangle without its vertices lies in its open circumdisk. So INCIRCLE gives a positive value.

All bad triangles are found. Call a triangle bad if p∈Dtp \in D_t. Let tt be bad and pick a point cc inside tt so that the segment from cc to pp misses every vertex. Follow the segment: it crosses triangles t=t0′,t1′,…,tk′t = t_0', t_1', \dots, t_k', where tk′t_k' contains pp. If ti′t_i' is bad and the segment leaves it through the edge xyxy into ti+1′t_{i+1}', then pp is in H−H^- or on the open edge xyxy (with ti′t_i' in H+H^+). In the first case, Lemma 2 gives p∈Dti′∩H−⊆Dti+1′p \in D_{t_i'} \cap H^- \subseteq D_{t_{i+1}'}. In the second case, pp is on the open segment xyxy, which by Lemma 1 lies in both disks. So ti+1′t_{i+1}' is bad, and tt is joined to a bad triangle that contains pp by a path of bad neighbours. The triangles that contain pp are t0t_0 and, if pp is on an edge, the neighbour across it, which is also bad. The search grows the cavity from t0t_0 through shared edges, so it finds every bad triangle.

The cavity is star shaped from pp. Let xyxy be an edge of the cavity boundary, with the bad triangle tt in H+H^+. If the other side of xyxy has no triangle, xyxy is an edge of the super triangle, and pp, which is strictly inside it, is in H+H^+. Otherwise the triangle uu on the other side is good. If pp were in H−H^-, Lemma 2 would give p∈Dup \in D_u. If pp were on the line xyxy, it would be on the open segment, since p∈Dtp \in D_t, and then p∈Dup \in D_u by Lemma 1. Both contradict that uu is good. So p∈H+p \in H^+, and the new triangle (x,y,p)(x, y, p) is counterclockwise. The new triangles are the cones from pp over the boundary of a region that is star shaped from pp, so they tile the cavity, and the triangulation outside it does not change.

The new disks are empty. Take the new triangle (x,y,p)(x, y, p) with parameter sps_p. Since p∈H+p \in H^+ is inside CtC_t, Lemma 1 gives sp<sts_p < s_t. If a good triangle uu is across xyxy, then pp is not inside DuD_u, and Lemma 1 gives su≤sps_u \le s_p. So Dp∩H+⊆DtD_p \cap H^+ \subseteq D_t and Dp∩H−⊆DuD_p \cap H^- \subseteq D_u, and DpD_p on the line is the open segment xyxy, which lies in DtD_t. The old disks DtD_t and DuD_u held no earlier point, so DpD_p holds none either; pp is on CpC_p. If no triangle is across xyxy, the side H−H^- is outside the super triangle and holds no point. The disks of the triangles outside the cavity do not contain pp, by the definition of bad. □\square

Corollary 4 (the returned triangles). The triangles returned by DELAUNAY, the ones with no super vertex, are counterclockwise, have disjoint interiors, share edges properly, and have empty open circumdisks with respect to all input points. Each step L5 and L11 keeps a subset of them, so the DistMesh output has the same properties for the returned rounded points. This is the property the tests check with an exact INCIRCLE against every point.

The super triangle is finite, so a thin triangle on the convex hull can be missing from the result when the hull has nearly collinear points. The returned triangles are still Delaunay, and in the tests the square is covered exactly.

Proposition 5 (inside a convex domain). Let the domain Ω={x:fd(x)≤0}\Omega = \{x : f_d(x) \le 0\} be convex. If every returned point satisfies fd≤0f_d \le 0, every returned triangle lies in Ω\Omega.

Proof. A triangle is the convex hull of its vertices, and a convex set contains the convex hull of any of its points. □\square

For the disk, the projection p−fd(p)∇fd(p)p - f_d(p) \nabla f_d(p) with the exact gradient moves a point outside onto the circle, and the numerical gradient and the rounding to 2−242^{-24} leave it within about 10−710^{-7} of it, which is what the test checks. For a nonconvex domain, the centroid test of L5 does not prove that a triangle lies inside: a triangle can cut across a thin notch with its centroid in the domain. That case is a known pitfall of the method, not a proved property.

Termination. DELAUNAY stops, since each insertion visits finitely many triangles. Each pass of L3 to L10 does finite work. L3 runs at most max_iter times. So DISTMESH stops. Whether L10 is reached before the cap is a measured fact: with h0=0.2h_0 = 0.2 on the unit disk it took 90 iterations, with h0=0.1h_0 = 0.1 it took 197, and on the square with h0=0.25h_0 = 0.25 it took 51.

Complexity

One iteration costs O(n)O(n) for the forces and the projection, because a planar triangulation has O(n)O(n) edges. A retriangulation costs O(nlog⁡n)O(n \log n) with a good Delaunay code; the simple Bowyer-Watson here finds the first triangle by a linear scan, which costs O(n2)O(n^2) per triangulation. So kk iterations cost O(kn2)O(k n^2) here and O(knlog⁡n)O(k n \log n) with a fast Delaunay code, and in practice only a small fraction of the iterations retriangulate. The number of iterations kk is not bounded by any proof; in the runs above it grew from 90 to 197 when the number of points grew about four times. The space is O(n)O(n).

Properties

  • Simple. The whole method is a force loop around a Delaunay call. The original MATLAB code has about one page.
  • Implicit geometry. The domain enters only through fdf_d, so set operations on distance functions, such as minimum for union and maximum for intersection, give new domains at no cost.
  • Exact Delaunay output, proved. Each triangulation is exactly Delaunay for the returned points.
  • No convergence proof. The stopping test may never be met; the cap is needed.
  • Good shapes in practice. The measured smallest mean ratio is above 0.8 on the test domains, but no bound is proved.

Variants and improvements

  • Size functions. With a relative size function h(x)h(x), each bar uses L0=h(midpoint)⋅Fscale⋅L_0 = h(\text{midpoint}) \cdot F_\text{scale} \cdot a common scale, and L1 rejects grid points with probability that depends on hh. A mesh sizing function gives hh.
  • Higher dimensions. The same loop with a tetrahedral Delaunay code makes tetrahedral meshes. Slivers are common in 3D, because the forces do not see them.
  • Surfaces. Points can be projected onto the zero set of fdf_d to mesh an implicit surface.
  • Energy view. Optimal Delaunay triangulation and the centroidal Voronoi tessellation, computed by Lloyd's algorithm, move points by the gradient of an energy and come with a proof that the energy goes down. DistMesh has no such energy for its repulsive only forces.

When to use it

Use it for a quick mesh of a domain that has a simple distance function: disks, rectangles with holes, set operations of such shapes, or a level set from a simulation. It is good for teaching and for small problems, where the short code and the regular triangles matter more than speed. For large meshes, sharp corners that are not given as fixed points, or a need for a proved angle bound, use Delaunay refinement, advancing front mesh generation or isosurface stuffing.

Pitfalls

  • Corners not fixed. A corner of the domain that is not in the fixed list is cut off: the points near it are pushed to the two sides, and the mesh rounds the corner.
  • Thin features. The centroid test can keep a triangle that spans a notch narrower than h0h_0. Only for a convex domain does the test prove that the triangles are inside.
  • Inexact distance. With an approximate fdf_d, such as the maximum of the distances to the sides of a square near a corner, the projection may not land on the boundary in one step.
  • No convergence. The stopping test may never be met. Always cap the iterations and check the final mesh.
  • Float predicates. With float in-circle tests, a retriangulation of nearly cocircular points, as on the initial equilateral grid, can be wrong. Use exact predicates.
  • Wrong scale factor. With Fscale≤1F_\text{scale} \le 1, many bars do not push, the points do not reach the boundary, and the boundary triangles get bad.

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.

distmesh.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/distmesh/. The authors are listed in prov/M30YY9.jsonl.

"""DistMesh in the plane, after Persson and Strang, for a uniform size h0.

The domain is {x : fd(x) <= 0} for a signed distance function fd. Points start
on an equilateral grid, then move by the forces of a truss of repulsive
springs, are projected back onto the boundary when they leave the domain, and
are retriangulated by Delaunay when they have moved far enough. There is no
proof that the iteration stops, so it has an iteration cap.

Positions are floats. Each Delaunay triangulation is computed exactly: the
points are rounded to integers on the grid of step 2**-BITS, and the orientation
and in-circle tests run on Python integers. The returned points are those
rounded points, so the returned triangles are exactly Delaunay for them.
"""

import math
from typing import Callable, Dict, List, Sequence, Tuple

from mg3geom import incircle, orient2d

BITS = 24
Vec = Tuple[float, float]
Tri = Tuple[int, int, int]


def to_int(p: Vec) -> Tuple[int, int]:
    return (round(p[0] * (1 << BITS)), round(p[1] * (1 << BITS)))


def from_int(q: Tuple[int, int]) -> Vec:
    return (q[0] / (1 << BITS), q[1] / (1 << BITS))


def delaunay(pts: Sequence[Tuple[int, int]]) -> List[Tri]:
    """Bowyer-Watson with exact integer predicates. The points must be distinct.
    A large super triangle is used; triangles that touch it are dropped. Every
    returned triangle has an empty circumcircle with respect to all points."""
    n = len(pts)
    if len(set(pts)) != n:
        raise ValueError("two points round to the same grid point")
    span = max(max(abs(c) for c in p) for p in pts) + 1
    big = 64 * span
    P = list(pts) + [(-big, -big), (big, -big), (0, big)]
    tris: Dict[Tri, None] = {(n, n + 1, n + 2): None}
    owner: Dict[Tuple[int, int], Tri] = {(n, n + 1): (n, n + 1, n + 2), (n + 1, n + 2): (n, n + 1, n + 2),
                                         (n + 2, n): (n, n + 1, n + 2)}

    def add(t: Tri):
        tris[t] = None
        a, b, c = t
        owner[(a, b)] = owner[(b, c)] = owner[(c, a)] = t

    def remove(t: Tri):
        del tris[t]
        a, b, c = t
        for e in ((a, b), (b, c), (c, a)):
            if owner.get(e) == t:
                del owner[e]

    for v in range(n):
        p = P[v]
        start = None
        for t in tris:
            a, b, c = t
            if orient2d(P[a], P[b], p) >= 0 and orient2d(P[b], P[c], p) >= 0 and orient2d(P[c], P[a], p) >= 0:
                start = t
                break
        # the cavity: triangles whose circumcircle contains p, grown from start
        bad = {start}
        stack = [start]
        while stack:
            a, b, c = stack.pop()
            for x, y in ((a, b), (b, c), (c, a)):
                u = owner.get((y, x))
                if u is not None and u not in bad and incircle(P[u[0]], P[u[1]], P[u[2]], p) > 0:
                    bad.add(u)
                    stack.append(u)
        boundary = []
        for a, b, c in bad:
            for x, y in ((a, b), (b, c), (c, a)):
                if owner.get((y, x)) not in bad:
                    boundary.append((x, y))
        for t in bad:
            remove(t)
        for x, y in boundary:
            add((x, y, v))
    return [t for t in tris if max(t) < n]


def distmesh(fd: Callable[[Vec], float], h0: float, bbox: Tuple[float, float, float, float],
             pfix: Sequence[Vec] = (), max_iter: int = 1000):
    """Returns (points, triangles, iterations, converged). Parameters as in
    Persson and Strang: Fscale 1.2, deltat 0.2, geps 0.001 h0, ttol 0.1,
    dptol 0.001, and a numerical gradient step sqrt(machine eps) h0."""
    fscale, deltat, geps, ttol, dptol = 1.2, 0.2, 0.001 * h0, 0.1, 0.001
    deps = math.sqrt(2.0 ** -52) * h0
    x0, y0, x1, y1 = bbox
    pts: List[Vec] = []
    j = 0
    while y0 + j * h0 * math.sqrt(3) / 2 <= y1 + 1e-12:  # @line L1
        y = y0 + j * h0 * math.sqrt(3) / 2
        i = 0
        while x0 + (i + (j % 2) / 2) * h0 <= x1 + 1e-12:
            p = (x0 + (i + (j % 2) / 2) * h0, y)
            if fd(p) < geps:  # @line L2
                pts.append(p)
            i += 1
        j += 1
    fixed = [from_int(to_int(p)) for p in pfix]
    nfix = len(fixed)
    pts = fixed + [p for p in pts if all(math.hypot(p[0] - q[0], p[1] - q[1]) > 1e-12 for q in fixed)]
    old = None
    tris: List[Tri] = []
    converged = False
    it = 0
    for it in range(1, max_iter + 1):  # @line L3
        if old is None or max(math.hypot(p[0] - q[0], p[1] - q[1]) for p, q in zip(pts, old)) / h0 > ttol:  # @line L4
            pts = [from_int(to_int(p)) for p in pts]
            old = list(pts)
            tris = [t for t in delaunay([to_int(p) for p in pts])  # @line L5
                    if fd(((pts[t[0]][0] + pts[t[1]][0] + pts[t[2]][0]) / 3,
                           (pts[t[0]][1] + pts[t[1]][1] + pts[t[2]][1]) / 3)) < -geps]
            bars = sorted({(min(a, b), max(a, b)) for t in tris for a, b in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0]))})
        lengths = [math.hypot(pts[a][0] - pts[b][0], pts[a][1] - pts[b][1]) for a, b in bars]  # @line L6
        l0 = fscale * math.sqrt(sum(l * l for l in lengths) / len(lengths))
        force = [[0.0, 0.0] for _ in pts]
        for (a, b), l in zip(bars, lengths):
            f = max(l0 - l, 0.0)  # @line L7
            fx, fy = f * (pts[a][0] - pts[b][0]) / l, f * (pts[a][1] - pts[b][1]) / l
            force[a][0] += fx
            force[a][1] += fy
            force[b][0] -= fx
            force[b][1] -= fy
        for k in range(nfix):
            force[k] = [0.0, 0.0]
        pts = [(p[0] + deltat * f[0], p[1] + deltat * f[1]) for p, f in zip(pts, force)]  # @line L8
        new = []
        for k, p in enumerate(pts):
            d = fd(p)
            if d > 0 and k >= nfix:  # @line L9
                gx = (fd((p[0] + deps, p[1])) - d) / deps
                gy = (fd((p[0], p[1] + deps)) - d) / deps
                p = (p[0] - d * gx, p[1] - d * gy)
            new.append(p)
        pts = new
        moves = [deltat * math.hypot(*f) for p, f in zip(pts, force) if fd(p) < -geps]
        if not moves or max(moves) / h0 < dptol:  # @line L10
            converged = True
            break
    pts = [from_int(to_int(p)) for p in pts]  # @line L11
    tris = [t for t in delaunay([to_int(p) for p in pts])
            if fd(((pts[t[0]][0] + pts[t[1]][0] + pts[t[2]][0]) / 3,
                   (pts[t[0]][1] + pts[t[1]][1] + pts[t[2]][1]) / 3)) < -geps]
    return pts, tris, it, converged  # @line L12


def disk(p: Vec) -> float:
    """Signed distance to the unit circle."""
    return math.hypot(p[0], p[1]) - 1.0


def square(p: Vec) -> float:
    """Signed distance function of the square [-1, 1]^2 as in Persson and Strang
    (exact inside, and outside except near the corners)."""
    return -min(min(min(1.0 + p[1], 1.0 - p[1]), 1.0 + p[0]), 1.0 - p[0])
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_distmesh.py 95 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/distmesh/. The authors are listed in prov/M30YY9.jsonl.

import random
from fractions import Fraction as F
from itertools import combinations

from distmesh import delaunay, disk, distmesh, square, to_int
from mg3geom import boundary_edges, exact, incircle, is_valid_planar_mesh, mean_ratio, orient2d


def is_delaunay(ipts, tris):
    """Exact empty circle test of every triangle against every point."""
    for t in tris:
        a, b, c = (ipts[i] for i in t)
        for k, p in enumerate(ipts):
            if k not in t and incircle(a, b, c, p) > 0:
                return False
    return True


def brute_delaunay(ipts):
    """All counterclockwise triples whose circumcircle has no point strictly inside."""
    out = set()
    for i, j, k in combinations(range(len(ipts)), 3):
        if orient2d(ipts[i], ipts[j], ipts[k]) < 0:
            j, k = k, j
        if orient2d(ipts[i], ipts[j], ipts[k]) == 0:
            continue
        if all(incircle(ipts[i], ipts[j], ipts[k], p) <= 0 for p in ipts):
            out.add(frozenset((i, j, k)))
    return out


def test_delaunay_matches_brute_force():
    rng = random.Random(5)
    compared = 0
    for _ in range(60):
        n = rng.randint(3, 14)
        pts = list({(rng.randint(-20, 20), rng.randint(-20, 20)) for _ in range(n)})
        if len(pts) < 3 or all(orient2d(pts[0], pts[1], p) == 0 for p in pts):
            continue
        tris = delaunay(pts)
        brute = brute_delaunay(pts)
        # the Delaunay triangulation is unique when no fourth point is on a
        # circumcircle of the brute force triangles
        if all(incircle(*[pts[i] for i in t], p) != 0
               for t in brute for k, p in enumerate(pts) if k not in t):
            assert {frozenset(t) for t in tris} == brute
            compared += 1
        assert all(orient2d(*[pts[i] for i in t]) > 0 for t in tris)
        assert is_delaunay(pts, tris)
    assert compared >= 20


def check_mesh(fd, pts, tris):
    E = [exact(p) for p in pts]
    assert len({p for p in E}) == len(E)                       # distinct points
    assert all(orient2d(*[E[i] for i in t]) > 0 for t in tris)   # counterclockwise
    assert is_valid_planar_mesh(E, tris)                        # conforming
    assert is_delaunay([to_int(p) for p in pts], tris)          # exact Delaunay
    for t in tris:
        c = (sum(pts[i][0] for i in t) / 3, sum(pts[i][1] for i in t) / 3)
        assert fd(c) < 0                                        # centroid inside
        assert all(fd(pts[i]) < 1e-6 for i in t)                # vertices inside or on the boundary, to the rounding
    assert min(mean_ratio(*[pts[i] for i in t]) for t in tris) > 0.7


def test_unit_disk():
    pts, tris, it, converged = distmesh(disk, 0.2, (-1, -1, 1, 1))
    assert converged and it < 1000
    check_mesh(disk, pts, tris)
    # every boundary vertex lies on the circle, to rounding
    for a, b in boundary_edges(tris):
        assert abs(disk(pts[a])) < 1e-6
    area = sum(F(orient2d(*[exact(pts[i]) for i in t])) for t in tris) / 2
    assert 3.10 < area < 3.1416                                  # inscribed polygon


def test_square_with_fixed_corners():
    corners = ((-1, -1), (1, -1), (1, 1), (-1, 1))
    pts, tris, it, converged = distmesh(square, 0.25, (-1, -1, 1, 1), pfix=corners)
    assert converged
    check_mesh(square, pts, tris)
    E = [exact(p) for p in pts]
    assert all(-1 <= c <= 1 for p in E for c in p)              # exactly inside the closed square
    area = sum(orient2d(*[E[i] for i in t]) for t in tris) / 2
    assert area == 4                                            # the triangles cover the square exactly


def test_iteration_cap_still_gives_a_delaunay_mesh():
    pts, tris, it, converged = distmesh(disk, 0.2, (-1, -1, 1, 1), max_iter=3)
    assert it == 3 and not converged
    assert is_valid_planar_mesh([exact(p) for p in pts], tris)
    assert is_delaunay([to_int(p) for p in pts], tris)

History

Per-Olof Persson and Gilbert Strang published DistMesh in SIAM Review in 2004 with a MATLAB code of about one page, as part of Persson's doctoral work on mesh generation with distance functions. The idea of a truss of springs that moves the points of a mesh is older, but the combination of a signed distance function, a repulsive only force law and Delaunay retriangulation in a few lines of code made the method popular for teaching and research. The Delaunay step goes back to the insertion methods that Adrian Bowyer and David Watson published, separately, in 1981.

References

  1. Per-Olof Persson and Gilbert Strang, A simple mesh generator in MATLAB, SIAM Review 46(2), 2004, 329 to 345, the truss analogy, the repulsive force law, the scaling factor Fscale, the projection with the signed distance function, the retriangulation test and the stopping test (general locator)
  2. Adrian Bowyer, Computing Dirichlet tessellations, The Computer Journal 24(2), 1981, 162 to 166, incremental Delaunay construction by removal of the triangles whose circumcircle contains the new point (general locator)
  3. David F. Watson, Computing the n-dimensional Delaunay tessellation with application to Voronoi polytopes, The Computer Journal 24(2), 1981, 167 to 172, the same insertion method in any dimension (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
  • a scene preset for the example