Algorithm Search⌘K

Algorithmresearch

Mixed-integer quadrangulation

Also called MIQ.

Bommes, Zimmer and Kobbelt's quad remeshing that aligns a parameterization with a smooth cross field and rounds its singularities and seams to integers.

Time
O(k n^3) greedy_denseO(k n^(3/2)) greedy_nested_dissection
Space
O(n^2) extraO(n log n) nested_dissection
Where
k = the number of integer variables; n = the number of vertices
Properties
deterministicnot exactiterative
Origin
David Bommes, Henrik Zimmer, Leif Kobbelt, 2009

Mixed-integer quadrangulation, MIQ, turns a triangle mesh into a mesh of quadrilaterals whose edges follow the principal directions and feature lines of the shape. It works in three stages. It computes a smooth cross field, four directions at right angles on each triangle, aligned with the curvature and the features. It computes a global parameterization (u,v)(u, v) whose gradients follow the cross field, with a scale hh for the edge length. And it reads the quads off the integer iso-lines u∈Zu \in \mathbb{Z} and v∈Zv \in \mathbb{Z}. The iso-lines only close up into a quad mesh if the singular vertices of the field map to integer points and the seams of the cut mesh are crossed by integer jumps. These are integer constraints on a quadratic energy, a mixed-integer problem. MIQ solves it with greedy rounding: round one integer variable at a time, the one closest to an integer, and solve the rest again. This page explains the full method and gives code only for the rounding step on a toy grid, where it can be checked exactly; the cross field, the seams and the extraction are not in the code.

In plain words

To cover a curved shape with square tiles, first draw on it at every point the two directions the tiles should follow. Then give every point two numbers, like the street and avenue numbers of a city grid, so that the numbers grow along those directions at a steady rate.

The tile edges are where a number is a whole number. For the tiles to fit, some special points must sit exactly on whole numbers, and where the grid is cut open to lie flat, the numbers on the two sides must differ by whole numbers.

Asking for whole numbers makes the problem much harder. The method first finds the best answer with any numbers. Then it fixes one number at a time to the nearest whole number, picking the one that is closest already, and improves the rest.

The problem

The input is a triangle mesh with faces oriented so that the outward normal follows the right-hand rule, a target edge length hh, and optionally feature curves. The output is a mesh of quadrilaterals, with a few vertices of valence other than 4, whose edges are about hh long and follow the principal curvature directions and the features. In the parameterization stage the task is: find (u,v)(u, v) on a cut of the mesh into a disk that minimizes

E(u,v)=∑TAT(∥h∇uT−dT∥2+∥h∇vT−dT⊥∥2),E(u, v) = \sum_T A_T \left( \lVert h \nabla u_T - \mathbf{d}_T \rVert^2 + \lVert h \nabla v_T - \mathbf{d}_T^{\perp} \rVert^2 \right),

where dT\mathbf{d}_T is a direction of the cross field on TT, subject to: the values on the two sides of a seam differ by a rotation by a multiple of 90°90° and a translation by an integer vector; each singular vertex maps to an integer point; and each feature curve lies on an integer iso-line.

The algorithm

The full method:

  1. Cross field. Choose on each triangle an angle θT\theta_T, with integer period jumps pijp_{ij} across each edge, which say how many quarter turns the cross turns between two triangles. Minimize the smoothness energy ∑ij(θi+κij+π2pij−θj)2\sum_{ij} (\theta_i + \kappa_{ij} + \tfrac{\pi}{2} p_{ij} - \theta_j)^2, where κij\kappa_{ij} is the angle between the two triangle frames, with θ\theta fixed on feature edges. Most pijp_{ij} are set to 0 on a spanning tree of the dual graph; the rest are integers found by greedy rounding.
  2. Cut graph. Cut the mesh along a tree of edges through all singular vertices, so that it becomes a disk.
  3. Parameterization. Minimize E(u,v)E(u, v) with the integer constraints, again by greedy rounding. A stiffening loop raises the weight of triangles that come out distorted or flipped and solves again.
  4. Extraction. Trace the integer iso-lines of (u,v)(u, v) over the triangles and across the seams, and build the quad mesh from their crossings.

