Algorithm Search⌘K

Algorithmadvanced

Optimization-based mesh smoothing

Also called Freitag-Plassmann smoothing, local mesh optimization.

Moves each vertex to maximise the worst quality of its incident elements, a nonsmooth optimisation that, unlike Laplacian smoothing, cannot invert elements.

Time
O(s d^3) per-vertex
Space
O(d) extra
Where
d = the number of elements around the vertex; s = the number of steps
Properties
deterministicnot exactiterative
Origin
Lori A. Freitag, Paul Plassmann, 2000

Optimization-based mesh smoothing moves one vertex of a mesh at a time to the position that makes the worst element around it as good as possible. The worst quality is the minimum of several smooth functions, so it has corners and ordinary gradient methods do not apply. Freitag and Plassmann solve it as a nonsmooth problem: they keep the set of elements that are nearly the worst, take the direction of least norm in the convex hull of their quality gradients, and search along it. A step is accepted only if the worst quality goes up and no element turns over, so, unlike Laplacian smoothing, the method never inverts an element. For the mean ratio of triangles the problem has convex level sets, so a stationary point is the best position over the whole star.

In plain words

A point of a mesh is joined to a ring of neighbours. Each triangle around it has a score, and the worst score is what matters, because one bad triangle can spoil a simulation.

The method looks at the triangles that are now the worst, and finds a direction that makes all of them better at the same time. It moves the point a little in that direction, but only if the worst score really goes up and no triangle turns inside out. When no direction helps the worst triangles together, it stops.

Laplacian smoothing simply moves the point to the middle of its neighbours. That is cheap, but in a ring shaped like an arrow the middle can lie outside the ring, and a triangle flips over. This method checks every move, so that cannot happen.

The problem

A free vertex at xx has star triangles τi=(x,ai,bi)\tau_i = (x, a_i, b_i) whose outer edges form a closed polygon, the link. The quality of τi\tau_i is the mean ratio from the mesh quality measures,

qi(x)=43 Ai(x)ℓi12+ℓi22+ℓi32,q_i(x) = \frac{4\sqrt3\,A_i(x)}{\ell_{i1}^2 + \ell_{i2}^2 + \ell_{i3}^2},

which is 1 for an equilateral triangle, 0 for a flat one and negative for a clockwise one. The problem is to find

max⁡x∈KQ(x),Q(x)=min⁡iqi(x),\max_{x \in K} Q(x), \qquad Q(x) = \min_i q_i(x),

where KK, the kernel of the star, is the set of positions with all Ai>0A_i > 0. QQ is not differentiable where two qualities tie, which is the usual case at the optimum, because if one quality were alone at the bottom the point could move to raise it. For a whole mesh, the method is applied to each free vertex in turn.

The algorithm

ORIENT2D is the exact orientation test. The tolerance δ\delta defines the active set, and ε\varepsilon the stopping test.

  1. SMOOTH-VERTEX(x, link)
  2. 1if ORIENT2D(x, a_i, b_i) ≤ 0 for some i then fail ▷ tangled: untangle first
  3. 2repeat at most max_iter times
  4. 3q_i ← q_i(x) for all i; m ← min_i q_i
  5. 4I ← {i : q_i ≤ m + δ}; G ← {∇q_i(x) : i ∈ I}
  6. 5d ← the point of least norm in the convex hull of G
  7. 6if |d|² ≤ ε then return x ▷ stationary
  8. 7α ← min over inactive j with |d|² > ∇q_j · d of (q_j − m) / (|d|² − ∇q_j · d), or 1 if none
  9. 8halve α until x + αd passes ORIENT2D for all i and min_i q_i(x + αd) > m, at most 60 times
  10. 9if no α passed then return x
  11. 10x ← x + αd
  12. 11return x

L5 is a small quadratic program. In the plane the hull of the gradients is a polygon, and its point of least norm is the origin, a gradient, or the foot of the origin on a segment between two gradients, so it is found by checking these cases. L7 predicts the step from linear models: along dd, every active quality rises at rate at least ∣d∣2|d|^2, and the step ends where an inactive quality, rising more slowly, would meet them. L8 then backtracks until the real worst quality rises. In 3D the same scheme works with the tetrahedron mean ratio 12(3V)2/3/∑ℓ212(3V)^{2/3}/\sum \ell^2 and a small quadratic program in L5.

