Algorithmadvanced
Fudos-Hoffmann cluster reduction
Also called triangle decomposition solving, bottom-up cluster merging.
Solves well-constrained 2D systems by merging rigid clusters three at a time whenever three clusters pairwise share an element, in O(n^2) time.
- Time
- O(m (n + m)) worstΘ(n + m) best
- Space
- Θ(n + m) extra
- Where
- m = the number of distance constraints; n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ioannis Fudos, Christoph M. Hoffmann, 1997
The Fudos-Hoffmann reduction is the bottom-up form of graph-constructive solving for planar sketches. Its unit is the cluster, a set of points whose relative placement is fixed. It starts with one cluster per distance constraint, and it merges three clusters into one whenever they pairwise share one point, at three different points, because the three shared points then form a triangle with known sides. When one cluster holds every point, the graph is triangle-decomposable, and the list of merges is a plan: each merge is one circle-circle intersection and two rigid motions. The analysis takes time, which is for the constraints of a well-constrained system, and the final clusters do not depend on the order of the merges. A system that is well-constrained but not triangle-decomposable, such as the triangular prism, stops with several clusters, and the reduction reports them.
In plain words
Think of each rod of a structure as a small rigid piece. Two pieces that share a joint can swing about it. Three pieces that share joints in a ring, the first with the second, the second with the third and the third with the first, cannot swing: the three joints form a triangle with known sides, so the three pieces together form one rigid piece.
The method looks for such rings again and again, replacing three pieces by one bigger piece. If one piece is left at the end, the whole structure is rigid, and the order of the merges says how to build it: for each merge, draw the triangle of the three joints with ruler and compass, then move the three pieces onto it. Each triangle can open to the left or to the right, and the method keeps the side that the user's draft shows.
The problem
Input. A constraint graph of points and distance constraints, with a length for each edge, and optionally an integer draft placement that shows the intended shape. The graph is Laman-sparse: every points span at most edges, which is the condition of Laman's theorem without the total count.
Output. The final set of clusters and the list of merges. If one cluster holds all of , the graph is triangle-decomposable, and the solver also returns a placement with for every edge, the one whose merge triangles have the orientations of the draft. Otherwise the output lists the rigid clusters; a merge that finds two clusters with two common points reports that the graph is over-constrained.
Clusters. A merge is valid for clusters when , , and are distinct. The new cluster is . In the full method of Fudos and Hoffmann, clusters can also hold lines, and angle constraints give clusters of lines with fixed directions; this page treats points and distances, where all ideas already appear.
The algorithm
FH-REDUCE(V, E)- 1
S ← {{u, v} : uv ∈ E} ▷ one cluster per constraint - 2
W ← a stack that holds every cluster of S - 3
while W is not empty do - 4
A ← pop(W); if A ∉ S then continue - 5
for each cluster B ≠ A of S that meets A, let s(B) be the point it shares with A - 6
if B meets A in two points then fail "over-constrained" - 7
find B, C among them with a common point x ∉ A; if s(B) = s(C) then fail "over-constrained" - 8
if there are no such B, C then continue - 9
N ← A ∪ B ∪ C; append (A, B, C) to merges - 10
S ← (S − {A, B, C}) ∪ {N}; push N on W - 11
return S, merges FH-SOLVE(V, E, d, x̂)- 12
S, merges ← FH-REDUCE(V, E); fail unless S = {V} - 13
place each cluster {u, v} with u at (0, 0) and v at (d(uv), 0) - 14
for each (A, B, C) in merges, in order do - 15
p ← the point of A ∩ B; q ← the point of A ∩ C; r ← the point of B ∩ C - 16
s ← sign of ORIENT(x̂(p), x̂(q), x̂(r)), computed exactly; 0 counts as +1 - 17
R ← the point at distance |pr| (measured in B) from A's p and |qr| (measured in C) from A's q, on side s of pq - 18
move B by the proper rigid motion that takes its p to A's p and its r to R - 19
move C by the proper rigid motion that takes its q to A's q and its r to R - 20
give N the coordinates of A and of the moved B and C - 21
return the coordinates of the cluster V
The reduction. Lines L1 and L2 make each constraint a cluster of two points, and the stack holds the clusters that may still be part of a merge. Line L4 takes one; a cluster that an earlier merge used up is skipped. Lines L5 and L6 collect the clusters that meet , each with its common point. Line L7 looks for two of them, and , that also meet each other outside : then pairwise share one point. To find them fast, keep a table from each point to the first collected cluster that holds it; a second cluster that holds gives the pair. If and meet at the same point, they share two points, and the graph is over-constrained. Line L10 replaces the three clusters by their union and pushes it, since the new cluster can be part of a new merge.
The construction. Each cluster has coordinates in its own frame. In a merge, already has and , so the distance is known, and and give and . Line L17 places on the circle of radius about and the circle of radius about , on the side of the draft. Lines L18 and L19 move and onto this triangle. Each motion is a rotation and a translation, fixed by two points, so it never mirrors a cluster.
The sign. Line L16 is the only place where the draft enters. The predicate is the orientation test of the three draft points: the sign of . Computed in floating point, a value near zero can have the wrong sign by catastrophic cancellation, and then line L17 builds the mirror triangle. The draft here has integer coordinates and the sign is exact; for a floating-point draft, use exact arithmetic or a filtered predicate such as Shewchuk's, as in exact geometric computation. A collinear draft gives the sign 0, and the fixed rule "0 counts as +1" is a crude form of simulation of simplicity. Given a sign vector instead of a draft, one entry per merge, the solver follows any of the branches.
Example
Take six points with the constraints : two triangles and joined by three bars, two of which meet at point 0. (The prism, whose bars are disjoint, does not decompose.) The draft is , , , , , for the points 0 to 5, and the squared lengths are measured on it: , , , , , , , and .
The stack holds the nine edge clusters in input order, so the first pop is . It meets and at 1 and and at 5, but no two of these share a point outside , so line L8 goes on. The next pop, , finds and , which meet at 3. These are the four merges. The column "squared sides" lists , , , and the last column is the exact orientation determinant of the draft points .
| merge | squared sides | ORIENT | ||||
|---|---|---|---|---|---|---|
| 1 | 4, 0, 3 | 45, 17, 26 | ||||
| 2 | 4, 3, 5 | 17, 20, 65 | ||||
| 3 | 5, 0, 1 | 65, 17, 36 | ||||
| 4 | 1, 0, 2 | 36, 25, 25 |
In merge 3, the side is not a constraint: it is measured inside the cluster built by the first two merges. The run makes merges. With these signs, FH-SOLVE returns , , , , and : the draft turned so that the first cluster lies on the -axis. All nine distances hold, and all signed areas equal those of the draft.
The other sign vectors show why a branch can fail. The draft has 0 and 5 on the same side of the line 34. If merges 1 and 2 put them on opposite sides, the measured side becomes , so is longer than , and merge 3 has no real triangle. So 8 of the sign vectors fail, and the other 8 give 8 different real placements.
On the prism, the reduction builds the two triangles and stops with five clusters: , and the bars , , . No three of them pairwise share a point.
Correctness
The proof shows the following for a Laman-sparse graph.
- Cluster invariant. At every step the edge sets of the clusters partition , a cluster holds exactly edges, and two clusters share at most one point. A merge keeps the count, since . Two clusters with two common points would span more than edges on their points, so lines L6 and L7 fail only on graphs that are not sparse.
- No merge is missed. Every triple of clusters that could merge contains a cluster that is still on the stack. So when the stack is empty, no merge is possible.
- The result does not depend on the order. Every cluster formed in any run, in any order, lies inside a cluster of every final state. Two final states therefore have the same clusters.
- The solution. By induction over the merges, each cluster is placed so that all its constraints hold. If the lengths come from the draft and no merge triangle is flat in the draft, the placement is the draft moved by a proper rigid motion. Every solution in which the points and of each merge are distinct arises from one sign vector, so a triangle-decomposable system has at most such solutions up to proper motion.
Proof: On a Laman-sparse graph the Fudos-Hoffmann reduction finds a merge whenever one exists, its final clusters do not depend on the order, and the construction gives every solution up to proper motionfull
Let be a graph with vertices and edges, and for let be the number of edges with both ends in . Call sparse if for every with . A state of the reduction is a family of clusters; each cluster is a vertex set together with the set of the edges that were merged into it. Three clusters form a valid triple if , , with distinct. A state is terminal if it has no valid triple. Line numbers refer to the pseudocode on the main page.
Lemma 1 (cluster invariant). Let be sparse. At every step, the sets partition , every cluster has and , the set of edges inside , and two clusters share at most one vertex. Lines L6 and L7 never fail.
Proof. First, two clusters with , and disjoint edge sets share at most one vertex. If , then
which contradicts sparsity. Second, and give .
Line L1 makes one cluster per edge, with , and the edge sets partition . Consider a merge of a valid triple. No vertex lies in all three clusters, since such a vertex would equal , and . So , and the new cluster gets the edge set , of size . The partition of stays, and the first claim gives the bound on shared vertices for the new state.
Line L6 fails only if and share two vertices. Line L7 fails only if and share and the vertex , again two vertices. By the first claim, neither happens.
So a failure in line L6 or L7 proves that is not sparse. From now on is sparse.
Lemma 2 (line L7 finds a merge exactly when one exists). Let be a current cluster. Lines L5 to L8 find a valid triple that contains if one exists, and every triple that they return is valid.
Proof. If is a valid triple, then and meet , and they share , which is not in , since would put in all three clusters. So the search of line L7 finds some pair. Conversely, let line L7 return and that meet in the single points and share . By Lemma 1, , and differs from and , since these lie in . So the triple is valid.
Lemma 3 (no merge is missed). At every step, every valid triple of the current state has a member that is on the stack .
Proof. At the start every cluster is on . A pop of a cluster that is no longer current changes nothing. Let line L4 pop a current cluster . If line L8 continues, then by Lemma 2 no valid triple contains , and every other valid triple keeps its member on , which is not . If lines L9 and L10 merge into and push , then a valid triple of the new state either contains , which is on , or consists of three clusters other than , and . Those three clusters did not change, so they formed a valid triple before the merge, with a member on , and that member is still on .
Theorem 1 (termination and terminal state). The reduction stops after at most pops, and its final state is terminal.
Proof. Each merge lowers the number of clusters by 2, from at the start, so there are at most merges and as many pushes after line L2. Each pop removes one entry of . When is empty, Lemma 3 says that no valid triple exists.
Theorem 2 (confluence). Let be any terminal state reached from , and consider any run of the reduction, with any order of the stack. Every cluster formed in that run lies inside a cluster of . Consequently all runs end with the same family of clusters.
Proof. By induction over the order of formation. An edge cluster : the edge lies in for some cluster of (Lemma 1), and , so . A merge of a valid triple with , , : by induction , and for clusters of . Then , and .
- If , and are pairwise different, then by Lemma 1 their pairwise intersections are exactly , and , which are distinct. They form a valid triple of , which contradicts that is terminal.
- If exactly two are equal, say , then contains and , and contains both as well. So and share the two vertices , which contradicts Lemma 1. The cases (shared ) and (shared ) are the same.
So , and lies inside it.
Now let and be two final states. Each is terminal by Theorem 1. A cluster of lies in a cluster of , and lies in a cluster of . If , then shares vertices with , which contradicts Lemma 1. So , every cluster of is a cluster of , and by symmetry .
In particular, whether the final state is , that is, whether is triangle-decomposable, does not depend on the order. If it is, then the number of merges is , and since , this is .
For the construction, let be the lengths, and say that a placement of a cluster satisfies if for all . Two placements of a set are properly congruent if a rotation followed by a translation takes one to the other.
Lemma 4 (each step keeps the constraints). If no merge fails in line L17, then after each merge the coordinates of satisfy .
Proof. Line L13 places each edge cluster at the distance . In a merge, by induction , and are satisfied in their own frames. Line L17 gives a point with and , where the subscript names the frame. Since these lengths are equal, the proper motion of line L18 takes to and exactly to , and it keeps all distances inside . The same holds for in line L19, with and . The vertices that lie in two of the clusters are , and , and they get the same coordinates from both clusters. Every edge of lies inside one of the three clusters and holds there.
Lemma 5 (the signs of a solution reproduce it). Let be triangle-decomposable, and let be any placement with for every edge and for the points of every merge. Run lines L14 to L20 with the sign of merge equal to the sign of for that merge, with 0 counted as . Then no merge fails, and after each merge the placement of is properly congruent to restricted to .
Proof. By induction. Any two placements of an edge cluster at the same distance are properly congruent. In a merge, let be the proper motion with on . The point has distance from and from , and these are the lengths that and measure, because and are properly congruent to . So the circles of line L17 meet, and their centers differ because . If the triangle is not flat, the two meeting points are mirror images in the line , and the one on the side of the sign is , because keeps orientations. If it is flat, the circles touch in one point, which is . So . A proper motion is fixed by the images of two distinct points, so the motion of line L18 is , where on , and it moves to . The same holds for , and so on .
Theorem 3 (the construction). Let be triangle-decomposable.
- Every placement that FH-SOLVE returns satisfies all constraints.
- If the lengths are measured on an integer draft and no merge triangle is flat in , FH-SOLVE returns a placement properly congruent to .
- Every real solution with for the points of every merge is properly congruent to the output for one of the sign vectors. So the system has at most such solutions up to proper motion.
Proof. Part 1 is Lemma 4 for the cluster . Part 2 is Lemma 5 with : no merge triangle is flat in , so , and line L16 computes the sign of exactly from the integer coordinates, so the signs are those of Lemma 5. Part 3 is Lemma 5 for the solution , with merges.
A solution with for some merge is degenerate: the circles of line L17 are then concentric, and the implementation stops with an error instead of choosing a point on a circle.
Theorem 4 (running time). FH-REDUCE runs in time and FH-SOLVE in time, so both run in time for a sparse graph.
Proof. By Lemma 1 the clusters are edge-disjoint, and a cluster with points has edges, so the sizes of all current clusters add up to at most . One pop of line L4 scans the clusters that meet and their vertices, with a table from vertices to clusters, in time, and by Theorem 1 there are pops. In FH-SOLVE, each of the merges moves at most points in lines L18 and L19 and does other work. Sparsity gives .
Complexity
- One pop. Lines L5 to L8 scan the clusters that meet and the points of each. The clusters are edge-disjoint and a cluster with points has edges, so all clusters together have at most points, and one pop costs .
- All pops. The stack receives edge clusters and one cluster per merge, and each merge removes two clusters, so there are at most pops. The reduction takes time, which is for a Laman graph. If no cluster meets another at all (a matching), each pop is and the time is .
- The construction. Each merge moves the points of and , so the moves cost at most the total size of the clusters, per merge and in all. Each square root and each orientation test is in the real RAM.
- Space. The clusters, the table from points to clusters and the stack take space.
Properties
- Exact analysis. The reduction uses only the graph, so it is exact and fast, and the plan holds for all values of the lengths.
- Order independent. The final clusters, and so the answer to "is the graph triangle-decomposable", do not depend on the order of the stack. The list of merges does depend on it.
- Solutions in a quadratic tower. Each merge solves one quadratic equation, so the coordinates lie in a tower of quadratic extensions: the solution is ruler-and-compass constructible.
- Generic rigidity of clusters. Each cluster is placed up to finitely many choices, so it is rigid for generic lengths. The converse fails: a rigid graph such as the prism need not reduce.
- All roots or one root. With the draft signs the solver returns the intended solution; with all sign vectors it lists all real solutions, up to , except degenerate ones in which two shared points of a merge coincide, and the branches that fail a triangle inequality drop out, as in the example.
Variants and improvements
- Lines and angles. Fudos and Hoffmann treat lines as entities as well. Two lines with an angle constraint fix only directions, so the method keeps sets of lines with fixed directions, with their own merge rules, and the triangle rule then works with points and lines mixed.
- Top-down form. Owen's decomposition splits the graph at separation pairs from the top. Joan-Arinyo, Soto-Riera, Vila-Marta and Vilaplana-Pastó proved that it succeeds on the same graphs as the bottom-up reduction.
- General clusters. A DR-plan replaces the triangle rule by any minimal dense subgraph, found by flows, so a system such as the prism becomes one step for a general solver.
- Completion of under-constrained systems. When the reduction ends with several clusters, adding distance constraints between them that create new triangles makes the system decomposable. The added constraints are then shown to the user as free dimensions.
- Incremental analysis. When the user adds one constraint, only clusters that meet it can change, so the reduction can restart from the old clusters.
When to use it
- To solve planar sketches with points, lines, distances and angles, which are triangle-decomposable in most practical cases, exactly and fast.
- To list all solutions of a sketch, or to choose one by the orientations of the draft.
- To reuse the plan: the analysis runs once, and each change of a dimension costs only the construction.
Do not use it alone for systems such as the prism or , which are well-constrained but not triangle-decomposable; use a DR-plan with a general solver for the parts that remain. Do not use it in space, where the triangle rule does not make rigid clusters.
Pitfalls
- Missing the distinct-points test (line L7). If line L7 accepts and that meet at the same point, the three clusters do not form a triangle: and share two points. Merging them silently accepts an over-constrained system, such as four points with all six distances, and the construction then fails or violates a constraint.
- Not pushing the new cluster (line L10). If line L10 does not push on the stack, merges that need are never found, and the reduction reports a decomposable graph as not decomposable. In the example, merges 2, 3 and 4 each use the cluster that the merge before them made.
- The sign in floating point (line L16). A floating-point orientation of nearly collinear draft points can have the wrong sign, and line L17 then builds the mirror triangle. Compute the sign exactly.
- A mirror in the motion (lines L18 and L19). A motion that matches two points but allows a reflection, such as a best-fit transform, can mirror a cluster and destroy the orientations that earlier merges chose. Use the rotation and translation fixed by two points.
- Hiding a missing solution (line L17). When , the circles do not meet. Code that clamps the negative square to 0 without a test returns a point that violates two constraints; clamp only within a relative tolerance, as the implementation does, and report the failure otherwise.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fudos-hoffmann-reduction/. The authors are listed in prov/G145A2.jsonl.
"""Fudos-Hoffmann bottom-up triangle reduction, for points and distances in the plane.
A cluster is a set of points whose relative placement is fixed. The reduction starts
with one cluster per distance constraint and merges three clusters that pairwise share
one point, at three different points. The solver then places the clusters in the order
of the merges, one circle-circle intersection per merge.
"""
from math import sqrt
Edge = tuple[int, int]
Merge = tuple[frozenset[int], frozenset[int], frozenset[int]]
def reduce_clusters(n: int, edges: list[Edge]) -> tuple[list[frozenset[int]], list[Merge]]:
"""Run the triangle reduction on the constraint graph (range(n), edges).
Precondition: the edges are distinct pairs of distinct vertices in range(n), and
the graph is Laman-sparse (every k >= 2 vertices span at most 2k - 3 edges).
Returns the final clusters and the merges (A, B, C) in the order they were made.
Raises ValueError if two clusters share two vertices; this can only happen if the
graph is not Laman-sparse. Not every graph that is not sparse is detected.
Cost: O(n + m) space and O((n + m) * (number of clusters)) time, which is O(n^2)
for m <= 2n - 3.
"""
members: dict[int, frozenset[int]] = {}
of_vertex: list[set[int]] = [set() for _ in range(n)]
seen_edges: set[frozenset[int]] = set()
for u, v in edges:
if not (0 <= u < n and 0 <= v < n) or u == v:
raise ValueError("bad edge")
e = frozenset((u, v))
if e in seen_edges:
raise ValueError("repeated edge")
seen_edges.add(e)
k = len(members)
members[k] = e # @line L1
of_vertex[u].add(k)
of_vertex[v].add(k)
next_id = len(members)
work = list(members) # @line L2
plan: list[Merge] = []
while work: # @line L3
a = work.pop() # @line L4
if a not in members:
continue
ca = members[a]
shared: dict[int, int] = {} # cluster that meets A -> the vertex it shares with A
for v in ca: # @line L5
for b in of_vertex[v]:
if b == a:
continue
if b in shared: # @line L6
raise ValueError("over-constrained: two clusters share two points")
shared[b] = v
holder: dict[int, int] = {} # vertex outside A -> a cluster that meets A and holds it
found: tuple[int, int] | None = None
for b, vb in shared.items(): # @line L7
for x in members[b]:
if x in ca:
continue
c = holder.get(x)
if c is None:
holder[x] = b
continue
if shared[c] == vb:
raise ValueError("over-constrained: two clusters share two points")
found = (b, c)
break
if found is not None:
break
if found is None: # @line L8
continue
b, c = found
cb, cc = members[b], members[c]
plan.append((ca, cb, cc)) # @line L9
new = ca | cb | cc
for k in (a, b, c): # @line L10
for v in members.pop(k):
of_vertex[v].discard(k)
members[next_id] = new
for v in new:
of_vertex[v].add(next_id)
work.append(next_id)
next_id += 1
return list(members.values()), plan # @line L11
def is_triangle_decomposable(n: int, edges: list[Edge]) -> bool:
"""True if the reduction ends with one cluster that holds all n vertices."""
if n == 1 and not edges:
return True
clusters, _ = reduce_clusters(n, edges)
return len(clusters) == 1 and len(clusters[0]) == n
def orient(p: tuple[int, int], q: tuple[int, int], r: tuple[int, int]) -> int:
"""Sign of the orientation determinant of three integer points, computed exactly."""
d = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])
return (d > 0) - (d < 0)
def _third_point(p: complex, q: complex, r1: float, r2: float, side: int) -> complex:
"""The point at distance r1 from p and r2 from q, to the left of p->q if side > 0."""
d = abs(q - p)
if d == 0.0:
raise ValueError("two points of a triangle coincide")
x = (d * d + r1 * r1 - r2 * r2) / (2.0 * d)
h2 = r1 * r1 - x * x
scale = max(r1, r2, d) ** 2
if h2 < -1e-9 * scale:
raise ValueError("no real solution: the circles do not meet")
h = sqrt(h2) if h2 > 0.0 else 0.0
ex = (q - p) / d
return p + ex * complex(x, h if side > 0 else -h)
def _move(pts: dict[int, complex], u: int, w: int, pu: complex, pw: complex) -> dict[int, complex]:
"""Apply the proper rigid motion that takes pts[u], pts[w] to pu and a point on the ray to pw."""
z = (pw - pu) / (pts[w] - pts[u])
z /= abs(z)
return {v: pu + z * (x - pts[u]) for v, x in pts.items()}
def solve(
n: int,
lengths: dict[Edge, float],
draft: list[tuple[int, int]] | None = None,
signs: list[int] | None = None,
) -> list[tuple[float, float]]:
"""Place n points so that |p_u - p_v| = lengths[(u, v)] for every constraint.
Precondition: the constraint graph is triangle-decomposable and the lengths are
positive. The root of merge i is chosen by signs[i] if signs is given, else by the
exact orientation sign of the three shared points in the integer draft (0 counts
as +1). Raises ValueError if the graph is not decomposable or a triangle has no
real solution. Cost: O(n^2) for the reduction plus O(n^2) for the moves.
"""
edges = list(lengths)
if n == 1 and not edges:
return [(0.0, 0.0)]
clusters, plan = reduce_clusters(n, edges) # @line L12
if len(clusters) != 1 or len(clusters[0]) != n:
raise ValueError("not triangle-decomposable")
if signs is not None and len(signs) != len(plan):
raise ValueError("one sign per merge is needed")
coords: dict[frozenset[int], dict[int, complex]] = {}
for (u, v), d in lengths.items(): # @line L13
if not d > 0.0:
raise ValueError("lengths must be positive")
coords[frozenset((u, v))] = {u: 0j, v: complex(d, 0.0)}
for i, (ca, cb, cc) in enumerate(plan): # @line L14
(p,) = ca & cb # @line L15
(q,) = ca & cc
(r,) = cb & cc
xa, xb, xc = coords.pop(ca), coords.pop(cb), coords.pop(cc)
if signs is not None:
side = signs[i]
elif draft is not None:
side = orient(draft[p], draft[q], draft[r]) or 1 # @line L16
else:
side = 1
pr = abs(xb[r] - xb[p])
qr = abs(xc[r] - xc[q])
rr = _third_point(xa[p], xa[q], pr, qr, side) # @line L17
new = dict(xa)
for v, x in _move(xb, p, r, xa[p], rr).items(): # @line L18
new.setdefault(v, x)
for v, x in _move(xc, q, r, xa[q], rr).items(): # @line L19
new.setdefault(v, x)
coords[ca | cb | cc] = new # @line L20
final = coords[clusters[0]]
return [(final[v].real, final[v].imag) for v in range(n)] # @line L21
test_fudos_hoffmann_reduction.py 263 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fudos-hoffmann-reduction/. The authors are listed in prov/G145A2.jsonl.
import random
from fractions import Fraction
from itertools import combinations
from math import sqrt
import pytest
from fudos_hoffmann_reduction import is_triangle_decomposable, orient, reduce_clusters, solve
Edge = tuple[int, int]
EXAMPLE_EDGES = [(0, 1), (0, 2), (1, 2), (3, 4), (3, 5), (4, 5), (0, 3), (0, 4), (1, 5)]
EXAMPLE_DRAFT = [(0, 0), (6, 0), (3, -4), (-1, 5), (3, 6), (7, 4)]
PRISM = [(0, 1), (0, 2), (1, 2), (3, 4), (3, 5), (4, 5), (0, 3), (1, 4), (2, 5)]
K33 = [(u, v) for u in range(3) for v in range(3, 6)]
def sparse(n: int, edges: list[Edge]) -> bool:
"""Brute force over vertex subsets: every k >= 2 vertices span at most 2k - 3 edges."""
for s in range(1 << n):
k = bin(s).count("1")
if k >= 2 and sum(1 for u, v in edges if s >> u & 1 and s >> v & 1) > 2 * k - 3:
return False
return True
def closure(n: int, edges: list[Edge], rng: random.Random) -> set[frozenset[int]]:
"""Brute force: merge a random triple of clusters that pairwise share one point,
at three different points, until no triple is left."""
state = [frozenset(e) for e in edges]
while True:
triples = []
for x, y, z in combinations(range(len(state)), 3):
a, b, c = state[x], state[y], state[z]
ab, ac, bc = a & b, a & c, b & c
if len(ab) == len(ac) == len(bc) == 1 and len(ab | ac | bc) == 3:
triples.append((x, y, z))
if not triples:
return set(state)
x, y, z = rng.choice(triples)
new = state[x] | state[y] | state[z]
state = [s for i, s in enumerate(state) if i not in (x, y, z)] + [new]
def rank(rows: list[list[Fraction]]) -> int:
rows = [r[:] for r in rows]
r = 0
cols = len(rows[0]) if rows else 0
for c in range(cols):
piv = next((i for i in range(r, len(rows)) if rows[i][c] != 0), None)
if piv is None:
continue
rows[r], rows[piv] = rows[piv], rows[r]
for i in range(len(rows)):
if i != r and rows[i][c] != 0:
f = rows[i][c] / rows[r][c]
rows[i] = [a - f * b for a, b in zip(rows[i], rows[r])]
r += 1
return r
def rigid_by_rank(cluster: frozenset[int], edges: list[Edge], rng: random.Random) -> bool:
"""Exact rank of the rigidity matrix at random integer points: rank 2k - 3."""
vs = sorted(cluster)
k = len(vs)
if k == 2:
return True
col = {v: i for i, v in enumerate(vs)}
inner = [(u, v) for u, v in edges if u in cluster and v in cluster]
best = 0
for _ in range(2):
p = {v: (rng.randint(-60, 60), rng.randint(-60, 60)) for v in vs}
rows = []
for u, v in inner:
row = [Fraction(0)] * (2 * k)
dx, dy = p[u][0] - p[v][0], p[u][1] - p[v][1]
row[2 * col[u]], row[2 * col[u] + 1] = Fraction(dx), Fraction(dy)
row[2 * col[v]], row[2 * col[v] + 1] = Fraction(-dx), Fraction(-dy)
rows.append(row)
best = max(best, rank(rows))
return best == 2 * k - 3
def henneberg(n: int, rng: random.Random, type2: float) -> list[Edge]:
"""A random Laman graph by Henneberg steps, with type II steps at the given rate."""
edges = [(0, 1)]
for v in range(2, n):
if v >= 3 and rng.random() < type2:
u, w = edges.pop(rng.randrange(len(edges)))
x = rng.choice([t for t in range(v) if t not in (u, w)])
edges += [(u, v), (w, v), (x, v)]
else:
u, w = rng.sample(range(v), 2)
edges += [(u, v), (w, v)]
return edges
def lengths_of(draft: list[tuple[int, int]], edges: list[Edge]) -> dict[Edge, float]:
return {(u, v): sqrt((draft[u][0] - draft[v][0]) ** 2 + (draft[u][1] - draft[v][1]) ** 2) for u, v in edges}
def check_solution(pts: list[tuple[float, float]], lengths: dict[Edge, float]) -> None:
scale = max(lengths.values())
for (u, v), d in lengths.items():
got = sqrt((pts[u][0] - pts[v][0]) ** 2 + (pts[u][1] - pts[v][1]) ** 2)
assert abs(got - d) <= 1e-7 * scale
def check_congruent(pts: list[tuple[float, float]], draft: list[tuple[int, int]]) -> None:
"""All pairwise distances and all signed areas agree with the draft: the solution is
the draft moved by a proper rigid motion. The values are compared with a tolerance."""
n = len(draft)
scale = max(abs(c) for p in draft for c in p) + 1
for u, v in combinations(range(n), 2):
dd = (draft[u][0] - draft[v][0]) ** 2 + (draft[u][1] - draft[v][1]) ** 2
dp = (pts[u][0] - pts[v][0]) ** 2 + (pts[u][1] - pts[v][1]) ** 2
assert abs(dd - dp) <= 1e-6 * scale * scale
for u, v, w in combinations(range(n), 3):
exact = (draft[v][0] - draft[u][0]) * (draft[w][1] - draft[u][1]) - (draft[v][1] - draft[u][1]) * (draft[w][0] - draft[u][0])
approx = (pts[v][0] - pts[u][0]) * (pts[w][1] - pts[u][1]) - (pts[v][1] - pts[u][1]) * (pts[w][0] - pts[u][0])
assert abs(exact - approx) <= 1e-6 * scale * scale
def random_draft(n: int, rng: random.Random) -> list[tuple[int, int]]:
pts: set[tuple[int, int]] = set()
while len(pts) < n:
pts.add((rng.randint(-20, 20), rng.randint(-20, 20)))
out = list(pts)
rng.shuffle(out)
return out
def test_example() -> None:
clusters, plan = reduce_clusters(6, EXAMPLE_EDGES)
assert clusters == [frozenset(range(6))]
assert len(plan) == 4
assert plan[-1][0] | plan[-1][1] | plan[-1][2] == frozenset(range(6))
lengths = lengths_of(EXAMPLE_DRAFT, EXAMPLE_EDGES)
pts = solve(6, lengths, EXAMPLE_DRAFT)
check_solution(pts, lengths)
check_congruent(pts, EXAMPLE_DRAFT)
def test_edges_and_small() -> None:
assert is_triangle_decomposable(1, [])
assert is_triangle_decomposable(2, [(0, 1)])
assert is_triangle_decomposable(3, [(0, 1), (1, 2), (0, 2)])
assert not is_triangle_decomposable(3, [(0, 1), (1, 2)])
assert solve(2, {(0, 1): 5.0}) == [(0.0, 0.0), (5.0, 0.0)]
with pytest.raises(ValueError):
reduce_clusters(2, [(0, 1), (1, 0)])
with pytest.raises(ValueError):
reduce_clusters(2, [(0, 0)])
def test_prism_k33_k4() -> None:
clusters, _ = reduce_clusters(6, PRISM)
sizes = sorted(len(c) for c in clusters)
assert sizes == [2, 2, 2, 3, 3]
assert {frozenset((0, 1, 2)), frozenset((3, 4, 5))} <= set(clusters)
clusters, plan = reduce_clusters(6, K33)
assert len(clusters) == 9 and plan == []
k4 = list(combinations(range(4), 2))
with pytest.raises(ValueError):
reduce_clusters(4, k4)
def test_no_real_solution() -> None:
with pytest.raises(ValueError):
solve(3, {(0, 1): 1.0, (1, 2): 1.0, (0, 2): 3.0})
def test_all_small_graphs() -> None:
"""Every graph on n <= 5 points: an over-constraint report only on graphs that are not
sparse; on sparse graphs the clusters cover each edge once, are rigid by exact rank,
and equal the brute-force closure."""
rng = random.Random(7)
for n in range(2, 6):
pairs = list(combinations(range(n), 2))
for mask in range(1 << len(pairs)):
edges = [pairs[i] for i in range(len(pairs)) if mask >> i & 1]
ok = sparse(n, edges)
try:
clusters, plan = reduce_clusters(n, edges)
except ValueError:
assert not ok
continue
if not ok:
continue
assert len(plan) == (len(edges) - len(clusters)) // 2
for a, b in combinations(clusters, 2):
assert len(a & b) <= 1
for c in clusters:
inner = sum(1 for u, v in edges if u in c and v in c)
assert inner == 2 * len(c) - 3
for c in clusters:
if len(c) <= 4:
assert rigid_by_rank(c, edges, rng)
assert set(clusters) == closure(n, edges, rng)
def test_all_laman_graphs_on_six_points() -> None:
rng = random.Random(11)
pairs = list(combinations(range(6), 2))
count = 0
for chosen in combinations(range(len(pairs)), 9):
edges = [pairs[i] for i in chosen]
if not sparse(6, edges):
continue
count += 1
clusters, _ = reduce_clusters(6, edges)
if count % 7 == 0:
assert set(clusters) == closure(6, edges, rng)
for c in clusters:
assert sum(1 for u, v in edges if u in c and v in c) == 2 * len(c) - 3
assert count > 0
def test_random_solutions_against_constraints() -> None:
"""500 random decomposable graphs: the solution meets every constraint and, with the
draft orientations, it is the draft up to a proper rigid motion."""
rng = random.Random(2024)
done = 0
while done < 500:
n = rng.randint(3, 9)
edges = henneberg(n, rng, 0.3)
rng.shuffle(edges)
if not is_triangle_decomposable(n, edges):
continue
clusters, _ = reduce_clusters(n, edges)
for c in clusters:
assert rigid_by_rank(c, edges, rng)
draft = random_draft(n, rng)
lengths = lengths_of(draft, edges)
pts = solve(n, lengths, draft)
check_solution(pts, lengths)
check_congruent(pts, draft)
done += 1
def test_every_root_of_a_triangle_strip() -> None:
"""A strip of triangles on n points has 2^(n-2) solutions up to proper motion."""
rng = random.Random(5)
for n in range(3, 8):
edges = [(i, i + 1) for i in range(n - 1)] + [(i, i + 2) for i in range(n - 2)]
draft = random_draft(n, rng)
while any(orient(draft[i], draft[i + 1], draft[i + 2]) == 0 for i in range(n - 2)):
draft = random_draft(n, rng)
lengths = lengths_of(draft, edges)
_, plan = reduce_clusters(n, edges)
assert len(plan) == n - 2
shapes = set()
for bits in range(1 << (n - 2)):
signs = [1 if bits >> i & 1 else -1 for i in range(n - 2)]
pts = solve(n, lengths, signs=signs)
check_solution(pts, lengths)
z0 = complex(*pts[0])
rot = (complex(*pts[1]) - z0) / abs(complex(*pts[1]) - z0)
shapes.add(tuple((round(((complex(*p) - z0) / rot).real, 5), round(((complex(*p) - z0) / rot).imag, 5)) for p in pts))
assert len(shapes) == 2 ** (n - 2)
History
Fudos worked on the reduction in his Purdue PhD research with Hoffmann in the early 1990s, as the analysis phase of the constraint solver of Bouma, Fudos, Hoffmann, Cai and Paige (Computer-Aided Design, 1995). The 1997 paper in ACM Transactions on Graphics gave the cluster rules for points and lines, a proof of correctness, and the quadratic algorithm. It also showed that the choice of the intended root is hard in general, which became the root identification problem. Owen's top-down method of 1991 decomposes the same class of graphs, as Joan-Arinyo and his coauthors proved in 2002.
References
- Ioannis Fudos and Christoph M. Hoffmann, A graph-constructive approach to solving systems of geometric constraints, ACM Transactions on Graphics 16(2), 179 to 216, 1997, the cluster formation by triangles, its proof of correctness and its quadratic running time; Section 2.2 on multiple solutions and root identification
- William Bouma, Ioannis Fudos, Christoph M. Hoffmann, Jiazhen Cai and Robert Paige, Geometric constraint solver, Computer-Aided Design 27(6), 1995, the solver in which the reduction is the analysis phase, with points, lines, distances and angles (general locator)
- Robert Joan-Arinyo, Antoni Soto-Riera, Sebastià Vila-Marta and Josep Vilaplana-Pastó, Revisiting decomposition analysis of geometric constraint graphs, ACM Symposium on Solid Modeling and Applications (SM '02), 105 to 115, 2002, the proof that the bottom-up reduction and Owen's top-down method decompose the same class of graphs (general locator)
- Meera Sitharam, Audrey St. John and Jessica Sidman (editors), Handbook of Geometric Constraint Systems Principles, Chapman and Hall/CRC, 2018, the chapters on decomposition and constructive solving (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag G145A2 Edit this page History Report an error Markdown