Algorithm Search⌘K

Algorithmresearch

Blossom-Quad

Also called blossom quad meshing.

Remacle and coauthors' indirect quad mesher that pairs triangles into quads by a minimum cost perfect matching found with Edmonds' blossom algorithm.

Time
O(n^3) worst
Space
O(n) extra
Where
n = the number of triangles
Properties
deterministicexactrecursive
Origin
Jean François Remacle, Jonathan Lambrechts, Bruno Seny, Emilie Marchandise, Amaury Johnen, Christophe Geuzaine, 2012

Blossom-Quad is a method that turns a triangle mesh into a quad mesh by pairing every triangle with a neighbour. Two triangles that share an edge make a quad when the shared edge is removed. A good pairing uses each triangle exactly once and makes quads that are close to rectangles. Blossom-Quad states this as a graph problem: the triangles are the nodes of the dual graph, each pair that makes a convex quad is an edge with a cost that measures how bad the quad is, and the best pairing is a minimum cost perfect matching. Edmonds' blossom algorithm finds that matching exactly in polynomial time. Jean-François Remacle and his coauthors published the method in 2012. It finds the best pairing for the given triangles, but a perfect matching need not exist, and the method gives no bound on the worst quad.

In plain words

You have a floor covered with triangular tiles and you want four sided tiles. Two triangles that touch along a side can be glued into one four sided tile. You must glue every triangle to exactly one neighbour, and you want the glued tiles to look as much like rectangles as possible.

If you glue the best looking pair first, then the next best, and so on, you can end up with lonely triangles that have no free neighbour left. So instead, give every possible pair a score and ask a classic method from graph theory for the set of pairs that uses every triangle once and has the best total score. That method, the blossom method, never gets stuck where the greedy choice does.

The problem

The input is a conforming triangle mesh with an even number of triangles. The output is a conforming quad mesh of the same region with the same vertices, in which every quad is the union of two triangles that share an edge and is strictly convex, and the sum of the costs of the quads is as small as possible; or a report that no such quad mesh exists.

The algorithm

The cost of a quad here is 1−η1 - \eta, with the angle quality η=max⁡(0,1−2πmax⁡k∣π2−αk∣)\eta = \max(0, 1 - \tfrac{2}{\pi} \max_k |\tfrac{\pi}{2} - \alpha_k|) over the four corner angles αk\alpha_k, so a rectangle has cost 0. The cost is scaled by 10610^6 and rounded to an integer, so the matching is exact for the rounded costs. This measure and the scale are parameters of this code; the paper defines its own quality of a quad.

  1. BLOSSOM-QUAD(T)
  2. 1if the number of triangles is odd then fail
  3. 2build the dual graph: one node per triangle
  4. 3for each pair of triangles that share an edge and form a strictly convex quad, add a dual edge with the cost of that quad
  5. 4M ← a minimum cost perfect matching of the dual graph, by Edmonds' weighted blossom algorithm
  6. 5if the dual graph has no perfect matching then fail
  7. 6for each pair in M, remove the shared edge and make the quad
  8. 7return the quads

L4 runs the weighted blossom algorithm in Galil's O(n3)O(n^3) primal-dual form as a maximum weight matching, with the weight K+C−cK + C - c for the cost cc, where CC is larger than every cost and K=nCK = nC. With this KK, a larger matching always weighs more, so the maximum weight matching is perfect when a perfect matching exists, and among the perfect matchings it has the least cost. The weights are integers, so all dual values stay integers and every test is exact. The convexity test in L3 uses exact orientation tests.

Example

Take the centre o=(0,0)o = (0, 0) and the six points p1=(2,0)p_1 = (2, 0), p2=(1,2)p_2 = (1, 2), p3=(−1,2)p_3 = (-1, 2), p4=(−2,0)p_4 = (-2, 0), p5=(−1,−2)p_5 = (-1, -2) and p6=(1,−2)p_6 = (1, -2), with the six triangles opsps+1o p_s p_{s+1} around oo. Neighbouring triangles share an edge opso p_s, so the dual graph is a cycle of six nodes. Removing the edge op1o p_1 or op4o p_4 gives a quad with an angle of 126.9°126.9° at oo and quality 0.5900.590; removing op2o p_2, op3o p_3, op5o p_5 or op6o p_6 gives a quad whose worst angle is 116.6°116.6°, with quality 0.7050.705.

A cycle of six nodes has two perfect matchings: remove the edges at p1,p3,p5p_1, p_3, p_5, or the edges at p2,p4,p6p_2, p_4, p_6. Each has qualities 0.5900.590, 0.7050.705 and 0.7050.705, a total cost of 1.0001.000. The greedy choice fails here: it takes a pair of quality 0.7050.705 first, say the one across op2o p_2, then the next free pair of quality 0.7050.705, the one across op5o p_5, and the two triangles left over, op3p4o p_3 p_4 and op6p1o p_6 p_1, are not neighbours. The blossom algorithm returns a perfect matching.

Move p1p_1 to (3,0)(3, 0). The pairs across op2o p_2 and op6o p_6 now have quality 0.50.5. The matching at p1,p3,p5p_1, p_3, p_5 costs 1.0001.000 and the one at p2,p4,p6p_2, p_4, p_6 costs 1.4101.410, and the blossom algorithm returns the first.

