Algorithm Search⌘K

Algorithmcore

Force-closure test

Also called origin in the convex hull of primitive wrenches.

Decides whether a grasp is in force closure on linearized friction cones, by an exact linear feasibility test on the primitive contact wrenches.

Time
O(N^(d+1)) worst
Space
O(d N) extra
Where
N = the number of primitive wrenches (c contacts times k cone edges); d = the dimension of the wrench space (3 in the plane and 6 in space)
Properties
certificatedeterministicexact
Origin
Bud Mishra, Jacob T. Schwartz, Micha Sharir, 1987

The force-closure test decides whether a set of contacts can hold a rigid body against every external force and moment. Each contact can push only into the body, and with friction it can also push sideways, inside a friction cone. The test replaces each cone by a pyramid with a few edges, turns each edge into a wrench (a force together with its moment), and asks one question: can a strictly positive combination of these primitive wrenches sum to zero while the wrenches span all directions? That question is a small linear feasibility problem. It is the same as asking whether the origin lies strictly inside the convex hull of the primitive wrenches.

In plain words

Hold a box between your fingers. Every push or twist that the world gives the box must be cancelled by your fingers. A finger can only push, it cannot pull, and it can push a bit sideways because of friction. So each finger gives a small fan of pushes. The grasp is safe when the fans of all fingers together can make a push in every direction. The test checks this with a short list of the extreme pushes. It looks for a way to use every extreme push a little, so that all of them cancel. If such a mix exists, and the pushes point in all directions, then any outside push can also be cancelled, and the grasp is safe.

The problem

The input is a grasp of a rigid body with cc contacts. Contact ii has a point pip_i and a unit normal nin_i that points into the body, both in the body frame, and a friction coefficient μ\mu. The contact model is a frictionless point, a point with friction, or a soft finger. A wrench is written moment first: F=(m,f)\mathcal{F} = (m, f) in space, with d=6d = 6, and F=(mz,fx,fy)\mathcal{F} = (m_z, f_x, f_y) in the plane, with d=3d = 3.

Each friction cone is replaced by a polyhedral cone with edges fi1,…,fikf_{i1}, \ldots, f_{ik}. In the plane the cone has exactly the two edges ni±μtin_i \pm \mu t_i, where tit_i is nin_i turned by 90 degrees. In space the edges are ni+μ(cos⁡(2πj/k) ti1+sin⁡(2πj/k) ti2)n_i + \mu(\cos(2\pi j/k)\, t_{i1} + \sin(2\pi j/k)\, t_{i2}) for j=0,…,k−1j = 0, \ldots, k-1, where ti1,ti2t_{i1}, t_{i2} are unit tangents. These edges lie on the circular cone, so each pyramid is inside it. A frictionless contact has the one edge nin_i. The primitive wrenches are

w=(pi×fij, fij)for each contact i and each edge j.w = (p_i \times f_{ij},\ f_{ij}) \quad \text{for each contact } i \text{ and each edge } j.

There are NN of them; N=ckN = ck when all contacts have kk edges. Let FF be the d×Nd \times N matrix with these columns. The question is whether pos⁡(F)={Fk:k≥0}\operatorname{pos}(F) = \{F k : k \ge 0\} is all of Rd\mathbb{R}^d. That is force closure of the linearized grasp. With frictionless contacts it is first-order form closure.

The algorithm

Force closure holds if and only if rank⁡F=d\operatorname{rank} F = d and Fk=0F k = 0 for some kk with every entry positive. Scale kk so that its smallest entry is 1 and put y=k−1y = k - \mathbf{1}: the second condition becomes Fy=−F1F y = -F\mathbf{1} with y≥0y \ge 0. Lynch and Park write the same test as the linear program "minimize 1Tk\mathbf{1}^T k subject to Fk=0F k = 0 and k≥1k \ge \mathbf{1}". The feasibility problem is solved by phase one of the simplex method, in exact rational arithmetic, with Bland's rule so that it cannot cycle.

  1. FORCE-CLOSURE(contacts, μ, k) ▷ contacts (p_i, n_i), i = 1 .. c
  2. 1W ← empty list
  3. 2for each contact (p_i, n_i) do
  4. 3for each edge f of the linearized cone at contact i do
  5. 4append the wrench (p_i × f, f) to W
  6. 5F ← the d × N matrix with the wrenches of W as columns
  7. 6if rank F < d then return NOT CLOSED
  8. 7y ← PHASE-ONE(F, -F·1) ▷ find y ≥ 0 with F y = -F·1
  9. 8if y = NONE then return NOT CLOSED
  10. 9return CLOSED, with the certificate k = 1 + y
  11. PHASE-ONE(A, b) ▷ find y ≥ 0 with A y = b, or NONE
  12. 10negate each row i of [A | b] with b_i < 0
  13. 11add an artificial variable a_i to row i; the first basis is a
  14. 12repeat
  15. 13compute the reduced cost r_j of each column for the cost a_1 + ... + a_m
  16. 14if no r_j < 0 or the cost of the basis is 0 then exit the loop
  17. 15q ← the smallest j with r_j < 0 ▷ Bland's rule
  18. 16i ← the row with the least ratio b_i / A_iq over A_iq > 0, ties to the smallest basic index
  19. 17pivot on (i, q)
  20. 18if some a_i is not 0 then return NONE else return the y part of the basic solution

Line L6 rejects grasps whose wrenches lie in a proper subspace. Such a grasp can have Fk=0F k = 0 with k>0k > 0 (two opposite pushes along one line do), but it cannot resist a wrench outside that subspace. Line L14 stops as soon as the artificial variables are all zero. When F1=0F\mathbf{1} = 0 already, as in a symmetric grasp, the test stops at once with k=1k = \mathbf{1}. The vector kk of line L9 is a certificate: anyone can check k≥1k \ge \mathbf{1} and Fk=0F k = 0 in exact arithmetic without trusting the solver.

Example