Example

Take a free vertex at the origin with the link polygon (−2,0)(-2, 0), (0,−2)(0, -2), (6,−1)(6, -1), (1,0)(1, 0), (6,1)(6, 1), (0,2)(0, 2), shaped like an arrow pointing left with a notch at (1,0)(1, 0). The six triangles from the origin are counterclockwise, and the worst mean ratio is 0.0541.

Laplacian smoothing moves the vertex to the mean of the link vertices, (11/6,0)(11/6, 0). That point is beyond the notch, outside the kernel. The two triangles at the notch, (x,(6,−1),(1,0))(x, (6,-1), (1,0)) and (x,(1,0),(6,1))(x, (1,0), (6,1)), become clockwise, with mean ratio −0.0641-0.0641 each.

Max-min smoothing takes 4 accepted steps. The worst quality goes 0.0541,0.0979,0.1010,0.1011,0.10110.0541, 0.0979, 0.1010, 0.1011, 0.1011, and the vertex ends at about (−1.778,0)(-1.778, 0), where four of the six triangles tie at 0.1011. A grid search over the kernel with step about 0.05 finds its best value 0.1004 near (−1.733,0)(-1.733, 0), slightly below, as a grid must be. The best position is near the left corner, because the two long thin triangles toward (6,±1)(6, \pm1) are bad from anywhere.

On a 5×55 \times 5 square grid split into 50 triangles, with the 16 inner vertices moved randomly by up to 0.35, the worst mean ratio is 0.224. Sweeps of max-min smoothing over the inner vertices raise it to 0.695 after one sweep, 0.814 after three and 0.846 after five. Three sweeps of Laplacian smoothing give 0.855 on the same mesh. On a convex, nearly regular mesh Laplacian smoothing does as well; the gain of max-min is safety on bad stars. These are measurements.

Correctness

The full proof is in the proof file. Validity and monotonicity follow from the acceptance test of L8: the exact orientation test keeps every position in the kernel, and the worst quality rises at each accepted step. Since the other triangles of the mesh do not change, the worst quality of the whole mesh never goes down.

The optimality statement uses the shape of the quality. On the kernel, qi(x)≥tq_i(x) \ge t is the same as 43 Ai(x)−t Si(x)≥04\sqrt3\,A_i(x) - t\,S_i(x) \ge 0, where AiA_i is affine and the sum of squared edge lengths SiS_i is a convex quadratic, so the left side is a concave function and its superlevel set is convex. If 00 is in the convex hull of the active gradients at xx but some yy in the kernel were better, concavity would give ∇qi(x)⋅(y−x)>0\nabla q_i(x) \cdot (y - x) > 0 for every active ii, so no convex combination of these gradients could be zero. So a stationary point is a global maximum over the kernel. When d≠0d \ne 0, the least norm property gives ∇qi⋅d≥∣d∣2\nabla q_i \cdot d \ge |d|^2 for every active ii, so dd is a direction of ascent of the worst quality, like a subgradient step for a concave function.

What is measured is the quality value reached and how many steps it takes. What is proved is that elements never invert, the worst quality never goes down, and stationary points are optimal for one vertex.

Proof: Max-min smoothing never lowers the worst quality, keeps the star valid, and stops only where no position is betterfull

Setting. A free vertex at position xx has star triangles τi=(x,ai,bi)\tau_i = (x, a_i, b_i), i=1,…,mi = 1, \dots, m, whose outer edges aibia_i b_i form a closed polygon, the link. Let Ai(x)=12 orient(x,ai,bi)A_i(x) = \frac12\,\mathrm{orient}(x, a_i, b_i) be the signed area, Si(x)=∣x−ai∣2+∣x−bi∣2+∣ai−bi∣2S_i(x) = |x - a_i|^2 + |x - b_i|^2 + |a_i - b_i|^2 the sum of squared edge lengths, and

qi(x)=43 Ai(x)Si(x),Q(x)=min⁡iqi(x),q_i(x) = \frac{4\sqrt3\,A_i(x)}{S_i(x)}, \qquad Q(x) = \min_i q_i(x),