The rounding solver for "minimize a convex quadratic E(x)E(x) where the variables in II must be integers", which steps 1 and 3 share:

  1. GREEDY-ROUND(E, I, pins)
  2. 1x ← the minimizer of E with the pins held ▷ the relaxed problem
  3. 2while some variable of I is not fixed do
  4. 3k ← the unfixed variable of I with x_k closest to an integer
  5. 4fix x_k ← round(x_k)
  6. 5x ← the minimizer of E with all fixed variables held
  7. 6return x

The code of this page is a toy for this solver. It takes one coordinate uu on a grid of vertices with columns at positions xix_i. Each edge asks for ub−ua=tabu_b - u_a = t_{ab}, with tt equal to hh times the step in xx plus a small change per edge, a guiding field that is not quite integrable. Each feature column must lie on one integer iso-line u=ku = k, so the column is one integer variable. The energy is ∑(ub−ua−tab)2\sum (u_b - u_a - t_{ab})^2, a finite difference version of EE. All arithmetic is exact. The toy has no cross field, no seam and no singularity.

Degenerate cases. Ties in L3 are broken by the smallest index. If the term graph is connected and at least one variable is pinned, every solve in L1 and L5 has a unique solution, see the proof; without a pin the energy is unchanged by adding a constant, and the system is singular. In the full method, a period jump or a seam translation that is rounded wrongly can force fold-overs that no later step removes.

Example

Take a grid of 3 columns at x=0,2,7/2x = 0, 2, 7/2 and 2 rows, with h=9/5h = 9/5 and no change to the targets, so each horizontal edge asks for hh times its length: t=18/5t = 18/5 and 27/1027/10. All three columns are features, and the column at x=0x = 0 is pinned to u=0u = 0. With aa and bb the values of the other two columns, E(a,b)=2(a−18/5)2+2(b−a−27/10)2E(a, b) = 2(a - 18/5)^2 + 2(b - a - 27/10)^2.

step value
L1 a=18/5=3.6a = 18/5 = 3.6, b=63/10=6.3b = 63/10 = 6.3, E=0E = 0
L3 bb is 3/103/10 from 6, aa is 2/52/5 from 4, so bb is first
L4 to L5 b=6b = 6, then a=69/20=3.45a = 69/20 = 3.45
L3 to L5 a=3a = 3
L6 (a,b)=(3,6)(a, b) = (3, 6), E=9/10E = 9/10
round all at once (4,6)(4, 6), E=13/10E = 13/10
best integer point (4,7)(4, 7), E=1/2E = 1/2

Greedy rounding is better than rounding everything at once, but it misses the optimum. Fixing b=6b = 6 first pulled aa down below 3.53.5, and the choice could not be undone. On 40 random toy grids with up to 3 integer variables, greedy rounding matched the best integer point in a box around the relaxed solution in 35 cases and was better than rounding all at once in 9. These numbers are measurements on the tests of the page, not theorems.

When the arithmetic is floating point. The toy is exact, so the choice in L3 is exact. With floats, two variables at nearly the same distance from an integer can be ordered either way by rounding errors in the solve, and a value near k+1/2k + 1/2 can round to either side; both change the result, not only its accuracy. The full method has a second problem: the iso-lines are traced in floating point, and whether an integer line crosses a triangle, or which side of a seam a crossing lies on, is a sign test of the kind of the orientation test. Near a vertex of the parameterization these signs come from catastrophic cancellation, and extraction code has to make consistent decisions, for example with exact predicates on the (u,v)(u, v) values, to avoid holes in the quad mesh. This is the robustness problem of geometry.

Correctness