Take a planar box and two fingers with μ=3/5\mu = 3/5. Finger 1 touches the left side at p1=(−1,1/2)p_1 = (-1, 1/2) with n1=(1,0)n_1 = (1, 0); finger 2 touches the right side at p2=(1,−1/2)p_2 = (1, -1/2) with n2=(−1,0)n_2 = (-1, 0). With tit_i equal to nin_i turned by +90 degrees, the edges are (1,±3/5)(1, \pm 3/5) at finger 1 and (−1,∓3/5)(-1, \mp 3/5) at finger 2. The planar moment of a force ff at pp is pxfy−pyfxp_x f_y - p_y f_x. Lines L1 to L5 give

F=(−11/101/10−11/101/1011−1−13/5−3/5−3/53/5),−F1=(2,0,0).F = \begin{pmatrix} -11/10 & 1/10 & -11/10 & 1/10 \\ 1 & 1 & -1 & -1 \\ 3/5 & -3/5 & -3/5 & 3/5 \end{pmatrix}, \qquad -F\mathbf{1} = (2, 0, 0).

The rank is 3, so line L6 passes. PHASE-ONE starts with the artificial values a=(2,0,0)a = (2, 0, 0) and cost 2.

Pivot Entering (rqr_q) Leaving row (ratio) Basic values Cost
start a1=2a_1 = 2, a2=0a_2 = 0, a3=0a_3 = 0 2
1 y1y_1 (−1/2-1/2) row 2 (0) a1=2a_1 = 2, y1=0y_1 = 0, a3=0a_3 = 0 2
2 y4y_4 (−1/5-1/5) row 3 (0) a1=2a_1 = 2, y1=0y_1 = 0, y4=0y_4 = 0 2
3 y2y_2 (−1/5-1/5) row 1 (10) y2=10y_2 = 10, y1=0y_1 = 0, y4=10y_4 = 10 0

The first two pivots are degenerate: the basis changes and the point does not. After the third pivot the cost is 0, so line L14 exits and line L9 returns k=(1,11,1,11)k = (1, 11, 1, 11). The check: the moments give −11/10+11/10−11/10+11/10=0-11/10 + 11/10 - 11/10 + 11/10 = 0, the xx forces give 1+11−1−11=01 + 11 - 1 - 11 = 0, and the yy forces give 3/5−33/5−3/5+33/5=03/5 - 33/5 - 3/5 + 33/5 = 0. The grasp is in force closure.

With μ=1/3\mu = 1/3 the same fingers give −F1=(2,0,0)-F\mathbf{1} = (2, 0, 0) again, but after one pivot no reduced cost is negative and the cost is still 2. The test returns NOT CLOSED. The reason is geometric: the line through the two contacts makes the angle arctan⁡(1/2)≈26.57\arctan(1/2) \approx 26.57 degrees with the normals, and the fingers can squeeze along that line only when it is inside both friction cones, that is when μ>1/2\mu > 1/2 (the antipodal grasp condition). At μ=1/2\mu = 1/2 exactly the line is on the edge of the cones, and the exact test correctly returns NOT CLOSED.

Correctness

The full proof is in proofs/correctness.md. It has four steps. First, the wrenches that the contacts can apply are exactly pos⁡(F)\operatorname{pos}(F), because a linearized cone is the set of nonnegative combinations of its edges. Second, pos⁡(F)=Rd\operatorname{pos}(F) = \mathbb{R}^d if and only if rank⁡F=d\operatorname{rank} F = d and Fk=0F k = 0 for some k>0k > 0: given any wrench x=Fzx = F z, add a large multiple of kk to zz to make it nonnegative. Third, a k>0k > 0 exists if and only if a k≥1k \ge \mathbf{1} exists, by scaling. Fourth, phase one with Bland's rule stops, and it ends with cost 0 if and only if the system Fy=−F1F y = -F\mathbf{1}, y≥0y \ge 0 has a solution. The proof also shows the convex hull form: pos⁡(F)=Rd\operatorname{pos}(F) = \mathbb{R}^d if and only if the origin is in the interior of conv⁡(F)\operatorname{conv}(F).

The answer is about the linearized cones. Because the spatial edges lie on the true cones, a CLOSED answer is also true for the circular cones. A NOT CLOSED answer is not: a grasp can be in force closure with the circular cones and fail the test with a coarse pyramid. In the plane the cone is exactly the two-edge cone, and the test is exact.

Proof: The force-closure test decides whether the primitive wrenches positively span the wrench spacefull

We use the notation of the page. The primitive wrenches are w1,…,wN∈Rdw_1, \ldots, w_N \in \mathbb{R}^d, with d=3d = 3 in the plane and d=6d = 6 in space. They are the columns of the d×Nd \times N matrix FF. The set of wrenches that the contacts can apply is the cone pos⁡(W)={Fk:k≥0}\operatorname{pos}(W) = \{F k : k \ge 0\}, because each linearized friction cone is the set of nonnegative combinations of its edges, and the wrench map of one contact is linear. The linearized grasp is in force closure when pos⁡(W)=Rd\operatorname{pos}(W) = \mathbb{R}^d: each external wrench can be balanced by contact forces inside the linearized cones. We write 1\mathbf{1} for the vector of NN ones, and k>0k > 0 or k≥1k \ge 1 for an inequality in each component.

Lemma 1 (algebraic form). pos⁡(W)=Rd\operatorname{pos}(W) = \mathbb{R}^d if and only if rank⁡F=d\operatorname{rank} F = d and Fk=0F k = 0 for some k>0k > 0.

Proof. Assume pos⁡(W)=Rd\operatorname{pos}(W) = \mathbb{R}^d. Then span⁡(W)⊇pos⁡(W)=Rd\operatorname{span}(W) \supseteq \operatorname{pos}(W) = \mathbb{R}^d, so rank⁡F=d\operatorname{rank} F = d. The vector −F1-F\mathbf{1} is in pos⁡(W)\operatorname{pos}(W), so −F1=Fa-F\mathbf{1} = F a for some a≥0a \ge 0. Then k=1+ak = \mathbf{1} + a has k≥1>0k \ge \mathbf{1} > 0 and Fk=0F k = 0.