the mean ratio of τi\tau_i and the worst quality of the star. The kernel of the star is K={x:Ai(x)>0 for all i}K = \{x : A_i(x) > 0 \text{ for all } i\}, an intersection of open half-planes, so it is open and convex. A position in KK gives a valid star: all triangles are counterclockwise and they tile the link polygon.

Claim 1 (monotone and valid). SMOOTH-VERTEX started at x0∈Kx_0 \in K produces positions x0,x1,…x_0, x_1, \dots in KK with Q(x0)<Q(x1)<⋯Q(x_0) < Q(x_1) < \cdots, and it stops after at most max_iter steps.

Proof. A step is taken only after the test of L8 succeeds: the new position passes the exact orientation test, so it is in KK, and its worst quality, as computed, is larger than the current one. Otherwise the loop ends at L9. The loop has a fixed bound on its iterations. □\square

The orientation test is exact, because each float coordinate converts to a Fraction without rounding. The quality comparison is done in floats, so "larger" means larger as computed. Validity is exact; the monotone quality is exact up to the rounding of the quality formula.

Lemma 2 (convex superlevel sets). For each ii and each t≥0t \ge 0, the set {x∈K:qi(x)≥t}\{x \in K : q_i(x) \ge t\} is convex. So qiq_i and QQ are quasi-concave on KK.

Proof. On KK, Si>0S_i > 0, so qi(x)≥tq_i(x) \ge t if and only if φi,t(x)=43 Ai(x)−t Si(x)≥0\varphi_{i,t}(x) = 4\sqrt3\,A_i(x) - t\,S_i(x) \ge 0. Here AiA_i is affine and SiS_i is a convex quadratic, so φi,t\varphi_{i,t} is concave and its superlevel set is convex. The superlevel sets of QQ are intersections of those of the qiq_i. □\square

Freitag and Plassmann state this convexity of the level sets for their quality measures; this is the version for the mean ratio.

Theorem 3 (stationary means optimal). Let x∈Kx \in K, q∗=Q(x)q^* = Q(x), and let I={i:qi(x)=q∗}I = \{i : q_i(x) = q^*\} be the active set. If 00 lies in the convex hull of {∇qi(x):i∈I}\{\nabla q_i(x) : i \in I\}, then Q(y)≤Q(x)Q(y) \le Q(x) for every y∈Ky \in K.

Proof. Suppose y∈Ky \in K has Q(y)>q∗Q(y) > q^*. Take i∈Ii \in I and let φ=φi,q∗\varphi = \varphi_{i,q^*} from Lemma 2. Then φ(x)=Si(x) (qi(x)−q∗)=0\varphi(x) = S_i(x)\,(q_i(x) - q^*) = 0 and φ(y)=Si(y) (qi(y)−q∗)>0\varphi(y) = S_i(y)\,(q_i(y) - q^*) > 0. Since φ\varphi is concave and differentiable,

∇φ(x)⋅(y−x)≥φ(y)−φ(x)>0.\nabla\varphi(x) \cdot (y - x) \ge \varphi(y) - \varphi(x) > 0.

By the quotient rule, ∇qi=(43 ∇Ai−qi∇Si)/Si\nabla q_i = \bigl(4\sqrt3\,\nabla A_i - q_i \nabla S_i\bigr)/S_i, so at xx, where qi(x)=q∗q_i(x) = q^*, ∇φ(x)=Si(x) ∇qi(x)\nabla\varphi(x) = S_i(x)\,\nabla q_i(x). Hence ∇qi(x)⋅(y−x)>0\nabla q_i(x) \cdot (y - x) > 0 for every i∈Ii \in I. Every convex combination gg of these gradients then has g⋅(y−x)>0g \cdot (y - x) > 0, so g≠0g \ne 0, which contradicts the assumption. □\square

Lemma 4 (the direction rises). Let dd be the point of least norm in the convex hull CC of {∇qi(x):i∈I}\{\nabla q_i(x) : i \in I\}, and suppose d≠0d \ne 0. Then ∇qi(x)⋅d≥∣d∣2>0\nabla q_i(x) \cdot d \ge |d|^2 > 0 for every i∈Ii \in I. So for small α>0\alpha > 0, Q(x+αd)>Q(x)Q(x + \alpha d) > Q(x).