On the toy, the energy with at least one fixed variable has a positive definite matrix, because the term graph is connected, so every solve has one exact solution. Each round fixes one more integer variable and never changes a fixed one, so the loop stops after as many rounds as there are integer variables, with every one of them an integer. The relaxed energy is a lower bound and every rounded solution an upper bound on the best integer energy. If the relaxed solution is already integral, greedy rounding returns it. The example shows that greedy rounding is not optimal. The full proof is below. For the full method there is no guarantee: the result can have fold-overs, which makes the extracted quad mesh invalid in those regions.

Proof: Greedy rounding on the toy grid stops with a feasible integer solution whose energy lies between the relaxed and the rounded energies, and it can miss the optimumfull

This proof is about the rounding step of MIQ on the toy problem of the page, not about the full method with a cross field, seams and singularities.

Setting. There are variables x0,…,xn−1x_0, \ldots, x_{n-1} and terms (a,b,t)(a, b, t) with a≠ba \ne b and tt rational. The energy is E(x)=∑(xb−xa−t)2E(x) = \sum (x_b - x_a - t)^2. The term graph has the variables as nodes and an edge for each term; it is connected. A set PP of variables is pinned to integers, with P≠∅P \ne \emptyset, and a set I⊇PI \supseteq P of variables must be integers. The greedy rounding of the page is: solve the relaxed problem with PP fixed; then, while some variable of II is not fixed, fix the one whose current value is closest to an integer at that integer and solve again with all fixed variables held.

Claim.

  1. For any set S⊇PS \supseteq P of fixed variables with any fixed values, the energy has a unique minimizer over the other variables, and the code computes it exactly.
  2. Greedy rounding stops after ∣I∖P∣|I \setminus P| rounds, and the result xgx^g has xkg∈Zx^g_k \in \mathbb{Z} for every k∈Ik \in I and xkgx^g_k equal to the pin for every k∈Pk \in P.
  3. Let xrx^r be the relaxed minimizer, x∗x^* a minimizer of EE with the integer constraints, and xdx^d the result of rounding all of II at once. Then E(xr)≤E(x∗)≤E(xg)E(x^r) \le E(x^*) \le E(x^g) and E(x∗)≤E(xd)E(x^*) \le E(x^d).
  4. If xkrx^r_k is an integer for every k∈Ik \in I, then xg=xrx^g = x^r and greedy rounding is optimal.
  5. Greedy rounding is not optimal in general: the example of the page has E(xg)=9/10>1/2=E(x∗)E(x^g) = 9/10 > 1/2 = E(x^*).

Step 1 (part 1). With the variables in SS held, EE is y⊤Ly−2c⊤y+consty^\top L y - 2 c^\top y + \text{const} in the free variables yy, where LL is the submatrix, on the free rows and columns, of the Laplacian of the term graph (an edge counted once per term). So y⊤Ly=∑(yb−ya)2y^\top L y = \sum (y_b - y_a)^2 over the terms, with ya=0y_a = 0 for a fixed aa. If y⊤Ly=0y^\top L y = 0, every term has yb=yay_b = y_a, so yy is constant on each connected component of the term graph, which is the whole graph, and it is 0 at a fixed variable because S≠∅S \ne \emptyset. So y=0y = 0, LL is positive definite, and the minimizer is the unique solution of Ly=cL y = c. The entries are rational and Gaussian elimination in exact rational arithmetic returns that solution exactly, with no zero pivot since LL is nonsingular.

Step 2 (part 2). Each round fixes one variable of II that was not fixed, and no round unfixes one, so after ∣I∖P∣|I \setminus P| rounds the loop stops. A fixed variable keeps its value in every later solve, because the solve of Step 1 changes only the free variables. Each variable of I∖PI \setminus P is fixed at an integer, and each variable of PP is never changed from its pin.

