Algorithm Search⌘K

Algorithmadvanced

Brost-Goldberg modular fixture algorithm

Also called modular fixture synthesis.

Brost and Goldberg's complete algorithm that lists all form closure fixtures of three locators and a clamp on a lattice plate for a polygonal part.

Time
O(n^4 d^6) worst
Space
O(n + K) extra
Where
K = number of fixtures in the output; d = diameter of the part in lattice units; n = number of edges of the part
Properties
deterministicexactiterative
Origin
Randy C. Brost, Kenneth Y. Goldberg, 1994

The Brost-Goldberg algorithm finds every planar modular fixture of a fixed class for a polygonal part. A modular fixture plate has holes on a square lattice. The class has three locators, which are pins in holes, and one clamp, which is anchored at a hole and pushes along a lattice axis. The algorithm puts the three locators on lattice points, tries each triple of edges, solves for each pose of the part that puts the locators on those edges, and then searches the holes near the part for a clamp that gives form closure. It is complete: it returns each fixture of the class, or it reports that there is none. Brost and Goldberg (1996) published it, and it is the standard example of a complete algorithm in fixture planning. This page gives an exact version for point locators and proves that it is complete.

In plain words

You have a flat part with straight edges and a steel plate with a grid of holes. You put three pins in three holes and push the part against them. A clamp in a fourth hole presses the part against the pins. The part must not be able to slide or turn at all.

The algorithm tries all the ways to do this. It keeps the first pin in one fixed hole, because a shift of the whole layout by grid steps gives the same fixture. It picks two more holes that are close enough to touch the part at the same time. For each choice of three edges, it finds the ways to place the part so that each pin touches its edge. Then it looks at the holes next to the part for a clamp that pushes the part against the pins and holds it.

The problem

Input. A simple polygon PP with nn edges and rational vertices in counterclockwise order, and a clamp reach ρ>0\rho > 0. The lattice is Z2\mathbb{Z}^2 with unit spacing.

Fixture. A fixture is a pose gg of the part (a rotation RR and a translation tt, so a body point xx goes to Rx+tRx + t), three lattice points q1<q2<q3q_1 < q_2 < q_3 in lexicographic order, three edges e1,e2,e3e_1, e_2, e_3, and a clamp (v,d)(v, d), so that:

  1. each qkq_k is in the relative interior of the edge g(ek)g(e_k), not at a vertex;
  2. v∈Z2v \in \mathbb{Z}^2 is strictly outside g(P)g(P), and dd is one of (±1,0)(\pm 1, 0) and (0,±1)(0, \pm 1);
  3. the first point uu of the boundary of g(P)g(P) on the ray v+sdv + s d, s>0s > 0, is in the relative interior of an edge ee, with ∣u−v∣≤ρ\lvert u - v \rvert \le \rho and u∉{q1,q2,q3}u \notin \{q_1, q_2, q_3\};
  4. the four contacts give form closure: their wrenches positively span R3\mathbb{R}^3.

All contacts are frictionless points. The wrench of a contact at pp with inner normal ν\nu is (νx,νy,pxνy−pyνx)(\nu_x, \nu_y, p_x \nu_y - p_y \nu_x). A locator is a point, and the clamp is a point at the end of a plunger. This is the model of Zhuang and Goldberg (1996) for the fixtures of Brost and Goldberg, with point fixture elements and ρ=1\rho = 1.

Output. Every fixture with q1=(0,0)q_1 = (0, 0), each one time. A translation by an integer vector maps fixtures to fixtures, so all other fixtures are these, moved on the plate.

The algorithm

Write mkm_k for the outward normal of edge eke_k in the part frame and hk=mk⋅akh_k = m_k \cdot a_k, where aka_k is the start vertex of eke_k. Then eke_k lies on the line mk⋅x=hkm_k \cdot x = h_k.

  1. MODULAR-FIXTURES(P, ρ) ▷ P: polygon with edges e_1 .. e_n, counterclockwise
  2. 1D ← the diameter of P
  3. 2for each pair of lattice points q2 < q3, with q1 = (0,0) < q2 and |q_i − q_j| ≤ D for all i, j
  4. 3for each triple (e_a, e_b, e_c) of edges of P
  5. 4for each pose g that puts q1, q2, q3 on the lines of g(e_a), g(e_b), g(e_c)
  6. 5if some q_k is not strictly inside its edge of g(P) then skip this pose
  7. 6for each lattice point v outside g(P), near g(P), and each d ∈ {+x, −x, +y, −y}
  8. 7u ← the first point of ∂g(P) on the ray v + s·d; skip unless u is inside an edge e, |u − v| ≤ ρ and u ∉ {q1, q2, q3}
  9. 8if the wrenches of q1, q2, q3 and u positively span R^3 then output (q, edges, g, (v, d, e, u))

Line L2. The three locators touch the part at the same time, so each pair of them is at most the diameter DD apart. The first locator is at the origin, and the other two come after it in lexicographic order. So q2q_2 and q3q_3 are lattice points in a half disk of radius DD.

Line L4. Rotate by the angle θ\theta, with c=cos⁡θc = \cos\theta and s=sin⁡θs = \sin\theta. The locator qkq_k is on the line of g(ek)g(e_k) when (Rmk)⋅t=(Rmk)⋅qk−hk(R m_k) \cdot t = (R m_k) \cdot q_k - h_k. These are three linear equations in the two entries of tt. If the three normals are not all parallel, the equations have a solution if and only if the 3×33 \times 3 determinant of the system is zero. Expand it along the right side. The cofactors C1=m2×m3C_1 = m_2 \times m_3, C2=m3×m1C_2 = m_3 \times m_1 and C3=m1×m2C_3 = m_1 \times m_2 do not change under a rotation, and (Rm)⋅q=c (m⋅q)+s (m×q)(R m) \cdot q = c\,(m \cdot q) + s\,(m \times q). So the condition is one linear equation in cc and ss:

Ac+Bs+C0=0,A=∑kCk (mk⋅qk),B=∑kCk (mk×qk),C0=−∑kCkhk.A c + B s + C_0 = 0, \qquad A = \sum_k C_k\,(m_k \cdot q_k), \quad B = \sum_k C_k\,(m_k \times q_k), \quad C_0 = -\sum_k C_k h_k.

With r2=A2+B2>0r^2 = A^2 + B^2 > 0 and Δ=r2−C02≥0\Delta = r^2 - C_0^2 \ge 0, the line meets the unit circle at

c=−AC0±BΔr2,s=−BC0∓AΔr2,c = \frac{-A C_0 \pm B\sqrt{\Delta}}{r^2}, \qquad s = \frac{-B C_0 \mp A\sqrt{\Delta}}{r^2},

so there are at most two poses. Cramer's rule on two equations with independent normals gives tt. If all three normals are parallel or r2=0r^2 = 0, the line returns no pose. The proof shows that such a triple never gives form closure.

Exact arithmetic. Each coordinate of a pose is in the field Q(Δ)\mathbb{Q}(\sqrt{\Delta}). The implementation stores a number as a+bΔa + b\sqrt{\Delta} with rational aa and bb. The sign of such a number is exact: if aa and bb have opposite signs, compare a2a^2 with b2Δb^2 \Delta. So every test of lines L5 to L8 is an exact sign test, and a contact at the end of an edge is never accepted by rounding.

Lines L6 and L7. A clamp hole is within ρ\rho of the boundary, so it is in the bounding box of g(P)g(P) grown by ρ\rho. The implementation first drops the pairs (v,d)(v, d) whose segment of length ρ\rho is far from every edge in floating point, with a margin of 10−710^{-7}. Then it tests "vv outside g(P)g(P)" with an exact point in polygon test, and finds the first hit uu exactly. A hit at a vertex, or on an edge along the ray, is not a valid contact.