Proof. For g∈Cg \in C and s∈[0,1]s \in [0, 1], the point d+s(g−d)d + s(g - d) is in CC, so ∣d+s(g−d)∣2≥∣d∣2|d + s(g - d)|^2 \ge |d|^2. The derivative at s=0s = 0 is 2d⋅(g−d)≥02 d \cdot (g - d) \ge 0, which gives g⋅d≥∣d∣2g \cdot d \ge |d|^2. Each active qiq_i then rises at rate at least ∣d∣2|d|^2 along dd. Each inactive qjq_j is above q∗q^* by a positive margin and is continuous, and KK is open. So for small α\alpha all qi(x+αd)>q∗q_i(x + \alpha d) > q^* and x+αd∈Kx + \alpha d \in K. □\square

Consequence. If the line search of L8 fails at a point where d≠0d \ne 0, the failure comes from the bound on the number of halvings, not from the absence of a better point. If the method stops at L6, with ∣d∣2|d|^2 below the tolerance, the point is stationary up to that tolerance, and by Theorem 3 an exactly stationary point is a global maximum of QQ over the kernel. The test of the page compares the result with a grid search over the kernel, the reference method, and they agree to within the grid resolution.

The active set of the code contains every ii with qi≤q∗+δq_i \le q^* + \delta, a slightly larger set than II. This makes the direction more cautious near ties; it does not change Claim 1, which rests only on the tests of L8.

What is not proved. Nothing here bounds QQ from below: if the link polygon is bad, every position is bad. The kernel can be empty, in which case no position gives a valid star and the method cannot start; this is the task of mesh untangling. Over a whole mesh, smoothing one vertex at a time raises the worst quality of each star but does not reach the best positions of all vertices together, and it does not change the connectivity.

Complexity

One iteration computes dd qualities and gradients in O(d)O(d) time, solves the least norm problem over at most dd gradients, which costs O(d3)O(d^3) with the case check of the plane and is constant in practice because the active set has two to four members, and runs a line search of at most 60 trials of O(d)O(d) each. With ss steps, a vertex costs O(sd3)O(s d^3) in the worst case, and the number of steps is small in practice, often under 10. A sweep over a mesh with nn free vertices costs O(n)O(n) vertex smoothings. Each vertex costs more than a Laplacian move, which is one average, so codes often apply the method only where the quality is below a threshold. The space is O(d)O(d).

Properties

  • Never inverts, proved. Each accepted position passes an exact orientation test.
  • Monotone, proved. The worst quality of the star, and of the mesh, never goes down.
  • Globally optimal for one vertex, proved. For the mean ratio, the level sets are convex, so a stationary point is the best position in the kernel.
  • Local in the mesh. Vertices are moved one at a time; the result over a mesh is not a joint optimum.
  • Nonsmooth. The objective is a minimum of smooth functions, so the method works with an active set.

Variants and improvements

  • Smart Laplacian. Move the vertex to the Laplacian target only if the worst quality rises; otherwise keep it. This is cheaper but stops at worse positions.
  • Combined smoothing. Use Laplacian smoothing first and the max-min method only for vertices whose star has quality below a threshold. Freitag studied such combinations in the late 1990s.
  • Other measures. The same scheme works with the smallest angle, the smallest sine of a dihedral angle in 3D, or the condition number of the element Jacobian. The convexity of level sets must be checked for each measure.
  • Linear programming. Amenta, Bern and Eppstein showed that for some measures, such as the smallest angle, the best position solves an LP-type problem, which can be solved in linear time in the number of elements for a fixed dimension.
  • Untangling. If the kernel is empty or the start is tangled, mesh untangling maximises the smallest signed area first, which Freitag and Plassmann pose as a linear program.
  • With topology changes. In 3D, smoothing is combined with flips in topological tetrahedral mesh improvement, because moving vertices alone cannot remove many bad tetrahedra.
  • Global energies. Optimal Delaunay triangulation moves vertices to lower an integral error and changes the connectivity.

When to use it