Step 3 (part 3). xrx^r minimizes EE over the set {x:xP=pins}\{x : x_P = \text{pins}\}, which contains every point that also has integer values on II, so E(xr)≤E(x∗)E(x^r) \le E(x^*). xgx^g and xdx^d are such points by part 2 (the same argument applies to xdx^d, which fixes all of II at integers and solves once), so E(x∗)≤E(xg)E(x^*) \le E(x^g) and E(x∗)≤E(xd)E(x^*) \le E(x^d).

Step 4 (part 4). If xrx^r is integer on II, the first round fixes a variable at its current value. The minimizer with that value held is still xrx^r, because xrx^r is the minimizer over a larger set and it satisfies the new constraint. By induction every round keeps xrx^r, so xg=xrx^g = x^r, and E(xg)=E(xr)≤E(x∗)E(x^g) = E(x^r) \le E(x^*) gives optimality.

Step 5 (part 5). In the example, E(a,b)=2(a−18/5)2+2(b−a−27/10)2E(a, b) = 2(a - 18/5)^2 + 2(b - a - 27/10)^2 with a,ba, b integers. The relaxed solution is (18/5,63/10)(18/5, 63/10), whose distances to the nearest integers are 2/52/5 and 3/103/10, so bb is rounded first to 6. Then a=(18/5+33/10)/2=69/20a = (18/5 + 33/10)/2 = 69/20 minimizes (a−18/5)2+(6−a−27/10)2(a - 18/5)^2 + (6 - a - 27/10)^2, and aa is rounded to 3. So E(xg)=2(9/25+9/100)=9/10E(x^g) = 2(9/25 + 9/100) = 9/10. The point (4,7)(4, 7) gives 2(4/25+9/100)=1/22(4/25 + 9/100) = 1/2. ■\blacksquare

What is not proved. Greedy rounding has no bound on E(xg)/E(x∗)E(x^g) / E(x^*), and how often it is optimal is only measured: on the 40 random grids of the tests it matched the best integer point in a box around xrx^r in 35 cases. Minimizing a positive definite quadratic over integer points is the closest vector problem of lattices, which is NP-hard in general, so no fast exact method is expected.

Complexity

The relaxed problem is a sparse positive definite system with O(n)O(n) unknowns. Greedy rounding solves it once per integer variable, kk times. With dense elimination, as in the code of this page, that is O(kn3)O(k n^3) time; with a sparse factorization and nested dissection, O(kn3/2)O(k n^{3/2}). The integer variables are the singular vertices, the seam translations and the feature lines, so kk is much smaller than nn, but kk global solves can still be slow on big meshes. To save time, MIQ updates the solution after a rounding by local Gauss-Seidel sweeps near the rounded variable and uses a full solve when the local update is not enough; the code of this page does not do this and solves the whole system each time, so the page gives no measured speed-up. Exact optimization is hopeless in general: minimizing a positive definite quadratic over integer points is the closest vector problem, which is NP-hard.

Properties

  • Heuristic. Greedy rounding gives a feasible integer solution but no bound on how far it is from the optimum.
  • Aligned. The quads follow the cross field, so they follow curvature and features.
  • Global. One parameterization covers the whole surface, with singularities where the cross field needs them.
  • Not guaranteed valid. Fold-overs in the parameterization give degenerate or missing quads.
  • Deterministic. The rounding order is fixed by the values and the tie rule.

Variants and improvements

  • Rounding all at once. Faster, but worse: in the example it gives 13/1013/10 against 9/109/10.
  • Exact mixed-integer solvers. Branch and bound on the integer variables gives the optimum for small problems, see mixed-integer programming. It is too slow for meshes with hundreds of singularities.
  • Integer-grid maps (Bommes and coauthors 2013). State the conditions under which a parameterization defines a valid quad mesh and add convex constraints that prevent fold-overs, which makes the result reliable at a higher cost.
  • QuadCover (Kälberer, Nieser and Polthier 2007). An earlier global method for the same problem, with a cross field and integer constraints, that first makes the field integrable.
  • Field and parameterization in one. Later methods change the cross field during rounding, or simplify the layout of singularities, so that fewer integer constraints conflict.

