Algorithm Search⌘K

Algorithmadvanced

Pebble game for rigidity

Also called Jacobs-Hendrickson pebble game.

Jacobs and Hendrickson's O(n^2) algorithm that tests Laman's condition by moving two pebbles per vertex along edges, and finds rigid components and redundant edges.

Time
O(n m) worstΘ(n + m) best
Space
Θ(n + m) extra
Where
m = the number of edges; n = the number of vertices
Properties
deterministicexactiterative
Origin
Donald J. Jacobs, Bruce Hendrickson, 1997

The pebble game of Jacobs and Hendrickson decides the Laman counts of a graph, and so generic rigidity in the plane, without any coordinates and without looking at the exponentially many vertex subsets. Each vertex holds two pebbles, and an edge is accepted when four pebbles can be brought to its two ends by moving pebbles back along accepted edges. The accepted edges form a largest set of independent bars, the rejected edges are redundant, and a second pass finds the rigid components. On a graph with nn vertices and mm edges it takes O(nm)O(nm) time, and O(n2)O(n^2) for the Laman test of a graph with 2n−32n - 3 edges.

In plain words

Give every joint of a structure two tokens. A token stands for one way in which the joint can still move. When a new rod arrives between two joints, it can only take away a way of moving if the two joints, together, still have four free tokens: three of the four are the ways the pair can move as a whole, and only the fourth can be used up. If they do, one token is put on the rod. If they do not, the rod adds nothing new, and it is redundant.

The tokens can be moved. A joint can take a token from a neighbor if it hands its own token to the rod between them in return. So the search for four tokens is a search along the rods. In the end, the rods that got a token are the useful ones.

The problem

The input is a graph G=(V,E)G = (V, E) with V={0,…,n−1}V = \{0, \ldots, n-1\} and a list of mm edges uvuv with u≠vu \ne v, in a fixed order. A repeated edge is allowed. The outputs are:

  • for each edge, whether it is independent of the earlier accepted edges or redundant, where a set FF of edges is independent when every set XX of k≥2k \ge 2 vertices spans at most 2k−32k - 3 edges of FF;
  • the rank, the number of accepted edges, and from it the answers to "is GG generically rigid in the plane" (rank 2n−32n - 3) and "is GG a Laman graph" (m=2n−3m = 2n - 3 and every edge accepted);
  • the rigid components: the maximal vertex sets XX with ∣X∣≥2|X| \ge 2 whose induced subgraph is generically rigid in the plane. Each edge lies in exactly one of them.

By Laman's theorem, the independent sets are exactly the edge sets whose rows in the rigidity matrix are independent at a generic placement, so they are the independent sets of a matroid, and the accepted edges are what the matroid greedy algorithm keeps.

The algorithm

The state is a directed graph DD on VV, one arc for each accepted edge, and a count peb[v]\mathrm{peb}[v] of free pebbles at each vertex. An arc u→vu \to v means that a pebble of uu covers the edge uvuv, so peb[v]+outdegD(v)=2\mathrm{peb}[v] + \mathrm{outdeg}_D(v) = 2 at all times.

  1. PEBBLE-GAME(n, E)
  2. 1for each vertex v do peb[v] ← 2; D ← the directed graph on V with no arcs
  3. 2for each edge uv of E, in the given order do
  4. 3for (x, y) in ((u, v), (v, u)) do
  5. 4while peb[x] < 2 and FIND-PEBBLE(x, y) succeeds do nothing more
  6. 5if peb[u] + peb[v] = 4 then
  7. 6peb[u] ← peb[u] - 1; add the arc u → v to D; mark uv independent
  8. 7else mark uv redundant
  9. 8return the marks and D
  10. FIND-PEBBLE(x, y)
  11. 9search D by depth-first search from x for a vertex w ∉ {x, y} with peb[w] > 0
  12. 10if there is no such w then return false
  13. 11reverse every arc of the path from x to w; peb[w] ← peb[w] - 1; peb[x] ← peb[x] + 1
  14. 12return true
  15. RIGID-COMPONENTS(n, E)
  16. 13run PEBBLE-GAME(n, E); C ← an empty list
  17. 14for each edge uv of E such that no set in C contains both u and v do
  18. 15gather pebbles on u and v as in lines L3 and L4, but stop at 3 in total
  19. 16X ← the vertices from which D reaches some w ∉ {u, v} with peb[w] > 0
  20. 17add V ∖ X to C
  21. 18return C

The search in line L9 may pass through yy but must not take a pebble from it, because yy needs its pebbles too. Reversing a path in line L11 moves one pebble from ww to xx: every inner vertex of the path loses one out-arc and gains one, so its count stays. Every out-degree is at most 2, so the search is cheap.

Example

Take n=6n = 6 and the edges in the order 01,02,12,13,23,03,34,45,35,2501, 02, 12, 13, 23, 03, 34, 45, 35, 25: a K4K_4 on {0,1,2,3}\{0, 1, 2, 3\}, a triangle 345345 that shares vertex 3 with it, and the edge 2525. The column "moves" lists the successful searches, written x←wx \leftarrow w when xx takes a pebble from ww.

step edge moves result free pebbles on 0,1,2,3,4,50, 1, 2, 3, 4, 5 after
1 0101 none accept, arc 0→10 \to 1 1, 2, 2, 2, 2, 2
2 0202 0←10 \leftarrow 1 accept, arc 0→20 \to 2 1, 1, 2, 2, 2, 2
3 1212 1←01 \leftarrow 0 accept, arc 1→21 \to 2 0, 1, 2, 2, 2, 2
4 1313 1←21 \leftarrow 2 accept, arc 1→31 \to 3 0, 1, 1, 2, 2, 2
5 2323 2←12 \leftarrow 1 accept, arc 2→32 \to 3 0, 0, 1, 2, 2, 2
6 0303 0←20 \leftarrow 2, then the search from 0 fails redundant: only 3 pebbles 1, 0, 0, 2, 2, 2
7 3434 none accept, arc 3→43 \to 4 1, 0, 0, 1, 2, 2
8 4545 none accept, arc 4→54 \to 5 1, 0, 0, 1, 1, 2
9 3535 3←43 \leftarrow 4 accept, arc 3→53 \to 5 1, 0, 0, 1, 0, 2
10 2525 2←32 \leftarrow 3, 2←02 \leftarrow 0 accept, arc 2→52 \to 5 0, 0, 1, 0, 0, 2

