Algorithm Search⌘K

Algorithmadvanced

Independent contact regions

Also called Nguyen's independent regions.

Computes segments on two edges of a polygon such that any choice of one finger contact in each segment gives a force-closure grasp, with the smaller segment as long as possible.

Time
O(n^2) worst
Space
O(1) extra
Where
n = the number of edges of the polygon, when every pair of edges is tried
Properties
deterministicexactoptimal
Origin
Van Duc Nguyen, 1988

Independent contact regions are segments on the edges of an object, one for each finger, chosen so that the grasp is in force closure for every choice of one contact point in each segment. A finger then does not need to hit an exact point: any point in its segment works, whatever the other fingers do inside their own segments. This page computes the regions for two fingers with friction on two edges of a convex polygon. It writes Nguyen's two-finger condition as a small linear program and solves it in exact arithmetic, so the smaller region is as long as possible.

In plain words

Pinch a flat part between two fingers. The pinch holds when the line between the two fingers is steep enough against each edge, so that friction can stop the fingers from sliding off. A robot never puts its fingers exactly where it planned. So it is better to plan two short pieces of edge, one for each finger, such that every pair of points from the two pieces makes a good pinch. Then small errors do not matter. The method checks the four pairs of end points of the two pieces. If those four pairs are good, every pair in between is good too. It then stretches the pieces as far as these checks allow, so that the shorter piece is as long as possible.

The problem

The input is a convex polygon with vertices in counterclockwise order, two different edges ii and jj, and a friction coefficient μ>0\mu > 0. Edge ee starts at AeA_e, has the direction DeD_e (the vector to its end point) and the inward normal nen_e, which is DeD_e turned by 90 degrees counterclockwise. A finger on edge ee touches the point Ae+tDeA_e + t D_e with the parameter t∈[0,1]t \in [0, 1]. The fingers are point contacts with friction. In the plane the friction cone CeC_e has exactly two edges, ne+μDen_e + \mu D_e and ne−μDen_e - \mu D_e, so there is no linearization error.

Nguyen (1988) showed that two contacts p1p_1 on edge ii and p2p_2 on edge jj form a force-closure grasp if and only if the vector d=p2−p1d = p_2 - p_1 lies strictly inside CiC_i and −d-d lies strictly inside CjC_j. In words, the segment between the fingers lies inside both friction cones. This is the antipodal grasp condition.

The output is two parameter intervals (s1,u1)(s_1, u_1) on edge ii and (s2,u2)(s_2, u_2) on edge jj such that every t1∈(s1,u1)t_1 \in (s_1, u_1) and every t2∈(s2,u2)t_2 \in (s_2, u_2) satisfy Nguyen's condition, with the smaller width min⁡(u1−s1,u2−s2)\min(u_1 - s_1, u_2 - s_2) as large as possible. The widths are fractions of the edge lengths, which keeps every number rational. If no pair of points on the two edges gives force closure, the output is NONE.

The algorithm

Write d(t1,t2)=(Aj−Ai)+t2Dj−t1Did(t_1, t_2) = (A_j - A_i) + t_2 D_j - t_1 D_i. This is affine in the parameters. A vector vv is in the cone with edges g0,g1g_0, g_1, ordered so that cross⁡(g0,g1)>0\operatorname{cross}(g_0, g_1) > 0, if and only if cross⁡(g0,v)≥0\operatorname{cross}(g_0, v) \ge 0 and cross⁡(v,g1)≥0\operatorname{cross}(v, g_1) \ge 0, where cross⁡(a,b)=axby−aybx\operatorname{cross}(a, b) = a_x b_y - a_y b_x. So each cone condition at one pair of parameters is two linear inequalities.

  1. INDEPENDENT-REGIONS(polygon, i, j, μ)
  2. 1for e in (i, j): A_e, D_e ← the start and the direction of edge e; n_e ← D_e turned by +90 degrees
  3. 2for e in (i, j): g_e0, g_e1 ← n_e + μ D_e and n_e - μ D_e, ordered so that cross(g_e0, g_e1) > 0
  4. 3d(t_1, t_2) ← (A_j - A_i) + t_2 D_j - t_1 D_i ▷ affine in t_1, t_2
  5. 4for each corner (t_1, t_2) in {s_1, u_1} × {s_2, u_2} do
  6. 5add cross(g_i0, d) ≥ 0 and cross(d, g_i1) ≥ 0 ▷ d in the cone at p_1
  7. 6add cross(g_j0, -d) ≥ 0 and cross(-d, g_j1) ≥ 0 ▷ -d in the cone at p_2
  8. 7add 0 ≤ s_1, u_1 ≤ 1, 0 ≤ s_2, u_2 ≤ 1, u_1 - s_1 ≥ z, u_2 - s_2 ≥ z
  9. 8(z*, s_1, u_1, s_2, u_2) ← maximize z subject to these constraints ▷ two-phase simplex, Bland's rule
  10. 9if the program is infeasible or z* = 0 then return NONE
  11. 10return the open intervals (s_1, u_1) on edge i and (s_2, u_2) on edge j

The program has five variables and twenty constraints: sixteen from lines L4 to L6 and four from line L7. The solver is the two-phase simplex method in rational arithmetic, with Bland's rule so that it cannot cycle. To find the best pair of edges of an nn-gon, run it on each of the n(n−1)/2n(n-1)/2 pairs and keep the largest z∗z^*.

Example