Line L8. Let w1,…,w4w_1, \ldots, w_4 be the four wrenches, each with the inner normal of its edge. Set λi=(−1)idet⁡(wj:j≠i)\lambda_i = (-1)^i \det(w_j : j \ne i). Then ∑iλiwi=0\sum_i \lambda_i w_i = 0. The four wrenches positively span R3\mathbb{R}^3 if and only if all λi\lambda_i are nonzero and have the same sign. This is the planar form closure test of kinematic fixture analysis.

Example

The part is the triangle with vertices (0,0)(0, 0), (2,0)(2, 0) and (1,32)(1, \tfrac32), with ρ=1\rho = 1. Edge e0e_0 is the base, edge e1e_1 the right side and edge e2e_2 the left side. The diameter is D=2D = 2. The counts after each line are:

line what is counted count
L2 lattice points q>(0,0)q > (0,0) with ∣q∣≤2\lvert q \rvert \le 2 6
L2 pairs q2<q3q_2 < q_3 with ∣q3−q2∣≤2\lvert q_3 - q_2 \rvert \le 2 10
L3 pairs times edge triples (10×2710 \times 27) 270
L4 poses 428
L5 poses with each locator inside its edge 48
L8 fixtures 56

The 56 fixtures use 36 different pairs of locator sites and edge triples. One of them has q=((0,0),(1,0),(1,1))q = ((0,0), (1,0), (1,1)) and the edges (e0,e0,e1)(e_0, e_0, e_1). In the part frame, m0=(0,−2)m_0 = (0, -2) with h0=0h_0 = 0, and m1=(32,1)m_1 = (\tfrac32, 1) with h1=3h_1 = 3. The cofactors are (3,−3,0)(3, -3, 0), so A=0A = 0, B=−6B = -6 and C0=0C_0 = 0. The equation is −6s=0-6 s = 0: two locators on the base make the base horizontal. The poses are c=1c = 1 and c=−1c = -1.

  • For c=−1c = -1, the base goes to the segment from (53,0)(\tfrac53, 0) to (113,0)(\tfrac{11}3, 0). It does not contain (0,0)(0, 0), so line L5 skips the pose.
  • For c=1c = 1, the first equation gives ty=0t_y = 0 and the second gives 32tx+ty=−12\tfrac32 t_x + t_y = -\tfrac12, so t=(−13,0)t = (-\tfrac13, 0). The placed triangle is (−13,0)(-\tfrac13, 0), (53,0)(\tfrac53, 0), (23,32)(\tfrac23, \tfrac32). The points (0,0)(0,0) and (1,0)(1,0) are inside the base, and (1,1)(1,1) is inside the right side.

The inner normals have the length of their edge: (0,2)(0, 2) on the base, (−32,−1)(-\tfrac32, -1) on the right side and (32,−1)(\tfrac32, -1) on the left side. The locator wrenches are w1=(0,2,0)w_1 = (0, 2, 0), w2=(0,2,2)w_2 = (0, 2, 2) and w3=(−32,−1,12)w_3 = (-\tfrac32, -1, \tfrac12). Six pairs (v,d)(v, d) reach the inside of an edge within distance 1:

vv dd uu result
(0,−1)(0, -1) +y+y (0,0)(0, 0) skip at L7, uu is a locator
(1,−1)(1, -1) +y+y (1,0)(1, 0) skip at L7, uu is a locator
(1,2)(1, 2) −y-y (1,1)(1, 1) skip at L7, uu is a locator
(2,1)(2, 1) −x-x (1,1)(1, 1) skip at L7, uu is a locator
(0,1)(0, 1) +x+x (13,1)(\tfrac13, 1) on e2e_2 w4=(32,−1,−116)w_4 = (\tfrac32, -1, -\tfrac{11}6), λ=(2,4,6,6)\lambda = (2, 4, 6, 6), a fixture
(0,1)(0, 1) −y-y (0,12)(0, \tfrac12) on e2e_2 w4=(32,−1,−34)w_4 = (\tfrac32, -1, -\tfrac34), λ=(214,34,6,6)\lambda = (\tfrac{21}4, \tfrac34, 6, 6), a fixture

For the first fixture, 2w1+4w2+6w3+6w4=(0,0,0)2 w_1 + 4 w_2 + 6 w_3 + 6 w_4 = (0, 0, 0) with all weights positive, so the four contacts positively span R3\mathbb{R}^3. The clamp on the left side pushes the part to the right and down, against the two pins under the base and the pin on the right side.

Correctness

Theorem. MODULAR-FIXTURES(P,ρ)(P, \rho) returns each fixture with q1=(0,0)q_1 = (0, 0) exactly one time, and nothing else.

Soundness follows from the exact tests: line L4 puts the locators on the edge lines, line L5 checks that they are inside the edges, lines L6 and L7 check the clamp, and line L8 checks form closure. For completeness, take a fixture with q1=0q_1 = 0. Its locators are points of g(P)g(P), so they are at most DD apart and line L2 tries them. Line L3 tries its edges. Its pose solves the equation of line L4. That equation has at most two solutions unless the three locator wrenches are linearly dependent. Then the null vector of the four wrenches has λ4=0\lambda_4 = 0, so there is no form closure. The clamp hole is in the box of line L6, and the float filter never drops a real hit. A pose and its locators fix the edges, so no fixture comes out twice. The full proof is below.

Proof: MODULAR-FIXTURES returns each normalized fixture exactly one timefull

We use the definitions of the page. PP is a simple polygon with edges e1,…,ene_1, \ldots, e_n in counterclockwise order. Edge eke_k has the outward normal mkm_k and lies on the line mk⋅x=hkm_k \cdot x = h_k. A pose gg is a rotation RR by an angle θ\theta, with c=cos⁡θc = \cos\theta and s=sin⁡θs = \sin\theta, and a translation tt. A fixture is a tuple (g,q1,q2,q3,e1,e2,e3,v,d)(g, q_1, q_2, q_3, e_1, e_2, e_3, v, d) with conditions 1 to 4 of the page. It is normalized when q1=(0,0)q_1 = (0, 0).

Lemma 1 (translation). If FF is a fixture and z∈Z2z \in \mathbb{Z}^2, then FF moved by zz (each qkq_k, vv and the translation of gg shifted by zz) is a fixture. So the set of all fixtures is the set of normalized fixtures and their integer translations.

Proof. A shift by zz maps lattice points to lattice points and keeps the conditions "inside an edge", "outside the part", the first hit of an axis ray, and distances. The wrench of a contact at p+zp + z with normal ν\nu is (ν,(p+z)×ν)(\nu, (p + z) \times \nu), and (p+z)×ν=p×ν−zyνx+zxνy(p + z) \times \nu = p \times \nu - z_y \nu_x + z_x \nu_y. So each new wrench is TT times the old one, with the same invertible matrix

T=(100010−zyzx1)T = \begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ -z_y & z_x & 1 \end{pmatrix}

for every contact. Hence the four wrenches positively span R3\mathbb{R}^3 before the shift if and only if they do after it. A fixture with q1=zq_1 = z moved by −z-z is normalized. □\square

Lemma 2 (line L2). The sites of a normalized fixture are among the pairs of line L2.

Proof. Each qkq_k is a point of g(P)g(P), and gg is an isometry, so ∣qi−qj∣≤D\lvert q_i - q_j \rvert \le D, the diameter of PP. By the order q1<q2<q3q_1 < q_2 < q_3 and q1=(0,0)q_1 = (0,0), the points q2q_2 and q3q_3 come after the origin in lexicographic order. The implementation lists all lattice points (x,y)(x, y) with 0≤x≤⌊D⌋+10 \le x \le \lfloor D \rfloor + 1, ∣y∣≤⌊D⌋+1\lvert y \rvert \le \lfloor D \rfloor + 1, (x,y)>(0,0)(x, y) > (0, 0) and x2+y2≤D2x^2 + y^2 \le D^2. These are all lattice points after the origin within distance DD. It then keeps each pair q2<q3q_2 < q_3 with ∣q3−q2∣2≤D2\lvert q_3 - q_2 \rvert^2 \le D^2. □\square