Conversely, assume rank⁡F=d\operatorname{rank} F = d and Fk=0F k = 0 with k>0k > 0. Let x∈Rdx \in \mathbb{R}^d. Because the columns of FF span Rd\mathbb{R}^d, there is a z∈RNz \in \mathbb{R}^N with Fz=xF z = x, with entries of any sign. Let t=max⁡(0,max⁡i(−zi/ki))t = \max(0, \max_i (-z_i / k_i)). Then z+tk≥0z + t k \ge 0, and F(z+tk)=x+t⋅0=xF(z + t k) = x + t \cdot 0 = x. So x∈pos⁡(W)x \in \operatorname{pos}(W). □\square

Lemma 2 (scaling). There is a k>0k > 0 with Fk=0F k = 0 if and only if there is a y≥0y \ge 0 with Fy=−F1F y = -F \mathbf{1}.

Proof. If Fk=0F k = 0 with k>0k > 0, let s=min⁡iki>0s = \min_i k_i > 0. Then k′=k/sk' = k / s has k′≥1k' \ge \mathbf{1} and Fk′=0F k' = 0, so y=k′−1≥0y = k' - \mathbf{1} \ge 0 and Fy=−F1F y = -F\mathbf{1}. Conversely, if y≥0y \ge 0 and Fy=−F1F y = -F\mathbf{1}, then k=1+y≥1>0k = \mathbf{1} + y \ge \mathbf{1} > 0 and Fk=0F k = 0. □\square

Lemma 3 (phase one). PHASE-ONE(A,b)(A, b) stops. It returns a y≥0y \ge 0 with Ay=bA y = b if one exists, and NONE if none exists.

Proof. Line L10 multiplies some equations by −1-1. This does not change the set of solutions, and afterwards b≥0b \ge 0. Line L11 adds one artificial variable ai≥0a_i \ge 0 to row ii and gives the auxiliary problem: minimize 1Ta\mathbf{1}^T a subject to Ay+a=bA y + a = b, y≥0y \ge 0, a≥0a \ge 0. The point y=0y = 0, a=ba = b is feasible, and it is the basic solution of the first basis (the artificial columns form an identity matrix). A point yy with Ay=bA y = b and y≥0y \ge 0 exists if and only if the optimal value of the auxiliary problem is 00.

The loop of lines L12 to L17 is the simplex method on this problem. We use three standard facts about a simplex tableau. (a) A pivot is a sequence of row operations, so each tableau describes the same set of solutions as the system of line L11. (b) The ratio test of line L16 picks the row in which the entering variable first drives a basic variable to 00, so the basic solution stays nonnegative. (c) For each feasible point xx (the vector of all yy and aa variables), the cost is zB+∑jrjxjz_B + \sum_j r_j x_j, where zBz_B is the cost of the current basic solution and rjr_j are the reduced costs of line L13. Fact (c) follows when one substitutes the tableau rows, which give each basic variable as a function of the nonbasic ones, into the cost; the reduced cost of a basic variable is 00.

Line L16 always finds a row. If rq<0r_q < 0 and column qq has no positive entry, then xqx_q can grow without limit while each basic variable stays nonnegative. By fact (c), the cost then goes to −∞-\infty. But the cost 1Ta\mathbf{1}^T a is never negative, so this cannot happen.

The loop stops. Each pivot keeps the cost or lowers it. Bland's rule (line L15 for the entering index, and the ties of line L16 broken by the smallest basic index) never visits the same basis twice (Bland 1977). There are at most (N+dd)\binom{N + d}{d} bases, so the loop makes finitely many pivots.

The loop exits at line L14 in one of two cases. If the cost of the basic solution is 00, then every artificial variable is 00, and the yy part satisfies Ay=bA y = b, y≥0y \ge 0. If no reduced cost is negative, then by fact (c) each feasible point costs at least zBz_B, so zBz_B is the optimal value. Line L18 then returns the yy part if zB=0z_B = 0, and NONE if zB>0z_B > 0. By the remark at the end of the first paragraph, both answers are correct. □\square

Theorem. FORCE-CLOSURE returns CLOSED if and only if the linearized grasp is in force closure. When it returns CLOSED, the vector kk that it gives has k≥1k \ge \mathbf{1} and Fk=0F k = 0.

Proof. Lines L1 to L4 put into WW the wrench (pi×f,f)(p_i \times f, f) of each edge ff of each linearized cone, so the columns of FF (line L5) are the primitive wrenches. If rank⁡F<d\operatorname{rank} F < d, the grasp is not in force closure by Lemma 1, and line L6 returns NOT CLOSED. Otherwise line L7 calls PHASE-ONE(F,−F1)(F, -F\mathbf{1}). By Lemma 3 it returns a yy exactly when some y≥0y \ge 0 has Fy=−F1F y = -F\mathbf{1}. By Lemma 2 this happens exactly when some k>0k > 0 has Fk=0F k = 0, and by Lemma 1 (with rank⁡F=d\operatorname{rank} F = d) exactly when the grasp is in force closure. Line L9 returns k=1+yk = \mathbf{1} + y, and the proof of Lemma 2 shows that k≥1k \ge \mathbf{1} and Fk=0F k = 0. ■\blacksquare

Corollary (convex hull form). pos⁡(W)=Rd\operatorname{pos}(W) = \mathbb{R}^d if and only if the origin is in the interior of the convex hull of w1,…,wNw_1, \ldots, w_N.

Proof. If a ball B(0,r)B(0, r) lies in conv⁡(W)\operatorname{conv}(W), it lies in the cone pos⁡(W)\operatorname{pos}(W). A cone that contains a ball about the origin is all of Rd\mathbb{R}^d, because each x≠0x \ne 0 is a positive multiple of rx/(2∥x∥)r x / (2 \lVert x \rVert).

