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.
- Solves
- Fixture planning
- 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
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with edges and rational vertices in counterclockwise order, and a clamp reach . The lattice is with unit spacing.
Fixture. A fixture is a pose of the part (a rotation and a translation , so a body point goes to ), three lattice points in lexicographic order, three edges , and a clamp , so that:
- each is in the relative interior of the edge , not at a vertex;
- is strictly outside , and is one of and ;
- the first point of the boundary of on the ray , , is in the relative interior of an edge , with and ;
- the four contacts give form closure: their wrenches positively span .
All contacts are frictionless points. The wrench of a contact at with inner normal is . 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 .
Output. Every fixture with , 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 for the outward normal of edge in the part frame and , where is the start vertex of . Then lies on the line .
MODULAR-FIXTURES(P, ρ) ▷ P: polygon with edges e_1 .. e_n, counterclockwise- 1
D ← the diameter of P - 2
for each pair of lattice points q2 < q3, with q1 = (0,0) < q2 and |q_i − q_j| ≤ D for all i, j - 3
for each triple (e_a, e_b, e_c) of edges of P - 4
for each pose g that puts q1, q2, q3 on the lines of g(e_a), g(e_b), g(e_c) - 5
if some q_k is not strictly inside its edge of g(P) then skip this pose - 6
for each lattice point v outside g(P), near g(P), and each d ∈ {+x, −x, +y, −y} - 7
u ← 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} - 8
if 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 apart. The first locator is at the origin, and the other two come after it in lexicographic order. So and are lattice points in a half disk of radius .
Line L4. Rotate by the angle , with and . The locator is on the line of when . These are three linear equations in the two entries of . If the three normals are not all parallel, the equations have a solution if and only if the determinant of the system is zero. Expand it along the right side. The cofactors , and do not change under a rotation, and . So the condition is one linear equation in and :
With and , the line meets the unit circle at
so there are at most two poses. Cramer's rule on two equations with independent normals gives . If all three normals are parallel or , 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 . The implementation stores a number as with rational and . The sign of such a number is exact: if and have opposite signs, compare with . 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 of the boundary, so it is in the bounding box of grown by . The implementation first drops the pairs whose segment of length is far from every edge in floating point, with a margin of . Then it tests " outside " with an exact point in polygon test, and finds the first hit exactly. A hit at a vertex, or on an edge along the ray, is not a valid contact.
Line L8. Let be the four wrenches, each with the inner normal of its edge. Set . Then . The four wrenches positively span if and only if all 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 , and , with . Edge is the base, edge the right side and edge the left side. The diameter is . The counts after each line are:
| line | what is counted | count |
|---|---|---|
| L2 | lattice points with | 6 |
| L2 | pairs with | 10 |
| L3 | pairs times edge triples () | 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 and the edges . In the part frame, with , and with . The cofactors are , so , and . The equation is : two locators on the base make the base horizontal. The poses are and .
- For , the base goes to the segment from to . It does not contain , so line L5 skips the pose.
- For , the first equation gives and the second gives , so . The placed triangle is , , . The points and are inside the base, and is inside the right side.
The inner normals have the length of their edge: on the base, on the right side and on the left side. The locator wrenches are , and . Six pairs reach the inside of an edge within distance 1:
| result | |||
|---|---|---|---|
| skip at L7, is a locator | |||
| skip at L7, is a locator | |||
| skip at L7, is a locator | |||
| skip at L7, is a locator | |||
| on | , , a fixture | ||
| on | , , a fixture |
For the first fixture, with all weights positive, so the four contacts positively span . 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 returns each fixture with 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 . Its locators are points of , so they are at most 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 , 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. is a simple polygon with edges in counterclockwise order. Edge has the outward normal and lies on the line . A pose is a rotation by an angle , with and , and a translation . A fixture is a tuple with conditions 1 to 4 of the page. It is normalized when .
Lemma 1 (translation). If is a fixture and , then moved by (each , and the translation of shifted by ) is a fixture. So the set of all fixtures is the set of normalized fixtures and their integer translations.
Proof. A shift by 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 with normal is , and . So each new wrench is times the old one, with the same invertible matrix
for every contact. Hence the four wrenches positively span before the shift if and only if they do after it. A fixture with moved by is normalized.
Lemma 2 (line L2). The sites of a normalized fixture are among the pairs of line L2.
Proof. Each is a point of , and is an isometry, so , the diameter of . By the order and , the points and come after the origin in lexicographic order. The implementation lists all lattice points with , , and . These are all lattice points after the origin within distance . It then keeps each pair with .
Lemma 3 (the pose equation). Fix the sites and the edges , and let , and . Assume that not all are zero. A pose puts each on the line of if and only if and is the unique solution of the three equations below, with , and as on the page.
Proof. The point is on the line of if and only if is on the line of , that is , or
This is a system with of size . A cofactor is a minor of up to sign, since for a rotation. Some , so has rank 2, the solution is unique if it exists, and it exists if and only if the matrix is singular. The expansion of its determinant along the column is . Next, , so
So .
Lemma 4 (line L4 is complete). If a fixture uses the sites and the edges , its pose is one of the poses of line L4.
Proof. Let be the locator wrenches and the clamp wrench. We first show that are linearly independent. Set , with the index from 0 to 3. For each coordinate , is the expansion along the first column of the matrix with rows . This matrix has two equal columns, so the sum is 0, and . If are dependent, then . Then either the four wrenches have rank less than 3, or their null space is spanned by , 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 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 are all multiples of one vector , so the three wrenches lie in the plane spanned by and , and they are dependent.
- . Then the pose equation is . If , no pose exists. If , every angle has a pose by Lemma 3, and depends smoothly on . Along this family each stays on the line of . In the moving part frame, the curve stays on the line of , 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 with , so , and for . A nonzero vector is orthogonal to the three wrenches, so they are dependent.
So in a fixture, not all are zero and . The pose satisfies and . The line meets the circle only if its distance from the origin is at most 1, that is . Substitution shows that the two points of the page satisfy both equations: and . A line meets a circle in at most two points, so these are all the solutions, and one solution when . By Lemma 3 the translation is the unique solution of the system, which Cramer's rule gives from two rows with .
Lemma 5 (exact signs). Each number that lines L5 to L8 test is in the field , and its sign is computed exactly.
Proof. The inputs are rational, and , and are in , so all coordinates of are in , and so are all sums, products and quotients of them. If is the square of a rational, . Otherwise is irrational and is zero only if . If and 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 because is irrational.
Lemma 6 (line L5). A pose passes line L5 if and only if each is in the relative interior of .
Proof. By Lemma 3, is on the line of . Write and . The point is strictly between and if and only if . Line L5 tests these two signs exactly (Lemma 5).
Lemma 7 (lines L6 and L7). For a pose that passes line L5, lines L6 and L7 keep exactly the pairs of condition 2 and 3.
Proof. If satisfies conditions 2 and 3, then with and . So is in the bounding box of grown by . The implementation scans the integer points from or less to or more, and the same for , which covers the box with a margin of one unit against rounding of the float bounds. The float filter drops only if the segment from to is more than 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 , so a real hit is never dropped. The test " strictly outside " 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 over the crossings of the ray with the edges, computed exactly. A crossing at an end of an edge, two crossings at the same , or an edge on the line of the ray mark the hit as a vertex, and line L7 skips it. Line L7 then checks and with exact signs.
Lemma 8 (line L8). Line L8 accepts the four wrenches if and only if they positively span .
Proof. The proof of Lemma 4 gives . If the rank is 3, some minor is not zero, so , and the null space of the map has dimension , so it is spanned by . Then a strictly positive null vector exists if and only if all are nonzero with one sign. If the rank is less than 3, all are zero, line L8 rejects, and the wrenches do not span . By the positive span lemma, line L8 is right in both cases. The signs are exact by Lemma 5.
Theorem. MODULAR-FIXTURES outputs each normalized fixture exactly one time, and outputs nothing else.
Proof. Soundness. An output has 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 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 with its and . By Lemma 8, line L8 outputs it.
Uniqueness. Two outputs from different iterations differ in the sites, in the pose, or in . 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 fix the edge that contains 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.
Termination. The loops of lines L2, L3, L4 and L6 are over finite sets: a finite set of lattice points, triples, at most two poses, and a finite box of holes with four directions.
Complexity
Let be the number of edges and the diameter in lattice units. Count field operations in ; for a fixed input, the numbers have bounded size.
- Lines L2 and L3. There are lattice points in a half disk of radius , so pairs, and edge triples. Line L4 runs times and costs each time.
- Line L5. At most poses per triple, and work for each, after the part is placed in .
- Lines L6 to L8. The box has holes. For each, the float filter, the point in polygon test and the first hit cost . So one pose that passes line L5 costs .
The worst case is . In practice few poses pass line L5 (48 of 428 in the example), so the time is close to the of the pose step. Only the holes within of the boundary can hold the clamp. Each edge is at most long, so there are such holes. A scan of only these holes costs per pose, and the worst case becomes . This is the bound that Zhuang and Goldberg (1996) state for the algorithm of Brost and Goldberg. It is better than when . The extra space is , where 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 , 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 . 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 .
Variants and improvements
- Round locators. Real locators are pins of radius , with less than half the lattice spacing. A pin of radius touches an edge where a point touches the edge moved out by . So a version for round pins works with the boundary of the Minkowski sum of and a disk of radius , 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 , and test "strictly inside" as two exact sign tests.
- One root at line L4. The line meets the unit circle in two points when . 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 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 , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SBR91R Edit this page History Report an error Markdown