Lemma 3 (the pose equation). Fix the sites qkq_k and the edges eke_k, and let C1=m2×m3C_1 = m_2 \times m_3, C2=m3×m1C_2 = m_3 \times m_1 and C3=m1×m2C_3 = m_1 \times m_2. Assume that not all CkC_k are zero. A pose puts each qkq_k on the line of g(ek)g(e_k) if and only if Ac+Bs+C0=0A c + B s + C_0 = 0 and tt is the unique solution of the three equations below, with AA, BB and C0C_0 as on the page.

Proof. The point qkq_k is on the line of g(ek)g(e_k) if and only if g−1(qk)=RT(qk−t)g^{-1}(q_k) = R^{\mathsf T}(q_k - t) is on the line of eke_k, that is mk⋅RT(qk−t)=hkm_k \cdot R^{\mathsf T}(q_k - t) = h_k, or

(Rmk)⋅t=(Rmk)⋅qk−hk,k=1,2,3.(R m_k) \cdot t = (R m_k) \cdot q_k - h_k, \qquad k = 1, 2, 3.

This is a system Mt=bM t = b with MM of size 3×23 \times 2. A cofactor CkC_k is a 2×22 \times 2 minor of MM up to sign, since (Rmi)×(Rmj)=mi×mj(R m_i) \times (R m_j) = m_i \times m_j for a rotation. Some Ck≠0C_k \ne 0, so MM has rank 2, the solution tt is unique if it exists, and it exists if and only if the 3×33 \times 3 matrix [M∣b][M \mid b] is singular. The expansion of its determinant along the column bb is ∑kCkbk\sum_k C_k b_k. Next, RTq=(cqx+sqy,−sqx+cqy)R^{\mathsf T} q = (c q_x + s q_y, -s q_x + c q_y), so

(Rm)⋅q=m⋅RTq=c (m⋅q)+s (mxqy−myqx)=c (m⋅q)+s (m×q).(R m) \cdot q = m \cdot R^{\mathsf T} q = c\,(m \cdot q) + s\,(m_x q_y - m_y q_x) = c\,(m \cdot q) + s\,(m \times q).

So ∑kCkbk=Ac+Bs+C0\sum_k C_k b_k = A c + B s + C_0. □\square

Lemma 4 (line L4 is complete). If a fixture uses the sites qkq_k and the edges eke_k, its pose is one of the poses of line L4.

Proof. Let w1,w2,w3w_1, w_2, w_3 be the locator wrenches and w4w_4 the clamp wrench. We first show that w1,w2,w3w_1, w_2, w_3 are linearly independent. Set λi=(−1)idet⁡(wj:j≠i)\lambda_i = (-1)^i \det(w_j : j \ne i), with the index ii from 0 to 3. For each coordinate jj, ∑iλi(wi)j\sum_i \lambda_i (w_i)_j is the expansion along the first column of the 4×44 \times 4 matrix with rows ((wi)j,wi)((w_i)_j, w_i). This matrix has two equal columns, so the sum is 0, and ∑iλiwi=0\sum_i \lambda_i w_i = 0. If w1,w2,w3w_1, w_2, w_3 are dependent, then λ4=±det⁡(w1,w2,w3)=0\lambda_4 = \pm\det(w_1, w_2, w_3) = 0. Then either the four wrenches have rank less than 3, or their null space is spanned by λ\lambda, which has a zero entry. In both cases no strictly positive combination of them is zero, so by the positive span lemma (the vectors positively span R3\mathbb{R}^3 if and only if they span it and a strictly positive combination is zero) there is no form closure. This contradicts condition 4.

Now the two cases that line L4 drops:

  • All three normals parallel. Then the forces of w1,w2,w3w_1, w_2, w_3 are all multiples of one vector ν\nu, so the three wrenches lie in the plane spanned by (ν,0)(\nu, 0) and (0,0,1)(0, 0, 1), and they are dependent.
  • r2=A2+B2=0r^2 = A^2 + B^2 = 0. Then the pose equation is C0=0C_0 = 0. If C0≠0C_0 \ne 0, no pose exists. If C0=0C_0 = 0, every angle θ\theta has a pose gθg_\theta by Lemma 3, and gθg_\theta depends smoothly on θ\theta. Along this family each qkq_k stays on the line of gθ(ek)g_\theta(e_k). In the moving part frame, the curve θ↦gθ−1(qk)\theta \mapsto g_\theta^{-1}(q_k) stays on the line of eke_k, so the first-order change of the gap at each locator is zero. The derivative of the family at the pose of the fixture is a twist ξ\xi with ω=1\omega = 1, so ξ≠0\xi \ne 0, and wk⋅ξ=0w_k \cdot \xi = 0 for k=1,2,3k = 1, 2, 3. A nonzero vector is orthogonal to the three wrenches, so they are dependent.

So in a fixture, not all CkC_k are zero and r2>0r^2 > 0. The pose satisfies Ac+Bs+C0=0A c + B s + C_0 = 0 and c2+s2=1c^2 + s^2 = 1. The line meets the circle only if its distance ∣C0∣/r\lvert C_0 \rvert / r from the origin is at most 1, that is Δ=r2−C02≥0\Delta = r^2 - C_0^2 \ge 0. Substitution shows that the two points of the page satisfy both equations: Ac+Bs=(−A2C0−B2C0)/r2=−C0A c + B s = (-A^2 C_0 - B^2 C_0)/r^2 = -C_0 and c2+s2=r2(C02+Δ)/r4=1c^2 + s^2 = r^2 (C_0^2 + \Delta) / r^4 = 1. A line meets a circle in at most two points, so these are all the solutions, and one solution when Δ=0\Delta = 0. By Lemma 3 the translation is the unique solution of the system, which Cramer's rule gives from two rows with mi×mj≠0m_i \times m_j \ne 0. □\square

Lemma 5 (exact signs). Each number that lines L5 to L8 test is in the field K=Q(Δ)K = \mathbb{Q}(\sqrt{\Delta}), and its sign is computed exactly.

Proof. The inputs are rational, and cc, ss and tt are in KK, so all coordinates of g(P)g(P) are in KK, and so are all sums, products and quotients of them. If Δ\Delta is the square of a rational, K=QK = \mathbb{Q}. Otherwise Δ\sqrt{\Delta} is irrational and a+bΔa + b\sqrt{\Delta} is zero only if a=b=0a = b = 0. If aa and bb have the same sign, or one is zero, the sign is clear. If they have opposite signs, the sign is that of the term with the larger absolute value, and a2≠b2Δa^2 \ne b^2 \Delta because Δ\sqrt{\Delta} is irrational. □\square

Lemma 6 (line L5). A pose passes line L5 if and only if each qkq_k is in the relative interior of g(ek)g(e_k).

Proof. By Lemma 3, qkq_k is on the line of g(ek)=[a,b]g(e_k) = [a, b]. Write δ=b−a\delta = b - a and μ=(qk−a)⋅δ\mu = (q_k - a) \cdot \delta. The point is strictly between aa and bb if and only if 0<μ<δ⋅δ0 < \mu < \delta \cdot \delta. Line L5 tests these two signs exactly (Lemma 5). □\square

Lemma 7 (lines L6 and L7). For a pose that passes line L5, lines L6 and L7 keep exactly the pairs (v,d)(v, d) of condition 2 and 3.