Conversely, let pos⁡(W)=Rd\operatorname{pos}(W) = \mathbb{R}^d. Lemma 1 gives rank⁡F=d\operatorname{rank} F = d and Fk=0F k = 0 with k>0k > 0. Let λ=k/(1Tk)\lambda = k / (\mathbf{1}^T k). Then λ>0\lambda > 0, 1Tλ=1\mathbf{1}^T \lambda = 1 and Fλ=0F \lambda = 0. Let F+=FT(FFT)−1F^+ = F^T (F F^T)^{-1}, which exists because FF has rank dd, and let x∈Rdx \in \mathbb{R}^d with ∥x∥≤ρ\lVert x \rVert \le \rho. Put z=F+xz = F^+ x and μ=λ+z−(1Tz)λ\mu = \lambda + z - (\mathbf{1}^T z) \lambda. Then Fμ=0+x−0=xF \mu = 0 + x - 0 = x and 1Tμ=1+1Tz−1Tz=1\mathbf{1}^T \mu = 1 + \mathbf{1}^T z - \mathbf{1}^T z = 1. Each ∣zi∣\lvert z_i \rvert is at most ∥F+∥ρ\lVert F^+ \rVert \rho, so for ρ\rho small enough each μi>0\mu_i > 0. Then x∈conv⁡(W)x \in \operatorname{conv}(W), so the ball B(0,ρ)B(0, \rho) lies in conv⁡(W)\operatorname{conv}(W). □\square

What the test does not decide. The theorem is about the linearized cones. Each edge that the code builds lies on the boundary of the true circular cone, so each pyramid lies inside its true cone. If the linearized grasp is in force closure, the true grasp is in force closure too, because its wrench cone is larger. The converse can be false in space: a grasp can be in force closure with the circular cones and not with the pyramids. In the plane a friction cone has exactly two edges, so the planar test is exact. With μ=0\mu = 0 each cone is the ray of the normal, and the test decides first-order form closure.

Reference. R. G. Bland, New finite pivoting rules for the simplex method, Mathematics of Operations Research 2(2), 103-107, 1977.

Complexity

Let NN be the number of primitive wrenches and dd the dimension of the wrench space. Building FF costs O(dN)O(dN). The rank test by Gaussian elimination costs O(d2N)O(d^2 N) arithmetic operations. Each simplex pivot updates a tableau with dd rows and N+d+1N + d + 1 columns, so it costs O(d(N+d))O(d(N + d)) operations. Bland's rule never repeats a basis, and there are at most (N+dd)\binom{N + d}{d} bases, so for fixed dd the test makes O(Nd)O(N^d) pivots and O(Nd+1)O(N^{d+1}) operations in the worst case. This bound is weak in practice: the tableau has only d≤6d \le 6 rows, and on grasps the method typically stops after a few pivots. Avis and Chvátal (1978) gave programs on which Bland's rule takes an exponential number of pivots, so the bound in NN and dd together is not polynomial.

Other solvers give better worst cases. For fixed dd, the linear program can be solved in O(N)O(N) operations by Megiddo's algorithm, and in expected O(d! N)O(d!\,N) by Seidel's algorithm. An interior point method runs in time polynomial in the input size for every dd. The extra space is the tableau, O(d(N+d))=O(dN)O(d(N + d)) = O(dN) entries.

The cost model here is the real RAM. The implementation uses exact rationals, and the size of the numbers grows during the pivots; for d≤6d \le 6 and a few dozen wrenches this growth is small.

Properties

  • Exact. With rational data and rational arithmetic, the answer is exact. It does not need a tolerance, and it gets boundary cases right, such as the cone edge at μ=1/2\mu = 1/2 in the example.
  • Certificate. A CLOSED answer comes with k≥1k \ge \mathbf{1} and Fk=0F k = 0. A NOT CLOSED answer from line L18 comes with an optimal phase-one basis. Its dual solution gives a direction u≠0u \ne 0 with uTw≤0u^T w \le 0 for each primitive wrench ww, so the contacts cannot apply the wrench uu. A NOT CLOSED answer from line L6 has a uu orthogonal to all columns of FF.
  • Frame invariant. Moving the reference point or rotating the body frame multiplies FF by an invertible matrix (an adjoint transpose), which changes neither the rank nor the solutions of Fk=0F k = 0. The answer does not depend on the frame or on the length unit, unlike the Ferrari-Canny metric.
  • Monotone. Adding a contact or an edge adds a column, so a closed grasp stays closed.

Variants and improvements

  • Lynch and Park's form. Minimize 1Tk\mathbf{1}^T k subject to Fk=0F k = 0, k≥1k \ge \mathbf{1}, after a rank check. For their example F=((0,0,−1,2),(−1,0,1,0),(0,−1,0,1))F = ((0, 0, -1, 2), (-1, 0, 1, 0), (0, -1, 0, 1)) the test returns k=(2,1,2,1)k = (2, 1, 2, 1).
  • A quantitative linear program. The Handbook's LP1 maximizes a margin δ\delta subject to Gnλ=0G_n \lambda = 0, λ≥δ1\lambda \ge \delta\mathbf{1}, δ≥0\delta \ge 0 and 1Tλ≤nc\mathbf{1}^T \lambda \le n_c, where GnG_n has the frictionless contact wrenches as columns and ncn_c is the number of contacts. With full rank, a positive optimum means first-order form closure, and the size of the optimum measures how far the grasp is from the boundary. The value depends on the length unit.
  • Convex hull. Compute the hull of the primitive wrenches, for example with Quickhull, and check that every facet has the origin strictly on its inner side. This also gives the Ferrari-Canny metric as the least facet distance. It is practical for d=3d = 3; for d=6d = 6 the hull can have Θ(N3)\Theta(N^3) facets.
  • Circular cones. Testing the true cones is a second-order cone program. It avoids the error of the pyramid at the price of an iterative solver.
  • Soft fingers. Each edge of the cone appears twice, with the torsional moment +γni+\gamma n_i and −γni-\gamma n_i, for the model ∣mn∣≤γfn\lvert m_n \rvert \le \gamma f_n. Two soft fingers can then hold a body in space, while two point contacts never can.

When to use it