Correctness

The proof file shows that the merges of a triangle mesh into strictly convex quads are exactly the perfect matchings of the convex dual graph. A matched pair loses only its shared edge, every other directed edge stays and is used once, and no vertex moves, so the quads form a conforming mesh of the same region with the same boundary. The parity rule follows from counting edge sides: 4Q=2Eint+Ebnd4Q = 2E_\text{int} + E_\text{bnd}, so a quad mesh has an even number of boundary edges, and a triangle mesh with an odd number of boundary edges has an odd number of triangles.

The reduction from the minimum cost perfect matching to the maximum weight matching is proved. The optimality of Edmonds' algorithm is the classical primal-dual theorem; the proof file outlines it, and the tests compare the code with a brute force over all matchings, on random graphs and on triangle meshes of at most 12 triangles.

Not proved, because it is false: that a perfect matching always exists. A triangle with one ear on each of its sides has four triangles, but its dual graph is a star, and two ears can never be paired. Also not proved: any bound on the worst quad, since the matching minimises the sum of the costs.

Proof: A perfect matching of the convex dual graph gives a conforming quad mesh, and the minimum cost perfect matching is found exactlyfull

What is proved and what is not. Four results are proved here: the parity rule for quad meshes, the fact that a perfect matching of the dual graph gives a conforming quad mesh of the same region (and every quad mesh made by merging pairs comes from one), the reduction from minimum cost perfect matching to maximum weight matching of the largest size, and the termination of the code. The optimality of Edmonds' weighted blossom algorithm itself is a classical theorem; it is stated with an outline of its primal-dual proof, and the tests check it against a brute force over all matchings. Not proved, because it is false in general: that a perfect matching always exists, and any bound on the quality of the quads.

Setting. TT is a conforming triangle mesh: counterclockwise triangles with exact coordinates, no directed edge used twice, and no vertex inside an edge. The convex dual graph GG has one node per triangle and one edge for each pair of triangles (u,v,k)(u, v, k) and (v,u,l)(v, u, l) that share the edge uvuv and whose union, the quad (u,l,v,k)(u, l, v, k), is strictly convex. Its cost is an integer c≥0c \ge 0.

Theorem 1 (parity). In a mesh of a planar region by QQ quads, in which every edge lies in one quad (a boundary edge) or two quads (an interior edge), the number EbE_b of boundary edges is even.

Proof. Count pairs (quad, edge of that quad), the edge sides. Each quad has 4 edges, so there are 4Q4Q pairs. Each interior edge is in two pairs and each boundary edge in one, so 4Q=2Ei+Eb4Q = 2E_i + E_b. Then Eb=4Q−2EiE_b = 4Q - 2E_i is even. □\square

The same count for the triangles gives 3∣T∣=2Ei′+Eb3|T| = 2E_i' + E_b. A merge does not change the boundary, so a triangle mesh with an odd number of boundary edges has an odd number of triangles, and it cannot be merged into quads. In general, ∣T∣|T| must be even (L1).

Theorem 2 (a perfect matching is a quad mesh). Let MM be a perfect matching of GG. Replace each matched pair by its quad. The result is a conforming mesh of the same region by ∣T∣/2|T|/2 strictly convex counterclockwise quads, with the same vertices and the same boundary edges. Conversely, every set of quads that partitions TT into pairs of neighbours with strictly convex unions is a perfect matching of GG.

Proof. Each triangle is in exactly one pair, so the quads number ∣T∣/2|T|/2, and each quad is the union of its two triangles, so the quads cover the same region with disjoint interiors and the same total area. A quad (u,l,v,k)(u, l, v, k) is strictly convex by the definition of GG, and it is counterclockwise because kk is left of u→vu \to v and ll right of it. Its four directed edges u→lu \to l, l→vl \to v, v→kv \to k, k→uk \to u are directed edges of its two triangles. The only edges that disappear are the two directions of the shared edge uvuv, which belong to this pair alone. So every directed edge of the new mesh is a directed edge of TT, used once, and an edge of TT that is not a matched diagonal keeps both of its sides, or its one side on the boundary. The vertices of the quads are vertices of TT, and no vertex lies inside a quad edge, because that edge is an edge of the conforming mesh TT. So the quad mesh is conforming, and its boundary edges are those of TT. For the converse, each pair is an edge of GG, and the pairs cover each triangle once, which is a perfect matching. □\square

So the merges of TT into convex quads are exactly the perfect matchings of GG, and the best merge for a cost that adds over the quads is a minimum cost perfect matching.

Lemma 3 (the reduction). Let n=∣T∣n = |T|, C=1+max⁡cC = 1 + \max c, K=nCK = nC, and give each edge the weight w=K+C−cw = K + C - c. Then every maximum weight matching has the largest size. If GG has a perfect matching, every maximum weight matching is a minimum cost perfect matching; if a maximum weight matching is not perfect, GG has no perfect matching.