Take the square with vertices (0,0)(0, 0), (2,0)(2, 0), (2,2)(2, 2), (0,2)(0, 2) and μ=1/2\mu = 1/2. Edge 1 is the right side, from (2,0)(2, 0) up to (2,2)(2, 2), with D1=(0,2)D_1 = (0, 2) and n1=(−2,0)n_1 = (-2, 0). Edge 3 is the left side, from (0,2)(0, 2) down to (0,0)(0, 0), with D3=(0,−2)D_3 = (0, -2) and n3=(2,0)n_3 = (2, 0). The cone edges are (−2,±1)(-2, \pm 1) at the right side and (2,±1)(2, \pm 1) at the left side. A finger at height y1y_1 on the right and a finger at height y3y_3 on the left give d=(−2, y3−y1)d = (-2,\ y_3 - y_1), and both cone conditions say ∣y3−y1∣≤1\lvert y_3 - y_1 \rvert \le 1.

The linear program returns z∗=1/2z^* = 1/2 with (s1,u1)=(1/2,1)(s_1, u_1) = (1/2, 1) and (s2,u2)=(0,1/2)(s_2, u_2) = (0, 1/2). In heights, both regions are 1<y<21 < y < 2, the upper halves of both sides. The four corner pairs are:

y1y_1 y3y_3 ∣y3−y1∣\lvert y_3 - y_1 \rvert On the boundary of the cones
1 1 0 no
1 2 1 yes
2 1 1 yes
2 2 0 no

Two corner pairs are on the boundary, so the closed segments are not regions, but the open ones are: two heights strictly between 1 and 2 differ by less than 1. No pair of regions does better. If the two height intervals have lengths L1L_1 and L3L_3, some pair of their points differs by at least (L1+L3)/2(L_1 + L_3)/2, so min⁡(L1,L3)≤1\min(L_1, L_3) \le 1, which is half of the side. Any two equal height intervals of length 1 are also optimal; the solver returns one of them.

On the adjacent sides of the same square, with the bottom edge i=0i = 0 and the right edge j=1j = 1, the answer depends on μ\mu. With μ=1\mu = 1 the closed conditions hold only on the segment where y=2−xy = 2 - x, which has no interior, so z∗=0z^* = 0 and the algorithm returns NONE: no two-finger grasp on these two edges is in force closure. With μ=2\mu = 2 it returns z∗=1/2z^* = 1/2, with the regions 0<x<10 < x < 1 on the bottom and 1<y<21 < y < 2 on the right. For the triangle with vertices (0,0)(0, 0), (4,0)(4, 0) and (1,3)(1, 3), the best pair of edges is the bottom and the right edge, with z∗=2/7z^* = 2/7 for μ=1\mu = 1, and no pair of edges works for μ=1/4\mu = 1/4.

Correctness

The full proof is in proofs/correctness.md. Lemma 1 proves Nguyen's condition from the force-closure characterization on the force-closure test page, using that the polygon is convex. Lemma 2 writes each closed cone as two cross product inequalities. Lemma 3 shows that four corner pairs suffice: the parameter rectangle is the convex hull of its corners, dd is affine, and the closed cones are convex. Lemma 4 shows that when z>0z > 0 the open rectangle maps into the open cones; the key step is that dd can move both ways along the edge direction, which is never parallel to a cone edge. The theorem then gives three facts: the returned open intervals are independent regions, no pair of regions has a larger smaller width, and NONE is returned exactly when no pair of contacts works.

Proof: The linear program finds the largest independent contact regions for two fingers on two edges of a convex polygonfull

We use the notation of the page. The polygon is convex and in counterclockwise order. Edge ee has the start point AeA_e, the direction DeD_e and the inward normal nen_e, which is DeD_e turned by +90 degrees, so ∣ne∣=∣De∣\lvert n_e \rvert = \lvert D_e \rvert. The point with parameter t∈[0,1]t \in [0, 1] is Ae+tDeA_e + t D_e. The friction coefficient is μ>0\mu > 0. The closed friction cone of edge ee is

Ce={λ0ge0+λ1ge1:λ0,λ1≥0},{ge0,ge1}={ne+μDe, ne−μDe},C_e = \{\lambda_0 g_{e0} + \lambda_1 g_{e1} : \lambda_0, \lambda_1 \ge 0\}, \qquad \{g_{e0}, g_{e1}\} = \{n_e + \mu D_e,\ n_e - \mu D_e\},

with the two generators ordered so that cross⁡(ge0,ge1)>0\operatorname{cross}(g_{e0}, g_{e1}) > 0, where cross⁡(a,b)=axby−aybx\operatorname{cross}(a, b) = a_x b_y - a_y b_x. Equivalently, v∈Cev \in C_e if and only if ∣v⋅De∣≤μ v⋅ne\lvert v \cdot D_e \rvert \le \mu\, v \cdot n_e. The cone is pointed: its half angle arctan⁡μ\arctan \mu is less than 90 degrees. The fingers touch edge ii at p1(t1)=Ai+t1Dip_1(t_1) = A_i + t_1 D_i and edge j≠ij \ne i at p2(t2)=Aj+t2Djp_2(t_2) = A_j + t_2 D_j, and d(t1,t2)=p2−p1d(t_1, t_2) = p_2 - p_1. This map is affine in (t1,t2)(t_1, t_2).