Use the test to accept or reject a candidate grasp in a grasp planner, to check a fixture layout, or to check a contact set in a simulation. Use the exact version when grasps sit on the boundary by design, for example an antipodal grasp at the cone edge or a fixture with symmetric locators. Use a floating point linear program solver when the data come from sensors and a tolerance is acceptable. Use a quality score such as Ferrari-Canny when you must rank closed grasps, not only accept them.

Pitfalls

  • Forgetting the rank test. Fk=0F k = 0 with k>0k > 0 is not enough. Two opposite fingers along one line satisfy it with rank 2 in the plane, and they cannot resist a moment.
  • k≥0k \ge 0 in place of k>0k > 0. The vector k=0k = 0 always solves Fk=0F k = 0. The condition must be strict, which the scaling to k≥1k \ge \mathbf{1} makes explicit.
  • Float tolerances. A float solver with a tolerance of 10−910^{-9} can call a boundary grasp closed. Either use exact arithmetic or report grasps within the tolerance as unsure.
  • Wrong normal direction. The normal points into the body. An outward normal turns each push into a pull and gives a wrong answer with no error.
  • Pyramid outside the cone. If the edges are on the circumscribed pyramid (μ/cos⁡(π/k)\mu / \cos(\pi/k)), the pyramid is larger than the true cone, and a CLOSED answer can be wrong for the true cone.
  • Mixed conventions. Murray, Li and Sastry write a wrench force first, Lynch and Park moment first. Any consistent order gives the same answer, but one matrix must not mix them.

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.

force_closure.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/force-closure-test/. The authors are listed in prov/ZZXTNV.jsonl.

"""Force-closure test by a linear program in exact arithmetic.

A wrench is written moment first. A planar wrench is (m_z, f_x, f_y) and a
spatial wrench is (m_x, m_y, m_z, f_x, f_y, f_z). The contact normal points
into the object. Each contact is a pair (p, n) of a point and a unit inward
normal, in the object frame.

The test builds the primitive wrenches (one per edge of each linearized
friction cone), checks that they span the wrench space, and then solves the
linear feasibility problem F k = 0, k >= 1 with a phase-one simplex method
and Bland's rule. All arithmetic is in fractions.Fraction, so the answer is
exact for the given (rational) data. A float input is converted to the exact
rational value of the float.

The module force_closure_test.py (the name that the page uses) re-exports
these functions. The code lives here because tools treat a file whose name
ends in _test.py as a test file.
"""

import math
from fractions import Fraction

FRICTIONLESS = "frictionless"
HARD = "hard"
SOFT = "soft"


def _q(x):
    """Return x as a Fraction, exactly."""
    return x if isinstance(x, Fraction) else Fraction(x)


def _cross3(a, b):
    return [a[1] * b[2] - a[2] * b[1],
            a[2] * b[0] - a[0] * b[2],
            a[0] * b[1] - a[1] * b[0]]