Proof. If (v,d)(v, d) satisfies conditions 2 and 3, then v=u−σdv = u - \sigma d with σ≤ρ\sigma \le \rho and u∈g(P)u \in g(P). So vv is in the bounding box of g(P)g(P) grown by ρ\rho. The implementation scans the integer points from ⌊min⁡x−ρ⌋−1\lfloor \min x - \rho \rfloor - 1 or less to ⌈max⁡x+ρ⌉+1\lceil \max x + \rho \rceil + 1 or more, and the same for yy, which covers the box with a margin of one unit against rounding of the float bounds. The float filter drops (v,d)(v, d) only if the segment from vv to v+ρdv + \rho d is more than 10−710^{-7} from every edge in floating point. For a real hit the true distance is 0, and the rounding error of the float distance for coordinates of moderate size is far below 10−710^{-7}, so a real hit is never dropped. The test "vv strictly outside g(P)g(P)" is the crossing number test with exact signs, after an exact test for a point on the boundary. The first hit is the minimum of s>0s > 0 over the crossings of the ray with the edges, computed exactly. A crossing at an end of an edge, two crossings at the same ss, or an edge on the line of the ray mark the hit as a vertex, and line L7 skips it. Line L7 then checks s≤ρs \le \rho and u∉{q1,q2,q3}u \notin \{q_1, q_2, q_3\} with exact signs. □\square

Lemma 8 (line L8). Line L8 accepts the four wrenches if and only if they positively span R3\mathbb{R}^3.

Proof. The proof of Lemma 4 gives ∑iλiwi=0\sum_i \lambda_i w_i = 0. If the rank is 3, some 3×33 \times 3 minor is not zero, so λ≠0\lambda \ne 0, and the null space of the map μ↦∑iμiwi\mu \mapsto \sum_i \mu_i w_i has dimension 4−3=14 - 3 = 1, so it is spanned by λ\lambda. Then a strictly positive null vector exists if and only if all λi\lambda_i are nonzero with one sign. If the rank is less than 3, all λi\lambda_i are zero, line L8 rejects, and the wrenches do not span R3\mathbb{R}^3. By the positive span lemma, line L8 is right in both cases. The signs are exact by Lemma 5. □\square

Theorem. MODULAR-FIXTURES(P,ρ)(P, \rho) outputs each normalized fixture exactly one time, and outputs nothing else.

Proof. Soundness. An output has q1=(0,0)q_1 = (0,0) and sites in order by line L2. Lemmas 3 and 6 give condition 1, Lemma 7 gives conditions 2 and 3, and Lemma 8 gives condition 4.

Completeness. Take a normalized fixture. By Lemma 2, line L2 tries its sites. Line L3 tries all n3n^3 triples, so it tries its edges. By Lemma 4, line L4 produces its pose. By Lemma 6 the pose passes line L5. By Lemma 7, lines L6 and L7 produce its clamp pair (v,d)(v, d) with its uu and ee. By Lemma 8, line L8 outputs it.

Uniqueness. Two outputs from different iterations differ in the sites, in the pose, or in (v,d)(v, d). The edges cannot be the only difference: the relative interiors of the edges of a simple polygon are disjoint, so a pose and a site qkq_k fix the edge that contains qkq_k in its interior. Two poses of line L4 for the same sites and edges are different points of the circle. So each fixture is output at most one time. ■\blacksquare

Termination. The loops of lines L2, L3, L4 and L6 are over finite sets: a finite set of lattice points, n3n^3 triples, at most two poses, and a finite box of holes with four directions.

Complexity

Let nn be the number of edges and d=Dd = D the diameter in lattice units. Count field operations in Q(Δ)\mathbb{Q}(\sqrt{\Delta}); for a fixed input, the numbers have bounded size.

  • Lines L2 and L3. There are O(d2)O(d^2) lattice points in a half disk of radius dd, so O(d4)O(d^4) pairs, and n3n^3 edge triples. Line L4 runs O(n3d4)O(n^3 d^4) times and costs O(1)O(1) each time.
  • Line L5. At most 22 poses per triple, and O(1)O(1) work for each, after the part is placed in O(n)O(n).
  • Lines L6 to L8. The box has O(d2)O(d^2) holes. For each, the float filter, the point in polygon test and the first hit cost O(n)O(n). So one pose that passes line L5 costs O(nd2)O(n d^2).

The worst case is O(n3d4⋅nd2)=O(n4d6)O(n^3 d^4 \cdot n d^2) = O(n^4 d^6). In practice few poses pass line L5 (48 of 428 in the example), so the time is close to the O(n3d4)O(n^3 d^4) of the pose step. Only the holes within ρ\rho of the boundary can hold the clamp. Each edge is at most dd long, so there are O(nd)O(n d) such holes. A scan of only these holes costs O(n2d)O(n^2 d) per pose, and the worst case becomes O(n3d4⋅n2d)=O(n5d5)O(n^3 d^4 \cdot n^2 d) = O(n^5 d^5). This is the bound that Zhuang and Goldberg (1996) state for the algorithm of Brost and Goldberg. It is better than O(n4d6)O(n^4 d^6) when n<dn < d. The extra space is O(n+K)O(n + K), where KK is the number of fixtures in the output.

Properties

  • Complete for its model. If the list is empty, no fixture of the class exists. This is the main property of the algorithm. A heuristic can only say that it did not find one.
  • Exact. All signs are computed in Q(Δ)\mathbb{Q}(\sqrt{\Delta}), so a fixture is never accepted or lost by rounding. The only floating point step is a filter with a margin.
  • Deterministic. The order of the output is the order of the loops.
  • Lattice invariant. The output has q1=(0,0)q_1 = (0,0). Each fixture stands for all its integer translations.
  • Output size. The number of fixtures grows fast with the size of the part: 56 for the triangle above, 76 for the right triangle with legs 2 and 32\tfrac32.

Variants and improvements

  • Round locators. Real locators are pins of radius rr, with rr less than half the lattice spacing. A pin of radius rr touches an edge where a point touches the edge moved out by rr. So a version for round pins works with the boundary of the Minkowski sum of PP and a disk of radius rr, which has arcs at the vertices. Brost and Goldberg treat pins of a fixed size.
  • Quality ranking. Brost and Goldberg rank the fixtures by a quality measure, so that a planner can take the best one. The complete list makes such a ranking possible.
  • Other fixture classes. Zhuang and Goldberg (1996) study fixtures with four clamps and no locators. They show that some convex polygons have no fixture with three locators and a clamp, so the empty answer of this algorithm can be correct for a part of any size. They also list complete algorithms for a vise with four locators on a split lattice (Wallack and Canny) and for fixtures with edge contacts (Overmars and others).
  • Three dimensions. A part in space needs at least 7 frictionless contacts for form closure (Markenscoff, Ni and Papadimitriou 1990). The same plan, contact sites, then poses, then a closure test, applies, but the poses solve larger systems.

When to use it

Use it when the part is planar, or a prismatic part with a planar section, and the shop has a lattice plate. Use it when you must know if a fixture exists, because it is complete. Use it when you want all the fixtures, to rank them by quality, by access for the tool or by the clamp position. For a single fixture of a large part, a heuristic search over a few candidate sites is faster. For parts with friction, curved edges or a 3D layout, the model does not apply, and a general fixture planning method with a kinematic analysis of each candidate is the usual way.

Pitfalls

  • Rounded poses at line L5. If line L4 gives a pose in floating point, line L5 can accept a contact at a vertex or reject a contact that is just inside the edge. Use exact arithmetic in Q(Δ)\mathbb{Q}(\sqrt{\Delta}), and test "strictly inside" as two exact sign tests.
  • One root at line L4. The line Ac+Bs+C0=0A c + B s + C_0 = 0 meets the unit circle in two points when Δ>0\Delta > 0. A version that keeps one root loses half of the poses, and the claim of completeness fails.
  • Mixed normals at line L8. The closure test needs the inner normal for all four contacts. If the locators use the outward normal and the clamp the inner one, line L8 gives the wrong answer. If all four use the outward normal, all λi\lambda_i change sign, and the test still works.
  • Vertex hits at line L7. If the clamp ray first meets a vertex, the contact normal is not defined. Line L7 must skip it, not take the normal of one of the two edges.
  • No normal form at line L2. Without q1=(0,0)q_1 = (0, 0), each fixture comes with all its integer translations, and the list is infinite.

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.