Use it after mesh generation when the worst element matters, for example before a finite element solve where one flat element ruins the conditioning, and when the mesh has nonconvex stars near the boundary or near features, where Laplacian smoothing can invert elements. Use plain Laplacian smoothing on a nearly regular mesh, where it is cheaper and as good. Use untangling first if some elements are already inverted.

Pitfalls

  • Average instead of minimum. Maximising the mean quality of the star can leave one bad element. The worst element is the target.
  • Quality measures without sign. A measure such as the ratio of the shortest edge to the circumradius, or the absolute value of the area, is positive for a clockwise triangle too. With such a measure the line search can step out of the kernel and accept a folded star. Use a signed measure, or test the orientation.
  • Float orientation. In exact arithmetic a rise of the signed worst quality from a positive value keeps the vertex in the kernel, but for a nearly flat element the float sign can be wrong. Test orientation exactly.
  • Tiny active set tolerance. With δ=0\delta = 0, the direction ignores a quality that is about to become the worst, and the steps become very short. A small positive δ\delta is better.
  • Expecting a fix for bad topology. Smoothing cannot fix a vertex of degree 3 or 12 in a triangle mesh; flips are needed.

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.

mg3geom.pyI0RawGitHub
# 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
optimization_based_mesh_smoothing.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimization-based-mesh-smoothing/. The authors are listed in prov/9DFJ45.jsonl.

"""Max-min optimization-based smoothing of one free vertex, after Freitag and Plassmann.

A free vertex x has a star of triangles (x, a, b), counterclockwise, whose outer
edges ab form the closed link polygon. The quality of a triangle is the mean
ratio q = 4 sqrt(3) A / (l1^2 + l2^2 + l3^2). The method moves x to raise the
smallest quality of its star: it takes as search direction the point of least
norm in the convex hull of the gradients of the nearly smallest qualities, and
it accepts a step only if the smallest quality goes up and every triangle stays
counterclockwise. The orientation test is exact (floats convert to Fractions
without rounding); the qualities are measured in floats.
"""

import math
from typing import List, Sequence, Tuple

from mg3geom import exact, orient2d

Vec = Tuple[float, float]
SQ3 = math.sqrt(3.0)