When to use it

Use it to turn a scanned or triangulated model into a quad mesh for subdivision surfaces, spline fitting or animation, where edge flow along curvature and features matters. Check the result for flipped parameter triangles and repair or re-run with stiffening, or use an integer-grid map method if validity must be guaranteed. For a quick uniform triangle mesh, isotropic remeshing is simpler.

Pitfalls

  • Greedy is not optimal. The order of rounding matters, and an early choice cannot be undone. The example shows a gap of almost a factor of 2.
  • Fold-overs. The energy does not forbid flipped triangles in (u,v)(u, v); then the iso-lines cross in a tangle and the extraction fails there.
  • Scale hh too large. If hh is large compared to the distance between singularities, rounding puts two singularities on the same integer point, which collapses quads.
  • Feature conflicts. Two feature lines that must lie on integer iso-lines at a distance that is not an integer multiple of hh force distortion between them.
  • Seams in floats. Tracing iso-lines across seams needs consistent decisions on both sides, or the quad mesh gets holes.

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.

mixed_integer_quadrangulation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixed-integer-quadrangulation/. The authors are listed in prov/SKTZEV.jsonl.

"""The rounding step of mixed-integer quadrangulation, on a toy grid.

This is a toy, not MIQ. There is no cross field, no singularity and no seam.
What it keeps is the mixed-integer problem that MIQ solves: a convex
quadratic energy in the parameter values, some of which must be integers,
solved by greedy rounding (Bommes, Zimmer and Kobbelt 2009).

The toy is one coordinate u of a parameterization of a grid of vertices
(i, j). Each edge (a, b) asks for u_b - u_a = t_ab, where the targets t come
from a guiding field (h times the x step, with a small change per edge).
Every vertex of a feature column must lie on one integer iso-line u = k, so
the whole column is one integer variable. Vertex (0, 0) is pinned to 0.

    E(u) = sum over edges (u_b - u_a - t_ab)^2

All arithmetic is exact (Fraction).
"""

import itertools
from fractions import Fraction

from mp3geom import solve


def round_half_up(x):
    return (Fraction(x) + Fraction(1, 2)).__floor__()


def toy_grid(xs, ny, h, features, bend=None):
    """Variables and energy terms of the toy grid.

    xs: the x coordinates of the columns, ny: the number of rows minus 1,
    h: the target number of grid lines per unit length, features: the indices
    of the feature columns, bend: optional {edge: change of target}.
    Returns (number of variables, terms [(a, b, t)], integer variables, pinned {var: value}).
    """
    var = {}
    nxt = 0
    for i in range(len(xs)):
        if i in features:
            for j in range(ny + 1):
                var[(i, j)] = nxt
            nxt += 1
        else:
            for j in range(ny + 1):
                var[(i, j)] = nxt
                nxt += 1
    bend = bend or {}
    terms = []
    for i in range(len(xs)):
        for j in range(ny + 1):
            if i + 1 < len(xs):
                e = ((i, j), (i + 1, j))
                terms.append((var[e[0]], var[e[1]], h * (xs[i + 1] - xs[i]) + bend.get(e, 0)))
            if j + 1 <= ny:
                e = ((i, j), (i, j + 1))
                terms.append((var[e[0]], var[e[1]], bend.get(e, 0)))
    integer = sorted({var[(i, 0)] for i in features})
    pinned = {var[(0, 0)]: 0}
    return nxt, terms, integer, pinned


def energy(terms, x):
    return sum((x[b] - x[a] - t) ** 2 for a, b, t in terms if a != b)