def _unit_circle(j, k):
    """Return (cos, sin) of 2 pi j / k, exact at multiples of 90 degrees."""
    if (4 * j) % k == 0:
        quarter = (4 * j // k) % 4
        return [(1, 0), (0, 1), (-1, 0), (0, -1)][quarter]
    angle = 2.0 * math.pi * j / k
    return math.cos(angle), math.sin(angle)


def _tangent_basis(n):
    """Return two tangent vectors t1, t2 with (t1, t2, n) orthonormal."""
    # Cross n with the coordinate axis that is least aligned with it.
    axis = min(range(3), key=lambda i: abs(n[i]))
    e = [0, 0, 0]
    e[axis] = 1
    t1 = _cross3(n, e)
    s = t1[0] * t1[0] + t1[1] * t1[1] + t1[2] * t1[2]
    if s != 1:
        r = math.sqrt(float(s))
        t1 = [float(v) / r for v in t1]
    t2 = _cross3(n, t1)
    return t1, t2


def cone_edges(n, mu, k=4):
    """Edges of the linearized friction cone at a contact with inward normal n.

    In the plane the cone has exactly two edges n + mu t and n - mu t, with t
    the normal turned by +90 degrees, so the cone is exact and k is not used.
    In space the k edges n + mu (cos(2 pi j/k) t1 + sin(2 pi j/k) t2) lie on
    the circular cone, so the pyramid is inside it (an inner approximation).
    With mu = 0 the cone is the single ray n.
    """
    if mu == 0:
        return [list(n)]
    if len(n) == 2:
        t = [-n[1], n[0]]
        return [[n[0] + mu * t[0], n[1] + mu * t[1]],
                [n[0] - mu * t[0], n[1] - mu * t[1]]]
    t1, t2 = _tangent_basis(n)
    edges = []
    for j in range(k):
        c, s = _unit_circle(j, k)
        edges.append([n[i] + mu * (c * t1[i] + s * t2[i]) for i in range(3)])
    return edges


def contact_wrench(p, f, moment=None):
    """Wrench (p x f + moment, f) of a force f applied at the point p."""
    if len(p) == 2:
        return [p[0] * f[1] - p[1] * f[0], f[0], f[1]]
    m = _cross3(p, f)
    if moment is not None:
        m = [m[i] + moment[i] for i in range(3)]
    return m + list(f)


def primitive_wrenches(contacts, mu=0, k=4, model=HARD, gamma=0):
    """Return the list W of primitive wrenches, as lists of Fractions.

    model is FRICTIONLESS, HARD (point contact with friction) or SOFT (soft
    finger, spatial only). A soft finger has the friction cone |f_t| <= mu f_n
    and the torsion limit |m_n| <= gamma f_n; each cone edge appears twice,
    with the moment +gamma n and -gamma n about the normal.
    """
    W = []  # @line L1
    for p, n in contacts:  # @line L2
        if model == FRICTIONLESS:
            edges = [list(n)]
        else:
            edges = cone_edges(n, mu, k)
        for f in edges:  # @line L3
            if model == SOFT:
                for sign in (1, -1):
                    w = contact_wrench(p, f, [sign * gamma * v for v in n])
                    W.append([_q(v) for v in w])  # @line L4
            else:
                W.append([_q(v) for v in contact_wrench(p, f)])  # @line L4
    return W


def rank(rows):
    """Rank of a matrix given as a list of rows, by exact Gaussian elimination."""
    M = [[_q(v) for v in row] for row in rows]
    if not M:
        return 0
    r = 0
    cols = len(M[0])
    for c in range(cols):
        pivot = next((i for i in range(r, len(M)) if M[i][c] != 0), None)
        if pivot is None:
            continue
        M[r], M[pivot] = M[pivot], M[r]
        for i in range(r + 1, len(M)):
            if M[i][c] != 0:
                f = M[i][c] / M[r][c]
                M[i] = [a - f * b for a, b in zip(M[i], M[r])]
        r += 1
        if r == len(M):
            break
    return r


def phase_one(A, b):
    """Find y >= 0 with A y = b, or return None if there is none.

    Phase one of the simplex method on a dense tableau, with Bland's rule
    for the entering and the leaving variable, so it always stops.
    """
    m = len(A)
    nv = len(A[0]) if m else 0
    T = []
    for i in range(m):  # @line L10
        row = [_q(v) for v in A[i]] + [_q(b[i])]
        if row[-1] < 0:
            row = [-v for v in row]
        T.append(row)
    for i in range(m):  # @line L11
        T[i] = T[i][:nv] + [Fraction(int(r == i)) for r in range(m)] + [T[i][nv]]
    basis = [nv + i for i in range(m)]
    total = nv + m
    cost = [0] * nv + [1] * m
    while True:  # @line L12
        red = [cost[j] - sum(cost[basis[i]] * T[i][j] for i in range(m))
               for j in range(total)]  # @line L13
        value = sum(T[i][total] for i in range(m) if basis[i] >= nv)
        if value == 0 or all(rc >= 0 for rc in red):  # @line L14
            break
        enter = next(j for j in range(total) if red[j] < 0)  # @line L15
        best = None  # @line L16
        for i in range(m):
            if T[i][enter] > 0:
                ratio = T[i][total] / T[i][enter]
                if best is None or ratio < best[0] or (
                        ratio == best[0] and basis[i] < basis[best[1]]):
                    best = (ratio, i)
        # The phase-one cost is at least 0, so a negative reduced cost always
        # has a positive entry in its column and best is never None.
        r = best[1]
        piv = T[r][enter]  # @line L17
        T[r] = [v / piv for v in T[r]]
        for i in range(m):
            if i != r and T[i][enter] != 0:
                f = T[i][enter]
                T[i] = [a - f * c for a, c in zip(T[i], T[r])]
        basis[r] = enter
    x = [Fraction(0)] * total  # @line L18
    for i in range(m):
        x[basis[i]] = T[i][total]
    if any(x[nv + i] != 0 for i in range(m)):
        return None
    return x[:nv]


def force_closure_of_wrenches(W):
    """Decide whether the wrenches W positively span the wrench space.

    Returns (True, k) with k a list of Fractions, every k_i >= 1 and
    sum_i k_i W_i = 0, or (False, None).
    """
    if not W:
        return False, None
    d = len(W[0])
    N = len(W)
    F = [[_q(W[j][i]) for j in range(N)] for i in range(d)]  # @line L5
    if rank(F) < d:  # @line L6
        return False, None
    b = [-sum(row) for row in F]
    y = phase_one(F, b)  # @line L7
    if y is None:  # @line L8
        return False, None
    return True, [1 + v for v in y]  # @line L9


def force_closure(contacts, mu=0, k=4, model=HARD, gamma=0):
    """Force-closure test of a grasp on its linearized friction cones.

    contacts is a list of (p, n): the contact point and the unit inward
    normal, with 2 or 3 coordinates. Returns (closed, k) as in
    force_closure_of_wrenches. With model FRICTIONLESS (or mu = 0) the test
    decides first-order form closure.
    """
    W = primitive_wrenches(contacts, mu, k, model, gamma)
    return force_closure_of_wrenches(W)
force_closure_test.py 18 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/force-closure-test/. The authors are listed in prov/ZZXTNV.jsonl.

"""Force-closure test: the public names of the implementation.

The code, with the @line markers of the pseudocode, is in force_closure.py.
Tools treat a file whose name ends in _test.py as a test file, so they do
not read markers in this file.
"""

from force_closure import (FRICTIONLESS, HARD, SOFT, cone_edges,
                           contact_wrench, force_closure,
                           force_closure_of_wrenches, phase_one,
                           primitive_wrenches, rank)

__all__ = ["FRICTIONLESS", "HARD", "SOFT", "cone_edges", "contact_wrench",
           "force_closure", "force_closure_of_wrenches", "phase_one",
           "primitive_wrenches", "rank"]
test_force_closure_test.py 282 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/force-closure-test/. The authors are listed in prov/ZZXTNV.jsonl.

import itertools
import math
import random
from fractions import Fraction as Q

from force_closure_test import (FRICTIONLESS, HARD, SOFT, cone_edges,
                                force_closure, force_closure_of_wrenches,
                                phase_one, primitive_wrenches, rank)


# Reference method, independent of the linear program. If the wrenches span
# R^d, they are not force closure exactly when some u != 0 has u . w >= 0 for
# every wrench w. That cone of u is then pointed, so it has an extreme ray,
# and an extreme ray is orthogonal to d - 1 linearly independent wrenches.
# The reference tries every such set of d - 1 wrenches.

def _null_vector(rows, d):
    M = [list(r) for r in rows]
    pivots = []
    r = 0
    for c in range(d):
        p = next((i for i in range(r, len(M)) if M[i][c] != 0), None)
        if p is None:
            continue
        M[r], M[p] = M[p], M[r]
        M[r] = [v / M[r][c] for v in M[r]]
        for i in range(len(M)):
            if i != r and M[i][c] != 0:
                f = M[i][c]
                M[i] = [a - f * b for a, b in zip(M[i], M[r])]
        pivots.append(c)
        r += 1
    if r != d - 1:
        return None
    free = next(c for c in range(d) if c not in pivots)
    u = [Q(0)] * d
    u[free] = Q(1)
    for i, c in enumerate(pivots):
        u[c] = -M[i][free]
    return u


def brute_force_closure(W):
    d = len(W[0])
    if rank(W) < d:
        return False
    for S in itertools.combinations(W, d - 1):
        u = _null_vector(S, d)
        if u is None:
            continue
        dots = [sum(a * b for a, b in zip(u, w)) for w in W]
        if all(x >= 0 for x in dots) or all(x <= 0 for x in dots):
            return False
    return True


def check_certificate(W, k):
    assert len(k) == len(W)
    assert all(v >= 1 for v in k)
    d = len(W[0])
    for i in range(d):
        assert sum(k[j] * W[j][i] for j in range(len(W))) == 0


def run(W):
    closed, k = force_closure_of_wrenches(W)
    if closed:
        check_certificate(W, k)
    else:
        assert k is None
    return closed


def rational_unit(rng):
    # A rational point on the unit circle.
    t = Q(rng.randint(-9, 9), rng.randint(1, 9))
    return ((1 - t * t) / (1 + t * t), 2 * t / (1 + t * t))


# Hand cases with known answers.

SQUARE = [((-1, Q(1, 2)), (1, 0)), ((1, Q(-1, 5)), (-1, 0)),
          ((Q(3, 10), -1), (0, 1)), ((Q(-2, 5), 1), (0, -1))]

CUBE7 = [((1, 0, Q(-1, 2)), (-1, 0, 0)), ((-1, Q(-1, 2), 0), (1, 0, 0)),
         ((Q(1, 2), 1, 0), (0, -1, 0)), ((0, -1, 0), (0, 1, 0)),
         ((Q(-1, 2), 0, 1), (0, 0, -1)), ((0, Q(-1, 2), -1), (0, 0, 1)),
         ((0, Q(1, 2), -1), (0, 0, 1))]


def test_square_form_closure():
    W = primitive_wrenches(SQUARE, model=FRICTIONLESS)
    assert W == [[Q(-1, 2), 1, 0], [Q(-1, 5), -1, 0],
                 [Q(3, 10), 0, 1], [Q(2, 5), 0, -1]]
    closed, k = force_closure(SQUARE, model=FRICTIONLESS)
    assert closed and k == [1, 1, 1, 1]
    assert brute_force_closure(W)


def test_pinwheel_is_not_closed():
    # Every contact gives the moment -1/2, so no combination cancels it.
    pin = [((-1, Q(1, 2)), (1, 0)), ((1, Q(-1, 2)), (-1, 0)),
           ((Q(1, 2), 1), (0, -1)), ((Q(-1, 2), -1), (0, 1))]
    W = primitive_wrenches(pin, model=FRICTIONLESS)
    assert all(w[0] == Q(-1, 2) for w in W)
    assert rank(W) == 3
    assert force_closure(pin, model=FRICTIONLESS) == (False, None)
    assert not brute_force_closure(W)


def test_lynch_park_example():
    # The columns of F = [[0,0,-1,2],[-1,0,1,0],[0,-1,0,1]].
    W = [[0, -1, 0], [0, 0, -1], [-1, 1, 0], [2, 0, 1]]
    W = [[Q(v) for v in w] for w in W]
    assert run(W)
    assert force_closure_of_wrenches(W)[1] == [2, 1, 2, 1]


def test_planar_antipodal():
    anti = [((-1, 0), (1, 0)), ((1, 0), (-1, 0))]
    for mu in (Q(1, 2), Q(1, 100), Q(3)):
        closed, k = force_closure(anti, mu)
        assert closed
        check_certificate(primitive_wrenches(anti, mu), k)
    assert force_closure(anti, 0) == (False, None)
    # Contacts off the common normal line: closed only if mu is large enough.
    off = [((-1, Q(1, 2)), (1, 0)), ((1, Q(-1, 2)), (-1, 0))]
    assert not force_closure(off, Q(1, 3))[0]
    assert not force_closure(off, Q(1, 2))[0]   # the line is on the cone edge
    assert force_closure(off, Q(3, 5))[0]


def test_disc_is_never_in_form_closure():
    rng = random.Random(11)
    for _ in range(30):
        c = rng.randint(1, 8)
        contacts = []
        for _ in range(c):
            x, y = rational_unit(rng)
            contacts.append(((x, y), (-x, -y)))
        W = primitive_wrenches(contacts, model=FRICTIONLESS)
        assert all(w[0] == 0 for w in W)
        assert not run(W)


def test_seven_contacts_on_a_cube():
    W = primitive_wrenches(CUBE7, model=FRICTIONLESS)
    closed, k = force_closure_of_wrenches(W)
    assert closed
    check_certificate(W, k)
    assert brute_force_closure(W)
    # Six of them are never enough.
    for i in range(7):
        assert not run(W[:i] + W[i + 1:])


def test_six_frictionless_contacts_are_never_enough():
    rng = random.Random(3)
    for _ in range(40):
        W = [[Q(rng.randint(-3, 3)) for _ in range(6)] for _ in range(6)]
        assert not run(W)


def test_spatial_two_and_three_fingers():
    a3 = [((-1, 0, 0), (1, 0, 0)), ((1, 0, 0), (-1, 0, 0))]
    W = primitive_wrenches(a3, Q(1, 2), 4)
    assert rank(W) == 5          # no moment about the line of the contacts
    assert not run(W)
    W = primitive_wrenches(a3, Q(1, 2), 4, SOFT, Q(1, 10))
    assert len(W) == 16 and run(W)
    three = [((-1, 0, 0), (1, 0, 0)), ((1, Q(1, 2), 0), (-1, 0, 0)),
             ((1, Q(-1, 2), 0), (-1, 0, 0))]
    W = primitive_wrenches(three, Q(1, 2), 4, HARD)
    assert run(W) and brute_force_closure(W)


def test_cone_edges_lie_on_the_cone():
    rng = random.Random(5)
    for _ in range(20):
        n = rational_unit(rng)
        mu = Q(rng.randint(1, 9), 4)
        for e in cone_edges(n, mu):
            normal = e[0] * n[0] + e[1] * n[1]
            tangent = -e[0] * n[1] + e[1] * n[0]
            assert normal == 1 and abs(tangent) == mu
    for k in (3, 4, 5, 8):
        for n in ((0, 0, 1), (0.6, 0.0, 0.8), (1 / math.sqrt(3),) * 3):
            for e in cone_edges(n, 0.5, k):
                fn = sum(e[i] * n[i] for i in range(3))
                ft = math.sqrt(sum((e[i] - fn * n[i]) ** 2 for i in range(3)))
                assert abs(fn - 1) < 1e-12 and abs(ft - 0.5) < 1e-12


def test_random_planar_wrenches_against_brute_force():
    rng = random.Random(7)
    seen = set()
    for _ in range(150):
        N = rng.randint(2, 7)
        W = [[Q(rng.randint(-2, 2)) for _ in range(3)] for _ in range(N)]
        got = run(W)
        assert got == brute_force_closure(W)
        seen.add(got)
    assert seen == {True, False}


def test_random_planar_grasps_against_brute_force():
    rng = random.Random(8)
    seen = set()
    for _ in range(80):
        c = rng.randint(2, 4)
        contacts = []
        for _ in range(c):
            x, y = rational_unit(rng)
            r = Q(rng.randint(1, 4), 2)
            dx, dy = rational_unit(rng)
            # A point on a ray from the center and a normal that points in.
            p = (r * x, r * y)
            n = (dx, dy) if dx * x + dy * y < 0 else (-dx, -dy)
            contacts.append((p, n))
        mu = Q(rng.randint(0, 4), 4)
        W = primitive_wrenches(contacts, mu)
        got = run(W)
        assert got == brute_force_closure(W)
        assert force_closure(contacts, mu)[0] == got
        seen.add(got)
    assert seen == {True, False}


def test_random_spatial_wrenches_against_brute_force():
    rng = random.Random(9)
    seen = set()
    for _ in range(40):
        N = rng.randint(6, 9)
        W = [[Q(rng.randint(-2, 2)) for _ in range(6)] for _ in range(N)]
        got = run(W)
        assert got == brute_force_closure(W)
        seen.add(got)
    assert seen == {True, False}


def test_finer_cone_keeps_closure():
    # The 2k-edge pyramid contains the k-edge pyramid, so closure persists.
    rng = random.Random(10)
    for _ in range(12):
        contacts = []
        for _ in range(3):
            ax = rng.randrange(3)
            s = rng.choice((1, -1))
            p = [Q(rng.randint(-2, 2), 2) for _ in range(3)]
            p[ax] = Q(s)
            n = [0, 0, 0]
            n[ax] = -s
            contacts.append((tuple(p), tuple(n)))
        mu = Q(rng.randint(1, 4), 4)
        if force_closure(contacts, mu, 4)[0]:
            assert force_closure(contacts, mu, 8)[0]


def test_phase_one_feasible_and_infeasible():
    rng = random.Random(12)
    for _ in range(60):
        m = rng.randint(1, 4)
        nv = rng.randint(1, 6)
        A = [[Q(rng.randint(-3, 3)) for _ in range(nv)] for _ in range(m)]
        y0 = [Q(rng.randint(0, 3)) for _ in range(nv)]
        b = [sum(A[i][j] * y0[j] for j in range(nv)) for i in range(m)]
        y = phase_one(A, b)
        assert y is not None and all(v >= 0 for v in y)
        assert [sum(A[i][j] * y[j] for j in range(nv)) for i in range(m)] == b
    # All entries positive and a negative right side: no y >= 0 exists.
    assert phase_one([[1, 2], [3, 1]], [-1, 2]) is None
    assert phase_one([[1, -1], [-1, 1]], [1, 1]) is None


def test_rank():
    assert rank([[1, 2], [2, 4]]) == 1
    assert rank([[0, 0], [0, 0]]) == 0
    assert rank([[1, 0, 0], [0, 1, 0], [1, 1, 0]]) == 2
    assert rank([]) == 0

History

Reuleaux (1875) and Somov (1897) studied how many frictionless contacts immobilize a body. Salisbury and Roth (1983) analyzed articulated hands in terms of the wrenches that the fingers apply. Mishra, Schwartz and Sharir (1987) wrote closure as the origin inside the convex hull of the contact wrenches and used Steinitz's theorem to show that a bounded number of fingers suffices. The linear program form is now the standard textbook test; Lynch and Park (2017) give it for form closure, and the Handbook chapter of Prattichizzo and Trinkle gives a quantitative version.

References

  1. Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 12, Section 12.1.7 (form closure, with the linear program test in Section 12.1.7.2) and Section 12.2.3 (force closure)
  2. Domenico Prattichizzo and Jeffrey C. Trinkle, Grasping, Chapter 38 of the Springer Handbook of Robotics, second edition, Springer, 2016, Section 38.4 (restraint analysis), Sections 38.4.1 (form closure, the linear program LP1) and 38.4.2 (force closure); the chapter is pages 955 to 988
  3. Richard M. Murray, Zexiang Li and S. Shankar Sastry, A Mathematical Introduction to Robotic Manipulation, CRC Press, 1994, Chapter 5 (grasp statics and force-closure grasps)
  4. Bud Mishra, Jacob T. Schwartz and Micha Sharir, On the existence and synthesis of multifinger positive grips, Algorithmica 2(4), 541-558, 1987, the whole paper (closure as the origin in the interior of the convex hull of the wrenches, and the finger counts from Steinitz's theorem)
  5. Robert G. Bland, New finite pivoting rules for the simplex method, Mathematics of Operations Research 2(2), 1977, pages 103 to 107 (the smallest index rule and the proof that it does not cycle)
  6. David Avis and Vašek Chvátal, Notes on Bland's pivoting rule, Mathematical Programming Study 8, 1978, pages 24 to 34 (programs on which the smallest index rule makes an exponential number of pivots)
  7. Nimrod Megiddo, Linear programming in linear time when the dimension is fixed, Journal of the ACM 31(1), 114-127, 1984, the whole paper (an O(N) algorithm for a linear program with a fixed number of variables)

About this page

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

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