In step 6, after 0←20 \leftarrow 2, the vertices that 0 can reach are 0,1,2,30, 1, 2, 3, and the only free pebbles among them are the one on 0 and the two on 3. So the set {0,1,2,3}\{0, 1, 2, 3\} already spans 2⋅4−3=52 \cdot 4 - 3 = 5 accepted edges, and 0303 would be a sixth. After step 9 the rank is 8 <9< 9, and RIGID-COMPONENTS returns {0,1,2,3}\{0, 1, 2, 3\} and {3,4,5}\{3, 4, 5\}: two rigid bodies joined at a hinge. Step 10 adds the ninth independent edge, the rank becomes 9=2n−39 = 2n - 3, and the whole graph is one rigid component. At the end 12−9=312 - 9 = 3 free pebbles remain, the three motions of the plane.

Correctness

The proof shows the following.

  • Invariant. At every step peb[v]≥0\mathrm{peb}[v] \ge 0 and peb[v]+outdegD(v)=2\mathrm{peb}[v] + \mathrm{outdeg}_D(v) = 2. So for every vertex set XX, 2∣X∣=peb(X)+iB(X)+out(X)2|X| = \mathrm{peb}(X) + i_B(X) + \mathrm{out}(X), where BB is the set of accepted edges, iB(X)i_B(X) the number of them inside XX, and out(X)\mathrm{out}(X) the number of arcs that leave XX.
  • Accepted edges are independent. Four pebbles on uu and vv mean iB(X)≤2∣X∣−4i_B(X) \le 2|X| - 4 for every X∋u,vX \ni u, v, so adding uvuv keeps the count 2∣X∣−32|X| - 3.
  • Rejected edges are dependent. If fewer than four pebbles can be gathered, the vertices reachable from the failed search form a set R∋u,vR \ni u, v with no arc leaving it and no free pebble except on uu and vv. The identity gives iB(R)≥2∣R∣−3i_B(R) \ge 2|R| - 3, so uvuv would break the count on RR.
  • Greedy basis. Hence an edge is accepted exactly when it is independent of the edges accepted before it, which is the greedy algorithm in the planar rigidity matroid. The number of accepted edges is the rank.
  • Components. After three pebbles are gathered on an edge uvuv, the vertices that cannot reach any other free pebble form a closed set with exactly 3 free pebbles, so it spans 2∣S∣−32|S| - 3 accepted edges and is rigid, and the largest rigid set that contains uu and vv has the same two properties, so the two sets are equal.
Proof: The pebble game accepts exactly the edges that are independent of the earlier accepted edges, finds the rigid components, and runs in O(nm) timefull

Let G=(V,E)G = (V, E) have n≥2n \ge 2 vertices and a list of mm edges uvuv with u≠vu \ne v; repeated edges are allowed. For a set FF of edges and X⊆VX \subseteq V, let iF(X)i_F(X) be the number of edges of FF with both ends in XX. Call FF sparse if iF(X)≤2∣X∣−3i_F(X) \le 2|X| - 3 for every XX with ∣X∣≥2|X| \ge 2. By Laman's theorem, the sparse sets are the independent sets of the generic rigidity matroid of the plane, and a vertex set XX with ∣X∣≥2|X| \ge 2 is rigid when G[X]G[X] is generically rigid, which means that E(X)E(X), the edges of GG inside XX, has rank 2∣X∣−32|X| - 3 in this matroid.

During the game, BB is the set of accepted edges and DD is its orientation. For X⊆VX \subseteq V let peb(X)=∑x∈Xpeb[x]\mathrm{peb}(X) = \sum_{x \in X} \mathrm{peb}[x], and let out(X)\mathrm{out}(X) be the number of arcs of DD from XX to V∖XV \setminus X. Call XX closed if out(X)=0\mathrm{out}(X) = 0. Line numbers refer to the pseudocode on the main page.

Lemma 1 (invariant). At every step, peb[v]≥0\mathrm{peb}[v] \ge 0 and peb[v]+outdegD(v)=2\mathrm{peb}[v] + \mathrm{outdeg}_D(v) = 2 for every vertex vv. Hence peb[v]≤2\mathrm{peb}[v] \le 2, and for every X⊆VX \subseteq V,

2∣X∣=peb(X)+iB(X)+out(X).(∗)2|X| = \mathrm{peb}(X) + i_B(X) + \mathrm{out}(X). \qquad (*)

Proof. Line L1 sets peb[v]=2\mathrm{peb}[v] = 2 with no arcs. Consider a move in line L11 along the path x=v0→v1→⋯→vk=wx = v_0 \to v_1 \to \cdots \to v_k = w, k≥1k \ge 1. After the reversal, xx has one out-arc less and one pebble more. Each inner vertex viv_i loses the arc vi→vi+1v_i \to v_{i+1} and gains the arc vi→vi−1v_i \to v_{i-1}, and its count stays. The vertex ww gains one out-arc and loses one pebble, and peb[w]>0\mathrm{peb}[w] > 0 before, so it stays at least 0. Line L6 runs only when peb[u]+peb[v]=4\mathrm{peb}[u] + \mathrm{peb}[v] = 4, so peb[u]=2\mathrm{peb}[u] = 2; it takes one pebble from uu and adds one out-arc at uu. So the invariant holds. Summing it over XX gives 2∣X∣=peb(X)+∑x∈Xoutdeg(x)2|X| = \mathrm{peb}(X) + \sum_{x \in X} \mathrm{outdeg}(x), and each arc with its tail in XX either has its head in XX, which gives iB(X)i_B(X), or leaves XX, which gives out(X)\mathrm{out}(X). □\square

