Algorithmresearch
Frontier vertex algorithm
Also called Hoffmann-Lomonosov-Sitharam frontier algorithm.
Builds a DR-plan of a constraint graph by finding minimal dense clusters with network flow and collapsing each to its frontier vertices, step by step.
- Time
- O(m^5 (n + m)^2) worstΘ(n + m) best
- Space
- Θ(n + m) extra
- Where
- m = the number of constraints; n = the number of entities
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Christoph M. Hoffmann, Andrew Lomonosov, Meera Sitharam, 2001
The Frontier vertex algorithm of Hoffmann, Lomonosov and Sitharam builds a DR-plan for a weighted constraint graph. It starts with every constraint as a small cluster. Then it repeats one step: find a smallest set of clusters and entities that is dense, that is, has no more degrees of freedom than one rigid body, by the network flows of degrees of freedom analysis; record that set as a new cluster with the old clusters as its children; and replace the new cluster in the graph by its frontier vertices, the entities that still have constraints to the outside, tied to one new core vertex. Keeping the frontier vertices is what lets two clusters share an entity, which the older planners that contract a cluster to one node get wrong. For points and distances in the plane, every cluster it finds is rigid and the roots of the plan are the rigid components of the graph.
In plain words
A drawing has many points and many rules between them. Some groups of points are fixed in shape by their own rules. The method finds such a group, the smallest one it can, and writes it down as one stiff piece. Then it simplifies the drawing: the inside of the piece is replaced by one block, but the points of the piece that touch other rules stay, so other pieces can still use them. On the simpler drawing it looks for the next small stiff group, which may now contain whole pieces, and so on. When no stiff group is left, the record of which piece was built from which smaller pieces is a plan for the solver: solve the small pieces first, then put them together.
The problem
The input is a constraint graph in the sense of the constraint graph page. Each entity has a weight , its degrees of freedom, and each constraint has a weight , the number of equations it adds. is the number of degrees of freedom of a rigid body: 3 in the plane and 6 in space. For a set of entities, let be the constraints with all their entities in , and let the density be
This page calls dense when , as Hoffmann, Lomonosov and Sitharam do. (The DR-plan page calls such a set rigid, and the constraint graph page keeps "dense" for .) The main case is points and distances in the plane: , and , so and the counts are those of Laman's theorem.
The output is a DR-plan: a list of clusters, each with its vertex set , its children (earlier clusters), its leaves (entities of in no child), its frontier and its density in . Each cluster is the union of its children and leaves, and the roots are the clusters that are no one's child, together with the entities in no constraint. A set with is rigid when is generically rigid in the plane, and the rigid components of are the maximal rigid sets.
The algorithm
The algorithm works on a simplified graph . Its nodes are points, the entities that are still present, and cores, one for each cluster that is not yet a child of another one. A cluster with frontier is shown in as its core , of weight , with an edge of weight to each . The rest of is gone from . The core, its frontier and these edges have density when all frontier weights are equal, so they look like one rigid body, which is what the cluster is.
A set of nodes of is closed when it holds the whole frontier of each core in it, and a target is a closed set that is dense and holds at least two cores. A target that holds two cores and no shared point would have density at most , so every target holds two cores and that share a point, a candidate pair. Given and , a set of largest density with is a maximum-weight closure: an edge of is a profit that needs both its ends, and a node is a cost . One minimum cut finds it.
FRONTIER(V, E, w, D)- 1
for each constraint uv of E, unless uv already lies inside a cluster do - 2
SIMPLIFY({u, v}) ▷ each constraint starts as a cluster - 3
repeat - 4
for each candidate pair {a, b} of S do - 5
Z ← MAX-CLOSURE(S, {a, b}); if ρ(Z) ≥ -D then X ← Z plus the frontier of each core in Z; leave the for - 6
if no pair gave a dense set then leave the repeat - 7
while some core c of X has a target inside X ∖ {c} do - 8
search X ∖ {c}, without the points that touch no other core of X, as in lines L4 and L5 - 9
X ← the target found - 10
SIMPLIFY(X): U ← the union of the vertex sets of the nodes of X - 11
add to X every core whose cluster lies inside U; their clusters are the children - 12
F ← the points of X with a neighbor outside X ▷ the frontier - 13
delete from S the nodes of X that are not in F, and the edges inside X - 14
add a core c of weight D, and an edge cf of weight w(f) for each f ∈ F - 15
record the cluster U with its children, leaves, frontier F and density ρ(U) in G - 16
return the clusters
Line L1 skips a repeated constraint, which the first copy has made a cluster. After lines L1 and L2, every edge of joins a core to a point. Line L5 adds the frontier of each core of , which keeps the set closed and never lowers its density, since a point with cores costs and brings . Lines L7 to L9 make the target minimal: they drop one core at a time, and the points that no other core touches, and look again. They drop cores and not points, because a set without a frontier point of one of its cores is not closed. Line L11 also absorbs clusters that the new set swallows whole, so that no cluster lies inside another one. Line L15 records the density in , not in : the simplified graph has lost the extra constraints inside each cluster.
Example
Take the triangular prism: points 0 to 5, the triangles 012 and 345, and the bars 03, 14 and 25. It has constraints and it is a Laman graph, so it is rigid. Every point has three constraints.
| step | target found | cores in it | density in | new cluster | frontier |
|---|---|---|---|---|---|
| L1, L2 | each bar | none | 9 clusters of two points | both ends | |
| 1 | 3 | ||||
| 2 | 3 | ||||
| 3 | all of | 5 | none |
The densities in use the count of the proofs page: a closed set with cores has density , where is the number of its cores at the point . In step 1 the first candidate pair is , which share the point 0, and the largest closure that holds them is the triangle. No smaller target exists: without , the set has density . The triangle keeps all three points, because each of them has a bar to the other triangle. In step 3 the simplified graph has the cores and of the triangles and the cores of the three bars, and every point lies in two cores. A proper closed part, such as with the bar 03, has density . So the last cluster has five children: two triangles and three bars. This is the step that the triangle merges of Fudos and Hoffmann cannot make, since no three of the clusters pairwise share a point. The solver must place the two triangles against each other with all three bars at once.
The frontier matters in the graph with triangles 012 and 345 and the bars 03, 04 and 15. When becomes a cluster, the point 0 stays on its frontier, since it has the bars 03 and 04. So the triangle 034 is still visible, and after the algorithm finds the cluster , made of the bars 03 and 04 and the triangle 345. A planner that contracts to one node no longer sees that 03 and 04 meet at one point (see the pitfalls of the DR-plan page).
Correctness
The proof shows the following for the algorithm above.
- The plan. Each cluster is the union of its children and leaves, each child is a proper subset made earlier, each cluster is a child at most once, every constraint lies in a root, and the roots cover . The main loop stops after at most steps. This holds for any positive weights.
- Finding and shrinking. A frontier vertex shared by two live clusters is never deleted, so shared entities stay visible. The search of lines L4 and L5 finds a target whenever there is one, and lines L7 to L9 return a target with no proper closed subset that is a target. This also holds for any positive weights.
- Rigidity in the plane. For points and distances in the plane, every cluster is generically rigid, and when the algorithm stops, the roots with two or more points are exactly the rigid components of . The proof uses Laman's theorem and the fact that the rigidity rank of a graph is the sum of over its rigid components.
The rigidity claims need the plane and the weights 2, 1 and 3. In space, with , and , the double banana has with no smaller dense part, so the algorithm makes it a cluster, but it is not rigid.
What is measured: the tests on this page check by brute force over all vertex subsets that every cluster is rigid by the Laman count, that the plan has the structure above, and that the roots are the rigid components, on random graphs with at most 7 points, together with the prism, , two triangles that share a point and the graph with the shared point 0. A further run on 400 random graphs with 2 to 7 points found no failure.
Proof: The Frontier algorithm builds a DR-plan whose clusters are rigid in the plane and whose roots are the rigid componentsfull
Line numbers refer to the pseudocode on the main page. has entities and distinct constraints; a repeated constraint is skipped in line L1, so we assume there is none. During the run, is the simplified graph. Its points are the entities still in , and its cores are the cores of the live clusters, those that are not yet a child. For a core , is the vertex set of its cluster and is the set of points joined to . For a point , . A set of nodes of is closed if for every core , and .
Lemmas 1 to 3 and Theorem 5 hold for any positive weights. Lemma 4 and Theorems 6 and 7 are for points and distances in the plane: , , . There, a set with is rigid when has rank in the generic rigidity matroid of the plane, that is, when the framework is infinitesimally rigid at a generic placement, and a rigid component is a maximal rigid set.
Lemma 1 (invariants). After each call of SIMPLIFY, for all live cores :
- a point is joined to if and only if , and every edge of that is not between two points joins a core to a point;
- if , then is a point of , so ;
- .
Moreover, no core is ever in a frontier, and after lines L1 and L2 no edge joins two points.
Proof. At the start there are no cores. Consider a call SIMPLIFY(), where is closed: in line L2, has no core, and in line L10, is closed by Lemma 2 and Lemma 3 below. Assume the claims before the call.
First, every point lies in . Either , or for a core ; then is joined to by claim 1, and since is closed. Let be with the cores added in line L11. For such an added core , consists of points of , so . Hence no core of has a neighbor outside , and no core is in the frontier of line L12.
Claim 2. Let be a live core that stays live, so and . Let . Then for some . If is a point, is joined to by claim 1. If is a core, is a point joined to by claim 2. In both cases is a point in with the neighbor , so : it stays a point and is joined to the new core and to .
Claim 1. The new core is joined exactly to . A point of in lies in , as shown, so after line L13 it is in or deleted; hence the points of left in are exactly . For an old core that stays live, a point deleted in line L13 had no neighbor outside , so it was not joined to , and by claim 1 it was not in . So the equivalence still holds for .
Claim 3. Before the call the live sets form an antichain. If for a live that stays live, then for each core , which is false; and if has no core, and would contain the constraint , which line L1 excludes. All live clusters inside are absorbed in line L11. So the antichain is kept.
Line L13 deletes the edges inside , so after line L2 for the edge is gone, and after lines L1 and L2 no edge joins two points.
After lines L1 and L2, every edge of joins a core to a point and has weight . For a closed set with cores and points , let be the number of cores of joined to . Then
For points and distances in the plane this reads . A target is a closed set with and .
Lemma 2 (the search finds targets). Let be a closed set of nodes, after lines L1 and L2. The search of lines L4 and L5 on returns only targets inside , each point of which is joined to a core of it. If contains a target, the search returns one.
Proof. MAX-CLOSURE(, ) is a maximum-weight closure in the network with a node for each edge of inside , of profit , that needs both its ends, and a node for each of cost , with and forced. By Picard's reduction, see maximum-weight closure, the source side of a minimum cut gives a set with and the largest . A point is on the source side only if an edge node that reaches it is, and then the other end of , a core, is too, since the arcs from have infinite capacity. So every point of is joined to a core of . Line L5 then adds for each core ; these points lie in since is closed, and each of them costs and brings with , so the density does not drop. The result is closed, holds the two cores and , and is a target if line L5 accepts it.
Let be a target with cores . If no point of were joined to two cores of , then by (1) . So two cores share a point, and is a candidate pair of . Since is a feasible set for MAX-CLOSURE(, ), that call returns a set of density at least , and line L5 accepts it. The search tries every candidate pair, so it returns a target.
Lemma 3 (minimal targets). Lines L7 to L9 end with a target such that no closed set is a target.
Proof. is a target when line L7 is reached, by Lemma 2, and line L9 replaces it by a target. For a core , let be without the points that are joined to no other core of . is closed, since every other core of keeps its frontier. A target found in lacks , so each change makes smaller, and the loop ends. At the end, by Lemma 2, no contains a target. Now let be a closed target. Every point of is joined to a core of (Lemma 2, and line L5 adds only frontier points), so if held every core of , it would hold every point too, and . So misses a core . Drop from the points joined to no core of : by (1) this raises the density by their weights and keeps closed, so the result is still a target. It lies in , which is a contradiction.
Lemma 4 (every core has two frontier points). For points and distances in the plane, let be the target of Lemma 3, with cores , . Then for every .
Proof. Suppose . If , at most one point lies on both cores, so by (1) , and is not a target. If , let be without and without the points joined only to . is closed and has cores. In (1), dropping adds 3, the point of , if there is one, loses at most 2, and the dropped points had the term 0. So , and is a target, against Lemma 3.
Theorem 5 (the plan). For any positive weights:
- each cluster is the union of its children and its leaves;
- each child is a proper subset of its parent and was made earlier;
- each cluster is a child of at most one cluster;
- the main loop stops after at most steps, so there are at most clusters;
- every constraint lies in a root, and the roots cover .
Proof. (1) The leaves are defined in line L15 as the entities of in no child. (2) A child is a live cluster inside before the call. A cluster of line L2 has no child, since a live cluster inside would be an earlier copy of , and its leaves are single entities. In line L10, holds at least two cores whose sets form an antichain (Lemma 1), so no child equals , and every point of lies in the set of a core of , so there are no leaves. (3) Line L13 deletes every core of , so a cluster stops being live when it becomes a child. (4) After lines L1 and L2 there are at most live clusters, and each step absorbs at least two and adds one. (5) Each constraint is in the cluster of line L2 for it or for its first copy. Follow the parent of that cluster, which is unique by (3); the sets grow along the way, and at the end the chain stops at a live cluster, which is a root. Line L16 lists as roots the live clusters and the entities in no constraint, so the roots cover .
For the rest, the weights are those of points and distances in the plane, and all frameworks are at one generic placement of . We use three facts about rigidity in the plane.
- (R1) If and are rigid and share at least two vertices, then is rigid with the edges . An infinitesimal motion is trivial on and on , and a trivial motion of the plane is fixed by its values at two distinct points, so the two agree.
- (R2) Every edge lies in exactly one rigid component, and two rigid components share at most one vertex. An edge is rigid, so it lies in a maximal rigid set; by (R1) two rigid components that share two vertices would have a rigid union.
- (R3) For a multigraph with rigid components , the rank of is . Take a basis of the edges inside each , so . The are disjoint by (R2), and their union spans , since each edge of lies in some and so in the closure of . So it is enough that the union is independent. If held a circuit , then minus any edge would be independent with edges, so is rigid by Laman's theorem and lies in one component ; then , which is impossible.
Theorem 6 (clusters are rigid). For points and distances in the plane, the vertex set of every cluster is rigid. Hence the recorded density is at least .
Proof. By induction on the order of the clusters. A cluster of line L2 is one constraint, which is rigid. Let the cluster come from the target of Lemma 3, with cores , , and points . Each with is rigid by induction, , and by Lemma 4. A vertex that lies in two of the sets is a point of in both frontiers, by Lemma 1. For each , let be a minimally rigid graph on , with edges, and let be the multigraph on that is the union of the .
If is rigid, is rigid. Let be an infinitesimal motion of the framework on with the edges . On each it is trivial, since is rigid. So on it keeps the length of each edge of each to first order, and as is rigid, agrees on with one trivial motion . On each , is a trivial motion that agrees with on the two or more points of , so it is . Every vertex of lies in some , so on . Thus the rank of is .
is rigid. Let be the rigid components of . Each spans the rigid graph , so by (R2) it lies in exactly one component; let be the cores with . An edge of lies in the component of , so the edges of inside are the edges of the with , and as every vertex of a rigid set with two or more vertices has an edge in it, . So is closed, and by (1),
since the number of edges of inside is at least their rank, . If some has two or more cores, is a target inside , so by Lemma 3, , and is rigid. Otherwise every has one core, and by (R3)
so is rigid. Finally, rigid means .
Theorem 7 (roots are the rigid components). For points and distances in the plane, when the algorithm stops, the live clusters are exactly the rigid components of . So the roots with two or more entities are the rigid components.
Proof. The algorithm stops when the search of lines L4 and L5 on all of , a closed set, finds nothing, so by Lemma 2 holds no target. Let be a rigid component, and let be the live cores with . For such , is rigid (Theorem 6), so is rigid by (R1), and as is maximal. Each edge of lies in a live cluster (Theorem 5), which then meets in two vertices, so the edges of are exactly .
Suppose . Consider the tuples of trivial motions that agree on every vertex lying in two or more of the sets . Each tuple gives an infinitesimal motion of , since every edge lies in some , and different tuples give different motions. is rigid, so these tuples form a space of dimension at most 3. A vertex in of the sets is a point in their frontiers (Lemma 1), and the agreement there is linear equations, so the dimension is at least . Let be with all their frontiers. is closed, and by Lemma 1, is the number of sets , , that contain . By (1),
so is a target in , a contradiction. Hence ; as every vertex of has an edge in , for the one core . So every rigid component is a live cluster. Conversely, a live cluster is rigid, so it lies in a rigid component, which is a live cluster; by the antichain of Lemma 1 the two are the same.
Running time. The number of edges between cores and points never grows: the new core gets one edge for each point of , and each point of had an edge to a core of , which line L13 deletes. So after lines L1 and L2, has at most nodes and edges. One MAX-CLOSURE runs a maximum flow on a network with nodes and arcs, and the flow value is at most the total weight ; each augmenting path carries at least one unit and is found by breadth-first search in , so one call costs . Two cores share a point in at most ways, so one search makes calls. Lines L7 to L9 make at most rounds, since each round removes a core, of at most searches each, and the main loop runs at most times (Theorem 5). The total is .
Complexity
Let be the size of . The number of core-point edges never grows: a new core gets at most one edge for each point of , and each such point had an edge to a core of , which is deleted. So has at most nodes and edges, and . One MAX-CLOSURE is a maximum flow in a network with nodes and arcs, and the flow is at most ; with augmenting paths of Edmonds and Karp and the weights 2, 1 and 3, each path carries at least one unit, so one flow costs . There are candidate pairs, since two cores share a point in at most ways. Lines L7 to L9 make at most rounds, each of at most searches. The main loop runs at most times. That gives flows and time, a crude bound for this simple version, in which each flow starts from zero. The flow test of degrees of freedom analysis, which adds the constraints one at a time and keeps the flow, is faster. In the best case no two constraints share an entity: there are no candidate pairs and the work is , with an index from points to clusters for line L11. The Python code scans all clusters in line L11 and needs for this case. Space is for , the network and the plan.
As a measured point, the Python code takes about 2 seconds on a random graph with 20 points and 69 constraints.
Properties
- Deterministic and exact. All weights are integers and the flows are integer flows, so the densities are exact. The order of the candidate pairs fixes which plan comes out.
- Bottom-up and not unique. A graph can have many DR-plans. The plan depends on which target is found first, and the largest cluster size, the cost of the plan, can depend on that order.
- Shared entities. A point in two live clusters is on the frontier of both, and it stays in until a cluster swallows both of them.
- Counts only. The algorithm sees the graph and the weights, not the geometry. Dependent or special constraints, such as three collinear points, are not seen.
Variants and improvements
- MFA. Hoffmann, Lomonosov and Sitharam also gave a modified Frontier algorithm, which changes how a cluster is found so that the plan stays closer to an optimal one more often (Part II).
- Incremental flows. The flow test of degrees of freedom analysis adds the constraints one at a time and detects a dense set when the extra units of the new constraint cannot be pushed. It reuses the flow and is faster than a fresh flow for each pair.
- Canonical DR-plans. For systems that are not over-constrained, Baker, Sitharam, Wang and Willoughby give canonical DR-plans and a polynomial algorithm that finds an optimal one, while optimal DR-planning is NP-hard in general.
- The pebble game. For points and distances in the plane, the pebble game finds the rigid components in time. It gives the roots of the plan but not the plan below them.
- Witness checks. A cluster that is dense by the count can still be flexible in space, or at special positions. A rank test at a random witness configuration can confirm each cluster.
When to use it
Use it when a constraint system must be solved in small pieces and the pieces can share entities, as in large 2D sketches and in assemblies of parts. It handles any weights, so it plans for points, lines, circles and rigid bodies with constraints of any number of equations. In the plane with points and distances its clusters are rigid. In space, or with special geometry, the counts can lie, and each cluster needs a check. If only the rigid components are needed, the pebble game is faster. If the whole system can be built by merging three clusters at a time, the triangle merges of Fudos and Hoffmann are simpler.
Pitfalls
- Contracting a cluster to one node. It hides shared entities, and the planner then misses clusters such as the triangle 034 of the example. Keep the frontier vertices.
- Shrinking by points. If the minimal step drops a frontier point of a core, the set is no longer closed and the core stands for points that are not there. The new frontier can then hold a core. Drop cores, and with them the points that no other core touches.
- The density in the simplified graph. In every cluster counts as exactly . For with points and distances the last target has density in , but in : one constraint is redundant. Compute the density of a cluster in .
- A single point is dense. With and , one point has . Ask for at least two cores, or two entities, in every target.
- Dense is not rigid in space. The double banana passes the count in space and is flexible. In the plane the counts are exact only for generic points and distances; other constraints, such as angles, break Laman's theorem.
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/frontier-vertex-algorithm/. The authors are listed in prov/HMKXPX.jsonl.
"""The Frontier vertex algorithm for a DR-plan of a weighted constraint graph.
Entities are the vertices 0..n-1, each with weight vertex_weight (its degrees of freedom), and constraints are the
edges, each with weight edge_weight. A set X is dense when rho(X) = w(E(X)) - w(X) >= -D. The default weights are
points and distances in the plane: 2, 1 and D = 3.
The planner first makes every constraint a cluster. Then it repeats: find a minimal dense set X of the simplified
graph that does not lie inside one cluster, by maximum closure computations with network flow; record the cluster
that X stands for; and simplify, which keeps the frontier vertices of the cluster (those with constraints to the
outside) and replaces the rest by one core vertex of weight D joined to each frontier vertex f by an edge of
weight w(f)."""
from collections import deque
from typing import Optional, Sequence
Edge = tuple[int, int]
BIG = 1 << 60
def max_flow(cap: list[dict[int, int]], s: int, t: int) -> int:
"""Edmonds-Karp on a residual graph given as a list of dicts; cap is changed into the residual graph."""
flow = 0
while True:
parent = {s: s}
queue = deque([s])
while queue and t not in parent:
x = queue.popleft()
for y, c in cap[x].items():
if c > 0 and y not in parent:
parent[y] = x
queue.append(y)
if t not in parent:
return flow
push, y = BIG, t
while y != s:
push = min(push, cap[parent[y]][y])
y = parent[y]
y = t
while y != s:
x = parent[y]
cap[x][y] -= push
cap[y][x] = cap[y].get(x, 0) + push
y = x
flow += push
class FrontierPlanner:
def __init__(self, n: int, edges: Sequence[Edge], vertex_weight: int = 2, edge_weight: int = 1,
D: int = 3) -> None:
self.n, self.D = n, D
self.vertex_weight, self.edge_weight = vertex_weight, edge_weight
self.w: dict[int, int] = {v: vertex_weight for v in range(n)}
self.adj: dict[int, dict[int, int]] = {v: {} for v in range(n)}
for u, v in edges:
if u == v:
raise ValueError("loop")
self.adj[u][v] = self.adj[u].get(v, 0) + edge_weight
self.adj[v][u] = self.adj[v].get(u, 0) + edge_weight
self.edges = list(edges)
self.clusters: list[dict] = []
self.core_of: dict[int, int] = {}
self.next_id = n
# ----- the simplified graph -----
def orig(self, x: int) -> frozenset:
return frozenset([x]) if x < self.n else self.clusters[self.core_of[x]]["vertices"]
def density(self, X: set) -> int:
inside = sum(wt for x in X for y, wt in self.adj[x].items() if y in X) // 2
return inside - sum(self.w[x] for x in X)
def close(self, Z: set, Y: set) -> set:
"""Add the frontier of every core in Z; this never lowers the density."""
Z = set(Z)
for c in [x for x in Z if x >= self.n]:
Z |= {f for f in self.adj[c] if f in Y}
return Z
def max_closure(self, Y: set, T: set) -> tuple[int, set]:
"""The largest density of a set Z with T <= Z <= Y, and such a set, by one minimum cut."""
ys = sorted(Y)
idx = {x: i + 2 for i, x in enumerate(ys)}
es = [(x, y, wt) for x in ys for y, wt in self.adj[x].items() if y in Y and x < y]
cap: list[dict[int, int]] = [dict() for _ in range(2 + len(ys) + len(es))]
for k, (x, y, wt) in enumerate(es):
e = 2 + len(ys) + k
cap[0][e] = wt
cap[e][idx[x]] = BIG
cap[e][idx[y]] = BIG
for x in ys:
if x not in T:
cap[idx[x]][1] = self.w[x]
f = max_flow(cap, 0, 1)
seen, queue = {0}, deque([0])
while queue:
a = queue.popleft()
for b, c in cap[a].items():
if c > 0 and b not in seen:
seen.add(b)
queue.append(b)
Z = {x for x in ys if idx[x] in seen} | set(T)
return sum(wt for _, _, wt in es) - f - sum(self.w[x] for x in T), Z
def candidate_pairs(self, Y: set) -> list[tuple[int, int]]:
"""Pairs that every dense set not inside one cluster must contain one of: the two ends of a constraint
that is not yet in a cluster, or two cores whose frontiers share a vertex."""
pairs = set()
for x in Y:
nbrs = sorted(y for y in self.adj[x] if y in Y)
if x < self.n:
pairs |= {(x, y) for y in nbrs if y < self.n and x < y}
cores = [y for y in nbrs if y >= self.n]
pairs |= {(a, b) for i, a in enumerate(cores) for b in cores[i + 1:]}
return sorted(pairs)
def find_dense(self, Y: set) -> Optional[set]:
for a, b in self.candidate_pairs(Y): # @line L4
value, Z = self.max_closure(Y, {a, b}) # @line L5
if value >= -self.D: # @line L5
return self.close(Z, Y)
return None
def minimal(self, X: set) -> set:
"""Shrink a dense set to one that has no proper dense subset outside every cluster."""
changed = True
while changed: # @line L7
changed = False
for c in sorted(x for x in X if x >= self.n):
Y = set(X) - {c}
Y = {y for y in Y if any(z in Y for z in self.adj[y])}
Z = self.find_dense(Y) # @line L8
if Z is not None:
X, changed = Z, True # @line L9
break
return X
def original_density(self, U: frozenset) -> int:
inside = sum(self.edge_weight for u, v in self.edges if u in U and v in U)
return inside - self.vertex_weight * len(U)
def simplify(self, X: set) -> int:
U = frozenset().union(*(self.orig(x) for x in X)) # @line L10
rho = self.original_density(U)
cores = {c for c in self.core_of if c in self.adj and self.orig(c) <= U} # @line L11
Xp = set(X) | cores
children = sorted(self.core_of[c] for c in cores)
covered = frozenset().union(*(self.clusters[i]["vertices"] for i in children))
frontier = {x for x in Xp if any(y not in Xp for y in self.adj[x])} # @line L12
assert all(x < self.n for x in frontier)
for x in Xp:
for y in list(self.adj[x]):
if y in Xp:
del self.adj[x][y]
for x in Xp - frontier: # @line L13
for y in self.adj.pop(x):
del self.adj[y][x]
del self.w[x]
c = self.next_id # @line L14
self.next_id += 1
self.w[c] = self.D
self.adj[c] = {}
for f in frontier:
self.adj[c][f] = self.adj[f][c] = self.w[f] # @line L14
self.core_of[c] = len(self.clusters)
self.clusters.append({"vertices": U, "children": children, "leaves": sorted(U - covered),
"frontier": frozenset(frontier), "density": rho}) # @line L15
return c
# ----- the algorithm -----
def run(self) -> list[dict]:
for u, v in self.edges: # @line L1
if u in self.adj and v in self.adj[u]:
self.simplify({u, v}) # @line L2
while True: # @line L3
X = self.find_dense(set(self.adj)) # @line L4
if X is None:
break # @line L6
X = self.minimal(X) # @line L7
self.simplify(X) # @line L10
return self.clusters # @line L16
def roots(self) -> list[frozenset]:
"""The clusters that are not children of another cluster, and the vertices in no cluster."""
live = [self.clusters[i]["vertices"] for c, i in self.core_of.items() if c in self.adj]
covered = frozenset().union(*live) if live else frozenset()
return live + [frozenset([v]) for v in range(self.n) if v not in covered]
def frontier_dr_plan(n: int, edges: Sequence[Edge], vertex_weight: int = 2, edge_weight: int = 1,
D: int = 3) -> tuple[list[dict], list[frozenset]]:
"""The clusters of the DR-plan, in the order made, and its roots."""
planner = FrontierPlanner(n, edges, vertex_weight, edge_weight, D)
clusters = planner.run()
return clusters, planner.roots()
test_frontier_vertex_algorithm.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/frontier-vertex-algorithm/. The authors are listed in prov/HMKXPX.jsonl.
import random
from itertools import combinations
from frontier_vertex_algorithm import FrontierPlanner, frontier_dr_plan
def laman_rank(vertices, edges):
"""The generic rank in the plane by the Laman count: a greedy basis, each step checked by brute force
over all vertex subsets of size k >= 2 (at most 2k - 3 edges each)."""
vs = sorted(vertices)
subsets = [set(X) for k in range(2, len(vs) + 1) for X in combinations(vs, k)]
count = [0] * len(subsets)
rank = 0
for u, v in edges:
if u not in vertices or v not in vertices:
continue
hit = [i for i, X in enumerate(subsets) if u in X and v in X]
if all(count[i] < 2 * len(subsets[i]) - 3 for i in hit):
rank += 1
for i in hit:
count[i] += 1
return rank
def is_rigid(U, edges):
return len(U) >= 2 and laman_rank(U, edges) == 2 * len(U) - 3
def rigid_components(n, edges):
"""The maximal vertex sets with at least two vertices that are generically rigid in the plane."""
rigid = [frozenset(X) for k in range(2, n + 1) for X in combinations(range(n), k) if is_rigid(set(X), edges)]
return {X for X in rigid if not any(X < Y for Y in rigid)}
def random_graph(rng, n, prob):
return [e for e in combinations(range(n), 2) if rng.random() < prob]
def check_plan(n, edges):
clusters, roots = frontier_dr_plan(n, edges)
for c in clusters:
U = c["vertices"]
# every cluster is rigid by the Laman count, and its density is at least -3
assert is_rigid(set(U), edges), (edges, sorted(U))
assert c["density"] >= -3
# every node is the union of its children and its leaves, and each child is a proper subset
parts = [clusters[i]["vertices"] for i in c["children"]] + [frozenset([v]) for v in c["leaves"]]
assert frozenset().union(*parts) == U
assert all(P < U for P in parts)
assert all(i < clusters.index(c) for i in c["children"])
# the plan covers the graph: every edge lies in a root, and every vertex in exactly the roots listed
for u, v in edges:
assert any(u in R and v in R for R in roots)
assert frozenset().union(*roots) == frozenset(range(n)) if n else True
# each cluster is a child of at most one later cluster, so the roots are the clusters never used as children
used = [i for c in clusters for i in c["children"]]
assert len(used) == len(set(used))
return clusters, roots
def test_random_graphs_clusters_rigid_and_plan_covers():
rng = random.Random(1)
for _ in range(40):
n = rng.randint(2, 7)
edges = random_graph(rng, n, rng.choice([0.4, 0.6, 0.8]))
check_plan(n, edges)
def test_roots_are_the_rigid_components():
rng = random.Random(2)
for _ in range(25):
n = rng.randint(3, 6)
edges = random_graph(rng, n, rng.choice([0.5, 0.7]))
_, roots = check_plan(n, edges)
assert {R for R in roots if len(R) >= 2} == rigid_components(n, edges)
def test_prism():
edges = [(0, 1), (0, 2), (1, 2), (3, 4), (3, 5), (4, 5), (0, 3), (1, 4), (2, 5)]
clusters, roots = check_plan(6, edges)
big = [c["vertices"] for c in clusters if len(c["vertices"]) >= 3]
assert big == [frozenset({0, 1, 2}), frozenset({3, 4, 5}), frozenset(range(6))]
assert roots == [frozenset(range(6))]
last = clusters[-1]
assert len(last["children"]) == 5 and last["density"] == -3
def test_shared_vertex_kept_by_frontier():
"""Vertex 0 lies in the triangle 012 and in the triangle 034; it stays a frontier vertex after 012 becomes a
cluster, so the triangle 034 is still found, inside the rigid cluster 0345."""
edges = [(0, 1), (0, 2), (1, 2), (3, 4), (3, 5), (4, 5), (0, 3), (0, 4), (1, 5)]
clusters, roots = check_plan(6, edges)
tri = next(c for c in clusters if c["vertices"] == frozenset({0, 1, 2}))
assert 0 in tri["frontier"]
sets = [c["vertices"] for c in clusters]
assert frozenset({0, 3, 4, 5}) in sets
assert roots == [frozenset(range(6))]
assert clusters[-1]["density"] == -3
def test_hinged_bodies_are_two_roots():
edges = [(0, 1), (0, 2), (1, 2), (2, 3), (2, 4), (3, 4)]
_, roots = check_plan(5, edges)
assert sorted(map(sorted, roots)) == [[0, 1, 2], [2, 3, 4]]
def test_over_constrained_k4():
edges = list(combinations(range(4), 2))
clusters, roots = check_plan(4, edges)
assert roots == [frozenset(range(4))]
assert clusters[-1]["density"] == -2
def test_isolated_vertex_is_a_root():
_, roots = check_plan(4, [(0, 1), (1, 2), (0, 2)])
assert frozenset([3]) in roots and frozenset([0, 1, 2]) in roots
def test_frontier_vertices_are_reported():
planner = FrontierPlanner(5, [(0, 1), (0, 2), (1, 2), (2, 3), (3, 4), (2, 4)])
clusters = planner.run()
tri = next(c for c in clusters if c["vertices"] == frozenset({0, 1, 2}))
assert tri["frontier"] == frozenset({2})
History
Earlier planners of the 1990s, such as the triangle merges of Fudos and Hoffmann and the splits of Owen, found rigid parts by patterns in the graph. In 1997 Hoffmann, Lomonosov and Sitharam showed how to find dense subgraphs of any weighted constraint graph with network flows, and how to shrink a dense subgraph to a minimal one. In 2001 they defined DR-plans and measures to compare planners (Part I), and gave the Frontier algorithm and its modified form (Part II), with the simplification to frontier vertices and a core. Later work by Sitharam and others studied optimal and canonical DR-plans; Baker, Sitharam, Wang and Willoughby (2015) showed that optimal DR-planning is NP-hard for over-constrained 2D systems and gave a polynomial algorithm for a broad class of other systems.
References
- Christoph M. Hoffmann, Andrew Lomonosov and Meera Sitharam, Decomposition plans for geometric constraint problems, Part II, New algorithms, Journal of Symbolic Computation 31(4), 409 to 427, 2001, the Frontier algorithm, its simplification of a cluster to its frontier vertices and one core vertex, and its modified form MFA (general locator)
- Christoph M. Hoffmann, Andrew Lomonosov and Meera Sitharam, Decomposition plans for geometric constraint systems, Part I, Performance measures for CAD, Journal of Symbolic Computation 31(4), 367 to 408, 2001, the definition of a DR-plan and the measures by which DR-planners are compared (general locator)
- Christoph M. Hoffmann, Andrew Lomonosov and Meera Sitharam, Finding solvable subsets of constraint graphs, Principles and Practice of Constraint Programming (CP97), LNCS 1330, 1997, the network flow test for dense subgraphs and the reduction of a dense subgraph to a minimal one (general locator)
- G. Laman, On graphs and rigidity of plane skeletal structures, Journal of Engineering Mathematics 4(4), 331 to 340, 1970, the counts that make a minimal dense set of points and distances rigid in the plane
- Troy Baker, Meera Sitharam, Menghan Wang and Joel Willoughby, Optimal decomposition and recombination of isostatic geometric constraint systems for designing layered materials, Computer Aided Geometric Design 40, 1 to 25, 2015, the abstract and introduction, on canonical DR-plans and the hardness of optimal DR-planning
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 HMKXPX Edit this page History Report an error Markdown