modular_fixture_design.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modular-fixture-design/. The authors are listed in prov/SBR91R.jsonl.

"""All planar modular fixtures with three locators and a clamp, after
Brost and Goldberg (1996).

Model, as on the page:
- The part is a simple polygon with rational vertices in counterclockwise
  order. It may be placed at any rotation and translation.
- The fixture plate has holes at the integer points. A locator is a point
  at a hole. The clamp is anchored at a hole v outside the part and pushes
  along one axis direction (+x, -x, +y or -y) until it meets the part,
  at distance at most `reach`.
- All four contacts are frictionless points in the relative interior of
  an edge, never at a vertex. The contact force is along the inner normal
  of the edge.
- A fixture must have form closure: the four contact wrenches positively
  span R^3.

Poses are computed exactly. The angle of a pose solves a linear equation in
cos and sin, so its coordinates lie in a field Q(sqrt(D)) with D rational,
and every test below is an exact sign test in that field.
"""

from collections import namedtuple
from fractions import Fraction
from math import isqrt

Fixture = namedtuple("Fixture", ["locators", "edges", "pose", "clamp"])
# locators: three lattice points (q1 < q2 < q3, q1 = (0, 0))
# edges: the edge index touched by each locator
# pose: (c, s, tx, ty), world point = R(c, s) x + (tx, ty)
# clamp: (v, direction, edge index, contact point)

DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1))


class Q2:
    """a + b sqrt(D) with rational a, b and a fixed rational D >= 0 that is
    not the square of a rational (or b = 0)."""

    __slots__ = ("a", "b", "d")

    def __init__(self, a, b=0, d=0):
        self.a = a if type(a) is Fraction else Fraction(a)
        self.b = b if type(b) is Fraction else Fraction(b)
        self.d = d if type(d) is Fraction else Fraction(d)

    def __add__(self, x):
        if isinstance(x, Q2):
            return Q2(self.a + x.a, self.b + x.b, self.d)
        return Q2(self.a + x, self.b, self.d)

    __radd__ = __add__

    def __neg__(self):
        return Q2(-self.a, -self.b, self.d)

    def __sub__(self, x):
        if isinstance(x, Q2):
            return Q2(self.a - x.a, self.b - x.b, self.d)
        return Q2(self.a - x, self.b, self.d)

    def __rsub__(self, x):
        return Q2(x - self.a, -self.b, self.d)

    def __mul__(self, x):
        if isinstance(x, Q2):
            return Q2(self.a * x.a + self.b * x.b * self.d, self.a * x.b + self.b * x.a, self.d)
        return Q2(self.a * x, self.b * x, self.d)

    __rmul__ = __mul__

    def __truediv__(self, x):
        if not isinstance(x, Q2):
            return Q2(self.a / x, self.b / x, self.d)
        n = x.a * x.a - x.b * x.b * self.d
        return self * Q2(x.a / n, -x.b / n, self.d)

    def sign(self):
        sa = (self.a > 0) - (self.a < 0)
        sb = (self.b > 0) - (self.b < 0)
        if sb == 0 or sa == sb:
            return sa if sa else sb
        if sa == 0:
            return sb
        # Opposite signs: compare a^2 with b^2 D. They differ, since sqrt(D) is irrational.
        return sa if self.a * self.a > self.b * self.b * self.d else sb

    def __float__(self):
        return float(self.a) + float(self.b) * float(self.d) ** 0.5

    def __repr__(self):
        return f"Q2({self.a}, {self.b}, {self.d})"


def _rational_sqrt(x):
    """sqrt(x) as a Fraction if x is the square of a rational, else None."""
    p, q = x.numerator, x.denominator
    rp, rq = isqrt(p), isqrt(q)
    if rp * rp == p and rq * rq == q:
        return Fraction(rp, rq)
    return None


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


def dot(a, b):
    return a[0] * b[0] + a[1] * b[1]


def edges_of(poly):
    """Edge k runs from poly[k] to poly[k+1]. Returns (start, end, outward normal, offset h)
    with the edge on the line m . x = h."""
    out = []
    n = len(poly)
    for k in range(n):
        p = tuple(Fraction(v) for v in poly[k])
        q = tuple(Fraction(v) for v in poly[(k + 1) % n])
        m = (q[1] - p[1], p[0] - q[0])  # outward for a counterclockwise polygon
        out.append((p, q, m, dot(m, p)))
    return out


def diameter_sq(poly):
    pts = [tuple(Fraction(v) for v in p) for p in poly]
    return max(dot((a[0] - b[0], a[1] - b[1]), (a[0] - b[0], a[1] - b[1])) for a in pts for b in pts)


def poses(edge_list, sites, chosen):
    """All poses (c, s, tx, ty) that put sites[k] on the line of edge chosen[k].

    With R m_a the rotated normal, the conditions are (R m_a) . t = (R m_a) . q_a - h_a.
    Three equations in t are consistent if and only if
    A cos + B sin + C0 = 0, with cofactors C_a that do not depend on the rotation.
    """
    ms = [edge_list[e][2] for e in chosen]
    hs = [edge_list[e][3] for e in chosen]
    cof = [cross(ms[1], ms[2]), cross(ms[2], ms[0]), cross(ms[0], ms[1])]
    if all(c == 0 for c in cof):
        return []  # all three normals parallel: never form closure
    a_ = sum(cof[i] * dot(ms[i], sites[i]) for i in range(3))
    b_ = sum(cof[i] * cross(ms[i], sites[i]) for i in range(3))
    c0 = -sum(cof[i] * hs[i] for i in range(3))
    r2 = a_ * a_ + b_ * b_
    if r2 == 0:
        return []  # no pose, or a continuum of poses that cannot have form closure
    disc = r2 - c0 * c0
    if disc < 0:
        return []
    root = _rational_sqrt(disc)
    if root is not None:
        cands = [(Q2((-a_ * c0 + sg * b_ * root) / r2), Q2((-b_ * c0 - sg * a_ * root) / r2)) for sg in (1, -1)]
    else:
        cands = [(Q2(-a_ * c0 / r2, sg * b_ / r2, disc), Q2(-b_ * c0 / r2, -sg * a_ / r2, disc)) for sg in (1, -1)]
    if disc == 0:
        cands = cands[:1]
    # Translation from two equations whose normals are not parallel.
    i, j = next((i, j) for i, j in ((0, 1), (1, 2), (2, 0)) if cross(ms[i], ms[j]) != 0)
    det = cross(ms[i], ms[j])
    out = []
    for c, s in cands:
        rm_i = rot(c, s, ms[i])
        rm_j = rot(c, s, ms[j])
        r_i = dot(rm_i, sites[i]) - hs[i]
        r_j = dot(rm_j, sites[j]) - hs[j]
        tx = (r_i * rm_j[1] - r_j * rm_i[1]) / det
        ty = (rm_i[0] * r_j - rm_j[0] * r_i) / det
        out.append((c, s, tx, ty))
    return out


def rot(c, s, v):
    return (c * v[0] - s * v[1], s * v[0] + c * v[1])


def to_world(pose, x):
    c, s, tx, ty = pose
    r = rot(c, s, x)
    return (r[0] + tx, r[1] + ty)


def strictly_inside_edge(world_edge, point):
    """Is point (known to be on the line of the edge) strictly between its ends?"""
    p, q = world_edge
    d = (q[0] - p[0], q[1] - p[1])
    u = dot((point[0] - p[0], point[1] - p[1]), d)
    return _sign(u) > 0 and _sign(dot(d, d) - u) > 0