Proof. Each weight lies in (K,K+C](K, K + C], because 0≤c<C0 \le c < C. A matching of size ss weighs at most s(K+C)s(K + C), and a matching of size s+1s + 1 weighs more than (s+1)K=sK+nC≥s(K+C)(s + 1)K = sK + nC \ge s(K + C), since s≤ns \le n. So a heavier matching never has a smaller size, and a maximum weight matching has the largest size. If a perfect matching exists, the largest size is n/2n/2, every matching of that size is perfect, and for a perfect matching MM, w(M)=(K+C) n/2−c(M)w(M) = (K + C)\,n/2 - c(M). So the largest weight is the smallest cost. If a maximum weight matching is not perfect, the largest size is below n/2n/2. □\square

Theorem 4 (Edmonds, 1965). The weighted blossom algorithm returns a maximum weight matching.

Outline of the classical proof. The algorithm keeps dual values yvy_v for vertices and zB≥0z_B \ge 0 for odd sets BB (the blossoms) such that every edge has slack yi+yj+∑B∋i,jzB−wij≥0y_i + y_j + \sum_{B \ni i, j} z_B - w_{ij} \ge 0, and every matched edge and every edge inside a blossom on the current tree paths has slack 0. It grows alternating trees on tight edges only, shrinks odd cycles of tight edges into blossoms, and augments along tight paths. When no tight edge helps, it changes the duals by the largest step that keeps them feasible; the four kinds of steps bring a vertex dual of an outer vertex to zero, make an edge from a tree to a free vertex tight, make an edge between two outer vertices tight, or bring the dual of an inner blossom to zero so it can be expanded. When a vertex dual reaches zero, its vertex can stay free at no loss, and the phase ends. At the end, the matching and the duals satisfy the complementary slackness conditions of the linear program of Edmonds' matching polytope, so the matching is optimal. The full proof is in Edmonds (1965) and in the textbooks of Korte and Vygen and of Schrijver.

What the code adds. The weights are integers and are doubled, so the starting vertex duals are even. Every dual step is a vertex dual, the dual of a blossom, the slack of an edge, or half the slack of an edge between two outer vertices; the code asserts that this slack is even, so all dual values stay integers and every comparison is exact. The code also has a mode that maximises the size first; Lemma 3 does not need it, and the tests check it separately. The tests compare the code with a brute force over all matchings on 150 random graphs of up to 9 vertices, in both modes, and with a brute force over all perfect matchings on 150 random graphs and on 56 triangle meshes of at most 12 triangles. A separate run on 3000 random graphs of up to 10 vertices found no difference.

Termination. Each augmentation adds one edge to the matching, so there are at most n/2+1n/2 + 1 phases. Within a phase, each dual step labels a new vertex or blossom, makes a new blossom, expands a blossom, or ends the phase, so a phase has O(n)O(n) dual steps, as Galil shows, and each step costs O(n+m)O(n + m) in this code. For the dual graph, m≤3n/2m \le 3n/2, so the whole run is O(n3)O(n^3). The dual graph and the merge are linear. So BLOSSOM-QUAD always stops.

What is not proved. A perfect matching need not exist. The test case is a triangle with one ear on each side: the convex dual graph is a star with three leaves, and two of the leaves can never be matched. The code then reports failure; a full mesher must change the triangle mesh. Also, the matching minimises the sum of costs, which is a measure of the average quad, not of the worst: no bound on the angles of the worst quad is proved, and a perfect matching can be forced to use poor quads. The quality of the result depends on the triangle mesh, and it is measured case by case.

Complexity

The dual graph has nn nodes and at most 3n/23n/2 edges. The weighted blossom algorithm in this code runs in O(n3)O(n^3) time. Faster forms run in O(nm+n2log⁡n)O(n m + n^2 \log n), or O(n2log⁡n)O(n^2 \log n) for the sparse dual graph, and practical codes for minimum cost perfect matching are fast on large meshes. The dual graph and the merge cost O(n)O(n).

Properties

  • Global. The pairing is optimal for the whole mesh, not built pair by pair, so it never strands a triangle when a perfect pairing exists.
  • Exact. With integer costs, the matching is exactly optimal.
  • Indirect. The quality of the quads depends on the triangle mesh; triangles close to right isosceles triangles give near squares.
  • No vertices added. The quads use the vertices of the triangle mesh.
  • Parity. The number of triangles must be even, which is the same as an even number of boundary edges.
  • No guarantee. A perfect matching may not exist, and no bound on the worst quad is known.

Variants and improvements

  • Q-Morph. An advancing front of quads over the triangle mesh, which aligns the quads with the boundary better; see Q-Morph.
  • Paving. A direct method that places rows of quads from the boundary; see Paving.
  • All-quad by splitting. Splitting each quad of a quad-dominant mesh into four quads, and each leftover triangle into three, always gives an all-quad mesh at the cost of more elements and worse angles.
  • Existence. For a closed surface, the dual graph is cubic, and when it has no bridge, Petersen's theorem gives a perfect matching, if all pairs are allowed; for planar meshes with a boundary there is no such result, and a mesher must fix the mesh near the boundary.
  • Other costs. Any cost that adds over the quads works, for example one that measures alignment with a direction field.

When to use it

