Algorithmadvanced
Owen's triconnected decomposition
Also called top-down constraint decomposition.
Owen's solver that splits the constraint graph at separation pairs into triconnected parts, solves each and reassembles them, for systems solvable by quadratics.
- Time
- O(n^2) worst
- Space
- O(n^2) extra
- Where
- m = the number of distance constraints, 2n - 3; n = the number of points
- Model
- Real RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John C. Owen, 1991
Owen's decomposition is the top-down form of graph-constructive solving for planar sketches. It looks for a separation pair , two points whose removal cuts the constraint graph in two. One side is rigid by itself; the other side is rigid once the distance is known, so the method gives it a virtual edge . Both sides are split again in the same way until every part is a triangle. The solver then works from the leaves: it solves the rigid side, measures there, solves the other side with that length, and glues the two sides at and by a rigid motion. Each triangle is one circle-circle intersection, so the solution needs only square roots. The method stops at a part with four or more points and no separation pair, that is, a 3-connected part such as the triangular prism, and these parts are exactly where square roots do not suffice. With a linear-time search for separation pairs the analysis takes time.
In plain words
Look at the sketch as a network of rods. Sometimes two joints hold the whole network together: if you pull them out, it falls into two pieces. Each piece is easier to solve than the whole.
One piece is fixed in shape by its own rods. The other piece is not, since it misses one rod: the one that the first piece holds in place between the two joints. So you solve the first piece, measure the distance between the two joints, and add that distance to the second piece as an extra rod. Now the second piece is fixed too. You solve it and lay it onto the first piece at the two joints.
Each piece is cut again until only triangles are left. A triangle with known sides is easy to draw with ruler and compass. If a piece cannot be cut, the method stops.
The problem
Input. A Laman graph : points and distance constraints, with every points spanning at most edges, as in Laman's theorem. Each edge has a length . An optional integer draft shows the intended shape.
Output. A decomposition tree whose leaves are triangles, or a report that some part is 3-connected and has no separation pair. For a tree, the solver also returns a placement with for every edge; each leaf triangle has the orientation of the draft.
Separation pairs. A pair is a separation pair of a part with vertex set if the graph on is not connected. A Laman graph with at least 3 points is 2-connected, so a separation pair is the smallest kind of vertex cut that it can have, and a part with no separation pair is 3-connected. Owen finds the pairs with the triconnected components algorithm of Hopcroft and Tarjan; this page splits at one pair at a time, which is simpler to state and to prove.
The algorithm
OWEN-DECOMPOSE(P, F) ▷ a part: points P, edges F (real and virtual)- 1
if |F| ≠ 2|P| − 3 then fail "not a Laman graph" - 2
if |P| = 3 then return TRI(P) - 3
{a, b} ← a separation pair of (P, F) - 4
if there is none then return FAIL ▷ the part is 3-connected - 5
K ← one component of the graph on P − {a, b}; P1 ← K ∪ {a, b}; P2 ← P − K - 6
F1 ← the edges inside P1, with ab if ab ∈ F; F2 ← the rest; if |F1| < 2|P1| − 3 then swap the two sides - 7
F2 ← F2 ∪ {ab}, marked virtual if ab ∉ F; return SPLIT(a, b, OWEN-DECOMPOSE(P1, F1), OWEN-DECOMPOSE(P2, F2)) OWEN-SOLVE(T, d, x̂)- 8
if T = TRI(u, v, w) then place u at (0, 0), v at (d(uv), 0), and w at distances d(uw), d(vw) on the side of the sign of ORIENT(x̂(u), x̂(v), x̂(w)), computed exactly, 0 counting as +1; return - 9
T = SPLIT(a, b, T1, T2); X1 ← OWEN-SOLVE(T1, d, x̂) ▷ the rigid side first - 10
if ab is virtual then d(ab) ← |X1(a) − X1(b)|; X2 ← OWEN-SOLVE(T2, d, x̂) - 11
return X1 together with X2 moved by the proper rigid motion that takes X2(a), X2(b) to X1(a), X1(b)
The split. Line L1 checks the count on each part, which also catches a wrong input. Line L3 finds a separation pair; with the Hopcroft-Tarjan low-point search for articulation points, run once with each point removed, it costs for a part with points and edges, and Hopcroft and Tarjan's triconnectivity algorithm does it in . Line L5 takes one component and gives the pair to both sides. Line L6 puts each edge on its side: an edge cannot join to the rest, because separates them. The two sides together have one edge too few to be two Laman graphs, so exactly one side has the full count and the other has one edge less; line L6 makes the full side the first side. Line L7 gives the other side the edge , which makes it a Laman graph too.
The solve. Line L8 draws a triangle. Lines L9 and L10 solve the rigid side first, because the length of a virtual edge is not a given value: it is measured on the solved rigid side. A real edge keeps its given length on both sides. Line L11 glues the two sides. The two placements agree on , so one rotation and one translation take and of the second side onto and of the first; the motion is proper, so it keeps the orientations that the triangles chose.
The sign. The draft enters only in line L8, through the orientation test of the three draft points. In floating point a nearly flat draft triangle can get the wrong sign by catastrophic cancellation, and the leaf is then mirrored. 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 flat draft triangle gives 0, and the rule "0 counts as +1" is a crude form of simulation of simplicity. A Laman graph that decomposes has leaves, so a vector of signs selects one of up to branches.
Example
Take the six points with the constraints : two triangles and , joined by bars and at point 0 and by the bar . The draft is , , , , , for the points 0 to 5, and the lengths are measured on it, with , , , , , , and . Its separation pairs are and . The decomposition makes three splits.
| part | pair | rigid side (first) | other side, with |
|---|---|---|---|
| , a real edge | , edges and | ||
| , not an edge | , after the swap | , edges and virtual | |
| , a real edge |
At the second split the component found first is , so line L6 first gets the side with only the two edges and , and it swaps the sides. The four leaves are solved in this order; the last column is the exact orientation of the draft points.
| leaf | squared sides , , | ORIENT | where the lengths come from |
|---|---|---|---|
| 36, 25, 25 | given | ||
| 26, 45, 17 | given | ||
| 17, 65, 20 | given; then glued at into | ||
| 36, 65, 17 | is measured on by line L10 |
Gluing at and then at gives the whole placement. The first leaf puts 0 at the origin and 1 at , as in the draft, so OWEN-SOLVE returns the draft itself. With other sign vectors, the measured length changes: if the leaves and put 0 and 5 on opposite sides of the line 34, then , the leaf violates the triangle inequality, and the branch has no real solution. So 8 of the 16 sign vectors give real placements.
The triangular prism, with the bars instead, is 3-connected: removing any two points leaves a connected graph. Line L4 fails at the root, although the prism is well-constrained for generic lengths. A triangle-decomposable graph is well-constrained, but a well-constrained graph need not be triangle-decomposable.
Correctness
The proof shows the following for a Laman graph .
- The split keeps Laman graphs. Each side has fewer points than the part. The side chosen first in line L6 is a Laman graph, and the other side becomes one when line L7 adds ; no set of its points that holds and can have the full count without , because together with the rigid side it would break the count of .
- The split lemma. is triangle-decomposable, in the sense of the Fudos-Hoffmann reduction, exactly when both sides are. For one direction, the merges of the second side, with the edge replaced by the rigid cluster of the first side, are merges of . For the other direction, intersect each cluster of with each side; the counts force the intersections to be clusters of the sides.
- Every decomposable part with 4 or more points has a separation pair. In the last merge of three clusters, one cluster has 3 or more points, and its two shared points cut it from the other two clusters.
- So the choice of pairs does not matter. By induction, OWEN-DECOMPOSE returns a tree, whatever separation pairs and components it picks, exactly when is triangle-decomposable. This is the theorem of Joan-Arinyo and his coauthors in the form for points and distances.
- The solution. Each part is placed so that its constraints hold, and the glue is exact. If the lengths come from the draft and no leaf triangle is flat in the draft, the result is the draft moved by a proper rigid motion. Every real solution that keeps the two points of each virtual edge apart comes from one sign vector.
Proof: Owen's decomposition splits a Laman graph down to triangles, for any choice of separation pairs, exactly when the graph is triangle-decomposable, and the solve gives every nondegenerate solutionfull
A part is a graph whose edges may include virtual edges; a virtual edge is an ordinary edge for all counts. For let be the set of edges with both ends in and . is sparse if for all with , and Laman if it is sparse and . A set with is rigid in if . is triangle-decomposable (TD) if the Fudos-Hoffmann reduction on ends with the single cluster ; by the confluence theorem of that reduction, this does not depend on the order of the merges. Line numbers refer to the pseudocode on the main page. Three facts are used often.
- (F1) A Laman graph with at least 3 points is 2-connected. If were a cut vertex, with , and no edge between and , then .
- (F2) In a sparse graph, if and are rigid and , then is rigid. Each edge inside or inside lies inside , and each edge inside both lies inside , so . Both terms on the left are at most their bounds, so both are equal to them.
- (F3) In a run of the reduction on a sparse graph, every cluster is rigid, its edge set is , and two clusters share at most one point (Lemma 1 of the reduction's proof).
Lemma 1 (one merge at the top). Let be Laman with . Then is TD if and only if , where , , with distinct, the sets , , partition , and each of , , is a single edge or TD.
Proof. If is TD, take the last merge of a run; by (F3) its three clusters have these properties. Conversely, the merges that reduce to one cluster are merges of , since validity depends only on the three clusters involved. Do them, then those of and . The edge sets partition , so the clusters , , are the whole state, and they form a valid triple. Merging them gives , and by confluence every run ends there.
Now fix a Laman part with and a separation pair , and let , , , be the sets of lines L5 to L7, after the swap of line L6. Write and , and let . The graph on has no edge between and , and both are nonempty.
Lemma 2 (the split keeps Laman graphs). and are Laman, , and , the set of all edges of inside . In particular, line L1 never fails on a part of a Laman graph.
Proof. with . Before the swap, line L6 puts in the first side all edges inside , the edge included if , and in the second side all other edges, which lie inside . Let . Sparsity of gives and , and if , then , so . Since ,
So exactly one side has . If , it is the first side, and there is no swap. If , line L6 swaps the sides when ; in both cases . So after line L6, , and is sparse as a subgraph of , so it is Laman. Line L7 gives the count . For sparsity, let with . If does not hold both and , its edges in are edges of , and . If it does, suppose . The edges of and of are distinct edges of inside , and , so
which contradicts sparsity of . So , and with the set has at most edges.
For , let be the set of edges of inside and . Write .
Lemma 3 (clusters meet the sides in rigid sets). Let be a cluster of a run of the reduction on , and let with . Then . Also, if meets both and , then .
Proof. For the last claim: an edge cluster cannot meet both, since no edge joins to . A larger cluster is rigid by (F3), so is Laman with at least 3 points and 2-connected by (F1). Every path from to in it passes through or . If missed one of them, the other would be a cut vertex of , or would not be connected.
Side 1: and are rigid in by Lemma 2 and (F3), so is rigid by (F2), and its edges in are those of because .
Side 2, in three cases. If , then . Its edges in are its edges in , except that the edge , if both its ends are in , is counted once in either graph. If and , then , which contradicts Lemma 2. Otherwise . If meets and , then , and is rigid with . Each edge inside lies inside or is an edge of inside , so , using . Adding gives . If meets but not , then , so with the one edge .
Lemma 4 (split lemma). is TD if and only if and are TD.
Proof. () Since , the merges that reduce to the cluster are merges of . Now replay a run of that ends in , with one change: a cluster of whose edge set holds becomes , with the edges of in place of . At each step at most one cluster holds , and it contains and . Any other cluster meets only inside , so . The pairwise intersections do not change, so every merge stays valid, and the run ends with .
() Take a run on that ends with . We show by induction over the order of formation: for each cluster and each side with , is a single edge or TD. For this gives the claim.
An edge cluster with is an edge of : either , or , which is in by line L7 and in when it is real.
Let be a merge with , , , and fix a side with . By induction, for with , is TD or an edge, so ; if , then .
(a) The sets , , are disjoint subsets of that miss at most one edge of it. An edge of inside is an edge of inside , so by (F3) it is inside exactly one of , , , and so inside one of , , . The only other edge is on side 2. Two of cannot both contain and , because the clusters share at most one point. Let if , and none of contains both; otherwise . Then
where the first equality is Lemma 3.
(b) If and , then . Otherwise lies in for the other side . Then holds and two points of ; either meets , and Lemma 3 gives , or with . Either way , and in the same way , so , a contradiction. The same holds for the other two pairs.
Let be the number of with .
- . By (b), , and , so , and (a) reads . So , the three edge sets partition , and Lemma 1 shows that is TD. It is Laman: its count is that of Lemma 3, and it is a subgraph of the sparse graph .
- , say . By (b), , and (a) gives . Since , this forces and . So , and and lie in with neither set holding both. Neither of them is , since lies in both sets; so, after renaming, and . Then , and the edge pairwise share , and , which are distinct, their edge sets partition , and Lemma 1 shows that is TD. The cases with another pair of clusters are the same.
- , say . (a) gives , so and , which is TD or an edge by induction.
- . (a) gives , so and : , a single edge.
Lemma 5 (a separation pair exists). A TD Laman graph with has a separation pair.
Proof. Take the three sets of Lemma 1. Since , one of them, say , has at least 3 points. Let and . An edge from to would lie inside or , so would lie in or , which is false. So no edge leaves , which is not empty, in the graph on , and this graph also holds . So is a separation pair.
Theorem 1 (the decomposition). For a Laman graph with points, OWEN-DECOMPOSE returns a tree, for every choice of separation pairs in line L3 and of components in line L5, if and only if is TD. A tree has leaves.
Proof. By induction on the number of points. A Laman graph with 3 points is a triangle, which is TD, and line L2 returns a leaf. Let . If is TD, Lemma 5 gives a separation pair, so line L3 finds one; by Lemma 2 both sides are smaller Laman graphs, by Lemma 4 both are TD, and by induction both calls return trees. If is not TD, either line L4 returns FAIL, or by Lemma 4 one side is not TD, its call returns FAIL by induction, and so does the whole call. Each split turns a part with edges into parts with edges in total, so the leaves have edges for splits, and for leaves; then gives .
Theorem 2 (the solve). Let be TD with positive lengths, and let OWEN-SOLVE run on its tree.
- If no leaf fails in line L8, the output satisfies every constraint.
- Let be a solution with for every virtual edge of the tree. With the sign of each leaf taken from , 0 counting as , no leaf fails, and the output is properly congruent to .
- If the lengths are measured on an integer draft and no leaf triangle is flat in , the output is properly congruent to . Every solution as in part 2 comes from one of the sign vectors.
Proof. A virtual edge made at a split lies only in the second side, so line L10 sets its length before any part that holds it is solved. By induction over the tree, each part is placed so that its edges hold with these lengths. A leaf holds its three lengths by line L8. At a split, satisfies ; satisfies and , with if is virtual and the given length, which also satisfies, if it is real. So , the proper motion of line L11 takes and exactly to and , and it keeps the distances in . The two sides share only and , so every edge of holds, which proves part 1.
For part 2, show by induction that each part is placed properly congruent to on its points. A leaf: the points , , have the leaf's lengths, which are positive since keeps the ends of virtual edges apart, so line L8 places and by a proper motion of , and of the two points at the right distances from them it takes the one on the side of the sign of ; if the triangle is flat, there is only one. A split: is properly congruent to on , so the measured length of a virtual is , the lengths of the second side are those of , and is properly congruent to on by induction. A proper motion is fixed by the images of two distinct points, so the motion of line L11 is the one that composes the two congruences, and the glued placement is properly congruent to on .
Part 3 is part 2 with , whose virtual edges have positive length since no leaf is flat, and whose signs line L8 computes exactly from the integer coordinates. A tree has leaves by Theorem 1.
Theorem 3 (running time). With a separation pair search that takes time linear in the size of a part, OWEN-DECOMPOSE and OWEN-SOLVE take time.
Proof. By Theorem 1 the tree has leaves and splits, and each part has at most points and edges, so the parts have points and edges in total. Lines L1 to L7 take time linear in the size of the part, given a linear-time pair search. Each leaf of OWEN-SOLVE costs , and each glue moves at most points.
Complexity
- The tree. A split of a part with points gives parts with points and one edge more in total. So a decomposition has leaves and splits, and every part has at most points: the parts have points and edges in total.
- The analysis. With a linear-time search for a separation pair, each part costs time linear in its size, and the decomposition takes time. This matches the quadratic bound in Owen's paper. The implementation finds a pair by runs of the articulation point search, per part, so it takes time.
- The solve. Each leaf is work with one square root. Each glue moves the points of the second side, at most , so the solve takes time.
- Space. The tree and its parts take space as stored here; storing each part only by its split pair and children brings this to .
Properties
- Exact analysis. The decomposition uses only the graph, so it holds for all values of the lengths.
- Same class as the bottom-up method. It decomposes exactly the triangle-decomposable graphs, the class of the Fudos-Hoffmann reduction.
- Quadratic equations only. Each leaf solves one quadratic equation over the field of the earlier values, so the solution is ruler-and-compass constructible, and the coordinates lie in an extension of degree at most .
- It stops at the right place. By the theorem of Owen and Power, a generic 3-connected Laman graph with more than 3 points has coordinates that are not solvable by radicals. So the parts where line L4 fails are, for generic lengths, exactly those that no method with square roots, or radicals of any order, can solve.
- Recursive. The two sides are independent once is known, so the recursion is natural, and the two sides of a split can be solved in parallel after the rigid side.
Variants and improvements
- All pairs at once. Owen computes the triconnected components of the graph in one pass with the algorithm of Hopcroft and Tarjan, and treats each component with its virtual edges as one part. The split at one pair at a time is the same idea, one cut per step.
- Points, lines, distances and angles. Owen's graphs have points and lines as vertices, each with 2 freedoms, and distances and angles as edges, each of weight 1. A part made only of lines with angles needs care, because angles fix only directions.
- Bottom-up form. The Fudos-Hoffmann reduction merges clusters from the leaves, and finds the same plan in the other direction.
- General parts. A DR-plan accepts any rigid part as a node, not only triangles, so a 3-connected part such as the prism becomes one node for a numerical or algebraic solver.
- Under-constrained sketches. When a sketch has too few constraints, the method can add virtual edges to complete it, which shows the user which dimensions are still free.
When to use it
- To analyze a planar sketch top-down, with the cut points visible, so that each part of the sketch is solved and changed separately.
- To get an exact solution by square roots and to choose it by the orientations of the draft.
- To check, in linear time per split, that a sketch can be solved by ruler and compass.
Do not use it alone for sketches with 3-connected parts, such as the prism or : pass these parts to a general solver inside a DR-plan. Do not use it in space, where two points do not fix a part.
Pitfalls
- Solving the wrong side first (line L6). If line L6 does not swap the sides, the side with one edge too few is solved first, and is not fixed there. In the example, at the pair the side has only and , so is free; the solver would measure a length that has nothing to do with the constraints.
- Forgetting the virtual edge (line L7). Without the second side has edges, line L1 rejects it, or a solver accepts a part that can still flex.
- The given length for a virtual edge (line L10). The length of a virtual edge must be measured on the solved rigid side. Taking it from the draft is wrong as soon as the dimensions differ from the draft, and the glue of line L11 then cannot match both and .
- A mirror in the glue (line L11). A motion that matches and but may reflect, such as a best-fit transform, can mirror the second side and destroy the orientations that its leaves chose. Use the rotation and translation fixed by the two points.
- The sign in floating point (line L8). A floating-point orientation of a nearly flat draft triangle can have the wrong sign and mirror a leaf. Compute it exactly.
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/owen-triconnected-decomposition/. The authors are listed in prov/AM42WY.jsonl.
"""Owen's top-down decomposition, for points and distances in the plane.
The constraint graph is split at a separation pair {a, b}. One side is rigid; the other
side gets a virtual edge ab and is rigid with it. Both sides are split again, until
every part is a triangle. The solver places the rigid side first, measures |ab| there,
places the other side with that length, and glues the two by a proper rigid motion.
"""
from math import sqrt
Edge = tuple[int, int]
# A node is ("tri", u, v, w) or ("split", a, b, rigid child, flexible child).
Node = tuple
def _key(u: int, v: int) -> Edge:
return (u, v) if u < v else (v, u)
def _articulation_points(verts: list[int], adj: dict[int, list[int]], skip: int) -> list[int]:
"""Articulation points of the graph on verts minus skip, by an iterative low-point DFS.
Raises ValueError if that graph is not connected. Cost O(n + m)."""
rest = [v for v in verts if v != skip]
root = rest[0]
disc = {root: 0}
low = {root: 0}
parent = {root: -1}
cut: set[int] = set()
root_children = 0
stack = [(root, iter(adj[root]))]
t = 1
while stack:
v, it = stack[-1]
advanced = False
for w in it:
if w == skip:
continue
if w not in disc:
disc[w] = low[w] = t
t += 1
parent[w] = v
if v == root:
root_children += 1
stack.append((w, iter(adj[w])))
advanced = True
break
if w != parent[v]:
low[v] = min(low[v], disc[w])
if advanced:
continue
stack.pop()
if stack:
u = stack[-1][0]
low[u] = min(low[u], low[v])
if u != root and low[v] >= disc[u]:
cut.add(u)
if len(disc) != len(rest):
raise ValueError("the constraint graph is not 2-connected, so it is not rigid")
if root_children >= 2:
cut.add(root)
return sorted(cut)
def separation_pair(verts: list[int], edges: set[Edge]) -> tuple[int, int] | None:
"""A pair {a, b} whose removal disconnects the graph, or None if there is none.
Precondition: the graph is 2-connected with at least 4 vertices. Cost O(n (n + m))."""
adj: dict[int, list[int]] = {v: [] for v in verts}
for u, v in sorted(edges):
adj[u].append(v)
adj[v].append(u)
for a in verts:
cut = _articulation_points(verts, adj, a)
if cut:
return (a, cut[0])
return None
def decompose(n: int, edges: list[Edge]) -> list[Node] | None:
"""Split the constraint graph (range(n), edges) at separation pairs, down to triangles.
Precondition: the graph is a Laman graph (2n - 3 edges, and every k >= 2 vertices
span at most 2k - 3 edges), n >= 3. Returns the list of nodes, root first, or None
if a part with four or more vertices has no separation pair (the method fails).
Raises ValueError if a count shows that the graph is not Laman.
Cost: O(n^3) here; O(n^2) with a linear-time triconnectivity algorithm.
"""
es = {_key(u, v) for u, v in edges}
if len(es) != len(edges) or any(u == v for u, v in edges):
raise ValueError("bad edges")
nodes: list[Node] = [()]
stack: list[tuple[int, list[int], set[Edge]]] = [(0, list(range(n)), es)]
while stack:
nid, verts, part = stack.pop()
k = len(verts)
if len(part) != 2 * k - 3: # @line L1
raise ValueError("a part has the wrong number of edges, so the graph is not Laman")
if k == 3: # @line L2
nodes[nid] = ("tri", *verts)
continue
pair = separation_pair(verts, part) # @line L3
if pair is None: # @line L4
return None
a, b = pair
inside = set(verts) - {a, b}
first = min(inside)
comp = {first}
todo = [first]
nbr: dict[int, list[int]] = {v: [] for v in verts}
for u, v in part:
nbr[u].append(v)
nbr[v].append(u)
while todo: # @line L5
v = todo.pop()
for w in nbr[v]:
if w in inside and w not in comp:
comp.add(w)
todo.append(w)
side1 = sorted(comp | {a, b})
side2 = sorted((inside - comp) | {a, b})
s1 = set(side1)
ab = _key(a, b)
e1 = {e for e in part if e[0] in s1 and e[1] in s1 and e != ab}
e2 = {e for e in part if e not in e1 and e != ab}
if ab in part: # @line L6
e1.add(ab)
elif len(e2) == 2 * len(side2) - 3:
side1, side2, e1, e2 = side2, side1, e2, e1
e2.add(ab) # @line L7
i1, i2 = len(nodes), len(nodes) + 1
nodes.extend(((), ()))
nodes[nid] = ("split", a, b, i1, i2)
stack.append((i2, side2, e2))
stack.append((i1, side1, e1))
return nodes
def is_decomposable(n: int, edges: list[Edge]) -> bool:
"""True if Owen's method splits the Laman graph down to triangles."""
if n == 2 and len(edges) == 1:
return True
return decompose(n, edges) is not None
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 _triangle(l_uv: float, l_uw: float, l_vw: float, side: int) -> tuple[complex, complex, complex]:
"""Place u at 0, v on the positive x axis, and w on the side given by the sign."""
if not (l_uv > 0.0 and l_uw > 0.0 and l_vw > 0.0):
raise ValueError("lengths must be positive")
x = (l_uv * l_uv + l_uw * l_uw - l_vw * l_vw) / (2.0 * l_uv)
h2 = l_uw * l_uw - x * x
if h2 < -1e-9 * max(l_uv, l_uw, l_vw) ** 2:
raise ValueError("no real solution: the triangle inequality fails")
h = sqrt(h2) if h2 > 0.0 else 0.0
return 0j, complex(l_uv, 0.0), complex(x, h if side > 0 else -h)
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 graph is a Laman graph that Owen's method splits into triangles,
and the lengths are positive. Triangle i, in the order the solver meets them, takes
signs[i] if given, else the exact orientation sign of its points in the integer
draft (0 counts as +1). Raises ValueError if the method fails or a triangle has no
real solution. Cost: the decomposition plus O(n^2) for the moves.
"""
if n == 2 and len(lengths) == 1:
((u, v), d), = lengths.items()
return [(0.0, 0.0), (d, 0.0)] if u == 0 else [(d, 0.0), (0.0, 0.0)]
length = {_key(u, v): d for (u, v), d in lengths.items()}
nodes = decompose(n, list(lengths))
if nodes is None:
raise ValueError("Owen's method fails: a part is 3-connected")
leaves = sum(1 for nd in nodes if nd[0] == "tri")
if signs is not None and len(signs) != leaves:
raise ValueError("one sign per triangle is needed")
placed: dict[int, dict[int, complex]] = {}
leaf = 0
stack: list[tuple[str, int]] = [("go", 0)]
while stack:
step, nid = stack.pop()
nd = nodes[nid]
if nd[0] == "tri": # @line L8
_, u, v, w = nd
if signs is not None:
side = signs[leaf]
elif draft is not None:
side = orient(draft[u], draft[v], draft[w]) or 1
else:
side = 1
leaf += 1
pu, pv, pw = _triangle(length[_key(u, v)], length[_key(u, w)], length[_key(v, w)], side)
placed[nid] = {u: pu, v: pv, w: pw}
continue
_, a, b, i1, i2 = nd
if step == "go": # @line L9
stack.append(("mid", nid))
stack.append(("go", i1))
elif step == "mid": # @line L10
r = placed[i1]
length.setdefault(_key(a, b), abs(r[a] - r[b]))
stack.append(("end", nid))
stack.append(("go", i2))
else: # @line L11
r, f = placed.pop(i1), placed.pop(i2)
z = (r[b] - r[a]) / (f[b] - f[a])
z /= abs(z)
glued = dict(r)
for v, x in f.items():
glued.setdefault(v, r[a] + z * (x - f[a]))
placed[nid] = glued
final = placed[0]
return [(final[v].real, final[v].imag) for v in range(n)]
test_owen_triconnected_decomposition.py 280 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/owen-triconnected-decomposition/. The authors are listed in prov/AM42WY.jsonl.
import random
from functools import lru_cache
from itertools import combinations
from math import sqrt
import pytest
from owen_triconnected_decomposition import decompose, is_decomposable, orient, separation_pair, 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 laman(n: int, edges: list[Edge]) -> bool:
"""Brute force: 2n - 3 edges, and every k >= 2 vertices span at most 2k - 3 edges."""
if len(edges) != 2 * n - 3:
return False
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 components(verts: frozenset[int], edges: frozenset[Edge]) -> list[frozenset[int]]:
left = set(verts)
out = []
while left:
start = left.pop()
comp = {start}
todo = [start]
while todo:
v = todo.pop()
for u, w in edges:
for x, y in ((u, w), (w, u)):
if x == v and y in left:
left.discard(y)
comp.add(y)
todo.append(y)
out.append(frozenset(comp))
return out
def brute_pairs(verts: frozenset[int], edges: frozenset[Edge]) -> list[tuple[int, int]]:
"""Every pair whose removal disconnects the graph, by a search on each pair."""
out = []
for a, b in combinations(sorted(verts), 2):
rest = verts - {a, b}
inner = frozenset(e for e in edges if e[0] in rest and e[1] in rest)
if len(components(rest, inner)) >= 2:
out.append((a, b))
return out
@lru_cache(maxsize=None)
def outcomes(verts: frozenset[int], edges: frozenset[Edge]) -> frozenset[bool]:
"""Brute force over every choice of separation pair and of the grouping of the
pieces: the set of results (split to triangles or stuck) that the choices reach."""
k = len(verts)
if len(edges) != 2 * k - 3:
return frozenset([False])
if k == 3:
return frozenset([True])
res: set[bool] = set()
pairs = brute_pairs(verts, edges)
if not pairs:
return frozenset([False])
for a, b in pairs:
ab = (min(a, b), max(a, b))
rest = verts - {a, b}
inner = frozenset(e for e in edges if e[0] in rest and e[1] in rest)
comps = components(rest, inner)
for r in range(1, len(comps)):
for group in combinations(comps, r):
s1 = frozenset().union(*group) | {a, b}
s2 = (rest - s1) | {a, b}
e1 = frozenset(e for e in edges if e[0] in s1 and e[1] in s1 and e != ab)
e2 = frozenset(e for e in edges if e not in e1 and e != ab)
if ab in edges:
e1 = e1 | {ab}
elif len(e2) == 2 * len(s2) - 3:
s1, s2, e1, e2 = s2, s1, e2, e1
e2 = e2 | {ab}
o1, o2 = outcomes(s1, e1), outcomes(s2, e2)
for x in o1:
for y in o2:
res.add(x and y)
return frozenset(res)
def triangle_closure(n: int, edges: list[Edge]) -> bool:
"""Independent oracle by the bottom-up definition: the set R of vertex sets that are
built from edges by gluing three members of R that pairwise share one point, at three
different points. The graph is decomposable when the full set is in R."""
r = {1 << u | 1 << v for u, v in edges}
full = (1 << n) - 1
grew = True
while grew and full not in r:
grew = False
items = sorted(r)
for i, x in enumerate(items):
for j in range(i + 1, len(items)):
y = items[j]
xy = x & y
if bin(xy).count("1") != 1:
continue
for z in items[j + 1:]:
xz, yz = x & z, y & z
if bin(xz).count("1") == 1 and bin(yz).count("1") == 1 and len({xy, xz, yz}) == 3:
u = x | y | z
if u not in r:
r.add(u)
grew = True
return full in r
def henneberg(n: int, rng: random.Random, type2: float) -> list[Edge]:
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:
"""Pairwise distances and signed areas agree with the draft, within 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 leaves(nodes: list) -> list[tuple[int, int, int]]:
return [nd[1:] for nd in nodes if nd[0] == "tri"]
def test_example() -> None:
nodes = decompose(6, EXAMPLE_EDGES)
assert nodes is not None
assert nodes[0][:3] == ("split", 0, 1)
assert len(leaves(nodes)) == 4
lengths = lengths_of(EXAMPLE_DRAFT, EXAMPLE_EDGES)
pts = solve(6, lengths, EXAMPLE_DRAFT)
check_solution(pts, lengths)
check_congruent(pts, EXAMPLE_DRAFT)
def test_edge_cases() -> None:
assert is_decomposable(2, [(0, 1)])
assert is_decomposable(3, [(0, 1), (1, 2), (0, 2)])
assert decompose(6, PRISM) is None
assert decompose(6, K33) is None
with pytest.raises(ValueError):
decompose(4, list(combinations(range(4), 2)))
with pytest.raises(ValueError):
solve(3, {(0, 1): 1.0, (1, 2): 1.0, (0, 2): 3.0})
with pytest.raises(ValueError):
solve(6, lengths_of(EXAMPLE_DRAFT, PRISM))
def test_separation_pairs_against_search() -> None:
rng = random.Random(3)
for _ in range(300):
n = rng.randint(4, 9)
edges = henneberg(n, rng, 0.4)
verts = list(range(n))
es = {(min(u, v), max(u, v)) for u, v in edges}
got = separation_pair(verts, es)
brute = brute_pairs(frozenset(verts), frozenset(es))
if got is None:
assert brute == []
else:
assert (min(got), max(got)) in brute
def test_all_laman_graphs_up_to_six_points() -> None:
"""On every Laman graph with n <= 6: every choice of pairs gives the same result, the
method agrees with it, and with the bottom-up triangle closure. On six points the
graphs that are not decomposable are the 10 labelings of K33 and the 60 of the prism."""
total = 0
counts = {True: 0, False: 0}
for n in range(3, 7):
pairs = list(combinations(range(n), 2))
for chosen in combinations(range(len(pairs)), 2 * n - 3):
edges = [pairs[i] for i in chosen]
if not laman(n, edges):
continue
total += 1
res = outcomes(frozenset(range(n)), frozenset(edges))
assert len(res) == 1
(truth,) = res
assert is_decomposable(n, edges) == truth
assert triangle_closure(n, edges) == truth
counts[truth] += 1
assert total == 1 + 6 + 100 + 3355
assert counts[False] == 70
def test_random_graphs_against_oracles() -> None:
"""500 random Laman graphs with 4 to 9 points: decomposable exactly when the closure
says so; then the solution meets every constraint and matches the draft."""
rng = random.Random(99)
seen = {True: 0, False: 0}
for _ in range(500):
n = rng.randint(4, 9)
edges = henneberg(n, rng, 0.5)
rng.shuffle(edges)
truth = triangle_closure(n, edges)
seen[truth] += 1
nodes = decompose(n, edges)
assert (nodes is not None) == truth
if n <= 7:
es = frozenset((min(u, v), max(u, v)) for u, v in edges)
assert outcomes(frozenset(range(n)), es) == frozenset([truth])
if nodes is None:
continue
assert len(leaves(nodes)) == n - 2
draft = random_draft(n, rng)
lengths = lengths_of(draft, edges)
pts = solve(n, lengths, draft)
check_solution(pts, lengths)
check_congruent(pts, draft)
assert seen[True] > 100 and seen[False] > 10
def test_every_root_of_a_triangle_strip() -> None:
rng = random.Random(8)
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)
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
Owen presented the method in 1991, at the first ACM Symposium on Solid Modeling Foundations and CAD/CAM Applications, as an algebraic method to place geometry from given distances and angles. He used the triconnected components algorithm that Hopcroft and Tarjan had published in 1973, and he showed that the decomposed systems need only quadratic equations, with a solution in an extension of degree a power of 2. The bottom-up method of Bouma, Fudos and Hoffmann followed a few years later, and in 2002 Joan-Arinyo, Soto-Riera, Vila-Marta and Vilaplana-Pastó proved that the two methods decompose the same class of graphs. Owen and Power proved in 2007 that the 3-connected parts where the method stops are, for generic lengths, not solvable by radicals.
References
- John C. Owen, Algebraic solution for geometry from dimensional constraints, ACM Symposium on Solid Modeling Foundations and CAD/CAM Applications (SMA '91), 397 to 407, 1991, the decomposition of the constraint graph at separation pairs with virtual edges, the use of the triconnected components algorithm, the solution by quadratic equations and the quadratic running time (general locator)
- John E. Hopcroft and Robert E. Tarjan, Dividing a graph into triconnected components, SIAM Journal on Computing 2(3), 135 to 158, 1973, the linear-time algorithm for separation pairs and triconnected components, with virtual edges (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 Owen's top-down analysis and the bottom-up reduction of Fudos and Hoffmann decompose the same class of graphs (general locator)
- Robert Joan-Arinyo, Antoni Soto-Riera, Sebastià Vila-Marta and Josep Vilaplana-Pastó, Revisiting decomposition analysis of geometric constraint graphs, Computer-Aided Design 36(2), 123 to 140, 2004, the journal version of the comparison of the top-down and bottom-up analyses (general locator)
- J. C. Owen and S. C. Power, The non-solvability by radicals of generic 3-connected planar Laman graphs, Transactions of the American Mathematical Society 359(5), 2269 to 2303, 2007, the main theorem, which shows that the 3-connected parts where the method stops need more than square roots (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 AM42WY Edit this page History Report an error Markdown