def _sign(x):
    if isinstance(x, Q2):
        return x.sign()
    return (x > 0) - (x < 0)


def _contact_wrench(normal_in, point):
    return (normal_in[0], normal_in[1], cross(point, normal_in))


def _det3(m):
    return (
        m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])
        - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
        + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
    )


def form_closure(wrenches):
    """Four planar wrenches positively span R^3 if and only if they have rank 3
    and the null vector of signed 3 x 3 minors has all entries of one strict sign."""
    lam = []
    for i in range(4):
        rest = [wrenches[j] for j in range(4) if j != i]
        lam.append(_sign(_det3(rest)) * (-1) ** i)
    return all(x > 0 for x in lam) or all(x < 0 for x in lam)


def _point_in_or_on(world_poly, v):
    """0 if v is strictly outside the polygon, 1 if inside or on the boundary."""
    n = len(world_poly)
    inside = False
    for k in range(n):
        p, q = world_poly[k], world_poly[(k + 1) % n]
        # On the boundary?
        if _sign(cross((q[0] - p[0], q[1] - p[1]), (v[0] - p[0], v[1] - p[1]))) == 0:
            if _sign(dot((v[0] - p[0], v[1] - p[1]), (v[0] - q[0], v[1] - q[1]))) <= 0:
                return 1
        # Crossing number with the ray to +x, half-open rule.
        if (_sign(p[1] - v[1]) > 0) != (_sign(q[1] - v[1]) > 0):
            # The crossing is to the right of v if and only if this cross
            # product has the sign of q_y - p_y.
            side = _sign(cross((q[0] - p[0], q[1] - p[1]), (v[0] - p[0], v[1] - p[1])))
            if (side > 0) == (_sign(q[1] - p[1]) > 0):
                inside = not inside
    return 1 if inside else 0


def _seg_point_dist(a, b, p):
    dx, dy = b[0] - a[0], b[1] - a[1]
    ll = dx * dx + dy * dy
    u = 0.0 if ll == 0 else max(0.0, min(1.0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / ll))
    ex, ey = a[0] + u * dx - p[0], a[1] + u * dy - p[1]
    return (ex * ex + ey * ey) ** 0.5


def _may_hit(fw, v, d, r, eps=1e-7):
    """A float filter that never rejects a real hit: is the segment from v to
    v + r d within eps of some edge?"""
    w = (v[0] + r * d[0], v[1] + r * d[1])
    n = len(fw)
    for k in range(n):
        p, q = fw[k], fw[(k + 1) % n]
        c1 = (q[0] - p[0]) * (v[1] - p[1]) - (q[1] - p[1]) * (v[0] - p[0])
        c2 = (q[0] - p[0]) * (w[1] - p[1]) - (q[1] - p[1]) * (w[0] - p[0])
        c3 = (w[0] - v[0]) * (p[1] - v[1]) - (w[1] - v[1]) * (p[0] - v[0])
        c4 = (w[0] - v[0]) * (q[1] - v[1]) - (w[1] - v[1]) * (q[0] - v[0])
        if c1 * c2 <= 0 and c3 * c4 <= 0:
            return True
        if min(_seg_point_dist(p, q, v), _seg_point_dist(p, q, w), _seg_point_dist(v, w, p), _seg_point_dist(v, w, q)) <= eps:
            return True
    return False


def first_hit(world_poly, v, d):
    """The first point of the boundary on the ray v + s d, s > 0, for an axis direction d.

    Returns (s, edge index) or None. Returns edge index -1 when the first
    point is a vertex or the ray runs along an edge.
    """
    best = None
    n = len(world_poly)
    ax, other = (0, 1) if d[0] != 0 else (1, 0)
    sgn = d[ax]
    for k in range(n):
        p, q = world_poly[k], world_poly[(k + 1) % n]
        dp = p[other] - v[other]
        dq = q[other] - v[other]
        sp, sq = _sign(dp), _sign(dq)
        if sp == 0 and sq == 0:
            # Edge on the line of the ray: the hit is at its nearer end, a vertex.
            for w in (p, q):
                s = (w[ax] - v[ax]) * sgn
                if _sign(s) > 0 and (best is None or _sign(s - best[0]) < 0):
                    best = (s, -1)
            continue
        if sp == sq:
            continue
        lam = dp / (dp - dq)  # point p + lam (q - p) is on the line of the ray
        x = p[ax] + lam * (q[ax] - p[ax])
        s = (x - v[ax]) * sgn
        if _sign(s) <= 0:
            continue
        at_vertex = sp == 0 or sq == 0
        if best is None or _sign(s - best[0]) < 0:
            best = (s, -1 if at_vertex else k)
        elif _sign(s - best[0]) == 0:
            best = (s, -1)
    return best


def fixtures(poly, reach=1):
    """Every fixture of the model, each once, with the smallest locator at the origin."""
    reach = Fraction(reach)
    edge_list = edges_of(poly)
    n = len(edge_list)
    d2 = diameter_sq(poly)  # @line L1
    dmax = isqrt(int(d2)) + 1
    origin = (0, 0)
    # Sites lexicographically after the origin, within the diameter.
    near = [
        (x, y)
        for x in range(0, dmax + 1)
        for y in range(-dmax, dmax + 1)
        if (x, y) > origin and x * x + y * y <= d2
    ]
    found = []
    for q2 in near:  # @line L2
        for q3 in near:
            if not q3 > q2:
                continue
            dx, dy = q3[0] - q2[0], q3[1] - q2[1]
            if dx * dx + dy * dy > d2:
                continue
            sites = (origin, q2, q3)
            for e1 in range(n):  # @line L3
                for e2 in range(n):
                    for e3 in range(n):
                        chosen = (e1, e2, e3)
                        for pose in poses(edge_list, sites, chosen):  # @line L4
                            found.extend(_complete(poly, edge_list, sites, chosen, pose, reach))
    return found


def _complete(poly, edge_list, sites, chosen, pose, reach):
    world = [to_world(pose, p) for p in poly]
    n = len(world)
    for k in range(3):  # @line L5
        e = chosen[k]
        if not strictly_inside_edge((world[e], world[(e + 1) % n]), sites[k]):
            return []
    c, s = pose[0], pose[1]
    wrenches = [_contact_wrench(rot(c, s, tuple(-v for v in edge_list[e][2])), q) for e, q in zip(chosen, sites)]
    # Candidate clamp holes: the bounding box of the placed part grown by the reach.
    fw = [(float(p[0]), float(p[1])) for p in world]
    xs = [p[0] for p in fw]
    ys = [p[1] for p in fw]
    r = float(reach)
    lo_x, hi_x = int(min(xs) - r) - 1, int(max(xs) + r) + 1
    lo_y, hi_y = int(min(ys) - r) - 1, int(max(ys) + r) + 1
    out = []
    for vx in range(lo_x, hi_x + 1):  # @line L6
        for vy in range(lo_y, hi_y + 1):
            v = (vx, vy)
            dirs = [dv for dv in DIRECTIONS if _may_hit(fw, v, dv, r)]
            if not dirs or _point_in_or_on(world, v):
                continue
            for dvec in dirs:
                hit = first_hit(world, v, dvec)  # @line L7
                if hit is None or hit[1] < 0 or _sign(hit[0] - reach) > 0:
                    continue
                e = hit[1]
                u = (v[0] + hit[0] * dvec[0], v[1] + hit[0] * dvec[1])
                if any(_sign(u[0] - q[0]) == 0 and _sign(u[1] - q[1]) == 0 for q in sites):
                    continue  # the clamp would touch the part at a locator
                normal_in = rot(c, s, tuple(-x for x in edge_list[e][2]))
                if form_closure(wrenches + [_contact_wrench(normal_in, u)]):  # @line L8
                    out.append(Fixture(sites, chosen, pose, (v, dvec, e, u)))
    return out