Use Blossom-Quad when you need a quad mesh from a triangle mesh and you want the best global pairing, for example for finite element analysis with quads, or to make a quad-dominant mesh with few triangles left. It is fast and simple when a good triangle mesh is given. If quads must follow the boundary in rows, Q-Morph or paving is better. If an all-quad mesh is required for every input, add a fallback for the case without a perfect matching.

Pitfalls

  • Odd counts. An odd number of triangles cannot be paired. Fix the count, for example by changing the number of boundary edges.
  • Greedy pairing. Pairing the best quads first can strand triangles. Use a matching algorithm.
  • Non-convex pairs. Two triangles can form a non-convex or flat quad. Leave such pairs out of the dual graph, or give them a very high cost.
  • Float costs. Ties and rounding in float costs can make the matching depend on the order of the edges. Use integer costs, or accept that ties are broken arbitrarily.
  • No perfect matching. The dual graph can lack a perfect matching even with an even count. Detect it and change the mesh.

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.

blossom_quad.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blossom-quad/. The authors are listed in prov/ZDC65T.jsonl.

"""Blossom-Quad: merge the triangles of a triangle mesh into quads by a minimum
cost perfect matching of the dual graph.

Two triangles that share an edge and form a strictly convex quad give a dual
edge. Its cost is 1 - eta, where eta = max(0, 1 - (2/pi) max_k |pi/2 - alpha_k|)
is an angle quality of the quad (1 for a rectangle), scaled to an integer so
that the matching is exact. A minimum cost perfect matching of the dual graph
is found by Edmonds' weighted blossom algorithm, in the O(n^3) primal-dual form
described by Galil, run as a maximum weight matching with the weights
K + C - cost, where K is large enough that size comes first. The quality measure and the scale are parameters of this
code. When the dual graph has no perfect matching, a full mesher must change
the triangle mesh, for example near the boundary; here the code reports
failure instead.
"""

import math
from typing import List, Optional, Sequence, Tuple

from mg3geom import orient2d

SCALE = 10 ** 6


# ---------------------------------------------------------------------------
# Edmonds' weighted blossom algorithm (maximum weight matching, optionally of
# the largest size). Vertices 0..n-1; edges (i, j, w) with integer w. Each edge
# k has two endpoints, 2k (the end i) and 2k + 1 (the end j); mate[v] is the
# endpoint at the far side of the matched edge of v, or -1.
# ---------------------------------------------------------------------------