Moves only reverse arcs, so they never change BB as a set of edges.

Lemma 2 (accepted edges are independent). BB is sparse at every step.

Proof. At the start BB is empty. Moves do not change BB. When line L6 accepts uvuv, then peb[u]+peb[v]=4\mathrm{peb}[u] + \mathrm{peb}[v] = 4 just before, so for every XX that contains uu and vv, (∗)(*) gives iB(X)≤2∣X∣−peb(X)≤2∣X∣−4i_B(X) \le 2|X| - \mathrm{peb}(X) \le 2|X| - 4. After the edge is added, iB(X)≤2∣X∣−3i_B(X) \le 2|X| - 3. Sets that do not contain both ends do not change. □\square

In particular, ∣B∣=iB(V)≤2n−3|B| = i_B(V) \le 2n - 3, so DD has at most 2n−32n - 3 arcs.

Lemma 3 (pebbles of the partner stay). During the search from xx with partner yy (line L9), peb[y]\mathrm{peb}[y] does not change.

Proof. The search never takes a pebble from yy. If the path passes through yy, then yy is an inner vertex, and its count stays, as in Lemma 1. □\square

So in lines L3 and L4, each successful search adds one pebble to xx, and the searches for the second end do not lower the count of the first end. Each loop of line L4 ends when peb[x]=2\mathrm{peb}[x] = 2 or when a search fails.

Lemma 4 (a failed search gives a closed set). Suppose that at some state the search from xx with partner yy fails, and let RR be the set of vertices that xx reaches in DD. Then RR is closed, every free pebble in RR lies on xx or yy, and y∈Ry \in R. This stays true while further searches with the ends xx and yy are made.

Proof. The set reached by a search is closed by definition, and a free pebble on a vertex of RR other than xx and yy would have been found. Now let a later search start at yy with partner xx (a search from xx fails again, since nothing has changed). If y∈Ry \in R, the search stays in the closed set RR and finds no pebble, so nothing changes. If y∉Ry \notin R, a path from yy that entered RR could not leave it again, and it would end at a vertex of RR with a free pebble other than xx and yy, which does not exist. So the path avoids RR, and reversing it changes no arc with an end in RR. So RR keeps its properties. It remains to show y∈Ry \in R. If not, RR is closed and peb(R)=peb[x]≤1\mathrm{peb}(R) = \mathrm{peb}[x] \le 1, because the search was made with peb[x]<2\mathrm{peb}[x] < 2. By (∗)(*), iB(R)=2∣R∣−peb(R)≥2∣R∣−1i_B(R) = 2|R| - \mathrm{peb}(R) \ge 2|R| - 1. For ∣R∣=1|R| = 1 this says 0≥10 \ge 1, and for ∣R∣≥2|R| \ge 2 it contradicts Lemma 2. □\square

Lemma 5 (rejected edges are dependent). If line L7 rejects uvuv, then B+uvB + uv is not sparse. More precisely, there is a set R∋u,vR \ni u, v with iB(R)=2∣R∣−3i_B(R) = 2|R| - 3.

Proof. Line L5 fails, so after lines L3 and L4 some end x∈{u,v}x \in \{u, v\} has peb[x]<2\mathrm{peb}[x] < 2, and its loop ended with a failed search. By Lemma 4 that failure persists to the end of line L4, so the set RR that xx reaches is closed, contains uu and vv, and has peb(R)=peb[u]+peb[v]≤3\mathrm{peb}(R) = \mathrm{peb}[u] + \mathrm{peb}[v] \le 3. By (∗)(*), iB(R)=2∣R∣−peb(R)≥2∣R∣−3i_B(R) = 2|R| - \mathrm{peb}(R) \ge 2|R| - 3, and by Lemma 2 equality holds. Adding uvuv gives 2∣R∣−22|R| - 2 edges inside RR. □\square

Theorem 1 (correctness of PEBBLE-GAME). The game marks an edge independent exactly when it is independent of the edges accepted before it, so the accepted edges are the basis that the matroid greedy algorithm picks in the given order. The number of accepted edges is the rank of EE in the planar generic rigidity matroid.

Proof. By Lemma 2, an accepted edge keeps BB sparse. By Lemma 5, a rejected edge would break sparsity. Sparsity is independence in the matroid, so the game is the greedy algorithm. Each rejected edge lies in the span of BB at the time it is rejected, and BB only grows, so at the end BB spans EE and is a basis: ∣B∣=rank⁡(E)|B| = \operatorname{rank}(E). □\square

So GG is generically rigid in the plane if and only if ∣B∣=2n−3|B| = 2n - 3, and GG is a Laman graph if and only if m=2n−3m = 2n - 3 and no edge is rejected.

Lemma 6 (every edge is spanned). After the game, every edge uvuv of EE lies in a set R∋u,vR \ni u, v with iB(R)=2∣R∣−3i_B(R) = 2|R| - 3. Hence, at every later state, peb[u]+peb[v]≤3\mathrm{peb}[u] + \mathrm{peb}[v] \le 3.

Proof. For an accepted edge take R={u,v}R = \{u, v\}, since iB(R)≥1i_B(R) \ge 1 and iB(R)≤1i_B(R) \le 1 by Lemma 2. For a rejected edge take the set of Lemma 5; BB only grows after it, and Lemma 2 keeps the equality. Then (∗)(*) gives peb(R)+out(R)=3\mathrm{peb}(R) + \mathrm{out}(R) = 3 at every state, so peb[u]+peb[v]≤peb(R)≤3\mathrm{peb}[u] + \mathrm{peb}[v] \le \mathrm{peb}(R) \le 3. □\square

Lemma 7 (three pebbles). For every edge uvuv of EE, line L15 ends with peb[u]+peb[v]=3\mathrm{peb}[u] + \mathrm{peb}[v] = 3.