test_modular_fixture_design.py 320 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modular-fixture-design/. The authors are listed in prov/SBR91R.jsonl.

import random
import unittest
from fractions import Fraction
from itertools import combinations, product
from math import isqrt

from modular_fixture_design import DIRECTIONS, Q2, diameter_sq, fixtures, form_closure

TRIANGLE = [(0, 0), (2, 0), (1, Fraction(3, 2))]
RIGHT = [(0, 0), (2, 0), (0, Fraction(3, 2))]
QUAD = [(0, 0), (Fraction(3, 2), 0), (Fraction(3, 2), 1), (0, Fraction(3, 2))]


def sgn(x):
    if isinstance(x, Q2):
        return x.sign()
    return (x > 0) - (x < 0)


def solve3(cols, target):
    """Solve sum_j x_j cols[j] = target for three vectors of R^3 by Cramer's rule."""

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

    d = det(*cols)
    if sgn(d) == 0:
        return None
    return [
        det(target, cols[1], cols[2]) / d,
        det(cols[0], target, cols[2]) / d,
        det(cols[0], cols[1], target) / d,
    ]


def closure_by_caratheodory(wrenches):
    """Each of +-e_k is a nonnegative combination of three of the wrenches."""
    for k in range(3):
        for s in (1, -1):
            target = [0, 0, 0]
            target[k] = s
            ok = False
            for trio in combinations(wrenches, 3):
                x = solve3(list(trio), target)
                if x is not None and all(sgn(v) >= 0 for v in x):
                    ok = True
                    break
            if not ok:
                return False
    return True


def poses_by_linear_family(poly, sites, chosen):
    """Poses from the linear system in (c, s, T1, T2), T = R^T t, then c^2 + s^2 = 1.

    The condition for site q on the line m . x = h of an edge in the part
    frame is m . R^T (q - t) = h, that is c (m . q) + s (m x q) - m . T = h.
    """
    n = len(poly)
    rows = []
    for q, e in zip(sites, chosen):
        p0 = poly[e]
        p1 = poly[(e + 1) % n]
        m = (Fraction(p1[1]) - p0[1], Fraction(p0[0]) - p1[0])
        h = m[0] * p0[0] + m[1] * p0[1]
        rows.append([m[0] * q[0] + m[1] * q[1], m[0] * q[1] - m[1] * q[0], -m[0], -m[1], h])
    # Gauss-Jordan on the 3 x 5 augmented matrix.
    a = [list(r) for r in rows]
    piv_cols = []
    r = 0
    for c in range(4):
        piv = next((i for i in range(r, 3) if a[i][c] != 0), None)
        if piv is None:
            continue
        a[r], a[piv] = a[piv], a[r]
        a[r] = [v / a[r][c] for v in a[r]]
        for i in range(3):
            if i != r and a[i][c] != 0:
                f = a[i][c]
                a[i] = [x - f * y for x, y in zip(a[i], a[r])]
        piv_cols.append(c)
        r += 1
    if r < 3:
        return []
    free = next(c for c in range(4) if c not in piv_cols)
    x0 = [Fraction(0)] * 4
    x1 = [Fraction(0)] * 4
    x1[free] = Fraction(1)
    for i, c in enumerate(piv_cols):
        x0[c] = a[i][4]
        x1[c] = -a[i][free]
    qa = x1[0] ** 2 + x1[1] ** 2
    qb = 2 * (x0[0] * x1[0] + x0[1] * x1[1])
    qc = x0[0] ** 2 + x0[1] ** 2 - 1
    out = []
    if qa == 0:
        if qb == 0:
            return []
        taus = [Q2(-qc / qb)]
    else:
        disc = qb * qb - 4 * qa * qc
        if disc < 0:
            return []
        rp, rq = isqrt(disc.numerator), isqrt(disc.denominator)
        if rp * rp == disc.numerator and rq * rq == disc.denominator:
            root = Fraction(rp, rq)
            taus = [Q2((-qb + root) / (2 * qa)), Q2((-qb - root) / (2 * qa))]
        else:
            taus = [Q2(-qb / (2 * qa), 1 / (2 * qa), disc), Q2(-qb / (2 * qa), -1 / (2 * qa), disc)]
        if disc == 0:
            taus = taus[:1]
    for tau in taus:
        c, s, t1, t2 = (x0[k] + tau * x1[k] for k in range(4))
        out.append((c, s, t1, t2))
    return out


def brute_force(poly, reach=1):
    """All fixtures, found by trying every triple of holes in a box and every clamp hole near it."""
    n = len(poly)
    poly = [tuple(Fraction(v) for v in p) for p in poly]
    # The holes of a fixture are points of the part, so their x range and
    # their y range are at most the diameter. A translation by an integer
    # vector moves them into [0, floor(diameter)]^2.
    big = isqrt(int(diameter_sq(poly)))
    box = [(x, y) for x in range(big + 1) for y in range(big + 1)]
    keys = set()
    for sites in combinations(box, 3):
        for chosen in product(range(n), repeat=3):
            for c, s, t1, t2 in poses_by_linear_family(poly, sites, chosen):
                # Contact points in the part frame: R^T q - T.
                local = [(c * q[0] + s * q[1] - t1, -s * q[0] + c * q[1] - t2) for q in sites]
                if not all(inside_edge(poly, e, x) for e, x in zip(chosen, local)):
                    continue
                wrenches = [wrench_world(poly, e, q, c, s) for e, q in zip(chosen, sites)]
                tx, ty = c * t1 - s * t2, s * t1 + c * t2
                world = [
                    (float(c * p[0] - s * p[1] + tx), float(s * p[0] + c * p[1] + ty)) for p in poly
                ]
                for v in product(range(-big - 3, 2 * big + 4), repeat=2):
                    # A clamp at v touches the part within reach, so v is
                    # within reach of the boundary. This float test keeps a
                    # margin and never drops such a hole.
                    if near_boundary(world, v) > reach + 1e-7:
                        continue
                    for d in DIRECTIONS:
                        hit = clamp_hit(poly, v, d, c, s, t1, t2, reach)
                        if hit is None:
                            continue
                        e, u = hit
                        if any(sgn(u[0] - q[0]) == 0 and sgn(u[1] - q[1]) == 0 for q in sites):
                            continue
                        if not closure_by_caratheodory(wrenches + [wrench_world(poly, e, u, c, s)]):
                            continue
                        keys.add(canonical(sites, chosen, (c, s, tx, ty), v, d, e))
    return keys


def near_boundary(world, v):
    """Float distance from the point v to the boundary of the polygon."""
    best = float("inf")
    n = len(world)
    for k in range(n):
        a, b = world[k], world[(k + 1) % n]
        dx, dy = b[0] - a[0], b[1] - a[1]
        u = ((v[0] - a[0]) * dx + (v[1] - a[1]) * dy) / (dx * dx + dy * dy)
        u = max(0.0, min(1.0, u))
        ex, ey = a[0] + u * dx - v[0], a[1] + u * dy - v[1]
        best = min(best, (ex * ex + ey * ey) ** 0.5)
    return best


def inside_edge(poly, e, x):
    """x lies strictly inside edge e of the polygon (part frame)."""
    n = len(poly)
    p, q = poly[e], poly[(e + 1) % n]
    d = (q[0] - p[0], q[1] - p[1])
    w = (x[0] - p[0], x[1] - p[1])
    if sgn(d[0] * w[1] - d[1] * w[0]) != 0:
        return False
    u = d[0] * w[0] + d[1] * w[1]
    return sgn(u) > 0 and sgn(d[0] * d[0] + d[1] * d[1] - u) > 0