def max_weight_matching(n: int, edges: Sequence[Tuple[int, int, int]], max_cardinality: bool = False) -> List[int]:
    """Return partner[v] (or -1) of a maximum weight matching; with
    max_cardinality, of a maximum weight matching among the largest matchings.
    Edge weights must be integers; all dual values stay integers."""
    if not edges:
        return [-1] * n
    edges = [(i, j, 2 * w) for i, j, w in edges]   # doubled, so every dual change is an integer
    m = len(edges)
    end = [edges[p // 2][p % 2] for p in range(2 * m)]
    remote = [[] for _ in range(n)]
    for k, (i, j, _) in enumerate(edges):
        remote[i].append(2 * k + 1)
        remote[j].append(2 * k)
    top = max(0, max(w for _, _, w in edges))
    mate = [-1] * n
    label = [0] * (2 * n)          # 0 free, 1 outer (S), 2 inner (T); 5 is a scan mark
    label_end = [-1] * (2 * n)
    in_blossom = list(range(n))
    parent = [-1] * (2 * n)
    children: List[Optional[list]] = [None] * (2 * n)
    base = list(range(n)) + [-1] * n
    child_ends: List[Optional[list]] = [None] * (2 * n)
    best_edge = [-1] * (2 * n)
    best_list: List[Optional[list]] = [None] * (2 * n)
    free_ids = list(range(n, 2 * n))
    dual = [top] * n + [0] * n
    allowed = [False] * m
    queue: List[int] = []

    def slack(k):
        i, j, w = edges[k]
        return dual[i] + dual[j] - 2 * w

    def leaves(b):
        if b < n:
            yield b
        else:
            for t in children[b]:
                yield from leaves(t)

    def assign_label(w, t, p):
        b = in_blossom[w]
        label[w] = label[b] = t
        label_end[w] = label_end[b] = p
        best_edge[w] = best_edge[b] = -1
        if t == 1:
            queue.extend(leaves(b))
        else:
            bb = base[b]
            assign_label(end[mate[bb]], 1, mate[bb] ^ 1)

    def scan_blossom(v, w):
        """Trace back from v and w; return the base of a new blossom, or -1
        if the two paths reach different roots (an augmenting path)."""
        path, found = [], -1
        while v != -1 or w != -1:
            b = in_blossom[v]
            if label[b] & 4:
                found = base[b]
                break
            path.append(b)
            label[b] = 5
            if label_end[b] == -1:
                v = -1
            else:
                v = end[label_end[b]]
                b = in_blossom[v]
                v = end[label_end[b]]
            if w != -1:
                v, w = w, v
        for b in path:
            label[b] = 1
        return found

    def add_blossom(bs, k):
        v, w, _ = edges[k]
        bb, bv, bw = in_blossom[bs], in_blossom[v], in_blossom[w]
        b = free_ids.pop()
        base[b] = bs
        parent[b] = -1
        parent[bb] = b
        path, ends = [], []
        while bv != bb:
            parent[bv] = b
            path.append(bv)
            ends.append(label_end[bv])
            v = end[label_end[bv]]
            bv = in_blossom[v]
        path.append(bb)
        path.reverse()
        ends.reverse()
        ends.append(2 * k)
        while bw != bb:
            parent[bw] = b
            path.append(bw)
            ends.append(label_end[bw] ^ 1)
            w = end[label_end[bw]]
            bw = in_blossom[w]
        children[b], child_ends[b] = path, ends
        label[b] = 1
        label_end[b] = label_end[bb]
        dual[b] = 0
        for x in leaves(b):
            if label[in_blossom[x]] == 2:
                queue.append(x)
            in_blossom[x] = b
        best_to = [-1] * (2 * n)
        for c in path:
            lists = ([[p // 2 for p in remote[x]] for x in leaves(c)] if best_list[c] is None else [best_list[c]])
            for lst in lists:
                for e in lst:
                    i, j, _ = edges[e]
                    if in_blossom[j] == b:
                        i, j = j, i
                    bj = in_blossom[j]
                    if bj != b and label[bj] == 1 and (best_to[bj] == -1 or slack(e) < slack(best_to[bj])):
                        best_to[bj] = e
            best_list[c] = None
            best_edge[c] = -1
        best_list[b] = [e for e in best_to if e != -1]
        best_edge[b] = -1
        for e in best_list[b]:
            if best_edge[b] == -1 or slack(e) < slack(best_edge[b]):
                best_edge[b] = e

    def expand_blossom(b, end_stage):
        for s in children[b]:
            parent[s] = -1
            if s < n:
                in_blossom[s] = s
            elif end_stage and dual[s] == 0:
                expand_blossom(s, end_stage)
            else:
                for x in leaves(s):
                    in_blossom[x] = s
        if not end_stage and label[b] == 2:
            entry = in_blossom[end[label_end[b] ^ 1]]
            j = children[b].index(entry)
            if j & 1:
                j -= len(children[b])
                step, trick = 1, 0
            else:
                step, trick = -1, 1
            p = label_end[b]
            while j != 0:
                label[end[p ^ 1]] = 0
                label[end[child_ends[b][j - trick] ^ trick ^ 1]] = 0
                assign_label(end[p ^ 1], 2, p)
                allowed[child_ends[b][j - trick] // 2] = True
                j += step
                p = child_ends[b][j - trick] ^ trick
                allowed[p // 2] = True
                j += step
            bv = children[b][j]
            label[end[p ^ 1]] = label[bv] = 2
            label_end[end[p ^ 1]] = label_end[bv] = p
            best_edge[bv] = -1
            j += step
            while children[b][j] != entry:
                bv = children[b][j]
                if label[bv] == 1:
                    j += step
                    continue
                hit = None
                for x in leaves(bv):
                    if label[x] != 0:
                        hit = x
                        break
                if hit is not None:
                    label[hit] = 0
                    label[end[mate[base[bv]]]] = 0
                    assign_label(hit, 2, label_end[hit])
                j += step
        label[b] = label_end[b] = -1
        children[b] = child_ends[b] = None
        base[b] = -1
        best_list[b] = None
        best_edge[b] = -1
        free_ids.append(b)

    def augment_blossom(b, v):
        t = v
        while parent[t] != b:
            t = parent[t]
        if t >= n:
            augment_blossom(t, v)
        i = j = children[b].index(t)
        if i & 1:
            j -= len(children[b])
            step, trick = 1, 0
        else:
            step, trick = -1, 1
        while j != 0:
            j += step
            t = children[b][j]
            p = child_ends[b][j - trick] ^ trick
            if t >= n:
                augment_blossom(t, end[p])
            j += step
            t = children[b][j]
            if t >= n:
                augment_blossom(t, end[p ^ 1])
            mate[end[p]] = p ^ 1
            mate[end[p ^ 1]] = p
        children[b] = children[b][i:] + children[b][:i]
        child_ends[b] = child_ends[b][i:] + child_ends[b][:i]
        base[b] = base[children[b][0]]

    def augment(k):
        v, w, _ = edges[k]
        for s, p in ((v, 2 * k + 1), (w, 2 * k)):
            while True:
                bs = in_blossom[s]
                if bs >= n:
                    augment_blossom(bs, s)
                mate[s] = p
                if label_end[bs] == -1:
                    break
                t = end[label_end[bs]]
                bt = in_blossom[t]
                s = end[label_end[bt]]
                j = end[label_end[bt] ^ 1]
                if bt >= n:
                    augment_blossom(bt, j)
                mate[j] = label_end[bt]
                p = label_end[bt] ^ 1

    for _ in range(n):
        label[:] = [0] * (2 * n)
        best_edge[:] = [-1] * (2 * n)
        for b in range(n, 2 * n):
            best_list[b] = None
        allowed[:] = [False] * m
        queue[:] = []
        for v in range(n):
            if mate[v] == -1 and label[in_blossom[v]] == 0:
                assign_label(v, 1, -1)
        augmented = False
        while True:
            while queue and not augmented:
                v = queue.pop()
                for p in remote[v]:
                    k = p // 2
                    w = end[p]
                    if in_blossom[v] == in_blossom[w]:
                        continue
                    if not allowed[k]:
                        ks = slack(k)
                        if ks <= 0:
                            allowed[k] = True
                    if allowed[k]:
                        if label[in_blossom[w]] == 0:
                            assign_label(w, 2, p ^ 1)
                        elif label[in_blossom[w]] == 1:
                            bs = scan_blossom(v, w)
                            if bs >= 0:
                                add_blossom(bs, k)
                            else:
                                augment(k)
                                augmented = True
                                break
                        elif label[w] == 0:
                            label[w] = 2
                            label_end[w] = p ^ 1
                    elif label[in_blossom[w]] == 1:
                        b = in_blossom[v]
                        if best_edge[b] == -1 or ks < slack(best_edge[b]):
                            best_edge[b] = k
                    elif label[w] == 0:
                        if best_edge[w] == -1 or ks < slack(best_edge[w]):
                            best_edge[w] = k
            if augmented:
                break
            kind, delta, d_edge, d_blossom = -1, None, -1, -1
            if not max_cardinality:
                kind, delta = 1, min(dual[:n])
            for v in range(n):
                if label[in_blossom[v]] == 0 and best_edge[v] != -1:
                    d = slack(best_edge[v])
                    if kind == -1 or d < delta:
                        kind, delta, d_edge = 2, d, best_edge[v]
            for b in range(2 * n):
                if parent[b] == -1 and label[b] == 1 and best_edge[b] != -1:
                    ks = slack(best_edge[b])
                    assert ks % 2 == 0
                    d = ks // 2
                    if kind == -1 or d < delta:
                        kind, delta, d_edge = 3, d, best_edge[b]
            for b in range(n, 2 * n):
                if base[b] >= 0 and parent[b] == -1 and label[b] == 2 and (kind == -1 or dual[b] < delta):
                    kind, delta, d_blossom = 4, dual[b], b
            if kind == -1:
                kind, delta = 1, max(0, min(dual[:n]))
            for v in range(n):
                if label[in_blossom[v]] == 1:
                    dual[v] -= delta
                elif label[in_blossom[v]] == 2:
                    dual[v] += delta
            for b in range(n, 2 * n):
                if base[b] >= 0 and parent[b] == -1:
                    if label[b] == 1:
                        dual[b] += delta
                    elif label[b] == 2:
                        dual[b] -= delta
            if kind == 1:
                break
            if kind == 2:
                allowed[d_edge] = True
                i, j, _ = edges[d_edge]
                if label[in_blossom[i]] == 0:
                    i, j = j, i
                queue.append(i)
            elif kind == 3:
                allowed[d_edge] = True
                queue.append(edges[d_edge][0])
            else:
                expand_blossom(d_blossom, False)
        if not augmented:
            break
        for b in range(n, 2 * n):
            if parent[b] == -1 and base[b] >= 0 and label[b] == 1 and dual[b] == 0:
                expand_blossom(b, True)
    return [end[mate[v]] if mate[v] >= 0 else -1 for v in range(n)]


def min_cost_perfect_matching(n: int, edges: Sequence[Tuple[int, int, int]]) -> Optional[List[int]]:
    """A perfect matching of least total cost, as partner[v], or None if the
    graph has no perfect matching. Costs are integers."""
    if n % 2:
        return None
    if n == 0:
        return []
    # weight K + C - cost: with K = n C, a larger matching always weighs more,
    # so a maximum weight matching has the largest size and, among those, the least cost
    C = 1 + max((c for _, _, c in edges), default=0)
    K = n * C
    partner = max_weight_matching(n, [(i, j, K + C - c) for i, j, c in edges])
    return partner if all(p >= 0 for p in partner) else None


# ---------------------------------------------------------------------------
# The mesher.
# ---------------------------------------------------------------------------

def quad_quality(P, q) -> float:
    """max(0, 1 - (2/pi) max_k |pi/2 - alpha_k|) over the four corner angles."""
    worst = 0.0
    for s in range(4):
        a, b, c = P[q[s - 1]], P[q[s]], P[q[(s + 1) % 4]]
        u = (float(a[0] - b[0]), float(a[1] - b[1]))
        v = (float(c[0] - b[0]), float(c[1] - b[1]))
        ang = abs(math.atan2(u[0] * v[1] - u[1] * v[0], u[0] * v[0] + u[1] * v[1]))
        worst = max(worst, abs(math.pi / 2 - ang))
    return max(0.0, 1.0 - 2.0 * worst / math.pi)


def dual_graph(P, tris: Sequence[Tuple[int, int, int]]):
    """The dual edges (t1, t2, cost, quad) of pairs of triangles that share an
    edge and form a strictly convex quad."""
    own = {}
    for k, (a, b, c) in enumerate(tris):
        for e in ((a, b), (b, c), (c, a)):
            own[e] = k
    out = []
    for (u, v), t1 in sorted(own.items()):
        t2 = own.get((v, u))
        if t2 is None or t1 > t2:
            continue
        k = next(x for x in tris[t1] if x not in (u, v))
        l = next(x for x in tris[t2] if x not in (u, v))
        q = (u, l, v, k)
        if all(orient2d(P[q[s]], P[q[(s + 1) % 4]], P[q[(s + 2) % 4]]) > 0 for s in range(4)):  # @line L3
            out.append((t1, t2, round(SCALE * (1.0 - quad_quality(P, q))), q))
    return out


def blossom_quad(P, tris: Sequence[Tuple[int, int, int]]):
    """Return (quads, total cost) or (None, reason). Quads are counterclockwise."""
    if len(tris) % 2:  # @line L1
        return None, "an odd number of triangles cannot be paired"
    dual = dual_graph(P, tris)  # @line L2
    partner = min_cost_perfect_matching(len(tris), [(t1, t2, c) for t1, t2, c, _ in dual])  # @line L4
    if partner is None:  # @line L5
        return None, "the dual graph has no perfect matching"
    quads, cost = [], 0
    for t1, t2, c, q in dual:  # @line L6
        if partner[t1] == t2:
            quads.append(q)
            cost += c
    return quads, cost  # @line L7
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_blossom_quad.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/blossom-quad/. The authors are listed in prov/ZDC65T.jsonl.

import random
from fractions import Fraction as F

from blossom_quad import blossom_quad, dual_graph, max_weight_matching, min_cost_perfect_matching
from mg3geom import boundary_edges, is_valid_planar_mesh, orient2d


def all_matchings(n, edges, perfect):
    """Every matching (perfect only, if asked) as a tuple of edge indices, by brute force."""
    out = []

    def go(v, used, chosen):
        while v < n and v in used:
            v += 1
        if v == n:
            out.append(tuple(chosen))
            return
        if not perfect:
            go(v + 1, used, chosen)
        for k, (i, j, _) in enumerate(edges):
            if (i == v and j not in used and j != v) or (j == v and i not in used and i != v):
                w = j if i == v else i
                go(v + 1, used | {v, w}, chosen + [k])
    go(0, frozenset(), [])
    return out


def partner_of(n, edges, chosen):
    p = [-1] * n
    for k in chosen:
        i, j, _ = edges[k]
        p[i], p[j] = j, i
    return p


def random_graph(rng, n, density, wmax):
    return [(i, j, rng.randint(1, wmax)) for i in range(n) for j in range(i + 1, n) if rng.random() < density]


def test_weighted_blossom_against_brute_force():
    rng = random.Random(1)
    for _ in range(150):
        n = rng.randint(1, 9)
        edges = random_graph(rng, n, rng.uniform(0.2, 0.8), rng.choice((3, 20, 1000)))
        every = all_matchings(n, edges, perfect=False)
        weight = lambda ch: sum(edges[k][2] for k in ch)
        for maxcard in (False, True):
            p = max_weight_matching(n, edges, max_cardinality=maxcard)
            assert all(p[p[v]] == v for v in range(n) if p[v] >= 0)
            chosen = [k for k, (i, j, _) in enumerate(edges) if p[i] == j]
            assert len(chosen) == sum(1 for v in range(n) if p[v] >= 0) // 2
            if maxcard:
                size = max(len(ch) for ch in every)
                assert len(chosen) == size
                assert weight(chosen) == max(weight(ch) for ch in every if len(ch) == size)
            else:
                assert weight(chosen) == max(weight(ch) for ch in every)


def test_min_cost_perfect_matching_against_brute_force():
    rng = random.Random(2)
    found = 0
    for _ in range(150):
        n = 2 * rng.randint(1, 5)
        edges = random_graph(rng, n, rng.uniform(0.3, 0.9), 50)
        every = all_matchings(n, edges, perfect=True)
        p = min_cost_perfect_matching(n, edges)
        if not every:
            assert p is None
            continue
        found += 1
        best = min(sum(edges[k][2] for k in ch) for ch in every)
        assert p is not None and all(p[v] >= 0 and p[p[v]] == v for v in range(n))
        cost = sum(c for i, j, c in edges if p[i] == j)
        assert cost == best
    assert found >= 80


def grid_mesh(rng, W, H):
    P = []
    for j in range(H + 1):
        for i in range(W + 1):
            x = F(i) + (F(rng.randint(-30, 30), 100) if 0 < i < W else 0)
            y = F(j) + (F(rng.randint(-30, 30), 100) if 0 < j < H else 0)
            P.append((x, y))
    v = lambda i, j: j * (W + 1) + i
    tris = []
    for j in range(H):
        for i in range(W):
            a, b, c, d = v(i, j), v(i + 1, j), v(i + 1, j + 1), v(i, j + 1)
            tris += [(a, b, c), (a, c, d)] if rng.random() < 0.5 else [(a, b, d), (b, c, d)]
    return P, tris


def fan_mesh(rng, k):
    """k triangles around a centre, with jittered rim points on a circle-like polygon."""
    import math
    P = [(F(0), F(0))]
    for s in range(k):
        t = 2 * math.pi * (s + rng.uniform(-0.2, 0.2)) / k
        r = rng.uniform(0.8, 1.2)
        P.append((F(round(1000 * r * math.cos(t)), 1000), F(round(1000 * r * math.sin(t)), 1000)))
    return P, [(0, 1 + s, 1 + (s + 1) % k) for s in range(k)]


def area(P, cells):
    return sum(sum(orient2d(P[c[0]], P[c[s]], P[c[s + 1]]) for s in range(1, len(c) - 1)) for c in cells)


def test_blossom_quad_against_all_perfect_matchings():
    rng = random.Random(3)
    meshes = []
    for W, H in ((1, 1), (2, 1), (3, 1), (2, 2), (3, 2), (2, 3)):
        for _ in range(6):
            meshes.append(grid_mesh(rng, W, H))
    for k in (4, 6, 8, 10, 12):
        for _ in range(4):
            meshes.append(fan_mesh(rng, k))
    unique = solved = 0
    for P, tris in meshes:
        assert len(tris) <= 12 and is_valid_planar_mesh(P, tris)
        dual = dual_graph(P, tris)
        edges = [(t1, t2, c) for t1, t2, c, _ in dual]
        every = all_matchings(len(tris), edges, perfect=True)
        quads, cost = blossom_quad(P, tris)
        if not every:
            assert quads is None and "no perfect matching" in cost
            continue
        solved += 1
        costs = sorted(sum(edges[k][2] for k in ch) for ch in every)
        assert cost == costs[0]
        if len(costs) == 1 or costs[1] > costs[0]:
            unique += 1
            best = next(ch for ch in every if sum(edges[k][2] for k in ch) == costs[0])
            assert sorted(quads) == sorted(dual[k][3] for k in best)
        # a perfect matching gives a conforming quad mesh of the same region
        assert 2 * len(quads) == len(tris)
        assert is_valid_planar_mesh(P, quads)
        assert area(P, quads) == area(P, tris)
        assert set(boundary_edges(quads)) == set(boundary_edges(tris))
        assert len(boundary_edges(quads)) % 2 == 0
    assert solved >= 40 and unique >= 30


def test_failures_and_parity():
    # odd number of triangles
    P = [(F(0), F(0)), (F(1), F(0)), (F(0), F(1)), (F(1), F(1)), (F(2), F(1))]
    quads, why = blossom_quad(P, [(0, 1, 2), (1, 3, 2), (1, 4, 3)])
    assert quads is None and "odd" in why
    # a centre triangle with three ears: the dual graph is a star, which has no perfect matching
    P = [(F(0), F(0)), (F(4), F(0)), (F(2), F(4)), (F(2), F(-2)), (F(5), F(3)), (F(-1), F(3))]
    tris = [(0, 1, 2), (0, 3, 1), (1, 4, 2), (2, 5, 0)]
    assert is_valid_planar_mesh(P, tris) and len(dual_graph(P, tris)) == 3
    quads, why = blossom_quad(P, tris)
    assert quads is None and "no perfect matching" in why
    # a boundary of odd length cannot bound a quad mesh: 4 Q = 2 E_int + E_bnd
    assert len(boundary_edges(tris)) == 6
    rng = random.Random(4)
    for _ in range(20):
        P, tris = grid_mesh(rng, rng.randint(1, 4), rng.randint(1, 3))
        quads, cost = blossom_quad(P, tris)
        if quads is not None:
            sides = {}
            for q in quads:
                for s in range(4):
                    e = frozenset((q[s], q[(s + 1) % 4]))
                    sides[e] = sides.get(e, 0) + 1
            assert 4 * len(quads) == 2 * sum(v == 2 for v in sides.values()) + sum(v == 1 for v in sides.values())

History

Jean-François Remacle, Jonathan Lambrechts, Bruno Seny, Emilie Marchandise, Amaury Johnen and Christophe Geuzaine published Blossom-Quad in the International Journal for Numerical Methods in Engineering in 2012. Earlier indirect methods merged triangles into quads by local or greedy rules, which can leave unpaired triangles. Blossom-Quad replaced those rules with an exact optimisation, using Jack Edmonds' 1965 algorithm for weighted matching in general graphs, whose odd cycles, the blossoms, give the method its name. The method is part of the open source mesh generator Gmsh.

References

  1. Jean-François Remacle, Jonathan Lambrechts, Bruno Seny, Emilie Marchandise, Amaury Johnen and Christophe Geuzaine, Blossom-Quad, a non-uniform quadrilateral mesh generator using a minimum-cost perfect-matching algorithm, International Journal for Numerical Methods in Engineering 89(9), 2012, 1102 to 1119, the dual graph of the triangles, the quality cost of a quad, the perfect matching, and the results (general locator)
  2. Jack Edmonds, Maximum matching and a polyhedron with 0,1-vertices, Journal of Research of the National Bureau of Standards 69B, 1965, 125 to 130, the weighted matching algorithm and the matching polytope (general locator)
  3. Zvi Galil, Efficient algorithms for finding maximum matching in graphs, ACM Computing Surveys 18(1), 1986, 23 to 38, the O(n^3) weighted matching algorithm for general graphs (general locator)

About this page

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

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