def minimize(n, terms, fixed):
    """The continuous minimizer of the energy with the fixed variables held. Exact."""
    free = [k for k in range(n) if k not in fixed]
    col = {k: c for c, k in enumerate(free)}
    m = len(free)
    a = [[Fraction(0)] * m for _ in range(m)]
    r = [[Fraction(0)] for _ in range(m)]
    for p, q, t in terms:
        if p == q:
            continue
        # gradient of (x_q - x_p - t)^2 / 2: +(x_q - x_p - t) for q, -(...) for p
        for v, s in ((q, 1), (p, -1)):
            if v not in col:
                continue
            for w, s2 in ((q, 1), (p, -1)):
                if w in col:
                    a[col[v]][col[w]] += s * s2
                else:
                    r[col[v]][0] -= s * s2 * fixed[w]
            r[col[v]][0] += s * t
    sol = solve(a, r) if m else []
    x = dict(fixed)
    for k in free:
        x[k] = sol[col[k]][0]
    return [Fraction(x[k]) for k in range(n)]


def greedy_rounding(n, terms, integer, pinned):
    """Bommes, Zimmer and Kobbelt's greedy rounding. Returns (x, order of rounding)."""
    fixed = dict(pinned)
    order = []
    todo = [k for k in integer if k not in fixed]
    x = minimize(n, terms, fixed)  # @line L1
    while todo:  # @line L2
        k = min(todo, key=lambda v: (abs(x[v] - round_half_up(x[v])), v))  # @line L3
        fixed[k] = Fraction(round_half_up(x[k]))  # @line L4
        order.append(k)
        todo.remove(k)
        x = minimize(n, terms, fixed)  # @line L5
    return x, order  # @line L6


def direct_rounding(n, terms, integer, pinned):
    """Round all integer variables of the relaxed solution at once, then re-solve the rest."""
    x = minimize(n, terms, dict(pinned))
    fixed = dict(pinned)
    for k in integer:
        if k not in fixed:
            fixed[k] = Fraction(round_half_up(x[k]))
    return minimize(n, terms, fixed)


def brute_force(n, terms, integer, pinned, radius=2):
    """The best integer assignment in a box of the given radius around the relaxed solution."""
    x = minimize(n, terms, dict(pinned))
    todo = [k for k in integer if k not in pinned]
    best = None
    for combo in itertools.product(*[range(round_half_up(x[k]) - radius, round_half_up(x[k]) + radius + 1) for k in todo]):
        fixed = dict(pinned)
        fixed.update(zip(todo, (Fraction(c) for c in combo)))
        y = minimize(n, terms, fixed)
        e = energy(terms, y)
        if best is None or e < best[0]:
            best = (e, y)
    return best[1]
mp3geom.py 136 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mp3 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small tools for triangle meshes, used by the mp3 pages.

Points are tuples of int, fractions.Fraction or float. The predicates are
exact when the coordinates are int or Fraction. A mesh is a list of faces,
each a tuple of three vertex indices, oriented so that the outward normal
follows the right-hand rule (counterclockwise seen from outside).
"""

from fractions import Fraction


def sub(a, b):
    return tuple(x - y for x, y in zip(a, b))


def add(a, b):
    return tuple(x + y for x, y in zip(a, b))


def scale(s, a):
    return tuple(s * x for x in a)


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def orient2d(a, b, c):
    """Twice the signed area of triangle abc: > 0 if counterclockwise."""
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def orient3d(a, b, c, d):
    """((b - a) x (c - a)) . (d - a): > 0 if d is on the side of the normal of abc."""
    return dot(cross(sub(b, a), sub(c, a)), sub(d, a))


def sign(x):
    return (x > 0) - (x < 0)


def solve(a, b, tol=0.0):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a list of n rows of length n, b is a list of n rows of length m
    (m right-hand sides). Entries are Fraction (exact) or float. Returns the
    n rows of x. Raises ValueError if a pivot has absolute value <= tol, so
    an exact singular matrix always raises when tol is 0.
    """
    n = len(a)
    m = len(b[0]) if n else 0
    rows = [list(a[i]) + list(b[i]) for i in range(n)]
    for col in range(n):
        piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
        if abs(rows[piv][col]) <= tol:
            raise ValueError("singular matrix")
        rows[col], rows[piv] = rows[piv], rows[col]
        pr = rows[col]
        inv = 1 / pr[col] if isinstance(pr[col], float) else Fraction(1) / pr[col]
        for r in range(col + 1, n):
            f = rows[r][col]
            if f:
                f = f * inv
                row = rows[r]
                for k in range(col, n + m):
                    if pr[k]:
                        row[k] -= f * pr[k]
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        row = rows[i]
        for k in range(m):
            s = row[n + k]
            for j in range(i + 1, n):
                if row[j]:
                    s -= row[j] * x[j][k]
            x[i][k] = s / row[i] if isinstance(s, float) or isinstance(row[i], float) else Fraction(s) / row[i]
    return x