def wrench_world(poly, e, point, c, s):
    n = len(poly)
    p, q = poly[e], poly[(e + 1) % n]
    m_in = (p[1] - q[1], q[0] - p[0])  # inner normal of a counterclockwise polygon
    w = (c * m_in[0] - s * m_in[1], s * m_in[0] + c * m_in[1])
    return [w[0], w[1], point[0] * w[1] - point[1] * w[0]]


def clamp_hit(poly, v, d, c, s, t1, t2, reach):
    """Work in the part frame. The first boundary point on the ray from v
    must be in an edge interior, at distance at most reach, and entering
    the part (which also proves that v is outside)."""
    n = len(poly)
    vl = (c * v[0] + s * v[1] - t1, -s * v[0] + c * v[1] - t2)
    dl = (c * d[0] + s * d[1], -s * d[0] + c * d[1])
    for k in range(n):
        if inside_edge(poly, k, vl):
            return None
    best = None
    for k in range(n):
        p, q = poly[k], poly[(k + 1) % n]
        e = (q[0] - p[0], q[1] - p[1])
        den = dl[0] * (-e[1]) + e[0] * dl[1]  # det [dl, -e]
        if sgn(den) == 0:
            continue
        r = (p[0] - vl[0], p[1] - vl[1])
        sd = (r[0] * (-e[1]) + e[0] * r[1]) / den
        lam = (dl[0] * r[1] - dl[1] * r[0]) / den
        if sgn(sd) <= 0 or sgn(lam) < 0 or sgn(lam - 1) > 0:
            continue
        vertex = sgn(lam) == 0 or sgn(lam - 1) == 0
        if best is None or sgn(sd - best[0]) < 0:
            best = (sd, k, vertex)
        elif sgn(sd - best[0]) == 0:
            best = (sd, k, True)
    # A vertex on the ray that is not on any crossing edge (touching) is
    # also found above as an end of two edges.
    if best is None or best[2] or sgn(best[0] - reach) > 0:
        return None
    sd, k, _ = best
    p, q = poly[k], poly[(k + 1) % n]
    m_out = (q[1] - p[1], p[0] - q[0])
    if sgn(dl[0] * m_out[0] + dl[1] * m_out[1]) >= 0:
        return None  # leaving the part: v was inside
    u = (v[0] + sd * d[0], v[1] + sd * d[1])
    return k, u


def canonical(sites, chosen, pose, v, d, e):
    pairs = sorted(zip(sites, chosen))
    ox, oy = pairs[0][0]
    shifted = tuple(((q[0] - ox, q[1] - oy), ed) for q, ed in pairs)
    c, s, tx, ty = pose
    pose_key = tuple(round(float(x), 9) for x in (c, s, tx - ox, ty - oy))
    return (shifted, pose_key, (v[0] - ox, v[1] - oy), d, e)


def key_of(f):
    return canonical(f.locators, f.edges, f.pose, f.clamp[0], f.clamp[1], f.clamp[2])


class TestQ2(unittest.TestCase):
    def test_sign_against_float(self):
        rng = random.Random(1)
        for _ in range(2000):
            a = Fraction(rng.randint(-50, 50), rng.randint(1, 9))
            b = Fraction(rng.randint(-50, 50), rng.randint(1, 9))
            d = Fraction(rng.choice([2, 3, 5, 7, 11, 13]), rng.choice([1, 4, 9]))
            x = Q2(a, b, d)
            f = float(a) + float(b) * float(d) ** 0.5
            self.assertEqual(x.sign(), (f > 0) - (f < 0))

    def test_field_operations(self):
        x = Q2(1, 2, 3)
        y = Q2(Fraction(1, 2), -1, 3)
        self.assertAlmostEqual(float(x * y), float(x) * float(y))
        self.assertAlmostEqual(float(x / y), float(x) / float(y))
        self.assertEqual((x - x).sign(), 0)


class TestFormClosure(unittest.TestCase):
    def test_pinwheel_and_symmetric_square(self):
        def w(p, n):
            return [n[0], n[1], p[0] * n[1] - p[1] * n[0]]

        half = Fraction(1, 2)
        pin = [w((0, 3 * half), (1, 0)), w((2, half), (-1, 0)), w((3 * half, 0), (0, 1)), w((half, 2), (0, -1))]
        sym = [w((0, 1), (1, 0)), w((2, 1), (-1, 0)), w((1, 0), (0, 1)), w((1, 2), (0, -1))]
        self.assertTrue(form_closure(pin))
        self.assertFalse(form_closure(sym))

    def test_against_caratheodory(self):
        rng = random.Random(4)
        for _ in range(400):
            ws = [[Fraction(rng.randint(-3, 3)) for _ in range(3)] for _ in range(4)]
            self.assertEqual(form_closure(ws), closure_by_caratheodory(ws))


class TestAgainstBruteForce(unittest.TestCase):
    def check(self, poly):
        found = fixtures(poly)
        keys = [key_of(f) for f in found]
        self.assertEqual(len(keys), len(set(keys)), "a fixture was listed twice")
        self.assertEqual(set(keys), brute_force(poly))
        return found

    def test_isosceles_triangle(self):
        found = self.check(TRIANGLE)
        self.assertGreater(len(found), 0)

    def test_quadrilateral(self):
        found = self.check(QUAD)
        self.assertGreater(len(found), 0)

    def test_each_fixture_is_valid(self):
        for f in fixtures(RIGHT):
            c, s, tx, ty = f.pose
            self.assertEqual(sgn(c * c + s * s - 1), 0)
            self.assertEqual(f.locators[0], (0, 0))
            self.assertTrue(f.locators[0] < f.locators[1] < f.locators[2])
            t1, t2 = c * tx + s * ty, -s * tx + c * ty
            poly = [tuple(Fraction(v) for v in p) for p in RIGHT]
            for q, e in zip(f.locators, f.edges):
                local = (c * q[0] + s * q[1] - t1, -s * q[0] + c * q[1] - t2)
                self.assertTrue(inside_edge(poly, e, local))
            v, d, e, u = f.clamp
            self.assertEqual(clamp_hit(poly, v, d, c, s, t1, t2, 1)[0], e)
            ws = [wrench_world(poly, ed, q, c, s) for ed, q in zip(f.edges, f.locators)]
            self.assertTrue(closure_by_caratheodory(ws + [wrench_world(poly, e, u, c, s)]))


if __name__ == "__main__":
    unittest.main()

History

Brost and Goldberg gave the algorithm at the IEEE International Conference on Robotics and Automation in 1994, and in its full form in IEEE Transactions on Robotics and Automation in 1996. It was the first complete algorithm for modular fixtures. Zhuang and Goldberg (1996) then asked if each polygon has such a fixture, and gave convex polygons of any width that touch at most two lattice points in any pose, so they have none. The idea of form closure goes back to Reuleaux (1876). Four frictionless contacts are necessary in the plane, and Markenscoff, Ni and Papadimitriou (1990) showed that four are enough for almost all planar parts, so three locators and a clamp is the smallest class that can work.

References

  1. Randy C. Brost and Kenneth Y. Goldberg, A complete algorithm for designing planar fixtures using modular components, IEEE Transactions on Robotics and Automation 12(1), 1996, 31 to 46, the fixture class of three locators and one clamp on a lattice plate for a polygonal part, the enumeration of locator triples and edge triples, and the claim of completeness
  2. Yan Zhuang and Ken Goldberg, On the existence of solutions in modular fixturing, International Journal of Robotics Research 15(6), 1996, 646 to 656, the formal model of lattice locators and clamps with a reach of one unit along a lattice axis, the O(n^5 d^5) bound that they give for the Brost and Goldberg algorithm, convex polygons of any width with no such fixture, and fixtures with four clamps
  3. Xanthippi Markenscoff, Luqun Ni and Christos H. Papadimitriou, The geometry of grasping, International Journal of Robotics Research 9(1), 1990, 61 to 74, four frictionless point contacts are necessary for form closure of a planar part, and enough for almost all parts

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