Algorithmcore
Cyclic coordinate descent inverse kinematics
Also called CCD inverse kinematics.
Turns one joint at a time, from the tip to the base, to point the end effector at the target, repeating until close.
- Time
- Θ(k n) worst
- Space
- Θ(n) extra
- Where
- k = the number of sweeps; n = the number of joints
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- L. C. T. Wang, C. C. Chen, 1991
Cyclic coordinate descent (CCD) solves the inverse kinematics of a chain of revolute joints by turning one joint at a time. Each joint, from the tip to the base, turns by the angle that brings the end effector as close to the target as possible, and that angle has a closed form. One sweep over the joints is cheap, needs no Jacobian and no linear solve, and never makes the error larger. CCD is popular in computer animation for long chains, but it has no general guarantee that it reaches a target in reach, and it tends to bend the joints near the tip the most.
In plain words
Think of a chain of rods with hinges, and a point the free end must touch. Start at the hinge next to the free end. Turn only that hinge, as far as needed to swing the free end as close to the point as it can go. Then do the same with the next hinge toward the base, and so on, up to the base. That is one sweep. Repeat sweeps until the end touches the point or stops moving closer. Each turn is easy to find, because one hinge can only move the end on a circle.
The problem
Input.
- A serial chain of revolute joints, given by forward kinematics: for a joint vector , the world position and unit axis of each joint and the end effector position .
- A target point , an initial guess , a tolerance and a sweep limit .
Output. A with , or the last iterate with the report that the tolerance was not met.
The version here matches positions only. Orientation targets need a combined cost per joint, as in the method of Wang and Chen.
The algorithm
CCD-IK(chain, t, θ0, ε, k_max)- 1
θ ← θ0 - 2
for k ← 1 to k_max - 3
(p_1..p_n, w_1..w_n, e) ← FORWARD-KINEMATICS(θ) - 4
if |e - t| ≤ ε then return θ - 5
for i ← n downto 1 ▷ from the tip to the base - 6
u ← (e - p_i) minus its part along w_i; v ← (t - p_i) minus its part along w_i - 7
φ ← atan2(w_i · (u × v), u · v) ▷ φ ← 0 if u · v = 0 and w_i · (u × v) = 0 - 8
θ_i ← θ_i + φ; e ← p_i + R(w_i, φ)(e - p_i) - 9
return θ with the report that the tolerance was not met
Line L7 is the least squares form of the first Paden-Kahan subproblem: the end effector moves on a circle about the axis of joint , and L7 picks the point of that circle nearest to the target. Line L8 moves the end effector with the Rodrigues formula instead of a new forward kinematics. This is valid because turning joint moves only the links after it, so and for , which the sweep uses next, do not change.
Joint limits are easy to add: clamp to the allowed range at L8.
Example
The planar 2R arm has m, both axes along , the target m and the start rad. At the start the hand is at m, and the error is 0.294173 m.
Sweep 1:
- Joint 2 turns by rad, and the error becomes 0.294106 m.
- Joint 1 turns by rad. The hand moves to m, on the line from the base through the target, and the error becomes 0.232222 m.
After the sweep, rad.
| sweeps | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| error (m) | 0.294173 | 0.232222 | 0.135220 | 0.073280 | 0.038185 |
After that, each sweep halves the error, and after 33 sweeps the error is below m at rad. Near the solution, one sweep acts to first order like one Gauss-Seidel sweep on the normal equations with , and the Gauss-Seidel ratio for this matrix is . This is an explanation of the observed ratio, not a proof. For the same arm and start, the Jacobian transpose method with its best fixed gain has the ratio 0.745.
For the target m, out of reach, the error stops falling after 90 sweeps, with the arm stretched along the axis and the error at 0.5 m.
In the tests, 20 random chains of 6 joints in space, with targets that forward kinematics puts in reach, all reach the target to m, in 7 to 181 sweeps.
Correctness
The proof page proves four facts.
- Best turn. Line L7 gives the angle that minimizes the distance from the end effector to the target over all turns of joint alone.
- Cheap update. Line L8 gives the true end effector position, and the positions and axes from L3 stay valid for the joints that the sweep visits next.
- Monotone error. The error never increases, so the errors converge.
- Fixed points. If a sweep does not move any joint, the gradient of the squared error is zero.
Convergence. CCD has no general convergence result, and the sources of this page prove none. The error converges to a limit, but the limit can be positive at a stationary point that is not a solution, and the joint vectors need not converge. For a target out of reach, the stretched arm that points at the target is a stationary point. The linear rate in the example is observed, not proved.
Proof: Each CCD update is the best turn of its joint, the error never increases, and a sweep that changes nothing stops at a stationary pointfull
We use the notation of the page, in exact arithmetic. The chain has revolute joints . For a joint vector , joint has the world position and the unit world axis , and is the position of the end effector. is the rotation about the unit vector by the angle , given by the Rodrigues formula. The error is .
Claim 1: line L7 gives the best angle for one joint
Fix , write , , and , and let and be the parts perpendicular to . If joint turns by and the other joints stay, the part of the chain after joint turns rigidly about the line through along , so the end effector moves to . Then
The Rodrigues formula gives . So , with and , since is perpendicular to .
If , write with ; then , which is largest exactly at . So of line L7 minimizes the distance, and it is the only minimizer up to multiples of . If , the distance does not depend on , and is a minimizer.
Claim 2: line L8 keeps the end effector right
Turning joint moves only the links after joint . So the positions and axes of joints , found by forward kinematics at line L3, do not change, and the joints that the sweep visits after joint can use them. The end effector moves to , which is the value that line L8 stores. By induction over the joints of the sweep, before each update , and are the true values for the current .
Claim 3: the error never increases
By Claim 1 with as one candidate, the update of joint gives an error at most the error before it. By Claim 2, the error that the loop sees is the true error. So the errors after each joint update form a nonincreasing sequence of numbers , and it converges.
The limit need not be 0, and Claim 3 does not say that the joint vectors converge.
Claim 4: a sweep that changes nothing stops at a stationary point
Let a sweep give for every joint. Then the sweep does not move the chain, so all joints see the same . By Claim 1, at joint means either , or and ; in both cases . The partial derivative of in is , the speed of the end effector along the error. Since and , this is . So the gradient of is zero, and is a stationary point; moreover, each joint alone is at its best angle.
A stationary point with is not a solution. For a target out of reach, the stretched chain that points at the target is such a point. So these claims give no guarantee that CCD finds a solution when one exists, and the page makes no such claim.
Complexity
Cost per sweep. Line L3 costs for a serial chain, and each joint update at L6 to L8 costs , in the real RAM. So one sweep costs , and sweeps cost . A version that calls forward kinematics again for each joint costs per sweep. The extra space is for the joint positions and axes.
Number of sweeps. It is not bounded in general, and it depends a lot on the start and the target, as the tests show.
Properties
- No Jacobian. CCD needs no Jacobian, no matrix inverse and no tuning gain.
- Always defined. Each update exists for every configuration, including singular ones and targets out of reach.
- Monotone. The error after each joint update is never larger than before.
- Order. The order from the tip to the base is the usual one; other orders give other iterates and other end poses.
- Uneven motion. The joints near the tip often turn much more than the joints near the base, which gives curled poses in long chains.
Variants and improvements
- Orientation. Wang and Chen minimize a weighted sum of a position and an orientation error for each joint, still in closed form.
- Joint limits. Clamp each angle at L8; the error still never increases, since the clamped angle lies between the old angle and the best one, where the error falls steadily.
- Damping. Scale each by a factor below 1, or limit its size, to spread the motion over the chain.
- Prismatic joints. The best slide along the axis is the projection of onto the axis.
- Other methods. FABRIK also works joint by joint, but on positions instead of angles; damped least squares moves all joints together.
When to use it
Use CCD for long chains, for interactive animation where each step must be cheap, and where joint limits must be applied joint by joint. For a robot arm that must reach a full pose accurately, use Newton-Raphson inverse kinematics or damped least squares, or a closed form solution when the arm has one.
Pitfalls
- No guarantee. CCD can stop at a stationary point that is not a solution, and nothing tells you this except the error at the end.
- Exact degenerate starts. For the 2R arm above, the straight start rad and the target m fold the arm to the base in one sweep, where joint 1 has no best angle. In exact arithmetic CCD stops there with an error of 1 m; in floating point, rounding moves it off that point.
- Curled poses. Since the tip joints turn first, the result can look unnatural; damping or a different order helps.
- Slow convergence. For targets near the boundary of the workspace, the error can fall slowly over many sweeps.
- Angle wrap. The angles grow by multiples of over many sweeps; wrap them before you compare them with joint limits.
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/cyclic-coordinate-descent-inverse-kinematics/. The authors are listed in prov/JXW2FC.jsonl.
"""Cyclic coordinate descent (CCD) inverse kinematics for a serial chain of
revolute joints in 3D, with a position target for the end effector.
The chain is a list of joints. Joint i has a unit axis axes[i] and a link
vector links[i], both given in the frame of the link before the joint (the
world frame for joint 0). With all angles zero the frames are aligned.
Joint 0 sits at the origin, joint i + 1 sits at the end of link i, and the
end effector sits at the end of the last link.
- joint_frames(axes, links, q) returns the world positions and axes of the
joints and the end effector position.
- best_angle(w, p, e, t) returns the angle about the axis (w, p) that brings
the point e as close as possible to the point t, in closed form.
- ccd_sweep(...) updates the joints once each, from the tip to the base.
- ik_ccd(...) repeats sweeps and returns (q, errors, ok).
Vectors are lists of 3 floats. The module needs only the standard library.
"""
import math
def add(a, b):
return [x + y for x, y in zip(a, b)]
def sub(a, b):
return [x - y for x, y in zip(a, b)]
def scale(s, a):
return [s * x for x in a]
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
def norm(a):
return math.sqrt(dot(a, a))
def rotate(w, phi, x):
"""Rotate the vector x about the unit axis w by the angle phi (Rodrigues)."""
c, s = math.cos(phi), math.sin(phi)
return add(add(scale(c, x), scale(s, cross(w, x))), scale((1.0 - c) * dot(w, x), w))
def rot_matrix(w, phi):
cols = [rotate(w, phi, e) for e in ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0])]
return [[cols[j][i] for j in range(3)] for i in range(3)]
def matmul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]
def matvec(a, x):
return [dot(row, x) for row in a]
def joint_frames(axes, links, q):
"""Return (positions, world_axes, end) of the chain at the joint angles q."""
r = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
p = [0.0, 0.0, 0.0]
positions, world_axes = [], []
for a, link, angle in zip(axes, links, q):
positions.append(p)
world_axes.append(matvec(r, a))
r = matmul(r, rot_matrix(a, angle))
p = add(p, matvec(r, link))
return positions, world_axes, p
def best_angle(w, p, e, t):
"""Return the angle phi about the axis through p along the unit vector w
that minimizes |p + R(w, phi)(e - p) - t|."""
u, v = sub(e, p), sub(t, p)
u_perp = sub(u, scale(dot(w, u), w)) # @line L6
v_perp = sub(v, scale(dot(w, v), w)) # @line L6
a = dot(u_perp, v_perp) # @line L7
b = dot(w, cross(u_perp, v_perp)) # @line L7
if a == 0.0 and b == 0.0:
return 0.0 # every angle is as good
return math.atan2(b, a) # @line L7
def ccd_sweep(axes, links, q, target):
"""One sweep from the tip to the base. Return (new q, end effector position).
Turning joint i moves only the end effector and the joints after i, so the
positions and axes of joints 0 to i - 1, found once by forward kinematics,
stay valid, and the end effector is rotated in place.
"""
q = list(q)
positions, world_axes, e = joint_frames(axes, links, q) # @line L3
for i in range(len(q) - 1, -1, -1): # @line L5
w, p = world_axes[i], positions[i]
phi = best_angle(w, p, e, target) # @line L6
q[i] += phi # @line L8
e = add(p, rotate(w, phi, sub(e, p))) # @line L8
return q, e
def ik_ccd(axes, links, target, q0, eps=1e-10, max_sweeps=1000, min_gain=0.0):
"""Repeat CCD sweeps. Return (q, errors, ok), with errors[k] the distance
to the target after k sweeps.
The loop stops when the error is at most eps (ok is True), or when a sweep
lowers the error by at most min_gain, or after max_sweeps sweeps.
"""
q = [float(x) for x in q0] # @line L1
err = norm(sub(joint_frames(axes, links, q)[2], target))
errors = [err]
for _ in range(max_sweeps): # @line L2
if err <= eps: # @line L4
return q, errors, True # @line L4
q, e = ccd_sweep(axes, links, q, target) # @line L5
new_err = norm(sub(e, target))
errors.append(new_err)
if err - new_err <= min_gain and new_err > eps:
return q, errors, False
err = new_err
return q, errors, err <= eps # @line L9
def planar_chain(lengths):
"""A planar chain in the x-y plane: every axis is z and every link points along x."""
return [[0.0, 0.0, 1.0] for _ in lengths], [[length, 0.0, 0.0] for length in lengths]
test_cyclic_coordinate_descent_inverse_kinematics.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cyclic-coordinate-descent-inverse-kinematics/. The authors are listed in prov/JXW2FC.jsonl.
"""Tests of CCD inverse kinematics: the closed form angle of one joint against
a brute force grid over the angle, the in-place update of the end effector
against forward kinematics, the monotone error, the 2R example of the page
against the closed form solution, random 3D chains with reachable targets,
and the stretched chain for a target out of reach."""
import math
import random
from cyclic_coordinate_descent_inverse_kinematics import (
add, best_angle, ccd_sweep, ik_ccd, joint_frames, norm, planar_chain, rotate, scale, sub)
def rand_unit(rng):
while True:
v = [rng.gauss(0.0, 1.0) for _ in range(3)]
n = norm(v)
if n > 1e-3:
return scale(1.0 / n, v)
def rand_chain(rng, n):
axes = [rand_unit(rng) for _ in range(n)]
links = [[rng.uniform(-0.6, 0.6) for _ in range(3)] for _ in range(n)]
return axes, links
def test_best_angle_against_a_grid():
rng = random.Random(1)
steps = 3600
for _ in range(20):
w = rand_unit(rng)
p, e, t = ([rng.uniform(-1.0, 1.0) for _ in range(3)] for _ in range(3))
def dist(phi):
return norm(sub(add(p, rotate(w, phi, sub(e, p))), t))
phi = best_angle(w, p, e, t)
grid = min(dist(2.0 * math.pi * k / steps) for k in range(steps))
assert dist(phi) <= grid + 1e-12
# The grid point next to the optimum is within the grid error.
assert grid - dist(phi) < 1e-4
def test_best_angle_reaches_a_point_on_the_circle():
# If t lies on the circle that e sweeps, the distance becomes zero.
rng = random.Random(2)
for _ in range(20):
w = rand_unit(rng)
p, e = [rng.uniform(-1.0, 1.0) for _ in range(3)], [rng.uniform(-1.0, 1.0) for _ in range(3)]
angle = rng.uniform(-3.0, 3.0)
t = add(p, rotate(w, angle, sub(e, p)))
phi = best_angle(w, p, e, t)
assert norm(sub(add(p, rotate(w, phi, sub(e, p))), t)) < 1e-12
assert abs(math.remainder(phi - angle, 2.0 * math.pi)) < 1e-9
def test_sweep_matches_forward_kinematics_and_error_never_increases():
rng = random.Random(3)
for _ in range(20):
axes, links = rand_chain(rng, 6)
q = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
target = [rng.uniform(-1.0, 1.0) for _ in range(3)]
err = norm(sub(joint_frames(axes, links, q)[2], target))
for _ in range(5):
# One joint at a time, by full forward kinematics, from the tip to the base.
qq = list(q)
for i in range(5, -1, -1):
pos, wax, e = joint_frames(axes, links, qq)
qq[i] += best_angle(wax[i], pos[i], e, target)
new = norm(sub(joint_frames(axes, links, qq)[2], target))
assert new <= err + 1e-12
err = new
q, e = ccd_sweep(axes, links, q, target)
assert max(abs(a - b) for a, b in zip(q, qq)) < 1e-9
assert norm(sub(e, joint_frames(axes, links, q)[2])) < 1e-12
def test_example_of_the_page():
axes, links = planar_chain([1.0, 1.0])
target = [1.0, 1.0, 0.0]
q, e = ccd_sweep(axes, links, [0.3, 1.2], target)
assert max(abs(a - b) for a, b in zip(q, [0.181657, 1.207482])) < 1e-6
assert abs(norm(sub(e, target)) - 0.232222) < 1e-6
q, errors, ok = ik_ccd(axes, links, target, [0.3, 1.2])
assert ok and len(errors) - 1 == 33
# The closed form solution with the elbow at 90 degrees.
assert abs(q[0]) < 1e-9 and abs(q[1] - math.pi / 2.0) < 1e-9
assert max(abs(a - b) for a, b in zip(errors[:5], [0.294173, 0.232222, 0.135220, 0.073280, 0.038185])) < 1e-6
for a, b in zip(errors[10:30], errors[11:31]):
assert abs(b / a - 0.5) < 1e-3
assert all(b <= a for a, b in zip(errors, errors[1:]))
def test_reachable_targets_on_random_chains():
rng = random.Random(4)
solved = 0
runs = 20
for _ in range(runs):
axes, links = rand_chain(rng, 6)
q_star = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
target = joint_frames(axes, links, q_star)[2]
q0 = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
q, errors, ok = ik_ccd(axes, links, target, q0, eps=1e-9, max_sweeps=3000)
assert all(b <= a + 1e-12 for a, b in zip(errors, errors[1:]))
assert abs(norm(sub(joint_frames(axes, links, q)[2], target)) - errors[-1]) < 1e-9
if ok:
solved += 1
assert norm(sub(joint_frames(axes, links, q)[2], target)) <= 1e-9
# CCD has no general guarantee, but with these seeds every run reaches its target.
assert solved == runs
def test_target_out_of_reach_stretches_the_chain():
lengths = [1.0, 0.7, 0.4]
axes, links = planar_chain(lengths)
for target in ([3.0, 1.0, 0.0], [-2.5, -0.5, 0.0], [0.2, 2.4, 0.0]):
q, errors, ok = ik_ccd(axes, links, target, [0.4, 0.4, 0.4], max_sweeps=2000)
assert not ok
d = norm(target)
assert abs(errors[-1] - (d - sum(lengths))) < 1e-6
# The chain points straight at the target.
assert abs(math.remainder(q[0] - math.atan2(target[1], target[0]), 2.0 * math.pi)) < 1e-3
assert abs(math.remainder(q[1], 2.0 * math.pi)) < 1e-3 and abs(math.remainder(q[2], 2.0 * math.pi)) < 1e-3
History
Coordinate descent is an old optimization method. Wang and Chen (1991) applied it to the inverse kinematics of manipulators, with a closed form solution for the best turn of each joint, and combined it with a second nonlinear programming method. The method became a standard tool for inverse kinematics in computer animation and games, where its cheap steps and simple handling of joint limits matter more than its weak guarantees.
References
- L.-C. T. Wang and C. C. Chen, A combined optimization method for solving the inverse kinematics problem of mechanical manipulators, IEEE Transactions on Robotics and Automation 7(4), 489-499, 1991, the cyclic coordinate descent part of the method
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 JXW2FC Edit this page History Report an error Markdown