def quality(x: Vec, a: Vec, b: Vec) -> float:
    """Mean ratio of the triangle (x, a, b); negative if it is clockwise."""
    s = (x[0] - a[0]) ** 2 + (x[1] - a[1]) ** 2 + (x[0] - b[0]) ** 2 + (x[1] - b[1]) ** 2 + (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
    return 2.0 * SQ3 * orient2d(x, a, b) / s


def quality_gradient(x: Vec, a: Vec, b: Vec) -> Vec:
    """Gradient of quality(x, a, b) with respect to x."""
    area = 0.5 * orient2d(x, a, b)
    ga = (0.5 * (a[1] - b[1]), 0.5 * (b[0] - a[0]))
    s = (x[0] - a[0]) ** 2 + (x[1] - a[1]) ** 2 + (x[0] - b[0]) ** 2 + (x[1] - b[1]) ** 2 + (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2
    gs = (2 * (x[0] - a[0]) + 2 * (x[0] - b[0]), 2 * (x[1] - a[1]) + 2 * (x[1] - b[1]))
    c = 4.0 * SQ3 / (s * s)
    return (c * (ga[0] * s - area * gs[0]), c * (ga[1] * s - area * gs[1]))


def min_quality(x: Vec, link: Sequence[Tuple[Vec, Vec]]) -> float:
    return min(quality(x, a, b) for a, b in link)


def valid(x: Vec, link: Sequence[Tuple[Vec, Vec]]) -> bool:
    """Exact test that every star triangle is counterclockwise."""
    ex = exact(x)
    return all(orient2d(ex, exact(a), exact(b)) > 0 for a, b in link)


def min_norm_point(gs: Sequence[Vec]) -> Vec:
    """The point of least norm in the convex hull of planar vectors. It is the
    origin, a vertex, or the foot of the origin on a segment between two of them."""
    best = min(gs, key=lambda g: g[0] * g[0] + g[1] * g[1])
    bn = best[0] ** 2 + best[1] ** 2
    for i in range(len(gs)):
        for j in range(i + 1, len(gs)):
            p, q = gs[i], gs[j]
            d = (q[0] - p[0], q[1] - p[1])
            dd = d[0] * d[0] + d[1] * d[1]
            if dd == 0:
                continue
            t = -(p[0] * d[0] + p[1] * d[1]) / dd
            if 0 < t < 1:
                f = (p[0] + t * d[0], p[1] + t * d[1])
                fn = f[0] ** 2 + f[1] ** 2
                if fn < bn:
                    best, bn = f, fn
            for k in range(j + 1, len(gs)):
                r = gs[k]
                o1 = p[0] * q[1] - p[1] * q[0]
                o2 = q[0] * r[1] - q[1] * r[0]
                o3 = r[0] * p[1] - r[1] * p[0]
                if (o1 >= 0 and o2 >= 0 and o3 >= 0) or (o1 <= 0 and o2 <= 0 and o3 <= 0):
                    if o1 + o2 + o3 != 0:
                        return (0.0, 0.0)
    return best


def smooth_vertex(x: Vec, link: Sequence[Tuple[Vec, Vec]], max_iter: int = 200,
                  delta: float = 1e-6, eps: float = 1e-12) -> Tuple[Vec, List[float]]:
    """Max-min smoothing of the free vertex x. Returns the new position and the
    smallest star quality after each accepted step (the first entry is the
    starting value). Raises ValueError if the star is tangled at the start."""
    if not valid(x, link):  # @line L1
        raise ValueError("the star is tangled; untangle it first")
    history = [min_quality(x, link)]
    for _ in range(max_iter):  # @line L2
        qs = [quality(x, a, b) for a, b in link]  # @line L3
        m = min(qs)
        active = [i for i, q in enumerate(qs) if q <= m + delta]  # @line L4
        grads = [quality_gradient(x, *link[i]) for i in active]
        d = min_norm_point(grads)  # @line L5
        dn = d[0] * d[0] + d[1] * d[1]
        if dn <= eps:  # @line L6
            break
        # L7: predicted step where the linear model of an inactive quality
        # meets the rising linear model m + alpha |d|^2 of the active ones
        alpha = None  # @line L7
        for i, q in enumerate(qs):
            if i in active:
                continue
            g = quality_gradient(x, *link[i])
            rate = dn - (g[0] * d[0] + g[1] * d[1])
            if rate > 0:
                cand = (q - m) / rate
                alpha = cand if alpha is None else min(alpha, cand)
        if alpha is None:
            alpha = 1.0
        accepted = False
        for _ in range(60):  # @line L8
            y = (x[0] + alpha * d[0], x[1] + alpha * d[1])
            if valid(y, link) and min_quality(y, link) > m:
                accepted = True
                break
            alpha /= 2
        if not accepted:  # @line L9
            break
        x = y  # @line L10
        history.append(min_quality(x, link))
    return x, history  # @line L11


def star_link(tris: Sequence[Tuple[int, int, int]], v: int) -> List[Tuple[int, int]]:
    """The link edges (a, b) of vertex v, from the triangles (v, a, b)."""
    out = []
    for t in tris:
        if v in t:
            r = t.index(v)
            out.append((t[(r + 1) % 3], t[(r + 2) % 3]))
    return out


def smooth_mesh(points: List[Vec], tris: Sequence[Tuple[int, int, int]], free: Sequence[int], sweeps: int = 3) -> List[Vec]:
    """Gauss-Seidel sweeps of max-min smoothing over the free vertices."""
    points = list(points)
    for _ in range(sweeps):
        for v in free:
            link = [(points[a], points[b]) for a, b in star_link(tris, v)]
            points[v], _ = smooth_vertex(points[v], link)
    return points


def laplacian_target(link: Sequence[Tuple[Vec, Vec]]) -> Vec:
    """The mean of the link vertices, the target of Laplacian smoothing."""
    n = len(link)
    return (sum(a[0] for a, _ in link) / n, sum(a[1] for a, _ in link) / n)
test_optimization_based_mesh_smoothing.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optimization-based-mesh-smoothing/. The authors are listed in prov/9DFJ45.jsonl.

import math
import random

from mg3geom import exact, orient2d
from optimization_based_mesh_smoothing import (laplacian_target, min_norm_point, min_quality, quality,
                                               quality_gradient, smooth_mesh, smooth_vertex, star_link, valid)


def ring(poly):
    n = len(poly)
    return [(poly[i], poly[(i + 1) % n]) for i in range(n)]


def random_star(rng):
    """A link polygon that is star-shaped about the origin, with 4 to 8 corners."""
    k = rng.randint(4, 8)
    while True:
        angles = sorted(rng.uniform(0, 2 * math.pi) for _ in range(k))
        gaps = [(angles[(i + 1) % k] - angles[i]) % (2 * math.pi) for i in range(k)]
        if max(gaps) < 0.9 * math.pi:
            break
    poly = [(round(r * math.cos(t), 3), round(r * math.sin(t), 3)) for t, r in ((t, rng.uniform(1, 4)) for t in angles)]
    return ring(poly)


def start_point(rng, link):
    while True:
        x = (rng.uniform(-0.3, 0.3), rng.uniform(-0.3, 0.3))
        if valid(x, link):
            return x


def grid_search(link, n=40):
    """Best smallest quality over valid points of a grid on the bounding box,
    then over a finer grid around the best point (the reference method)."""
    xs = [a[0] for a, _ in link]
    ys = [a[1] for a, _ in link]
    lo_x, hi_x, lo_y, hi_y = min(xs), max(xs), min(ys), max(ys)
    best_q, best = -1.0, None
    for level in range(3):
        hx, hy = (hi_x - lo_x) / n, (hi_y - lo_y) / n
        for i in range(n + 1):
            for j in range(n + 1):
                y = (lo_x + i * hx, lo_y + j * hy)
                if valid(y, link):
                    q = min_quality(y, link)
                    if q > best_q:
                        best_q, best = q, y
        lo_x, hi_x = best[0] - 3 * hx, best[0] + 3 * hx
        lo_y, hi_y = best[1] - 3 * hy, best[1] + 3 * hy
    return best_q, best


def test_quality_values():
    s = math.sqrt(3) / 2
    assert abs(quality((0.0, 0.0), (1.0, 0.0), (0.5, s)) - 1.0) < 1e-12
    assert quality((0.0, 0.0), (1.0, 0.0), (2.0, 0.0)) == 0.0
    assert quality((0.0, 0.0), (0.5, s), (1.0, 0.0)) < 0


def test_gradient_against_finite_differences():
    rng = random.Random(1)
    for _ in range(200):
        x, a, b = [(rng.uniform(-3, 3), rng.uniform(-3, 3)) for _ in range(3)]
        g = quality_gradient(x, a, b)
        h = 1e-6
        fx = (quality((x[0] + h, x[1]), a, b) - quality((x[0] - h, x[1]), a, b)) / (2 * h)
        fy = (quality((x[0], x[1] + h), a, b) - quality((x[0], x[1] - h), a, b)) / (2 * h)
        assert abs(fx - g[0]) < 1e-4 * (1 + abs(g[0]))
        assert abs(fy - g[1]) < 1e-4 * (1 + abs(g[1]))


def test_min_norm_point_against_optimality_conditions():
    # p is the least-norm point of the hull iff p is in the hull and
    # g . p >= |p|^2 for every generator g; the origin is in the hull iff
    # no direction u has g . u < 0 for all g (checked on 3600 directions)
    rng = random.Random(2)
    zeros = 0
    for _ in range(400):
        gs = [(rng.uniform(-2, 2), rng.uniform(-2, 2)) for _ in range(rng.randint(1, 5))]
        p = min_norm_point(gs)
        pp = p[0] ** 2 + p[1] ** 2
        if pp == 0:
            zeros += 1
            for k in range(3600):
                u = (math.cos(k * math.pi / 1800), math.sin(k * math.pi / 1800))
                assert max(g[0] * u[0] + g[1] * u[1] for g in gs) >= -1e-9
        else:
            assert all(g[0] * p[0] + g[1] * p[1] >= pp - 1e-9 for g in gs)
            u = (-p[0] / math.sqrt(pp), -p[1] / math.sqrt(pp))
            assert max(g[0] * u[0] + g[1] * u[1] for g in gs) < 0   # the origin is outside
    assert zeros > 20


def test_min_quality_never_decreases_and_stays_valid():
    rng = random.Random(3)
    for _ in range(60):
        link = random_star(rng)
        x0 = start_point(rng, link)
        x, hist = smooth_vertex(x0, link)
        assert all(h1 > h0 for h0, h1 in zip(hist, hist[1:]))
        assert valid(x, link)
        # the exact orientation of every triangle of the result is positive
        assert all(orient2d(exact(x), exact(a), exact(b)) > 0 for a, b in link)


def test_matches_grid_search():
    # min q is quasi-concave on the kernel, so a stationary point is a global
    # maximum; the grid search must not find anything clearly better
    rng = random.Random(4)
    for _ in range(12):
        link = random_star(rng)
        x0 = start_point(rng, link)
        x, hist = smooth_vertex(x0, link)
        gq, _ = grid_search(link)
        assert hist[-1] >= gq - 1e-4
        assert hist[-1] <= gq + 2e-3   # the fine grid gets close to the optimum


def test_laplacian_inverts_where_max_min_does_not():
    link = ring([(-2.0, 0.0), (0.0, -2.0), (6.0, -1.0), (1.0, 0.0), (6.0, 1.0), (0.0, 2.0)])
    x0 = (0.0, 0.0)
    assert valid(x0, link)
    lap = laplacian_target(link)
    assert lap == (11 / 6, 0.0)
    assert not valid(lap, link)
    assert min(quality(lap, a, b) for a, b in link) < 0
    x, hist = smooth_vertex(x0, link)
    assert valid(x, link)
    assert abs(hist[0] - 0.0541) < 1e-4 and abs(hist[-1] - 0.1011) < 1e-4


def test_tangled_start_is_rejected():
    link = ring([(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)])
    try:
        smooth_vertex((3.0, 0.0), link)
    except ValueError:
        return
    assert False, "a tangled star must be rejected"


def test_mesh_sweep_raises_worst_quality():
    rng = random.Random(5)
    n = 5
    pts = []
    for j in range(n + 1):
        for i in range(n + 1):
            inner = 0 < i < n and 0 < j < n
            pts.append((i + (rng.uniform(-0.35, 0.35) if inner else 0.0), j + (rng.uniform(-0.35, 0.35) if inner else 0.0)))
    tris = []
    for j in range(n):
        for i in range(n):
            v = j * (n + 1) + i
            tris += [(v, v + 1, v + n + 2), (v, v + n + 2, v + n + 1)]
    assert all(orient2d(exact(pts[a]), exact(pts[b]), exact(pts[c])) > 0 for a, b, c in tris)
    free = [j * (n + 1) + i for j in range(1, n) for i in range(1, n)]
    before = min(quality(pts[a], pts[b], pts[c]) for a, b, c in tris)
    out = smooth_mesh(pts, tris, free)
    after = min(quality(out[a], out[b], out[c]) for a, b, c in tris)
    assert after >= before
    assert all(orient2d(exact(out[a]), exact(out[b]), exact(out[c])) > 0 for a, b, c in tris)
    assert len(star_link(tris, free[0])) == 6

History

Laplacian smoothing, in which a vertex moves to the mean of its neighbours, was the standard for many years, and it can invert elements. In the 1990s several groups moved vertices by local optimisation instead. Lori Freitag and Paul Plassmann, with Mark Jones, worked on parallel optimisation-based smoothing in the mid 1990s, and Freitag and Ollivier-Gooch combined it with face and edge swaps for tetrahedra. Amenta, Bern and Eppstein studied the problem as an LP-type problem in 1999. Freitag and Plassmann's paper of 2000 gave the active set method described here, the proof that the level sets of the common quality measures are convex, and untangling by linear programming. The method is in the Mesquite library and in many mesh generators.

References

  1. Lori A. Freitag and Paul Plassmann, Local optimization-based simplicial mesh untangling and improvement, International Journal for Numerical Methods in Engineering 49(1-2), 2000, 109 to 125, the max-min formulation, the convexity of the level sets of the quality measures, the active set and the search direction of least norm, and the line search (general locator)
  2. Pascal Jean Frey and Paul-Louis George, Mesh Generation, Application to Finite Elements, 2nd edition, ISTE and Wiley, 2008, chapter 18 (mesh optimisation, including point relocation)

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.per-vertex
  • 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