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.
- Solves
- Mesh generation
- Time
- O(k n^2) worst
- Space
- O(n) extra
- Where
- k = the number of iterations; n = the number of points
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 given by a function that is the signed distance to the boundary, or close to it, a target edge length , a box that contains , and a list of fixed points such as corners. The output is a triangle mesh of a polygon close to , with all vertices in , the fixed points among them, boundary vertices on the boundary, and edges of length close to . This page treats a uniform size; the original method also takes a relative size function .
The algorithm
The parameters are the ones of Persson and Strang: , , , and .
DISTMESH(f_d, h0, box, fixed, cap)- 1
p ← the points of an equilateral grid of spacing h0 in the box - 2
keep the points with f_d < g_eps, and put the fixed points first - 3
for it ← 1 to cap do - 4
if some point moved more than t_tol · h0 since the last triangulation then - 5
T ← Delaunay(p); drop the triangles whose centroid has f_d ≥ −g_eps; bars ← the edges of T - 6
ℓ ← the bar lengths; L0 ← F_scale · sqrt(Σ ℓ² / number of bars) - 7
for each bar ij: push i and j apart by max(L0 − ℓ_ij, 0) - 8
p ← p + Δt · F, with no force on the fixed points - 9
for each moved point with f_d(p) > 0: p ← p − f_d(p) ∇f_d(p) - 10
if every interior point moved less than d_tol · h0 then break - 11
T ← Delaunay(p) without the outside triangles - 12
return p, T
L6 to L8 are one explicit Euler step of the truss equation ; see the Euler method. The force of a bar is linear in the compression and zero for a stretched bar, so bars only push. 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, 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 ; the in-circle test decides which triangles to remove.
Example
Take the unit disk with , 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 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 and , and the area of the mesh is 3.1200, just under because the boundary edges are chords.
On the square with the four corners fixed and , the run stops after 51 iterations with 87 points and 137 triangles. The smallest mean ratio is 0.852, the angles are between and , and the triangles cover the square exactly, with area 4. With 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 (the float positions times , rounded). For a triangle , is its open circumdisk and its circle. ORIENT2D and INCIRCLE are exact on integers.
Lemma 1 (pencil of circles). Let , let and be the two open half planes of the line , and let be the unit normal pointing into . Every circle through and has its centre at with and one real . Let be its open disk. If , then and , and the circle of in lies inside . Every meets the line in the open segment between and .
Proof. The power of a point with respect to the circle with parameter is with . It equals , which is affine in . For , , so the power strictly decreases as grows: a point of inside or on the circle for is strictly inside for . For the power strictly increases with . On the line, , so the power does not depend on , and it is negative exactly on the open segment .
Lemma 2 (adjacent triangles). Suppose every triangle of a triangulation has an empty open circumdisk. Let and share the edge , with in and in , and parameters , . Then , so .
Proof. Let be the third vertex of ; it lies on and in . If , Lemma 1 for puts the points of in inside , so , which is not empty.
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 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 that contains . The points are distinct, so 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 . Let be bad and pick a point inside so that the segment from to misses every vertex. Follow the segment: it crosses triangles , where contains . If is bad and the segment leaves it through the edge into , then is in or on the open edge (with in ). In the first case, Lemma 2 gives . In the second case, is on the open segment , which by Lemma 1 lies in both disks. So is bad, and is joined to a bad triangle that contains by a path of bad neighbours. The triangles that contain are and, if is on an edge, the neighbour across it, which is also bad. The search grows the cavity from through shared edges, so it finds every bad triangle.
The cavity is star shaped from . Let be an edge of the cavity boundary, with the bad triangle in . If the other side of has no triangle, is an edge of the super triangle, and , which is strictly inside it, is in . Otherwise the triangle on the other side is good. If were in , Lemma 2 would give . If were on the line , it would be on the open segment, since , and then by Lemma 1. Both contradict that is good. So , and the new triangle is counterclockwise. The new triangles are the cones from over the boundary of a region that is star shaped from , so they tile the cavity, and the triangulation outside it does not change.
The new disks are empty. Take the new triangle with parameter . Since is inside , Lemma 1 gives . If a good triangle is across , then is not inside , and Lemma 1 gives . So and , and on the line is the open segment , which lies in . The old disks and held no earlier point, so holds none either; is on . If no triangle is across , the side is outside the super triangle and holds no point. The disks of the triangles outside the cavity do not contain , by the definition of bad.
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 be convex. If every returned point satisfies , every returned triangle lies in .
Proof. A triangle is the convex hull of its vertices, and a convex set contains the convex hull of any of its points.
For the disk, the projection with the exact gradient moves a point outside onto the circle, and the numerical gradient and the rounding to leave it within about 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 on the unit disk it took 90 iterations, with it took 197, and on the square with it took 51.
Complexity
One iteration costs for the forces and the projection, because a planar triangulation has edges. A retriangulation costs with a good Delaunay code; the simple Bowyer-Watson here finds the first triangle by a linear scan, which costs per triangulation. So iterations cost here and with a fast Delaunay code, and in practice only a small fraction of the iterations retriangulate. The number of iterations 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 .
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 , 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 , each bar uses a common scale, and L1 rejects grid points with probability that depends on . A mesh sizing function gives .
- 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 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 . Only for a convex domain does the test prove that the triangles are inside.
- Inexact distance. With an approximate , 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 , 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.
# 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
- 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)
- 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)
- 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.
| 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 M30YY9 Edit this page History Report an error Markdown