Proof. The loops stop at a total of 3 or at a failed search. In the second case, Lemma 4 gives a closed set R∋u,vR \ni u, v with peb(R)=peb[u]+peb[v]≤2\mathrm{peb}(R) = \mathrm{peb}[u] + \mathrm{peb}[v] \le 2, so iB(R)≥2∣R∣−2i_B(R) \ge 2|R| - 2 by (∗)(*), against Lemma 2. □\square

Lemma 8 (union of rigid sets). If XX and YY are rigid and ∣X∩Y∣≥2|X \cap Y| \ge 2, then X∪YX \cup Y is rigid. So for each edge uvuv there is exactly one largest rigid set that contains uu and vv, its rigid component, and two rigid components share at most one vertex.

Proof. Take a generic placement pp, so the points are distinct. At pp, rigid sets give infinitesimally rigid subframeworks (Asimow and Roth). Let aa be an infinitesimal motion of G[X∪Y]G[X \cup Y]. It is an infinitesimal motion of G[X]G[X] and of G[Y]G[Y], so on XX it is a trivial motion T1T_1 and on YY a trivial motion T2T_2. A trivial motion of the plane has the form q↦ωJq+bq \mapsto \omega J q + b with JJ the rotation by a right angle. The difference T1−T2T_1 - T_2 vanishes at two distinct points psp_s and ptp_t of X∩YX \cap Y, so ωJ(ps−pt)=0\omega J (p_s - p_t) = 0, hence ω=0\omega = 0 and then b=0b = 0. So aa is trivial on X∪YX \cup Y, the subframework is infinitesimally rigid, and G[X∪Y]G[X \cup Y] is generically rigid. The set {u,v}\{u, v\} is rigid, because it spans the edge uvuv. So the union of all rigid sets that contain uu and vv is rigid, and it is the unique largest one. Two different components that share two vertices would have a rigid union larger than both. □\square

Lemma 9 (the component is tight in BB). Let CC be the rigid component of an edge uvuv of EE. Then iB(C)=2∣C∣−3i_B(C) = 2|C| - 3.

Proof. It suffices to show that B∩E(C)B \cap E(C) spans E(C)E(C) in the matroid, because then iB(C)=rank⁡E(C)=2∣C∣−3i_B(C) = \operatorname{rank} E(C) = 2|C| - 3. Edges of BB in E(C)E(C) are spanned trivially. Let e∈E(C)e \in E(C) be rejected. Then B+eB + e contains a unique circuit ZZ through ee, and Z∖e⊆BZ \setminus e \subseteq B. The vertex set WW of ZZ is rigid: ZZ has 2∣W∣−22|W| - 2 edges (shown below), and Z∖eZ \setminus e is independent, so E(W)E(W) has rank at least 2∣W∣−32|W| - 3. The sets WW and CC share the two ends of ee, so W∪CW \cup C is rigid by Lemma 8, and by maximality W⊆CW \subseteq C. So Z∖e⊆B∩E(C)Z \setminus e \subseteq B \cap E(C), and ee is spanned by B∩E(C)B \cap E(C). □\square

The circuit count in this proof is the standard fact for the count matroid: a circuit ZZ on vertex set WW has ∣Z∣=2∣W∣−2|Z| = 2|W| - 2, because ZZ is not sparse, so some X⊆WX \subseteq W has iZ(X)≥2∣X∣−2i_Z(X) \ge 2|X| - 2, and by minimality ZZ lies inside XX, so X=WX = W, and Z∖eZ \setminus e is sparse, so ∣Z∣−1≤2∣W∣−3|Z| - 1 \le 2|W| - 3.

Theorem 2 (correctness of RIGID-COMPONENTS). For each edge uvuv handled in line L14, the set S=V∖XS = V \setminus X of line L17 is the rigid component CC of uvuv. The list C\mathcal{C} holds every rigid component exactly once.

Proof. By Lemma 7, peb[u]+peb[v]=3\mathrm{peb}[u] + \mathrm{peb}[v] = 3 after line L15.

u,v∈Su, v \in S. Suppose uu reaches a vertex w∉{u,v}w \notin \{u, v\} with a free pebble. Then outdeg(u)≥1\mathrm{outdeg}(u) \ge 1, so peb[u]≤1\mathrm{peb}[u] \le 1 by Lemma 1, and reversing the path gives uu one more pebble, so peb[u]+peb[v]=4\mathrm{peb}[u] + \mathrm{peb}[v] = 4, against Lemma 6. The same holds for vv.

SS is rigid. If a vertex z∈Sz \in S had an arc to a vertex of XX, then zz would reach a free pebble off {u,v}\{u, v\}, so z∈Xz \in X. So SS is closed. A vertex w∈S∖{u,v}w \in S \setminus \{u, v\} with a free pebble would reach itself, so the only free pebbles in SS are on uu and vv, and peb(S)=3\mathrm{peb}(S) = 3. By (∗)(*), iB(S)=2∣S∣−3i_B(S) = 2|S| - 3. These edges of BB are independent and lie in E(S)E(S), so E(S)E(S) has rank 2∣S∣−32|S| - 3 and SS is rigid. Hence S⊆CS \subseteq C.

C⊆SC \subseteq S. By Lemma 9 and (∗)(*), peb(C)+out(C)=3\mathrm{peb}(C) + \mathrm{out}(C) = 3. Since u,v∈Cu, v \in C, peb(C)≥3\mathrm{peb}(C) \ge 3, so out(C)=0\mathrm{out}(C) = 0 and CC has no free pebble except on uu and vv. A vertex of CC reaches only vertices of CC, so it reaches no free pebble off {u,v}\{u, v\}, and C∩X=∅C \cap X = \emptyset.

So S=CS = C. The moves of line L15 do not change BB, and Lemmas 1 to 9 hold at every state, so later edges are handled correctly too. Every rigid component CC has ∣C∣≥2|C| \ge 2 and rank 2∣C∣−3≥12|C| - 3 \ge 1, so it contains an edge, and the first such edge reached in line L14 is not yet covered (by Lemma 8 no other component contains both its ends), so CC is added. Later edges of E(C)E(C) are covered and skipped, so no component is added twice. □\square

