Algorithmadvanced
Paden-Kahan subproblems
Also called Paden-Kahan subproblem method.
Three geometric subproblems of rotating points about one or two axes, with closed solutions, to which many inverse kinematics reduce.
- Time
- Θ(n) worst
- Space
- Θ(1) extra
- Where
- n = the number of joints of an arm that splits into subproblems
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Bradley E. Paden, William Kahan, 1986
The Paden-Kahan subproblems are three small geometric problems about rotations of points, each with a closed form solution. Subproblem 1 finds the angle of one rotation that moves a point to another point. Subproblem 2 finds the angles of two rotations, about axes that meet, that move a point to another point. Subproblem 3 finds the angle of one rotation that brings a point to a given distance from another point. Many arms with six joints, among them most industrial arms, have an inverse kinematics that splits into a chain of these subproblems. The method then gives every solution, with no iteration and no starting guess.
In plain words
Pin a stick to a wall at one end, so that it can only swing in a circle. If you mark a point on the stick and another point on the circle, there is exactly one swing angle that carries the first point to the second. That is the first subproblem. The second subproblem uses two pins at the same place, one after the other, and asks for both angles. The third asks for the swing angles that put the point at a given distance from a fixed spot. Each answer comes from a short formula. For a robot arm, you choose points that some joints leave in place. Then the joints that do move them form one of these three problems, and you solve the arm a few joints at a time.
The problem
Input.
- A revolute joint is a rotation about a line with a unit direction through a point . The rotation by takes a point to , where by Rodrigues' formula. In twist form this is with the screw axis .
- Subproblem 1: one axis and two points , . Find with .
- Subproblem 2: two axes and that meet at and are not parallel, and two points , . Find all with .
- Subproblem 3: one axis , two points , and a distance . Find all with .
Output. The solutions, or the report that there are none. Subproblem 1 has 0 or 1 solution when is off the axis. Subproblems 2 and 3 have 0, 1 or 2.
Use on an arm. For an arm in the space form of the product of exponentials, , and a target pose , the inverse kinematics asks for all with . The trick is to apply both sides to a point that the last joints leave in place, or to compare distances that the first joints do not change.
The algorithm
SUBPROBLEM-1(ω, r, p, q) ▷ θ with e^{[ξ]θ} p = q- 1
u ← p - r ; v ← q - r - 2
u' ← u - ω ω^T u ; v' ← v - ω ω^T v ▷ parts orthogonal to the axis - 3
if ω^T u ≠ ω^T v or |u'| ≠ |v'| then return NO SOLUTION - 4
return atan2(ω^T (u' × v'), u'^T v') SUBPROBLEM-2(ω1, ω2, r, p, q) ▷ θ1, θ2 with e^{[ξ1]θ1} e^{[ξ2]θ2} p = q- 5
u ← p - r ; v ← q - r ; k ← ω1^T ω2 - 6
α ← (k ω2^T u - ω1^T v) / (k^2 - 1) ; β ← (k ω1^T v - ω2^T u) / (k^2 - 1) - 7
γ² ← (|u|^2 - α^2 - β^2 - 2αβk) / |ω1 × ω2|^2 - 8
if γ² < 0 then return NO SOLUTION - 9
for γ in {+√γ², -√γ²} ▷ one value when γ² = 0 - 10
c ← r + α ω1 + β ω2 + γ (ω1 × ω2) ▷ the point between the two rotations - 11
θ2 ← SUBPROBLEM-1(ω2, r, p, c) ; θ1 ← SUBPROBLEM-1(ω1, r, c, q) - 12
output (θ1, θ2) SUBPROBLEM-3(ω, r, p, q, δ) ▷ θ with |e^{[ξ]θ} p - q| = δ- 13
u ← p - r ; v ← q - r ; u', v' as in L2 - 14
δ'^2 ← δ^2 - (ω^T (p - q))^2 - 15
θ0 ← atan2(ω^T (u' × v'), u'^T v') - 16
c ← (|u'|^2 + |v'|^2 - δ'^2) / (2 |u'| |v'|) - 17
if |c| > 1 then return NO SOLUTION - 18
return θ0 - arccos c and θ0 + arccos c ▷ one angle when |c| = 1
Line L4 is the signed angle from to about . Line L6 comes from two linear equations: the point rotates about from and about to , so and . Line L7 then fixes the length of to . Lines L14 to L16 are the law of cosines in the plane orthogonal to the axis. In floating point, the tests in L3, L8 and L17 use a small tolerance, and the code on this page clamps into when it is out by less than the tolerance.
An elbow arm. The code on this page solves an arm with six revolute joints in the layout of Murray, Li and Sastry. Axis 1 is vertical through the base. Axes 2 and 3 are horizontal and parallel, through the shoulder and the elbow. Axes 4, 5 and 6 meet at the wrist center . The solution takes four steps.
- The last three joints fix , so sends to the place that the first three joints must reach. The first two joints turn about axes through , so they keep the distance to , and . Subproblem 3 gives up to two values of .
- Subproblem 2 on the axes 1 and 2, which meet at , moves to and gives up to two pairs .
- Now . A point on axis 6 is left in place by joint 6, so subproblem 2 on the axes 4 and 5 with and gives up to two pairs .
- Subproblem 1 on axis 6, with a point off that axis, gives .
This gives up to solutions.
Example
Take the elbow arm with a base height, two arm links and a tool offset of and . At , the shoulder is , the elbow , the wrist center and the tool point . The axes are , and . The target is the pose of , with the position .
- Step 1: and . With two unit links, , so , and subproblem 3 returns .
- Step 2: for , subproblem 2 returns and , the shoulder turned by . For it returns and .
- Steps 3 and 4 give two wrist solutions for each of the four arm solutions.
| 0.300000 | -0.400000 | 0.900000 | 0.500000 | 0.700000 | -0.600000 |
| 0.300000 | -0.400000 | 0.900000 | -2.641593 | 2.441593 | 2.541593 |
| 0.300000 | 0.500000 | -0.900000 | -1.336808 | 1.957305 | -2.257324 |
| 0.300000 | 0.500000 | -0.900000 | 1.804785 | 1.184287 | 0.884269 |
| -2.841593 | 2.641593 | 0.900000 | 1.336808 | -1.957305 | 0.884269 |
| -2.841593 | 2.641593 | 0.900000 | -1.804785 | -1.184287 | -2.257324 |
| -2.841593 | -2.741593 | -0.900000 | 2.641593 | -2.441593 | -0.600000 |
| -2.841593 | -2.741593 | -0.900000 | -0.500000 | -0.700000 | 2.541593 |
The forward kinematics of each row matches the target to within . In each pair of rows, the second wrist solution is the first one with and moved by and replaced by , modulo , which is the usual wrist flip.
Correctness
Subproblem 1. A rotation about keeps the component of along and turns the orthogonal part by in the plane orthogonal to . So a solution exists exactly when and , and then is the signed angle from to , which L4 computes. If , the point is on the axis and every works.
Subproblem 2. If is a solution, put . Then has the same component along as , the same component along as , and the length . Since , and form a basis, these three facts give with , from L6 and from L7. Conversely, each such meets the conditions of subproblem 1 twice, once for about and once for about , so L11 gives a solution. So the solutions are in one to one correspondence with the real roots , and there are at most 2 when is off both axes.
Subproblem 3. The distance splits into the part along , which the rotation does not change, and the part in the orthogonal plane. So , and the condition is with from L16.
The arm. Every solution of the arm passes the tests of the four steps, and every output of the four steps satisfies , so the method returns exactly the set of solutions. The proof page gives the details, with the hypotheses that the chosen points are off the axes.
Proof: The three subproblems return exactly their solution sets, and the elbow arm solution returns exactly the inverse kinematics solutionsfull
We use the notation of the page. The proof is in exact arithmetic, in the real RAM. All axes have unit directions, and is the rotation by about . For a vector , write for its part orthogonal to .
Lemma 0. For every , . So the rotation keeps and , and it turns by the angle in the plane orthogonal to , in the positive sense about .
Proof. This is Rodrigues' formula with and .
Subproblem 1
Claim. Let and with . A with exists if and only if and , and then it is unique modulo and equal to .
Proof. The equation is . By Lemma 0, the part along gives and the orthogonal part gives , which forces . Conversely, if both conditions hold, and are an orthogonal basis of the plane with equal lengths, so for exactly one modulo . Taking dot products with and with gives and . Both have the positive factor , so atan2 returns .
If , then is on the axis, every leaves it in place, and there is a solution if and only if .
Subproblem 2
Claim. Let the axes and meet at with , let , , and suppose that is off axis 2 and is off axis 1. Then the pairs modulo with are in one to one correspondence with the real that satisfy line L7, and L9 to L12 output exactly these pairs.
Proof. Let , so and . The three vectors , and are a basis, so every vector has the form .
Suppose is a solution, and put , so that . By Lemma 0, , and . The first two equations read and , a linear system with determinant , whose solution is the pair of line L6. Since is orthogonal to and , , and is the equation of line L7. So is one of the vectors built in L10.
Conversely, let be a real root of L7 and the vector of L10, with . Then and , so for the parts orthogonal to . Since is off axis 2, , and the claim on subproblem 1 gives a unique with . In the same way, and give a unique with ; here is necessary for any solution, since rotations about lines through keep the distance to . So each root gives one solution, and different roots give different and so different . Every solution arises in this way by the first part. L7 has two real roots when , one when , and none when , which is the test of L8.
Subproblem 3
Claim. Let and with and . The set of with is modulo if and empty otherwise, with and from lines L15 and L16.
Proof. By Lemma 0, , a sum of two orthogonal parts. So . The vector has length and makes the signed angle with , where is the signed angle from to (by the computation in subproblem 1). By the law of cosines, . So the equation is with and . For it has no solution, and otherwise its solutions are , which coincide when .
The elbow arm
Let the arm be , with axis 1 through , axes 2 and 3 parallel, axis 2 through , and axes 4, 5 and 6 through . Write . We assume that the target is generic in the sense that each point given to a subproblem is off the axes of that subproblem; the code checks no more than this.
Claim. The four steps of the page return exactly the set of modulo with .
Proof. Let be a solution and . The rotations , and fix , so . The rotations and fix and keep distances, so , and is among the outputs of step 1 by the claim on subproblem 3. Then , so is among the outputs of step 2 by the claim on subproblem 2. Next , and for a point on axis 6, , so and is among the outputs of step 3. Finally , and step 4 returns by the claim on subproblem 1.
Conversely, take an output of the four steps. Step 4 gives on the point used there, and we must show it on all points. Both sides are rigid motions that fix : the left side because is on axis 6, and the right side because and fix and step 3 ensures for the point on axis 6, while by step 2. So and are two rigid motions that agree on , on (since fixes ) and on . These three points are not on one line, because is off axis 6 and and span that axis. A rigid motion of space that preserves orientation is fixed by the images of three points not on a line, so . Then , and .
Counting. Step 1 gives at most 2 values, and steps 2 and 3 at most 2 each, while step 4 gives 1, so there are at most solutions. The example of the page, and the test against a multi-start Newton search, show a target with all 8.
Complexity
Each subproblem is a fixed number of dot products, cross products, square roots and calls to atan2 and arccos, so it costs in the real RAM. An arm that splits into subproblems needs a fixed number of them per solution, and the products of the joint exponentials that form , and cost . For a fixed arm with six joints, all eight solutions take a few hundred arithmetic operations.
Properties
- All solutions. Each subproblem returns all of its solutions, so the arm solution lists the full finite set, not one solution near a guess.
- No iteration. There is no starting point, no tolerance on convergence and no failure mode from a poor guess.
- Frame free. The formulas use only axes and points, so they work in any base frame and do not need Denavit-Hartenberg parameters.
- Geometry first. The method needs the arm to have the right geometry, such as two axes that meet, or a point that some joints leave in place.
- Degenerate cases. If lies on an axis, subproblem 1 has infinitely many solutions; for the arm, this happens at a kinematic singularity, such as the wrist with the axes 4 and 6 in line.
Variants and improvements
- More subproblems. Paden's thesis describes four subproblems, and the textbook form keeps three. Elias and Wen add subproblems 4 to 6 and use the six of them to solve arms with three intersecting or three parallel axes, among other layouts.
- Approximate answers. Elias and Wen also give each subproblem a form that returns an approximate answer when there is no exact solution, which is useful near the edge of the workspace.
- Translations. Prismatic joints lead to similar subproblems, such as a translation along an axis followed by a rotation.
- Other arms. The Stanford arm, with a prismatic third joint, and arms with offsets also reduce to subproblems with a different order of steps.
- Arms that do not split. For a general 6R arm, use an algebraic method such as the Raghavan-Roth method, or a numerical one such as Newton-Raphson inverse kinematics.
When to use it
Use the subproblems when the arm has three axes that meet in a point, or other special geometry that lets you isolate joints, and you want all solutions in closed form. This covers most industrial arms with a spherical wrist; see Pieper's criterion and kinematic decoupling. When the arm does not have such geometry, use an algebraic or a numerical method.
Pitfalls
- Points on an axis. The point given to a subproblem must be off the axes of that subproblem, or the angle is not determined. Choose it once for the arm, not for each target.
- Tolerances. The exact tests of L3, L8 and L17 must be tests with a small tolerance in floating point, or a reachable target near the edge of the workspace can be rejected.
- The order of the rotations. Subproblem 2 is about , the second rotation first applied to ; swapping the axes swaps the meaning of the output.
- Duplicate solutions. When or , the two branches coincide; return one solution, or the caller counts it twice.
- Angle ranges. The angles come out of atan2 and arccos and need wrapping into the range of each joint, and the joint limits must be checked after.
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/paden-kahan-subproblems/. The authors are listed in prov/MGK2K1.jsonl.
"""The three Paden-Kahan subproblems and an elbow arm solved with them.
Each subproblem is about rotations about unit axes w that pass through a
point r. A rotation by theta takes a point x to r + Rot(w, theta) (x - r),
which is exp([xi] theta) x for the revolute twist xi = (w, -w x r).
- subproblem1(w, r, p, q): theta with exp([xi] theta) p = q.
- subproblem2(w1, w2, r, p, q): all (theta1, theta2) with
exp([xi1] theta1) exp([xi2] theta2) p = q, for two axes that meet at r.
- subproblem3(w, r, p, q, delta): all theta with |exp([xi] theta) p - q| = delta.
elbow_ik(g_d, lengths) applies them to a six joint elbow arm with a
spherical wrist (the arm of Murray, Li and Sastry, Section 3.3) and
returns every solution, up to 8. The arm is in the space form of the
product of exponentials, T(theta) = exp([S1] theta1) ... exp([S6] theta6) M.
The subproblems return an empty list, or None for subproblem 1, when
there is no solution.
"""
import math
import rbm
TOL = 1e-9
def _proj(w, x):
"""Return the part of x orthogonal to the unit vector w."""
d = rbm.dot(w, x)
return [xi - d * wi for xi, wi in zip(x, w)]
def rotate_about(w, r, theta, x):
"""Return the image of the point x under the rotation by theta about the line (w, r)."""
rot = rbm.so3_exp([theta * wi for wi in w])
return rbm.add(r, rbm.matvec(rot, rbm.sub(x, r)))
def subproblem1(w, r, p, q, tol=TOL):
"""Return theta with Rot(w, theta) (p - r) = q - r, or None if there is none.
If p lies on the axis, every theta works and 0.0 is returned.
"""
u = rbm.sub(p, r) # @line L1
v = rbm.sub(q, r)
u1 = _proj(w, u) # @line L2
v1 = _proj(w, v)
scale = 1.0 + rbm.norm(u) + rbm.norm(v)
if abs(rbm.dot(w, u) - rbm.dot(w, v)) > tol * scale or abs(rbm.norm(u1) - rbm.norm(v1)) > tol * scale: # @line L3
return None
if rbm.norm(u1) <= tol * scale:
return 0.0
return math.atan2(rbm.dot(w, rbm.cross(u1, v1)), rbm.dot(u1, v1)) # @line L4
def subproblem2(w1, w2, r, p, q, tol=TOL):
"""Return the list of (theta1, theta2) with Rot1(theta1) Rot2(theta2) p = q.
The axes (w1, r) and (w2, r) meet at r and are not parallel. The list
has 0, 1 or 2 pairs.
"""
u = rbm.sub(p, r) # @line L5
v = rbm.sub(q, r)
k = rbm.dot(w1, w2)
if abs(rbm.norm(u) - rbm.norm(v)) > tol * (1.0 + rbm.norm(u)):
return []
alpha = (k * rbm.dot(w2, u) - rbm.dot(w1, v)) / (k * k - 1.0) # @line L6
beta = (k * rbm.dot(w1, v) - rbm.dot(w2, u)) / (k * k - 1.0)
w12 = rbm.cross(w1, w2)
g2 = (rbm.dot(u, u) - alpha * alpha - beta * beta - 2.0 * alpha * beta * k) / rbm.dot(w12, w12) # @line L7
if g2 < -tol * (1.0 + rbm.dot(u, u)): # @line L8
return []
g = math.sqrt(max(g2, 0.0))
gammas = [g, -g] if g > tol * (1.0 + rbm.norm(u)) else [0.0]
out = []
for gamma in gammas: # @line L9
z = [alpha * a + beta * b + gamma * c for a, b, c in zip(w1, w2, w12)] # @line L10
c = rbm.add(r, z)
th2 = subproblem1(w2, r, p, c, tol=1e-6) # @line L11
th1 = subproblem1(w1, r, c, q, tol=1e-6)
if th1 is not None and th2 is not None:
out.append((th1, th2)) # @line L12
return out
def subproblem3(w, r, p, q, delta, tol=TOL):
"""Return the list of theta with |Rot(w, theta) (p - r) + r - q| = delta.
The list has 0, 1 or 2 angles in (-pi, pi].
"""
u = rbm.sub(p, r) # @line L13
v = rbm.sub(q, r)
u1 = _proj(w, u)
v1 = _proj(w, v)
d2 = delta * delta - rbm.dot(w, rbm.sub(p, q)) ** 2 # @line L14
th0 = math.atan2(rbm.dot(w, rbm.cross(u1, v1)), rbm.dot(u1, v1)) # @line L15
nu, nv = rbm.norm(u1), rbm.norm(v1)
if nu <= tol or nv <= tol:
return []
c = (nu * nu + nv * nv - d2) / (2.0 * nu * nv) # @line L16
if abs(c) > 1.0 + tol: # @line L17
return []
c = max(-1.0, min(1.0, c))
a = math.acos(c)
if a <= tol:
return [_wrap(th0)]
return [_wrap(th0 - a), _wrap(th0 + a)] # @line L18
def _wrap(x):
"""Return x moved into (-pi, pi]."""
y = math.fmod(x + math.pi, 2.0 * math.pi)
if y <= 0.0:
y += 2.0 * math.pi
return y - math.pi
# ---------------------------------------------------------------- the elbow arm
def elbow_arm(l0=1.0, l1=1.0, l2=1.0, l3=0.5):
"""Return (axes, M, points) of the elbow arm with a spherical wrist.
axes is a list of six (w, r) pairs at the zero configuration. The
shoulder is at (0, 0, l0), the elbow at (0, l1, l0) and the wrist
center at (0, l1 + l2, l0); the tool point is l3 further along y.
"""
qs = [0.0, 0.0, l0]
qe = [0.0, l1, l0]
qw = [0.0, l1 + l2, l0]
z, mx, y = [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]
axes = [(z, [0.0, 0.0, 0.0]), (mx, qs), (mx, qe), (z, qw), (mx, qw), (y, qw)]
m = rbm.make_T(rbm.eye(3), [0.0, l1 + l2 + l3, l0])
return axes, m, {"shoulder": qs, "elbow": qe, "wrist": qw}
def screw(w, r):
"""Return the space screw axis (w, -w x r) of a revolute joint."""
return list(w) + [-x for x in rbm.cross(w, r)]
def fk(axes, m, theta):
"""Return T(theta) = exp([S1] theta1) ... exp([Sn] thetan) M."""
t = rbm.eye(4)
for (w, r), th in zip(axes, theta):
t = rbm.mul(t, rbm.se3_exp([x * th for x in screw(w, r)]))
return rbm.mul(t, m)
def elbow_ik(axes, m, points, g_d):
"""Return every theta (a list of 6-tuples) with fk(axes, m, theta) = g_d."""
qs, qw = points["shoulder"], points["wrist"]
g1 = rbm.mul(g_d, rbm.T_inv(m))
pw = rbm.T_apply(g1, qw) # where the wrist center must go
delta = rbm.norm(rbm.sub(pw, qs))
(w1, _), (w2, _), (w3, r3), (w4, _), (w5, _), (w6, _) = axes
sols = []
for th3 in subproblem3(w3, r3, qw, qs, delta):
p3 = rotate_about(w3, r3, th3, qw)
for th1, th2 in subproblem2(w1, w2, qs, p3, pw):
t123 = fk(axes[:3], rbm.eye(4), [th1, th2, th3])
g2 = rbm.mul(rbm.T_inv(t123), g1) # = exp([S4] th4) exp([S5] th5) exp([S6] th6)
p6 = rbm.add(qw, w6) # a point on axis 6, off axes 4 and 5
for th4, th5 in subproblem2(w4, w5, qw, p6, rbm.T_apply(g2, p6)):
t45 = fk(axes[3:5], rbm.eye(4), [th4, th5])
g3 = rbm.mul(rbm.T_inv(t45), g2) # = exp([S6] th6)
p = rbm.add(qw, w4) # a point off axis 6
th6 = subproblem1(w6, qw, p, rbm.T_apply(g3, p), tol=1e-6)
if th6 is not None:
sols.append(tuple(_wrap(x) for x in (th1, th2, th3, th4, th5, th6)))
return sols
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.
Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.
The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""
import math
# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2
# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2
# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12
# ---------------------------------------------------------------- matrices
def zeros(n, m):
"""Return the n by m zero matrix."""
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, s):
"""Return s * a for a vector or a matrix a and a number s."""
if _is_matrix(a):
return [[s * x for x in row] for row in a]
return [s * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def mul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x, y):
"""Return the dot product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(x):
"""Return the Euclidean norm of a vector."""
return math.sqrt(dot(x, x))
def cross(a, b):
"""Return the cross product a x b of two 3-vectors."""
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
def _max_abs(a):
return max((abs(x) for row in a for x in row), default=0.0)
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a square matrix. b is a vector or a matrix with one column per
right-hand side; the result has the same shape as b. Raise ValueError
if a pivot is at most PIVOT_TOL times the largest entry of a.
"""
n = len(a)
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
k = len(rhs[0]) if rhs else 0
tol = PIVOT_TOL * _max_abs(a)
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
raise ValueError("matrix is singular to working precision")
m[c], m[piv] = m[piv], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0.0:
row_r, row_c = m[r], m[c]
for j in range(c, n + k):
row_r[j] -= f * row_c[j]
x = [[0.0] * k for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(k):
s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def inv(a):
"""Return the inverse of the square matrix a (see solve for errors)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a by elimination."""
n = len(a)
m = [list(map(float, row)) for row in a]
d = 1.0
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[piv][c] == 0.0:
return 0.0
if piv != c:
m[c], m[piv] = m[piv], m[c]
d = -d
d *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n):
m[r][j] -= f * m[c][j]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T.
a must be symmetric positive definite. Raise ValueError if a diagonal
entry of the factor is not positive.
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return low
def pinv_right(j):
"""Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
jt = transpose(j)
return mul(jt, inv(mul(j, jt)))
# ---------------------------------------------------------------- hat and vee
def hat3(w):
"""Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
return [
[0.0, -w[2], w[1]],
[w[2], 0.0, -w[0]],
[-w[1], w[0], 0.0],
]
def vee3(m):
"""Return the 3-vector w of a skew-symmetric matrix m = [w]."""
return [m[2][1], m[0][2], m[1][0]]
def hat6(v):
"""Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
w = hat3(v[:3])
return [
[w[0][0], w[0][1], w[0][2], v[3]],
[w[1][0], w[1][1], w[1][2], v[4]],
[w[2][0], w[2][1], w[2][2], v[5]],
[0.0, 0.0, 0.0, 0.0],
]
def vee6(m):
"""Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]
# ---------------------------------------------------------------- rotations
def rot_x(a):
"""Return the rotation by a radians about the x axis."""
c, s = math.cos(a), math.sin(a)
return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
def rot_y(a):
"""Return the rotation by a radians about the y axis."""
c, s = math.cos(a), math.sin(a)
return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
def rot_z(a):
"""Return the rotation by a radians about the z axis."""
c, s = math.cos(a), math.sin(a)
return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
def rpy(roll, pitch, yaw):
"""Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))
def so3_exp(w):
"""Return exp([w]) for exponential coordinates w = omega_hat * theta.
Rodrigues' formula in the form I + A [w] + B [w]^2 with
A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
"""
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
else:
a = math.sin(t) / t
b = (1.0 - math.cos(t)) / (t * t)
k = hat3(w)
k2 = mul(k, k)
return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]
def so3_log(r):
"""Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].
theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
above pi - NEAR_PI, the axis comes from the symmetric part
((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
from s. At theta = pi both signs are valid; the sign is then chosen so
that the largest component of the axis is positive.
"""
c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
c = max(-1.0, min(1.0, c))
s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
sn = norm(s)
t = math.atan2(sn, c)
if t < SERIES_THETA:
t2 = t * t
f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
return [f * x for x in s]
if t <= math.pi - NEAR_PI:
return [t / sn * x for x in s]
b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
# b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
# diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
k = max(range(3), key=lambda i: b[i][i])
col = [b[i][k] for i in range(3)]
axis = [x / norm(col) for x in col]
if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
axis = [-x for x in axis]
return [t * x for x in axis]
# ---------------------------------------------------------------- poses
def make_T(r, p):
"""Return the 4x4 pose [[r, p], [0, 1]]."""
return [
[r[0][0], r[0][1], r[0][2], p[0]],
[r[1][0], r[1][1], r[1][2], p[1]],
[r[2][0], r[2][1], r[2][2], p[2]],
[0.0, 0.0, 0.0, 1.0],
]
def _rp(t):
return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]
def T_inv(t):
"""Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
r, p = _rp(t)
rt = transpose(r)
return make_T(rt, [-x for x in matvec(rt, p)])
def T_apply(t, x):
"""Return R x + p, the image of the point x under the pose t."""
r, p = _rp(t)
return add(matvec(r, x), p)
def se3_exp(xi):
"""Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.
The rotation is so3_exp(w). The translation is G v with
G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
translation by v.
"""
w, v = xi[:3], xi[3:]
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
else:
b = (1.0 - math.cos(t)) / (t * t)
c = (t - math.sin(t)) / (t * t * t)
k = hat3(w)
k2 = mul(k, k)
g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
return make_T(so3_exp(w), matvec(g, v))
def se3_log(t):
"""Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].
w = so3_log(R) and v = G^(-1) p with
G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
"""
r, p = _rp(t)
w = so3_log(r)
th = norm(w)
if th < SERIES_THETA:
t2 = th * th
d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
else:
half = th / 2.0
d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
k = hat3(w)
k2 = mul(k, k)
gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
return w + matvec(gi, p)
def adjoint(t):
"""Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
r, p = _rp(t)
pr = mul(hat3(p), r)
out = zeros(6, 6)
for i in range(3):
for j in range(3):
out[i][j] = r[i][j]
out[i + 3][j + 3] = r[i][j]
out[i + 3][j] = pr[i][j]
return out
# ---------------------------------------------------------------- quaternions
def quat_mul(q, r):
"""Return the Hamilton product q r of quaternions (w, x, y, z)."""
a1, b1, c1, d1 = q
a2, b2, c2, d2 = r
return [
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
]
def quat_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return [q[0], -q[1], -q[2], -q[3]]
def quat_to_rot(q):
"""Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.
q need not be of unit length; the result is the rotation of q / |q|.
"""
w, x, y, z = q
n = w * w + x * x + y * y + z * z
s = 2.0 / n
return [
[1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
[s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
[s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
]
def quat_from_axis_angle(axis, angle):
"""Return (cos(angle / 2), sin(angle / 2) axis / |axis|).
A zero axis is allowed only with angle 0 (the identity); otherwise
raise ValueError.
"""
n = norm(axis)
if n == 0.0:
if angle == 0.0:
return [1.0, 0.0, 0.0, 0.0]
raise ValueError("zero axis with a nonzero angle")
s = math.sin(angle / 2.0) / n
return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]
# ---------------------------------------------------------------- derivatives
def num_jacobian(f, x, h=1e-6):
"""Return the Jacobian of f at x by central differences with step h.
f maps a list of n numbers to a list of m numbers; the result is m by n.
"""
cols = []
for i in range(len(x)):
xp = list(x)
xm = list(x)
xp[i] += h
xm[i] -= h
fp, fm = f(xp), f(xm)
cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
return transpose(cols)
# ---------------------------------------------------------------- self-test
def self_test():
"""Check the area check values; return True or raise AssertionError."""
r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
w = so3_log(want)
assert abs(norm(w) - 2.0943951) < 1e-7
assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
return True
test_paden_kahan_subproblems.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/paden-kahan-subproblems/. The authors are listed in prov/MGK2K1.jsonl.
"""Tests of the Paden-Kahan subproblems: each subproblem against a scan of
the angle, and the elbow arm against forward kinematics and against a
multi-start Newton search for all solutions."""
import math
import random
import rbm
from paden_kahan_subproblems import (
elbow_arm,
elbow_ik,
fk,
rotate_about,
screw,
subproblem1,
subproblem2,
subproblem3,
)
def rand_unit(rng):
while True:
v = [rng.uniform(-1.0, 1.0) for _ in range(3)]
n = rbm.norm(v)
if 0.2 < n <= 1.0:
return [x / n for x in v]
def rand_point(rng):
return [rng.uniform(-1.0, 1.0) for _ in range(3)]
def angle_diff(a, b):
d = math.fmod(a - b, 2.0 * math.pi)
return min(abs(d), 2.0 * math.pi - abs(d))
def circle(w, r, p):
"""Return t -> Rot(w, t) (p - r) + r, by Rodrigues' formula with the parts of p - r fixed once."""
u = rbm.sub(p, r)
d = rbm.dot(w, u)
par = rbm.add(r, rbm.scale(w, d))
perp = rbm.sub(u, rbm.scale(w, d))
side = rbm.cross(w, u)
return lambda t: [a + math.cos(t) * b + math.sin(t) * c for a, b, c in zip(par, perp, side)]
def scan_roots(f, n=4000):
"""Return the roots of a 2 pi periodic f found by sign changes on a grid, refined by bisection."""
xs = [-math.pi + 2.0 * math.pi * i / n for i in range(n + 1)]
fs = [f(x) for x in xs]
roots = []
for i in range(n):
if fs[i] == 0.0 or fs[i] * fs[i + 1] < 0.0:
a, b, fa = xs[i], xs[i + 1], fs[i]
for _ in range(60):
mid = 0.5 * (a + b)
fm = f(mid)
if fa * fm <= 0.0:
b = mid
else:
a, fa = mid, fm
roots.append(0.5 * (a + b))
return roots
def test_subproblem1_recovers_the_angle():
rng = random.Random(1)
for _ in range(200):
w, r, p = rand_unit(rng), rand_point(rng), rand_point(rng)
th = rng.uniform(-math.pi, math.pi)
q = rotate_about(w, r, th, p)
got = subproblem1(w, r, p, q)
assert got is not None and angle_diff(got, th) < 1e-9
def test_subproblem1_no_solution():
w, r, p = [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]
assert subproblem1(w, r, p, [0.0, 2.0, 0.0]) is None # wrong radius
assert subproblem1(w, r, p, [0.0, 1.0, 0.5]) is None # wrong height
def test_subproblem3_against_scan():
rng = random.Random(2)
counts = {0: 0, 1: 0, 2: 0}
for _ in range(40):
w, r, p, q = rand_unit(rng), rand_point(rng), rand_point(rng), rand_point(rng)
delta = rng.uniform(0.0, 2.5)
c = circle(w, r, p)
def f(t):
return rbm.norm(rbm.sub(c(t), q)) - delta
got = subproblem3(w, r, p, q, delta)
want = scan_roots(f, 1000)
assert len(got) == len(want)
counts[len(got)] += 1
for t in got:
assert abs(f(t)) < 1e-9
assert min(angle_diff(t, x) for x in want) < 1e-6
assert counts[0] > 0 and counts[2] > 0
def test_subproblem2_against_scan():
rng = random.Random(3)
for trial in range(30):
w1, w2, r, p = rand_unit(rng), rand_unit(rng), rand_point(rng), rand_point(rng)
if trial % 2 == 0:
t1, t2 = rng.uniform(-3.0, 3.0), rng.uniform(-3.0, 3.0)
q = rotate_about(w1, r, t1, rotate_about(w2, r, t2, p))
else: # a point at the right distance from r, usually without a solution
d = rand_unit(rng)
q = rbm.add(r, rbm.scale(d, rbm.norm(rbm.sub(p, r))))
got = subproblem2(w1, w2, r, p, q)
# Brute force: theta2 is a solution angle exactly when the point
# Rot2(theta2) p has the height of q along w1.
c2 = circle(w2, r, p)
want = scan_roots(lambda t: rbm.dot(w1, rbm.sub(c2(t), q)), 1000)
assert len(got) == len(want)
for th1, th2 in got:
img = rotate_about(w1, r, th1, rotate_about(w2, r, th2, p))
assert rbm.norm(rbm.sub(img, q)) < 1e-9
assert min(angle_diff(th2, x) for x in want) < 1e-6
if trial % 2 == 0:
assert any(angle_diff(a, t1) < 1e-8 and angle_diff(b, t2) < 1e-8 for a, b in got)
def pose_err(a, b):
return max(abs(a[i][j] - b[i][j]) for i in range(4) for j in range(4))
def space_jacobian(axes, theta):
t = rbm.eye(4)
cols = []
for (w, r), th in zip(axes, theta):
s = screw(w, r)
cols.append(rbm.matvec(rbm.adjoint(t), s))
t = rbm.mul(t, rbm.se3_exp([x * th for x in s]))
return rbm.transpose(cols)
def newton(axes, m, g_d, th, iters=30):
"""Plain Newton-Raphson on the space twist error; returns theta or None."""
th = list(th)
for _ in range(iters):
t = fk(axes, m, th)
vs = rbm.matvec(rbm.adjoint(t), rbm.se3_log(rbm.mul(rbm.T_inv(t), g_d)))
if rbm.norm(vs) < 1e-12:
return th
try:
step = rbm.solve(space_jacobian(axes, th), vs)
except ValueError:
return None
if rbm.norm(step) > 2.0:
step = rbm.scale(step, 2.0 / rbm.norm(step))
th = [a + b for a, b in zip(th, step)]
return None
def same(a, b, tol=1e-6):
return all(angle_diff(x, y) < tol for x, y in zip(a, b))
def test_elbow_ik_forward_kinematics():
axes, m, pts = elbow_arm()
rng = random.Random(4)
for _ in range(60):
th = [rng.uniform(-3.0, 3.0) for _ in range(6)]
g = fk(axes, m, th)
sols = elbow_ik(axes, m, pts, g)
assert 1 <= len(sols) <= 8
for s in sols:
assert pose_err(fk(axes, m, s), g) < 1e-9
assert any(same(s, th, 1e-7) for s in sols)
for i in range(len(sols)):
for j in range(i):
assert not same(sols[i], sols[j])
def test_elbow_ik_against_multistart_newton():
axes, m, pts = elbow_arm(1.0, 1.2, 0.9, 0.4)
rng = random.Random(5)
for _ in range(1):
g = fk(axes, m, [rng.uniform(-2.5, 2.5) for _ in range(6)])
sols = elbow_ik(axes, m, pts, g)
found = []
for _ in range(48):
q = newton(axes, m, g, [rng.uniform(-math.pi, math.pi) for _ in range(6)])
if q is not None and pose_err(fk(axes, m, q), g) < 1e-9:
if not any(same(q, f) for f in found):
found.append(q)
assert len(found) == len(sols) == 8
for q in found:
assert any(same(q, s) for s in sols)
def test_example_of_the_page():
axes, m, pts = elbow_arm()
th = [0.3, -0.4, 0.9, 0.5, 0.7, -0.6]
sols = elbow_ik(axes, m, pts, fk(axes, m, th))
assert len(sols) == 8
thirds = sorted(round(s[2], 6) for s in sols)
assert thirds == [-0.9] * 4 + [0.9] * 4
def test_out_of_reach():
axes, m, pts = elbow_arm()
g = rbm.make_T(rbm.eye(3), [0.0, 3.0, 1.0]) # wrist center 2.5 from the shoulder, reach 2
assert elbow_ik(axes, m, pts, g) == []
History
Paden (1986) wrote rigid motions as exponentials of twists in his Berkeley thesis and described a small set of subproblems that occur again and again in robot kinematics. He solved the Stanford arm and an elbow arm with them. The name joins Paden and William Kahan, whose part in the idea was not published as a paper. Murray, Li and Sastry (1994) gave the three subproblems their standard form in their textbook. Elias and Wen (2025) extended the set to six subproblems and solved many more arm layouts with them.
References
- Bradley E. Paden, Kinematics and Control of Robot Manipulators, PhD thesis, University of California, Berkeley, 1986 (Technical Report UCB/ERL M86/5), Chapter 2 (subproblems written with exponentials of twists) and Chapter 3 (the Stanford arm and an elbow arm solved with them)
- Richard M. Murray, Zexiang Li and S. Shankar Sastry, A Mathematical Introduction to Robotic Manipulation, CRC Press, 1994, Chapter 3, Section 3.3 (inverse kinematics, the Paden-Kahan subproblems and their use on an elbow arm)
- Alexander J. Elias and John T. Wen, IK-Geo: Unified robot inverse kinematics using subproblem decomposition, Mechanism and Machine Theory 209, 105971, 2025, the subproblems 1 to 3 in a least squares form, the new subproblems 4 to 6, and the arms with three intersecting or three parallel axes
Where this leads
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 MGK2K1 Edit this page History Report an error Markdown