def directed_edges(faces):
    """Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
    out = {}
    for f, tri in enumerate(faces):
        for k in range(3):
            e = (tri[k], tri[(k + 1) % 3])
            if e in out:
                raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
            out[e] = (f, k)
    return out


def neighbours(faces):
    """Map each vertex to the set of its neighbours."""
    nb = {}
    for tri in faces:
        for k in range(3):
            i, j = tri[k], tri[(k + 1) % 3]
            nb.setdefault(i, set()).add(j)
            nb.setdefault(j, set()).add(i)
    return nb


def boundary_loop(faces):
    """The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
    de = directed_edges(faces)
    nxt = {}
    for i, j in de:
        if (j, i) not in de:
            if i in nxt:
                raise ValueError("boundary vertex %r is not manifold" % (i,))
            nxt[i] = j
    if not nxt:
        raise ValueError("the mesh has no boundary")
    start = min(nxt)
    loop = [start]
    while True:
        v = nxt[loop[-1]]
        if v == start:
            break
        loop.append(v)
    if len(loop) != len(nxt):
        raise ValueError("the boundary has more than one loop")
    return loop


def euler_characteristic(faces):
    verts = {v for tri in faces for v in tri}
    edges = {frozenset((tri[k], tri[(k + 1) % 3])) for tri in faces for k in range(3)}
    return len(verts) - len(edges) + len(faces)
test_mixed_integer_quadrangulation.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mixed-integer-quadrangulation/. The authors are listed in prov/SKTZEV.jsonl.

import random
from fractions import Fraction

from mixed_integer_quadrangulation import (
    brute_force,
    direct_rounding,
    energy,
    greedy_rounding,
    minimize,
    toy_grid,
)


def random_instance(rng):
    ncol = rng.randint(3, 5)
    ny = rng.randint(1, 2)
    xs = [Fraction(0)]
    for _ in range(ncol - 1):
        xs.append(xs[-1] + Fraction(rng.randint(2, 9), 4))
    h = Fraction(rng.randint(3, 9), 5)
    features = set(rng.sample(range(1, ncol), rng.randint(1, min(3, ncol - 1))))
    bend = {}
    for i in range(ncol):
        for j in range(ny + 1):
            for e in (((i, j), (i + 1, j)), ((i, j), (i, j + 1))):
                bend[e] = Fraction(rng.randint(-3, 3), 10)
    return toy_grid(xs, ny, h, features, bend)


def test_example_of_the_page() -> None:
    xs = [Fraction(0), Fraction(2), Fraction(7, 2)]
    n, terms, integer, pinned = toy_grid(xs, 1, Fraction(9, 5), {0, 1, 2})
    assert n == 3 and integer == [0, 1, 2] and pinned == {0: 0}
    relaxed = minimize(n, terms, pinned)
    assert relaxed == [0, Fraction(18, 5), Fraction(63, 10)]
    assert energy(terms, relaxed) == 0
    g, order = greedy_rounding(n, terms, integer, pinned)
    assert order == [2, 1]
    assert g == [0, 3, 6]
    assert energy(terms, g) == Fraction(9, 10)
    d = direct_rounding(n, terms, integer, pinned)
    assert d == [0, 4, 6]
    assert energy(terms, d) == Fraction(13, 10)
    b = brute_force(n, terms, integer, pinned)
    assert b == [0, 4, 7]
    assert energy(terms, b) == Fraction(1, 2)