Theorem 3 (running time). PEBBLE-GAME takes O(nm)O(nm) time, the Laman test with early stop takes O(n2)O(n^2) time, RIGID-COMPONENTS takes O(nm)O(nm) time, and the space is Θ(n+m)\Theta(n + m).

Proof. DD has at most 2n−32n - 3 arcs (Lemma 2), so one depth-first search and one path reversal take O(n)O(n) time. For one edge, each loop of line L4 has at most two successful searches, because each adds one pebble to xx, Lemma 3 protects that count from the other loop, and peb[x]≤2\mathrm{peb}[x] \le 2. Each loop has at most one failed search. So each edge costs at most six searches, O(n)O(n) time, and PEBBLE-GAME takes O(nm)O(nm). The Laman test first checks m=2n−3m = 2n - 3 and stops at the first rejected edge, so it handles at most 2n−32n - 3 edges, in O(n2)O(n^2) time.

For the components: each component CC has iB(C)=2∣C∣−3≥1i_B(C) = 2|C| - 3 \ge 1 edges of BB (Lemma 9), and two components share no edge (Lemma 8), so there are at most ∣B∣≤min⁡(m,2n−3)|B| \le \min(m, 2n - 3) of them. Each one costs O(n)O(n) for line L15 (at most five searches) and O(n)O(n) for the backward search of line L16 over the O(n)O(n) arcs, so O(nm)O(nm) for all of them. For line L14, keep for each vertex the list of components that contain it, stored as hash sets; testing an edge looks at the at most 2n−32n - 3 components of uu, in O(n)O(n) time. So the total is O(n+nm)O(n + nm), which is O(nm)O(nm) when m≥1m \ge 1. The arrays peb\mathrm{peb}, the adjacency lists of DD and the marks take Θ(n+m)\Theta(n + m) space, and the component lists take O(n+∑C∣C∣)=O(n)O(n + \sum_C |C|) = O(n) more, because 2∣C∣−3≥∣C∣/22|C| - 3 \ge |C|/2 for ∣C∣≥2|C| \ge 2 and ∑C(2∣C∣−3)≤2n−3\sum_C (2|C| - 3) \le 2n - 3. □\square

Complexity

  • One search. DD has at most 2n−32n - 3 arcs, because the accepted edges satisfy the count on X=VX = V, and every out-degree is at most 2. So a depth-first search in line L9 and the reversal in line L11 take O(n)O(n) time.
  • One edge. Lines L3 and L4 make at most four successful searches, one per missing pebble, and at most two failed ones. So each edge costs O(n)O(n), and PEBBLE-GAME takes O(nm)O(nm) time. When no search is needed, as for a forest, each edge costs O(1)O(1), so the best case is Θ(n+m)\Theta(n + m).
  • Laman test. A Laman graph has m=2n−3m = 2n - 3, and the test can stop at the first redundant edge, so it takes O(n2)O(n^2) time. This is the bound of Jacobs and Hendrickson.
  • Components. Each component holds at least one accepted edge and two components share no edge, so there are at most 2n−32n - 3 of them. Each one costs O(n)O(n) for the gathering and the backward search in line L16. The membership test of line L14 costs O(n)O(n) per edge. So RIGID-COMPONENTS also takes O(nm)O(nm) time. Lee and Streinu keep the components during the game and get O(n2)O(n^2) for all of them.
  • Space. DD, the counts and the marks take Θ(n+m)\Theta(n + m) space.

Properties

  • Exact and combinatorial. The game uses only the graph. It decides generic rigidity, so it says nothing about a particular placement: at special positions, such as K3,3K_{3,3} on a conic, a graph that the game calls rigid gives an infinitesimally flexible framework.
  • Order dependent output, order independent rank. Which edges are marked redundant depends on the order, but their number does not, and neither do the rigid components.
  • Incremental. Edges can be added one at a time, and the state after each edge is a valid certificate: the orientation DD shows the count, and the free pebbles count the degrees of freedom, 2n−rank2n - \mathrm{rank}.
  • Deterministic. With a fixed order of the arcs in each adjacency list, the moves are fixed, as in the trace above.
  • The count matroid in general. The same game with kk pebbles per vertex and acceptance at ℓ+1\ell + 1 pebbles decides the (k,ℓ)(k, \ell) counts for 0≤ℓ<2k0 \le \ell < 2k (Lee and Streinu). The case (1,1)(1, 1) is the graphic matroid, and (2,3)(2, 3) is the planar rigidity matroid.

Variants and improvements

  • (k,ℓ)(k, \ell) pebble games. Lee and Streinu (2008) gave the general game and proved that it accepts exactly the (k,ℓ)(k, \ell)-sparse graphs. For k=6k = 6 and ℓ=6\ell = 6 it tests the body-and-bar counts of Tay's theorem in space.
  • Components during the game. Instead of a second pass, keep the components as the edges arrive. A new edge inside a known component is redundant at once, which saves the search.
  • Rigidity percolation and proteins. Jacobs and Hendrickson designed the game for networks with millions of sites, in models of glass, and Jacobs, Rader, Kuhn and Thorpe used a version for bond-bending networks in the program FIRST, which finds the rigid and flexible regions of proteins.
  • Other exact tests. Hendrickson (1992) tested the Laman counts by bipartite matching on doubled edges, and the two spanning tree form of Laman's theorem gives a test by spanning tree packing. Algorithms based on matroid sums by Gabow and Westermann are faster in theory.
  • Randomized rank. For any dimension, the rank of the rigidity matrix at a random integer placement gives the generic rank with high probability. It is slower, O(mn2)O(m n^2) by elimination, but it works in space, where no count test is known.

When to use it

  • To decide whether a sketch of points and distances is well-constrained in the generic sense, and to find over-constrained edges, in CAD degrees of freedom analysis.
  • To design a rigid formation or a sensor network in the plane, and to see which links are redundant.
  • To find rigid clusters in large planar networks, where computing ranks of large matrices would be too slow.