Lemma 1 (Nguyen's condition). The contacts p1,p2p_1, p_2 form a force-closure grasp if and only if d∈int⁡Cid \in \operatorname{int} C_i and −d∈int⁡Cj-d \in \operatorname{int} C_j.

Proof. Let WW be the 3×43 \times 4 matrix of the primitive wrenches (cross⁡(p,g),g)(\operatorname{cross}(p, g), g) of the four generators. By the characterization on the force-closure test page, the grasp is in force closure if and only if rank⁡W=3\operatorname{rank} W = 3 and Wk=0W k = 0 for some kk with all entries positive.

Assume d∈int⁡Cid \in \operatorname{int} C_i and −d∈int⁡Cj-d \in \operatorname{int} C_j. Then d=λ0gi0+λ1gi1d = \lambda_0 g_{i0} + \lambda_1 g_{i1} and −d=ν0gj0+ν1gj1-d = \nu_0 g_{j0} + \nu_1 g_{j1} with all four coefficients positive, because the interior of a two-generator cone is the set of strictly positive combinations. The forces dd at p1p_1 and −d-d at p2p_2 have the sum 0 and the total moment cross⁡(p1,d)−cross⁡(p2,d)=−cross⁡(d,d)=0\operatorname{cross}(p_1, d) - \operatorname{cross}(p_2, d) = -\operatorname{cross}(d, d) = 0, so k=(λ0,λ1,ν0,ν1)k = (\lambda_0, \lambda_1, \nu_0, \nu_1) is a positive null vector. For the rank, take moments about p1p_1; this multiplies WW by an invertible matrix. The two wrenches at p1p_1 become (0,gi0)(0, g_{i0}) and (0,gi1)(0, g_{i1}), which span all pure forces. The wrench of gj0g_{j0} at p2p_2 becomes (cross⁡(d,gj0),gj0)(\operatorname{cross}(d, g_{j0}), g_{j0}). Here cross⁡(d,gj0)≠0\operatorname{cross}(d, g_{j0}) \ne 0: if gj0g_{j0} were a positive multiple of −d-d, then −d-d would be on the boundary of CjC_j, not in its interior, and if it were a positive multiple of dd, then CjC_j would contain both dd and −d-d, which a pointed cone does not. So the rank is 3.

Conversely, let the grasp be in force closure, with Wk=0W k = 0 and k>0k > 0. Let f1=k1gi0+k2gi1f_1 = k_1 g_{i0} + k_2 g_{i1} and f2=k3gj0+k4gj1f_2 = k_3 g_{j0} + k_4 g_{j1}. These are in the interiors of CiC_i and CjC_j, so they are not zero. The force rows give f1+f2=0f_1 + f_2 = 0 and the moment row gives cross⁡(p1,f1)+cross⁡(p2,f2)=−cross⁡(d,f1)=0\operatorname{cross}(p_1, f_1) + \operatorname{cross}(p_2, f_2) = -\operatorname{cross}(d, f_1) = 0. If d=0d = 0, all four wrenches have zero moment about p1p_1 and the rank is at most 2, which is false. So d≠0d \ne 0 and f1=λdf_1 = \lambda d for some λ≠0\lambda \ne 0. The polygon is convex, so p2p_2 is in the closed inner half plane of edge ii, and d⋅ni≥0d \cdot n_i \ge 0. Every nonzero vector in CiC_i has a positive normal part, so f1⋅ni>0f_1 \cdot n_i > 0, and λ<0\lambda < 0 would give d⋅ni<0d \cdot n_i < 0. So λ>0\lambda > 0, d=f1/λ∈int⁡Cid = f_1 / \lambda \in \operatorname{int} C_i and −d=f2/λ∈int⁡Cj-d = f_2 / \lambda \in \operatorname{int} C_j. □\square

Lemma 2 (the cone as two inequalities). v∈Cev \in C_e if and only if cross⁡(ge0,v)≥0\operatorname{cross}(g_{e0}, v) \ge 0 and cross⁡(v,ge1)≥0\operatorname{cross}(v, g_{e1}) \ge 0.

Proof. The generators are a basis of the plane. Write v=λ0ge0+λ1ge1v = \lambda_0 g_{e0} + \lambda_1 g_{e1}. Then cross⁡(ge0,v)=λ1cross⁡(ge0,ge1)\operatorname{cross}(g_{e0}, v) = \lambda_1 \operatorname{cross}(g_{e0}, g_{e1}) and cross⁡(v,ge1)=λ0cross⁡(ge0,ge1)\operatorname{cross}(v, g_{e1}) = \lambda_0 \operatorname{cross}(g_{e0}, g_{e1}), and cross⁡(ge0,ge1)>0\operatorname{cross}(g_{e0}, g_{e1}) > 0. □\square

Lines L4 to L6 write, for each of the four corner pairs (t1,t2)∈{s1,u1}×{s2,u2}(t_1, t_2) \in \{s_1, u_1\} \times \{s_2, u_2\}, the inequalities of Lemma 2 for d∈Cid \in C_i and −d∈Cj-d \in C_j. Each is affine in (t1,t2)(t_1, t_2), so it is a linear constraint on the variables s1,u1,s2,u2s_1, u_1, s_2, u_2. Line L7 adds 0≤se0 \le s_e, ue≤1u_e \le 1 and ue−se≥zu_e - s_e \ge z. Call a point of this program feasible.

Lemma 3 (corners suffice). (s1,u1,s2,u2,z)(s_1, u_1, s_2, u_2, z) with z≥0z \ge 0 is feasible if and only if d(t1,t2)∈Ci∩(−Cj)d(t_1, t_2) \in C_i \cap (-C_j) for every (t1,t2)(t_1, t_2) in the closed rectangle R=[s1,u1]×[s2,u2]⊆[0,1]2R = [s_1, u_1] \times [s_2, u_2] \subseteq [0, 1]^2, and ue−se≥zu_e - s_e \ge z.

Proof. The rectangle is the convex hull of its four corners, and dd is affine, so d(R)d(R) is the convex hull of the four corner images. The set Ci∩(−Cj)C_i \cap (-C_j) is convex. So it contains d(R)d(R) if and only if it contains the corner images, which is what the constraints say by Lemma 2. □\square

Lemma 4 (the open rectangle is in the open cones). Let (s1,u1,s2,u2,z)(s_1, u_1, s_2, u_2, z) be feasible with z>0z > 0. Then every (t1,t2)(t_1, t_2) in the open rectangle (s1,u1)×(s2,u2)(s_1, u_1) \times (s_2, u_2) has d∈int⁡Cid \in \operatorname{int} C_i and −d∈int⁡Cj-d \in \operatorname{int} C_j.

Proof. Let v=d(t1,t2)v = d(t_1, t_2) and P=d(R)P = d(R). Suppose v∉int⁡Civ \notin \operatorname{int} C_i. By Lemma 3, v∈Civ \in C_i, so vv is on the boundary of the convex cone CiC_i, and there is a linear function ℓ≠0\ell \ne 0 with ℓ≥0\ell \ge 0 on CiC_i and ℓ(v)=0\ell(v) = 0. Because t1t_1 can move a little both ways inside the rectangle, v+ϵDiv + \epsilon D_i and v−ϵDiv - \epsilon D_i are in P⊆CiP \subseteq C_i for a small ϵ>0\epsilon > 0. So ℓ(v±ϵDi)=±ϵ ℓ(Di)≥0\ell(v \pm \epsilon D_i) = \pm \epsilon\, \ell(D_i) \ge 0, which forces ℓ(Di)=0\ell(D_i) = 0. Then ℓ(x)=κ x⋅ni\ell(x) = \kappa\, x \cdot n_i for some κ≠0\kappa \ne 0, and ℓ(ni)=κ∣ni∣2≥0\ell(n_i) = \kappa \lvert n_i \rvert^2 \ge 0 because ni∈Cin_i \in C_i, so κ>0\kappa > 0. Now ℓ(v)=0\ell(v) = 0 gives v⋅ni=0v \cdot n_i = 0, and v∈Civ \in C_i gives ∣v⋅Di∣≤μ v⋅ni=0\lvert v \cdot D_i \rvert \le \mu\, v \cdot n_i = 0, so v=0v = 0. Then ϵDi∈Ci\epsilon D_i \in C_i, which needs ∣ϵDi⋅Di∣≤μ ϵDi⋅ni=0\lvert \epsilon D_i \cdot D_i \rvert \le \mu\, \epsilon D_i \cdot n_i = 0, a contradiction. The same argument with −d-d, the cone CjC_j and the moves of t2t_2 gives −v∈int⁡Cj-v \in \operatorname{int} C_j. □\square

Theorem. Let z∗z^* be the optimum of the program of lines L1 to L8.

  1. If z∗>0z^* > 0, then the open intervals (s1,u1)(s_1, u_1) on edge ii and (s2,u2)(s_2, u_2) on edge jj returned by line L10 are independent contact regions: every choice of one contact in each gives force closure.
  2. Every pair of intervals I1,I2I_1, I_2 of parameters, open, closed or half open, that are independent contact regions has min⁡(∣I1∣,∣I2∣)≤z∗\min(\lvert I_1 \rvert, \lvert I_2 \rvert) \le z^*. So the returned regions maximize the smaller width.
  3. If the program is infeasible or z∗=0z^* = 0, then no pair of contacts on the two edges gives force closure, and line L9 correctly returns NONE.

Proof. Part 1 follows from Lemma 4 and Lemma 1.

Part 2. Let I1,I2I_1, I_2 be independent regions with closures [s1,u1][s_1, u_1] and [s2,u2][s_2, u_2]. By Lemma 1, every pair in I1×I2I_1 \times I_2 has d∈Ci∩(−Cj)d \in C_i \cap (-C_j). The set Ci∩(−Cj)C_i \cap (-C_j) is closed and dd is continuous, so every pair in the closed rectangle also satisfies it. By Lemma 3, the point (s1,u1,s2,u2,min⁡(u1−s1,u2−s2))(s_1, u_1, s_2, u_2, \min(u_1 - s_1, u_2 - s_2)) is feasible, so its last entry is at most z∗z^*.

Part 3. Suppose some pair (t1,t2)(t_1, t_2) gives force closure. By Lemma 1, d(t1,t2)d(t_1, t_2) is in the open set int⁡Ci∩(−int⁡Cj)\operatorname{int} C_i \cap (-\operatorname{int} C_j). By continuity there is ϵ>0\epsilon > 0 such that every pair in a square of side ϵ\epsilon inside [0,1]2[0, 1]^2 with the corner (t1,t2)(t_1, t_2) also has this property; such a square exists even when t1t_1 or t2t_2 is 0 or 1. By Lemma 3, the square gives a feasible point with z=ϵ>0z = \epsilon > 0, so the program is feasible and z∗>0z^* > 0. □\square

The solver. The program is feasible or not, and it is bounded, because 0≤se≤ue≤10 \le s_e \le u_e \le 1 and z≤u1−s1≤1z \le u_1 - s_1 \le 1. The two-phase simplex method with Bland's smallest index rule cannot cycle (Bland 1977), so phase one stops with a zero cost exactly when the program is feasible, and phase two stops at an optimal basic solution. All arithmetic is in exact rationals, so the comparisons z∗=0z^* = 0 and z∗>0z^* > 0 in line L9 have no rounding error.

Complexity

For one pair of edges the program has a fixed size, five variables and twenty constraints. Bland's rule never repeats a basis, so the number of pivots is bounded by a constant, and the work is O(1)O(1) arithmetic operations on rationals whose size depends only on the input coordinates and μ\mu. Over all pairs of edges of an nn-gon this is O(n2)O(n^2) time and O(1)O(1) extra space besides the best answer. The cost model is the real RAM; the implementation uses exact rationals. Its run time in Python is about 30 ms per pair of edges on a laptop (a measurement, not a bound).

Properties

  • Exact. All numbers are rational, so the test z∗>0z^* > 0 in line L9 is exact. Boundary cases, such as a segment on the edge of the friction cone, get the right answer.
  • Optimal for its objective. The smaller relative width is the largest possible over all pairs of intervals on the two edges. A different objective, such as the sum of the widths or the widths in length units, gives other regions.
  • Robustness margin. Each finger may land anywhere in its region, independently of the other finger. This is a guarantee about positioning errors along the edge, not about errors in μ\mu or in the shape.
  • Not unique. When several pairs of intervals reach z∗z^*, the solver returns one optimal vertex of the program.

Variants and improvements

  • Nguyen's construction. Nguyen (1988) builds the regions geometrically, from the friction cones on the edges. The linear program here uses the same condition and gives the regions with the largest smaller width.
  • More fingers and three dimensions. Ponce, Sullivan, Sudsang, Boissonnat and Merlet (1997) compute regions for four fingers on the faces of a polyhedron. The conditions are again linear in the contact positions, which is why linear programs appear there too.
  • Other objectives. Maximize the sum of the widths, weight the edges by their lengths, or require the regions to be centered on a planned grasp. Each is a different linear objective over the same constraints.
  • Curved objects. On a smooth boundary the cone directions change along the region, so the constraints are no longer linear. One approach samples the boundary and grows the regions around a good grasp, checking each new sample.

When to use it

Use it when a planner picks a grasp on a flat part with two fingers and the hand cannot reach the planned points exactly. The regions tell the controller how much error is safe on each finger. Use the plain force-closure test when the contacts are fixed and only a yes or no answer is needed. Use a grasp quality measure when you must rank closed grasps by the forces they can resist, not by the positioning error they allow.

Pitfalls

  • Closed versus open regions. The optimal closed segments can touch the boundary of a friction cone at their end points, as in the example. Only the open segments are regions.
  • Nonconvex polygons. Nguyen's condition in Lemma 1 uses convexity. On a nonconvex part, the segment between the fingers can leave the part, and the condition must be checked against the true contact normals and the reachability of the points.
  • Normal direction. The inward normal of a counterclockwise polygon is the edge direction turned by +90 degrees. A clockwise polygon flips every normal and turns every push into a pull.
  • Uncertain friction. The regions hold for the given μ\mu. Use a lower bound of the true friction coefficient, because a smaller μ\mu gives smaller regions.
  • Floating point. A float solver with a tolerance can report z∗>0z^* > 0 for a pair of edges where only boundary grasps exist, such as the adjacent sides with μ=1\mu = 1 in the example.

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.

independent_contact_regions.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/independent-contact-regions/. The authors are listed in prov/B0Z8Z4.jsonl.

"""Independent contact regions for two fingers with friction on a polygon.

Model: a rigid polygon in the plane, two point contacts with Coulomb
friction coefficient mu > 0, and Nguyen's condition: two contacts p1 and p2
give force closure if and only if the vector p2 - p1 is strictly inside the
friction cone at p1 and p1 - p2 is strictly inside the friction cone at p2.

The polygon is given in counterclockwise order, so the inward normal of the
edge from V_i to V_(i+1) is the edge direction turned by +90 degrees. A point
on edge i is V_i + t (V_(i+1) - V_i) with t in [0, 1]. A region is an
interval of t. The program finds two intervals [s1, u1] and [s2, u2] that
maximize the smaller of the widths u1 - s1 and u2 - s2, under the condition
that every pair of points of the two closed intervals has p2 - p1 in the
closed cone at p1 and p1 - p2 in the closed cone at p2. When the optimum z is
positive, the open intervals (s1, u1) and (s2, u2) are independent contact
regions: any choice of one contact in each gives force closure.

All arithmetic is exact, with fractions.Fraction. The linear program is
solved by the two-phase simplex method with Bland's rule.
"""

from fractions import Fraction


def _q(x):
    return x if isinstance(x, Fraction) else Fraction(x)


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


def edge(polygon, i):
    """Return (A, D, n): the start point, the direction and the inward normal."""
    k = len(polygon)
    a = (_q(polygon[i][0]), _q(polygon[i][1]))
    b = (_q(polygon[(i + 1) % k][0]), _q(polygon[(i + 1) % k][1]))
    d = (b[0] - a[0], b[1] - a[1])
    n = (-d[1], d[0])
    return a, d, n


def cone_generators(n, d, mu):
    """The two edges of the friction cone, ordered so that cross(g0, g1) > 0.

    n and d have the same length, so n +- mu d make the angle atan(mu) with n.
    """
    g0 = (n[0] + mu * d[0], n[1] + mu * d[1])
    g1 = (n[0] - mu * d[0], n[1] - mu * d[1])
    return (g0, g1) if cross(g0, g1) > 0 else (g1, g0)


# ---------------------------------------------------------------------------
# Linear programming: maximize c x subject to A x <= b and x >= 0.


def _pivot(T, basis, r, col):
    piv = T[r][col]
    T[r] = [v / piv for v in T[r]]
    for i in range(len(T)):
        if i != r and T[i][col] != 0:
            f = T[i][col]
            T[i] = [v - f * w for v, w in zip(T[i], T[r])]
    basis[r] = col


def _run(T, basis, cost, allowed):
    """Minimize cost over the tableau T with Bland's rule. Returns False if
    the program is unbounded."""
    while True:
        red = []
        for j in range(len(cost)):
            if not allowed[j]:
                red.append(0)
                continue
            red.append(cost[j] - sum(cost[basis[i]] * T[i][j]
                                     for i in range(len(T))))
        q = next((j for j in range(len(cost)) if red[j] < 0), None)
        if q is None:
            return True
        best = None
        for i in range(len(T)):
            if T[i][q] > 0:
                ratio = T[i][-1] / T[i][q]
                key = (ratio, basis[i])
                if best is None or key < best[0]:
                    best = (key, i)
        if best is None:
            return False
        _pivot(T, basis, best[1], q)


def simplex_max(A, b, c):
    """Maximize c x subject to A x <= b and x >= 0, in exact arithmetic.

    Returns (value, x, basis) or None if the program is infeasible. basis
    lists the basic columns of [A | I] at the optimum, one per kept row.
    Raises ArithmeticError if the program is unbounded.
    """
    m, n = len(A), len(c)
    neg = [i for i in range(m) if b[i] < 0]
    na = len(neg)
    width = n + m + na
    T, basis = [], []
    for i in range(m):
        row = [_q(v) for v in A[i]] + [Fraction(int(i == k)) for k in range(m)]
        row += [Fraction(0)] * na
        rhs = _q(b[i])
        if rhs < 0:
            row = [-v for v in row]
            rhs = -rhs
            a = n + m + neg.index(i)
            row[a] = Fraction(1)
            basis.append(a)
        else:
            basis.append(n + i)
        T.append(row + [rhs])
    allowed = [True] * width
    if na:
        cost1 = [Fraction(0)] * (n + m) + [Fraction(1)] * na
        _run(T, basis, cost1, allowed)
        if sum(T[i][-1] for i in range(m) if basis[i] >= n + m) > 0:
            return None
        # Drive the artificial variables out of the basis or drop the row.
        keep = []
        for i in range(len(T)):
            if basis[i] >= n + m:
                col = next((j for j in range(n + m) if T[i][j] != 0), None)
                if col is None:
                    continue
                _pivot(T, basis, i, col)
            keep.append(i)
        T = [T[i] for i in keep]
        basis = [basis[i] for i in keep]
        for j in range(n + m, width):
            allowed[j] = False
    cost2 = [-_q(v) for v in c] + [Fraction(0)] * (m + na)
    if not _run(T, basis, cost2, allowed):
        raise ArithmeticError("unbounded program")
    x = [Fraction(0)] * n
    for i, j in enumerate(basis):
        if j < n:
            x[j] = T[i][-1]
    value = sum(_q(ci) * xi for ci, xi in zip(c, x))
    return value, x, list(basis)


# ---------------------------------------------------------------------------
# Independent contact regions.

# Variables of the program, in this order.
S1, U1, S2, U2, Z = range(5)


def region_program(polygon, i, j, mu):
    """Build (A, b, c) for the regions on edges i and j of the polygon."""
    mu = _q(mu)
    A1, D1, n1 = edge(polygon, i)  # @line L1
    A2, D2, n2 = edge(polygon, j)  # @line L1
    a0, a1 = cone_generators(n1, D1, mu)  # @line L2
    b0, b1 = cone_generators(n2, D2, mu)  # @line L2
    A, b = [], []

    def at_least_zero(coef, const):
        # coef . x + const >= 0, written as -coef . x <= const.
        A.append([-v for v in coef])
        b.append(const)

    # p1 = A1 + t1 D1 and p2 = A2 + t2 D2, so d = p2 - p1 is
    # (A2 - A1) + t2 D2 - t1 D1, affine in (t1, t2).
    base = (A2[0] - A1[0], A2[1] - A1[1])  # @line L3
    for v1 in (S1, U1):  # @line L4
        for v2 in (S2, U2):  # @line L4
            for g, sign in ((a0, 1), (a1, -1), (b0, -1), (b1, 1)):
                # Cone at p1: cross(a0, d) >= 0 and cross(d, a1) >= 0.
                # Cone at p2, for -d: cross(b0, -d) >= 0, cross(-d, b1) >= 0.
                coef = [Fraction(0)] * 5
                coef[v1] = -sign * cross(g, D1)
                coef[v2] = sign * cross(g, D2)
                at_least_zero(coef, sign * cross(g, base))  # @line L5 @line L6
    for s, u in ((S1, U1), (S2, U2)):  # @line L7
        A.append([Fraction(int(k == u)) for k in range(5)])  # u <= 1
        b.append(Fraction(1))
        coef = [Fraction(0)] * 5  # u - s - z >= 0
        coef[u], coef[s], coef[Z] = Fraction(1), Fraction(-1), Fraction(-1)
        at_least_zero(coef, Fraction(0))
    c = [0, 0, 0, 0, 1]
    return A, b, c


def independent_regions(polygon, i, j, mu):
    """Nguyen's independent contact regions on edges i and j.

    Returns (z, (s1, u1), (s2, u2)) with z > 0, or None if no pair of points
    on the two edges gives force closure. Any contact in the open interval
    (s1, u1) of edge i and any contact in (s2, u2) of edge j give a
    force-closure grasp, and no pair of regions has both widths above z.
    """
    if i == j or _q(mu) <= 0:
        raise ValueError("two different edges and mu > 0 are needed")
    A, b, c = region_program(polygon, i, j, mu)
    res = simplex_max(A, b, c)  # @line L8
    if res is None or res[0] == 0:  # @line L9
        return None  # @line L9
    z, x, _ = res
    return z, (x[S1], x[U1]), (x[S2], x[U2])  # @line L10


def best_edge_pair(polygon, mu):
    """Try every pair of edges and return (z, i, j, r1, r2) with the largest z,
    or None if no pair of edges admits a force-closure grasp."""
    best = None
    k = len(polygon)
    for i in range(k):
        for j in range(i + 1, k):
            res = independent_regions(polygon, i, j, mu)
            if res is not None and (best is None or res[0] > best[0]):
                best = (res[0], i, j, res[1], res[2])
    return best


def point_on_edge(polygon, i, t):
    a, d, _ = edge(polygon, i)
    t = _q(t)
    return (a[0] + t * d[0], a[1] + t * d[1])
test_independent_contact_regions.py 209 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/independent-contact-regions/. The authors are listed in prov/B0Z8Z4.jsonl.

# All checks are exact, in fractions.Fraction. The reference methods are
# written here again from the definitions: the friction cone as
# |tangential part| <= mu * normal part, and force closure as a strictly
# positive null vector of the 3 x 4 matrix of primitive wrenches with rank 3.

import random
from fractions import Fraction as F

from independent_contact_regions import (best_edge_pair, independent_regions,
                                         point_on_edge, region_program,
                                         simplex_max)

SQUARE = [(0, 0), (2, 0), (2, 2), (0, 2)]
TRIANGLE = [(0, 0), (4, 0), (1, 3)]


def frame(polygon, i):
    k = len(polygon)
    (ax, ay), (bx, by) = polygon[i], polygon[(i + 1) % k]
    d = (F(bx - ax), F(by - ay))
    return d, (-d[1], d[0])  # tangent and inward normal of a CCW polygon


def in_closed_cone(v, polygon, i, mu):
    d, n = frame(polygon, i)
    normal = v[0] * n[0] + v[1] * n[1]
    tangential = v[0] * d[0] + v[1] * d[1]
    return abs(tangential) <= mu * normal


def det3(a, b, c):
    return (a[0] * (b[1] * c[2] - b[2] * c[1]) -
            a[1] * (b[0] * c[2] - b[2] * c[0]) +
            a[2] * (b[0] * c[1] - b[1] * c[0]))


def force_closure(polygon, i, t1, j, t2, mu):
    # Planar wrench (m_z, f_x, f_y) with m_z = p_x f_y - p_y f_x.
    W = []
    for e, t in ((i, t1), (j, t2)):
        p = point_on_edge(polygon, e, t)
        d, n = frame(polygon, e)
        for s in (1, -1):
            f = (n[0] + s * mu * d[0], n[1] + s * mu * d[1])
            W.append((p[0] * f[1] - p[1] * f[0], f[0], f[1]))
    k = [(-1) ** c * det3(*[W[x] for x in range(4) if x != c])
         for c in range(4)]
    return all(v > 0 for v in k) or all(v < 0 for v in k)


def solve(M, rhs):
    # Gauss-Jordan elimination in exact arithmetic.
    n = len(M)
    A = [list(M[r]) + [rhs[r]] for r in range(n)]
    for c in range(n):
        p = next(r for r in range(c, n) if A[r][c] != 0)
        A[c], A[p] = A[p], A[c]
        A[c] = [v / A[c][c] for v in A[c]]
        for r in range(n):
            if r != c and A[r][c] != 0:
                f = A[r][c]
                A[r] = [v - f * w for v, w in zip(A[r], A[c])]
    return [A[r][n] for r in range(n)]


def random_convex_polygon(rng):
    while True:
        pts = sorted(set((rng.randint(-6, 6), rng.randint(-6, 6))
                         for _ in range(8)))

        def cross(o, a, b):
            return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

        lower, upper = [], []
        for p in pts:
            while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
                lower.pop()
            lower.append(p)
        for p in reversed(pts):
            while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
                upper.pop()
            upper.append(p)
        hull = lower[:-1] + upper[:-1]
        if len(hull) >= 4:
            return hull


def random_case(rng):
    poly = random_convex_polygon(rng)
    i, j = rng.sample(range(len(poly)), 2)
    mu = rng.choice([F(1, 4), F(1, 2), F(1), F(2)])
    return poly, i, j, mu


def grid_optimum(polygon, i, j, mu, N):
    # The largest smaller width of two grid intervals such that every pair of
    # grid points in them satisfies the closed cone condition.
    ok = [[False] * (N + 1) for _ in range(N + 1)]
    for a in range(N + 1):
        p1 = point_on_edge(polygon, i, F(a, N))
        for b in range(N + 1):
            p2 = point_on_edge(polygon, j, F(b, N))
            v = (p2[0] - p1[0], p2[1] - p1[1])
            ok[a][b] = (in_closed_cone(v, polygon, i, mu) and
                        in_closed_cone((-v[0], -v[1]), polygon, j, mu))
    best = None
    for s1 in range(N + 1):
        for u1 in range(s1, N + 1):
            for s2 in range(N + 1):
                for u2 in range(s2, N + 1):
                    w = F(min(u1 - s1, u2 - s2), N)
                    if best is not None and w <= best:
                        continue
                    if all(ok[a][b] for a in range(s1, u1 + 1)
                           for b in range(s2, u2 + 1)):
                        best = w
    return best


def test_square_opposite_sides():
    z, (s1, u1), (s2, u2) = independent_regions(SQUARE, 1, 3, F(1, 2))
    assert z == F(1, 2)
    assert u1 - s1 == F(1, 2) and u2 - s2 == F(1, 2)
    # Edge 1 goes up and edge 3 goes down: the heights must match.
    y1 = (point_on_edge(SQUARE, 1, s1)[1], point_on_edge(SQUARE, 1, u1)[1])
    y3 = (point_on_edge(SQUARE, 3, u2)[1], point_on_edge(SQUARE, 3, s2)[1])
    assert y1 == y3


def test_square_adjacent_sides():
    assert independent_regions(SQUARE, 0, 1, F(1, 2)) is None
    assert independent_regions(SQUARE, 0, 1, F(1)) is None  # only the corner
    z, r1, r2 = independent_regions(SQUARE, 0, 1, F(2))
    assert z == F(1, 2)


def test_triangle():
    assert best_edge_pair(TRIANGLE, F(1, 4)) is None
    z, i, j, r1, r2 = best_edge_pair(TRIANGLE, F(1))
    assert (z, i, j) == (F(2, 7), 0, 1)


def test_dual_certificate_proves_optimality():
    # For max c x, A x <= b, x >= 0: a y >= 0 with A^T y >= c and b y = z
    # proves that z is the optimum.
    rng = random.Random(1)
    found = 0
    for _ in range(12):
        poly, i, j, mu = random_case(rng)
        A, b, c = region_program(poly, i, j, mu)
        res = simplex_max(A, b, c)
        if res is None:
            continue
        found += 1
        z, x, basis = res
        m, n = len(A), len(c)
        assert len(basis) == m
        cols = [[A[r][k] if k < n else F(int(r == k - n)) for r in range(m)]
                for k in basis]
        cB = [F(c[k]) if k < n else F(0) for k in basis]
        y = solve(cols, cB)  # B^T y = c_B
        assert all(v >= 0 for v in y)
        for k in range(n):
            assert sum(A[r][k] * y[r] for r in range(m)) >= c[k]
        assert sum(b[r] * y[r] for r in range(m)) == z
        for r in range(m):
            assert sum(A[r][k] * x[k] for k in range(n)) <= b[r]
    assert found >= 4


def test_against_grid_brute_force():
    rng = random.Random(2)
    N = 10
    seen_none = seen_some = 0
    for _ in range(10):
        poly, i, j, mu = random_case(rng)
        res = independent_regions(poly, i, j, mu)
        g = grid_optimum(poly, i, j, mu, N)
        if res is None:
            seen_none += 1
            # No pair of grid points gives force closure.
            assert not any(force_closure(poly, i, F(a, N), j, F(b, N), mu)
                           for a in range(N + 1) for b in range(N + 1))
        else:
            seen_some += 1
            z = res[0]
            assert g is not None and z - F(2, N) < g <= z
    assert seen_none >= 1 and seen_some >= 3


def test_every_choice_in_the_regions_is_force_closure():
    rng = random.Random(3)
    checked = 0
    for _ in range(12):
        poly, i, j, mu = random_case(rng)
        res = independent_regions(poly, i, j, mu)
        if res is None:
            continue
        z, (s1, u1), (s2, u2) = res
        assert z > 0 and u1 - s1 >= z and u2 - s2 >= z
        for _ in range(40):
            t1 = s1 + (u1 - s1) * F(rng.randint(1, 999), 1000)
            t2 = s2 + (u2 - s2) * F(rng.randint(1, 999), 1000)
            assert force_closure(poly, i, t1, j, t2, mu)
        checked += 1
    assert checked >= 4

History

Nguyen (1988) gave the force-closure condition for two fingers with friction in the plane and introduced independent regions of contact for the fingertips, so that a planned grasp stays in force closure under positioning errors. Ponce and his coauthors (1997) extended the computation to four fingers on polyhedra. Later work computes regions for more fingers, for three-dimensional objects given as meshes, and for hands whose fingers cannot reach every point.

References

  1. Van-Duc Nguyen, Constructing force-closure grasps, The International Journal of Robotics Research 7(3), 3-16, 1988, the whole paper (the force-closure condition for two fingers with friction in the plane, and independent regions of contact on the edges of a polygon)
  2. Jean Ponce, Steve Sullivan, Attawith Sudsang, Jean-Daniel Boissonnat and Jean-Pierre Merlet, On computing four-finger equilibrium and force-closure grasps of polyhedral objects, The International Journal of Robotics Research 16(1), 11-35, 1997, the whole paper (independent regions for four fingers on the faces of a polyhedron, by linear constraints)
  3. 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)

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