def test_rounding_bounds_on_random_grids() -> None:
    rng = random.Random(2009)
    greedy_worse = greedy_better_than_direct = 0
    for _ in range(40):
        n, terms, integer, pinned = random_instance(rng)
        relaxed = minimize(n, terms, pinned)
        g, order = greedy_rounding(n, terms, integer, pinned)
        d = direct_rounding(n, terms, integer, pinned)
        b = brute_force(n, terms, integer, pinned)
        e0, eg, ed, eb = (energy(terms, x) for x in (relaxed, g, d, b))
        assert sorted(order) == [k for k in integer if k not in pinned]
        for x in (g, d, b):
            assert all(x[k].denominator == 1 for k in integer)
            assert all(x[k] == v for k, v in pinned.items())
        assert e0 <= eb <= eg and eb <= ed
        greedy_worse += eg > eb
        greedy_better_than_direct += eg < ed
    # Measured: both effects occur on these seeds; neither is a theorem.
    assert greedy_worse > 0 and greedy_better_than_direct > 0


def test_relaxed_solution_is_a_minimum() -> None:
    rng = random.Random(7)
    for _ in range(10):
        n, terms, integer, pinned = random_instance(rng)
        x = minimize(n, terms, pinned)
        e = energy(terms, x)
        for k in range(n):
            if k in pinned:
                continue
            for d in (Fraction(1, 7), Fraction(-1, 7)):
                y = list(x)
                y[k] += d
                assert energy(terms, y) > e


def test_integer_targets_give_zero_energy() -> None:
    xs = [Fraction(k) for k in range(5)]
    n, terms, integer, pinned = toy_grid(xs, 2, Fraction(2), {1, 2, 3, 4})
    g, _ = greedy_rounding(n, terms, integer, pinned)
    assert energy(terms, g) == 0
    assert [g[k] for k in integer] == [2, 4, 6, 8]

History

Felix Kälberer, Matthias Nieser and Konrad Polthier gave QuadCover in 2007, a global parameterization method for quad meshing based on a cross field. David Bommes, Henrik Zimmer and Leif Kobbelt presented mixed-integer quadrangulation at SIGGRAPH 2009. Their key step was to treat the period jumps of the cross field and the integer constraints of the parameterization as variables of one mixed-integer problem each, solved by greedy rounding, with feature alignment and an adaptive scale. In 2013 Bommes, Campen, Ebke, Alliez and Kobbelt gave integer-grid maps, which state when a parameterization gives a valid quad mesh and how to enforce it. MIQ is a standard reference method for quad remeshing.

References

  1. David Bommes, Henrik Zimmer and Leif Kobbelt, Mixed-integer quadrangulation, ACM Transactions on Graphics 28(3), 2009, Article 77, the cross field with integer period jumps, the global parameterization with integer transition functions and integer singularities, and the greedy rounding solver
  2. David Bommes, Marcel Campen, Hans-Christian Ebke, Pierre Alliez and Leif Kobbelt, Integer-grid maps for reliable quad meshing, ACM Transactions on Graphics 32(4), 2013, Article 98, the conditions under which a parameterization defines a valid quad mesh, and the constraints that prevent fold-overs
  3. David Bommes, Bruno Lévy, Nico Pietroni, Enrico Puppo, Claudio Silva, Marco Tarini and Denis Zorin, Quad-mesh generation and processing, a survey, Computer Graphics Forum 32(6), 2013, 51 to 76, the section on parameterization-based quad meshing and its integer constraints

Where this leads

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.greedy_dense
  • a full proof of time.greedy_nested_dissection
  • a full proof of space.extra
  • a full proof of space.nested_dissection
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