Do not use it for bar-and-joint frameworks in three dimensions: the (3,6)(3, 6) count is not sufficient there, as the double banana shows, and (3,6)(3, 6) is not even a matroid count for the game (ℓ=6=2k\ell = 6 = 2k). Do not use it to check a particular placement: compute the rank of the rigidity matrix at the given coordinates instead.

Pitfalls

  • Taking the partner's pebble. The search from uu must not take a free pebble from vv, or the four pebbles are counted twice. It may still pass through vv.
  • Blocking the partner. Treating vv as a wall in the search from uu is wrong in the other direction: a path through vv to a free pebble is a legal move and may be the only one.
  • Three or four. An edge needs four pebbles to be accepted. Three pebbles is the test for components. Mixing the two gives either too many or too few accepted edges.
  • Repeated edges. A second copy of an accepted edge is redundant, because the pair already spans 1=2⋅2−31 = 2 \cdot 2 - 3 edges. Code that drops duplicates silently changes the counts of a multigraph.
  • Testing a vertex set by its accepted edges. The accepted edges inside a vertex set XX can be fewer than the rank of G[X]G[X], because an edge inside XX can be rejected through a circuit that leaves XX. For a rigid component the count is exact, but to test an arbitrary set, run a new game on G[X]G[X].
  • Recursion. A recursive search can be nn deep on a long path. Use an explicit stack, as the implementation does.

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.

pebble_game_rigidity.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pebble-game-rigidity/. The authors are listed in prov/AEGQ05.jsonl.

from typing import Sequence


class PebbleGame:
    """The (2, 3) pebble game of Jacobs and Hendrickson on the vertices 0 .. n-1.

    Each vertex starts with two free pebbles. An accepted edge is an arc of a
    directed graph, covered by one pebble of its tail, so for every vertex
    peb[v] + (out-degree of v) = 2 at all times. The accepted edges are an
    independent set of the generic 2D rigidity matroid: every set of k >= 2
    vertices spans at most 2k - 3 of them.
    """

    def __init__(self, n: int) -> None:
        if n < 1:
            raise ValueError("n must be at least 1")
        self.n = n
        self.peb = [2] * n  # @line L1
        self.out: list[list[int]] = [[] for _ in range(n)]  # @line L1
        self.accepted = 0

    def find_pebble(self, x: int, y: int) -> bool:
        """Move one free pebble to x from a vertex other than x and y.

        Searches the directed graph from x by depth-first search. On success it
        reverses the arcs of the path, so x gains a pebble, the end of the path
        loses one, and the other vertices keep their counts. Cost O(n), because
        every out-degree is at most 2.
        """
        parent = {x: x}
        stack = [x]
        found = -1
        while stack and found < 0:  # @line L9
            a = stack.pop()
            for b in self.out[a]:
                if b in parent:
                    continue
                parent[b] = a
                if b != y and self.peb[b] > 0:
                    found = b
                    break
                stack.append(b)
        if found < 0:  # @line L10
            return False
        b = found
        while b != x:  # @line L11
            a = parent[b]
            self.out[a].remove(b)
            self.out[b].append(a)
            b = a
        self.peb[found] -= 1  # @line L11
        self.peb[x] += 1  # @line L11
        return True  # @line L12

    def gather(self, u: int, v: int, target: int) -> int:
        """Gather free pebbles on u and v, up to target in total (target <= 4).

        Returns peb[u] + peb[v] at the end. It is less than target only when no
        sequence of moves can put target pebbles on u and v.
        """
        for x, y in ((u, v), (v, u)):  # @line L3
            while self.peb[x] < 2 and self.peb[u] + self.peb[v] < target:  # @line L4
                if not self.find_pebble(x, y):  # @line L4
                    break
        return self.peb[u] + self.peb[v]

    def add_edge(self, u: int, v: int) -> bool:
        """Try to accept the edge uv. Returns True if it is independent.

        Precondition: 0 <= u, v < n and u != v. Cost O(n).
        """
        if u == v or not (0 <= u < self.n and 0 <= v < self.n):
            raise ValueError("an edge needs two different vertices in range")
        if self.gather(u, v, 4) == 4:  # @line L5
            self.peb[u] -= 1  # @line L6
            self.out[u].append(v)  # @line L6
            self.accepted += 1
            return True
        return False  # @line L7

    def component_of(self, u: int, v: int) -> frozenset[int]:
        """The rigid component that contains u and v, for an edge uv already offered.

        Gathers three pebbles on u and v. Then a vertex is in the component
        exactly when it cannot reach a free pebble on a vertex other than u
        and v. Cost O(n).
        """
        self.gather(u, v, 3)  # @line L15
        rev: list[list[int]] = [[] for _ in range(self.n)]
        for a in range(self.n):
            for b in self.out[a]:
                rev[b].append(a)
        seen = [False] * self.n
        stack = [w for w in range(self.n) if w != u and w != v and self.peb[w] > 0]
        for w in stack:
            seen[w] = True
        while stack:  # @line L16
            b = stack.pop()
            for a in rev[b]:
                if not seen[a]:
                    seen[a] = True
                    stack.append(a)
        return frozenset(w for w in range(self.n) if not seen[w])  # @line L17


def pebble_game(n: int, edges: Sequence[tuple[int, int]]) -> list[bool]:
    """Run the (2, 3) pebble game on the edges in the given order.

    Returns one flag per edge: True if the edge is independent of the edges
    accepted before it, False if it is redundant. The accepted edges are the
    greedy basis of the generic 2D rigidity matroid for this order.
    Precondition: n >= 1, and each edge has two different ends in 0 .. n-1.
    Repeated edges are allowed (the second copy is redundant).
    Cost O(n m) time and O(n + m) space for m edges.
    """
    game = PebbleGame(n)
    marks = [game.add_edge(u, v) for u, v in edges]  # @line L2
    return marks  # @line L8


def rigidity_rank(n: int, edges: Sequence[tuple[int, int]]) -> int:
    """Rank of the edge set in the generic 2D rigidity matroid. Cost O(n m)."""
    return sum(pebble_game(n, edges))


def is_generically_rigid(n: int, edges: Sequence[tuple[int, int]]) -> bool:
    """True if the graph is generically rigid in the plane. Cost O(n m)."""
    return n == 1 or rigidity_rank(n, edges) == 2 * n - 3


def is_laman(n: int, edges: Sequence[tuple[int, int]]) -> bool:
    """True if the graph is generically minimally rigid in the plane.

    That is 2n - 3 edges and at most 2k - 3 edges on every k >= 2 vertices.
    A single vertex with no edges counts as minimally rigid. The game stops at
    the first redundant edge, so the cost is O(n^2).
    """
    if n == 1:
        return len(edges) == 0
    if len(edges) != 2 * n - 3:
        return False
    game = PebbleGame(n)
    return all(game.add_edge(u, v) for u, v in edges)


def rigid_components(n: int, edges: Sequence[tuple[int, int]]) -> list[frozenset[int]]:
    """The rigid components of the graph: the maximal vertex sets X with |X| >= 2
    whose induced subgraph is generically rigid in the plane.

    Every edge lies in exactly one component, and two components share at most
    one vertex. Isolated vertices are in no component. The components come in
    the order of their first edge. Cost O(n m).
    """
    game = PebbleGame(n)
    for u, v in edges:  # @line L13
        game.add_edge(u, v)
    comps: list[frozenset[int]] = []  # @line L13
    member: list[set[int]] = [set() for _ in range(n)]
    for u, v in edges:  # @line L14
        if member[u] & member[v]:  # @line L14
            continue
        comp = game.component_of(u, v)
        for w in comp:
            member[w].add(len(comps))
        comps.append(comp)  # @line L17
    return comps  # @line L18
test_pebble_game_rigidity.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pebble-game-rigidity/. The authors are listed in prov/AEGQ05.jsonl.

import random
from fractions import Fraction
from itertools import combinations

from pebble_game_rigidity import (
    PebbleGame,
    is_generically_rigid,
    is_laman,
    pebble_game,
    rigid_components,
    rigidity_rank,
)

Edge = tuple[int, int]


def greedy_marks(n: int, edges: list[Edge], within: int = -1) -> list[bool]:
    """Brute force over vertex subsets: keep an edge when, with the kept edges,
    every set of k >= 2 vertices (inside the mask within) still spans at most
    2k - 3 edges. This is the greedy basis of the count matroid."""
    full = (1 << n) - 1 if within < 0 else within
    subs = []
    s = full
    while s:
        if bin(s).count("1") >= 2:
            subs.append(s)
        s = (s - 1) & full
    cap = {s: 2 * bin(s).count("1") - 3 for s in subs}
    cnt = dict.fromkeys(subs, 0)
    marks = []
    for u, v in edges:
        b = 1 << u | 1 << v
        hit = [s for s in subs if s & b == b]
        ok = all(cnt[s] < cap[s] for s in hit)
        marks.append(ok)
        if ok:
            for s in hit:
                cnt[s] += 1
    return marks


def sparse(n: int, edges: list[Edge]) -> bool:
    """Every set of k >= 2 vertices spans at most 2k - 3 of the edges."""
    return all(greedy_marks(n, edges))


def matrix_rank(rows: list[list[Fraction]]) -> int:
    rows = [r[:] for r in rows]
    rank = 0
    cols = len(rows[0]) if rows else 0
    for c in range(cols):
        piv = next((i for i in range(rank, len(rows)) if rows[i][c] != 0), -1)
        if piv < 0:
            continue
        rows[rank], rows[piv] = rows[piv], rows[rank]
        for i in range(len(rows)):
            if i != rank and rows[i][c] != 0:
                f = rows[i][c] / rows[rank][c]
                rows[i] = [a - f * b for a, b in zip(rows[i], rows[rank])]
        rank += 1
    return rank


def matrix_rigidity_rank(n: int, edges: list[Edge], rng: random.Random) -> int:
    """Rank of the 2D rigidity matrix at a random integer point, in exact arithmetic."""
    p = [(Fraction(rng.randrange(-10**6, 10**6)), Fraction(rng.randrange(-10**6, 10**6))) for _ in range(n)]
    rows = []
    for u, v in edges:
        r = [Fraction(0)] * (2 * n)
        dx, dy = p[u][0] - p[v][0], p[u][1] - p[v][1]
        r[2 * u], r[2 * u + 1] = dx, dy
        r[2 * v], r[2 * v + 1] = -dx, -dy
        rows.append(r)
    return matrix_rank(rows)


def brute_components(n: int, edges: list[Edge]) -> set[frozenset[int]]:
    """Brute force: the maximal vertex sets X, |X| >= 2, whose induced edges have rank 2|X| - 3."""
    rigid = []
    for k in range(2, n + 1):
        for xs in combinations(range(n), k):
            s = set(xs)
            mask = sum(1 << x for x in xs)
            inside = [e for e in edges if e[0] in s and e[1] in s]
            if sum(greedy_marks(n, inside, mask)) == 2 * k - 3:
                rigid.append(frozenset(xs))
    return {x for x in rigid if not any(x < y for y in rigid)}


def random_graph(n: int, rng: random.Random) -> list[Edge]:
    pairs = list(combinations(range(n), 2))
    if rng.random() < 0.5:
        m = rng.randrange(0, min(len(pairs), 2 * n + 2) + 1)
    else:
        m = max(0, min(len(pairs), 2 * n - 3 + rng.choice((-1, 0, 0, 1))))
    edges = rng.sample(pairs, m)
    return [(v, u) if rng.random() < 0.5 else (u, v) for u, v in edges]


def check_invariant(game: PebbleGame) -> None:
    for v in range(game.n):
        assert game.peb[v] >= 0
        assert game.peb[v] + len(game.out[v]) == 2


def test_example_trace() -> None:
    edges = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (0, 3), (3, 4), (4, 5), (3, 5), (2, 5)]
    assert pebble_game(6, edges) == [True] * 5 + [False] + [True] * 4
    assert rigid_components(6, edges[:9]) == [frozenset({0, 1, 2, 3}), frozenset({3, 4, 5})]
    assert rigid_components(6, edges) == [frozenset(range(6))]
    assert rigidity_rank(6, edges[:9]) == 8
    assert is_generically_rigid(6, edges)
    assert not is_laman(6, edges)


def test_small_cases() -> None:
    assert is_laman(1, [])
    assert is_laman(2, [(0, 1)])
    assert not is_laman(2, [(0, 1), (1, 0)])
    assert pebble_game(2, [(0, 1), (1, 0)]) == [True, False]
    assert rigid_components(3, []) == []
    assert rigid_components(3, [(0, 1)]) == [frozenset({0, 1})]
    assert is_laman(3, [(0, 1), (1, 2), (0, 2)])
    assert not is_generically_rigid(4, [(0, 1), (1, 2), (2, 3), (3, 0)])
    # K4 plus a pendant vertex: 2n - 3 edges but flexible
    k4p = list(combinations(range(4), 2)) + [(3, 4)]
    assert len(k4p) == 7 and not is_laman(5, k4p) and rigidity_rank(5, k4p) == 6
    # K33 is a Laman graph
    k33 = [(a, b) for a in range(3) for b in range(3, 6)]
    assert is_laman(6, k33)


def test_against_brute_force() -> None:
    rng = random.Random(7)
    for _ in range(600):
        n = rng.randrange(1, 9)
        edges = random_graph(n, rng)
        marks = pebble_game(n, edges)
        assert marks == greedy_marks(n, edges)
        assert is_laman(n, edges) == (n == 1 and not edges or len(edges) == 2 * n - 3 and n >= 2 and sparse(n, edges))
        game = PebbleGame(n)
        for u, v in edges:
            game.add_edge(u, v)
            check_invariant(game)


def test_rank_against_matrix() -> None:
    rng = random.Random(11)
    for _ in range(300):
        n = rng.randrange(2, 9)
        edges = random_graph(n, rng)
        assert rigidity_rank(n, edges) == matrix_rigidity_rank(n, edges, rng)


def henneberg_graph(n: int, rng: random.Random) -> list[Edge]:
    """A random Laman graph on n >= 2 vertices, built by Henneberg moves."""
    edges: list[Edge] = [(0, 1)]
    for v in range(2, n):
        if v >= 3 and rng.random() < 0.5:
            a, b = edges.pop(rng.randrange(len(edges)))
            c = rng.choice([w for w in range(v) if w != a and w != b])
            edges += [(v, a), (v, b), (v, c)]
        else:
            a, b = rng.sample(range(v), 2)
            edges += [(v, a), (v, b)]
    rng.shuffle(edges)
    return edges


def test_henneberg_graphs_are_laman() -> None:
    rng = random.Random(3)
    for _ in range(300):
        n = rng.randrange(2, 40)
        edges = henneberg_graph(n, rng)
        assert is_laman(n, edges)
        assert rigid_components(n, edges) == [frozenset(range(n))]
        u, v = rng.sample(range(n), 2)
        moved = edges[1:] + [(u, v)]
        if n <= 8:
            assert is_laman(n, moved) == sparse(n, moved)
        elif n <= 16 and rng.random() < 0.2:
            assert rigidity_rank(n, moved) == matrix_rigidity_rank(n, moved, rng)


def test_components_against_brute_force() -> None:
    rng = random.Random(5)
    for _ in range(300):
        n = rng.randrange(2, 9)
        edges = random_graph(n, rng)
        comps = rigid_components(n, edges)
        assert len(comps) == len(set(comps))
        assert set(comps) == brute_components(n, edges)
        for u, v in edges:
            assert sum(1 for c in comps if u in c and v in c) == 1

History

Rigidity percolation, the study of when a random network becomes rigid, needed a fast exact test of the Laman counts on very large graphs. Hendrickson (1992) had given a polynomial test by bipartite matching. Jacobs and Thorpe used a pebble game for rigidity percolation in 1995, and in 1997 Jacobs and Hendrickson published the full algorithm, with its proof, the rigid cluster decomposition and a quadratic worst case. It later became the core of the FIRST program for proteins. Lee and Streinu (2008) generalized it to all (k,ℓ)(k, \ell) counts with 0≤ℓ<2k0 \le \ell < 2k, proved the equivalence with sparsity in this setting, and gave the component algorithms. The pebble game of rigidity is not related to the red-blue pebble game of I/O complexity.

References

  1. Donald J. Jacobs and Bruce Hendrickson, An algorithm for two-dimensional rigidity percolation, the pebble game, Journal of Computational Physics 137(2), 346 to 365, 1997, the pebble game for the Laman counts, the search for free pebbles, the rigid cluster decomposition, and the quadratic worst case bound
  2. Audrey Lee and Ileana Streinu, Pebble game algorithms and sparse graphs, Discrete Mathematics 308(8), 1425 to 1437, 2008, the (k, l) pebble games, the proof that they accept exactly the (k, l)-sparse graphs, and the detection of components
  3. G. Laman, On graphs and rigidity of plane skeletal structures, Journal of Engineering Mathematics 4(4), 331 to 340, 1970, the counts that the pebble game tests
  4. Bruce Hendrickson, Conditions for unique graph realizations, SIAM Journal on Computing 21(1), 65 to 84, 1992, the earlier matching-based test of the Laman counts and of redundant rigidity
  5. Jack Graver, Brigitte Servatius and Herman Servatius, Combinatorial Rigidity, Graduate Studies in Mathematics 2, American Mathematical Society, 1993, Chapter 4, Linear and Planar Rigidity (the generic rigidity matroid in the plane)

About this page

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

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