Algorithmadvanced
FABRIK
Also called forward and backward reaching inverse kinematics.
Solves the inverse kinematics of a chain by moving joint positions along lines in a backward and a forward pass, keeping link lengths.
- Time
- Θ(k n) worst
- Space
- Θ(n) extra
- Where
- k = the number of iterations; n = the number of links
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Andreas Aristidou, Joan Lasenby, 2011
FABRIK (forward and backward reaching inverse kinematics) solves the inverse kinematics of a chain by working on the joint positions instead of the joint angles. A backward pass puts the end effector on the target and pulls each joint back along a line so that each link keeps its length. A forward pass then puts the first joint back on the base and pushes the joints out again in the same way. Each step only finds a point on a line, so it is very cheap, and the error never increases. Aristidou and Lasenby (2011) introduced it for computer animation.
In plain words
Think of a chain of rigid rods joined end to end, with the first end fixed to a wall. Grab the free end and put it on the target. The next rod now has a gap at its far end, so drag that joint along the straight line toward its old place until the rod has its length again, and go on to the wall. The first joint is now off the wall. Put it back, and drag the joints in the same way from the wall out to the free end. The free end is now near the target, and usually nearer than before. Repeat until it is close enough. At the end, read the joint angles off the joint positions.
The problem
Input.
- The joint positions of a serial chain with ball or unconstrained joints, in the plane or in space, and the link lengths .
- The base , which stays fixed, a target , a tolerance and an iteration limit .
Output. New joint positions with the same base and link lengths and , or the stretched chain toward a target out of reach, or the last iterate with the report that the tolerance was not met.
The joint angles follow from the positions, by the direction of each link relative to the one before.
The algorithm
FABRIK(p_0..p_n, d_1..d_n, t, ε, k_max)- 1
b ← p_0 - 2
if |t - b| > d_1 + ... + d_n then - 3
for i ← 0 to n - 1: p_{i+1} ← p_i + d_{i+1} (t - p_i) / |t - p_i| - 4
return p, with the report that t is out of reach - 5
for k ← 1 to k_max - 6
if |p_n - t| ≤ ε then return p - 7
p_n ← t; for i ← n - 1 downto 0: p_i ← p_{i+1} + d_{i+1} (p_i - p_{i+1}) / |p_i - p_{i+1}| ▷ backward - 8
p_0 ← b; for i ← 0 to n - 1: p_{i+1} ← p_i + d_{i+1} (p_{i+1} - p_i) / |p_{i+1} - p_i| ▷ forward - 9
return p with the report that the tolerance was not met
Each update at L7 and L8 puts a joint on the sphere of radius about its neighbor, at the point of that sphere nearest to the old position of the joint. If the two points coincide, the direction is not defined, and any direction works; the code takes the first axis.
Example
The planar chain has the lengths m, the base at the origin and the start angles rad, so the joints are at , , and m. The target is m, and the start error is 0.871173 m.
- The backward pass puts on and moves and , and ends at m, off the base.
- The forward pass puts back at the origin, and ends at m. The error is now 0.065496 m.
| iterations | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| error (m) | 0.871173 | 0.065496 | 0.058673 | 0.054112 | 0.050900 |
The first iteration removes 92 % of the error, but then progress is slow: the ratio of errors tends to 0.9007, and the error falls below m after 232 iterations. The final angles are rad, and forward kinematics of these angles gives back the joint positions. For a 2R arm, FABRIK is much faster: with lengths 1 m, the start rad and the target m, it reaches to m in 2 iterations.
Correctness
The proof page proves these facts in exact arithmetic.
- Valid chain. After each forward pass, the base is at and every link has its length.
- Nearest points. Each update moves a joint to the nearest point at the right distance from its neighbor.
- Monotone error. The error never increases from one iteration to the next.
- Out of reach. If , line L3 gives the configuration nearest to the target, stretched along the line from the base.
- Fixed points. A solution does not change under an iteration.
- Stall on a line. If the base, the target and all joints lie on one line, every iterate stays on that line.
Convergence. Aristidou and Lasenby (2011) observed convergence in experiments. Aristidou, Chrysanthou and Lasenby (2016, Section 3.3) state and prove convergence for the unconstrained chain when the target is in reach. The stall on a line shows that a start where all joints lie on the line through the base and the target must be excluded: three links of 1 m on the axis can only put the end at or m on that line, so for the target m the error stays at 0.9 m. Monotone error alone does not give convergence to 0, and no rate is known in general; the example shows a linear tail.
Proof: FABRIK keeps the chain valid, never increases the error, solves targets out of reach in one step, and can stall on a linefull
We use the notation of the page, in exact arithmetic. The chain has the joint positions and the link lengths . A configuration is valid if for all and , the base. For points and , is the point at distance from on the ray towards .
These claims are about what each step does. They do not show that the iteration reaches a target in reach; Claim 6 shows that it can fail to.
Claim 1: each placement is a nearest point
For every with , .
Proof. By the triangle inequality, . The point lies on the line through and , on the same side of as , at distance from , so its distance to is .
If , every point at distance from is equally near to , and the claims below hold for any choice of the point. So in the backward pass, each new is the point at distance from the new that is nearest to the old , and the same holds in the forward pass with the roles swapped.
Claim 2: the output is a valid configuration
Proof. After the forward pass at line L8, , and each is placed at distance from , in the order . Later placements in the same pass move only later points, so all lengths hold at the end of the pass. The stretched chain of line L3 is built in the same way from .
The backward pass alone gives and all lengths, but may leave the base; the forward pass then gives the base back and may move off the target. This is why the method alternates.
Claim 3: for a target out of reach, line L3 gives the best configuration
Let .
Proof. For every valid configuration, , so . At line L3, at every step, since lies on the segment from towards at distance from . So every lies on the ray from to , , and , the lower bound.
Claim 4: the error never increases
Let before an iteration and after it, for a valid configuration.
Proof. First, along one pass the moves of the points never grow. In the backward pass, write for the new points. The point is at distance from , and by Claim 1 the new is the point at that distance from nearest to . So . The first move is , so .
In the forward pass, write for the new points. The same argument with the roles of and swapped gives , and the first move is . So .
So the errors converge to a limit, but Claim 4 does not say that the limit is 0.
Claim 5: solutions are fixed points
If a valid configuration has , one more iteration does not change it.
Proof. The backward pass sets , which does not change it. Then for , the point is at distance from the unchanged , so . The forward pass is unchanged in the same way, since .
So line L6 stops at a solution, and an iteration never moves away from one.
Claim 6: a chain on a line through the base and the target stays on it
If , and all lie on one line , all later iterates lie on .
Proof. lies on the line through and , which is when , and the passes only place points with and already on or equal to or .
For three links of length 1 m on the axis with , the end can only be at on the line, since it is a sum of three terms . The target m is in reach of the chain in the plane, but by Claim 6 the error stays at least 0.9 m for every iteration from a straight start. So a convergence result for targets in reach must exclude such starts. Section 3.3 of Aristidou, Chrysanthou and Lasenby (2016) states convergence for the unconstrained chain and a target in reach; the page cites it with this exception.
Complexity
Cost per iteration. Each pass does updates, each with one distance and one square root in fixed dimension, so one iteration costs in the real RAM. The test of reach at L2 costs once. So iterations cost , with extra space for the positions.
Number of iterations. It is not bounded in general; it ranged from 2 to 232 in the examples.
Properties
- No angles, no matrices. The method needs no Jacobian, no rotation matrices and no linear solves.
- Valid output. Every output is a valid chain with the right link lengths and base.
- Monotone. The error never increases.
- Smooth poses. The motion spreads over the whole chain, so the poses tend to look natural in animation, unlike the curled poses of cyclic coordinate descent.
- Positions only. The basic method treats each joint as a ball joint; hinge axes and joint limits need extra steps.
Variants and improvements
- Joint limits and hinges. After each placement, move the joint into the allowed cone or plane of the joint; Aristidou, Chrysanthou and Lasenby (2016) study such model constraints.
- Several end effectors. Aristidou and Lasenby (2011) treat trees of chains: each branch does its backward pass, a shared joint takes the mean of its proposals, and the forward pass goes from the root out.
- Orientation targets. A target orientation of the end link can be handled by a second target point for the joint before the end, at the right distance along the wanted direction.
- Other methods. Cyclic coordinate descent also updates one joint at a time, but on angles; damped least squares moves all joints together with a Jacobian.
When to use it
Use FABRIK for long chains and skeletons in animation and games, where the joints are close to ball joints and each frame needs a cheap update that gives natural poses. For an industrial arm with hinge joints and a full pose target, use Newton-Raphson inverse kinematics, damped least squares or a closed form solution.
Pitfalls
- Degenerate starts. A start with all joints on the line through the base and the target can stay there forever; a small bend of the start removes the stall.
- The test of reach. Line L2 checks only the outer radius of the workspace. A target inside the inner hole, such as a point closer to the base than for two links, passes the test, but no iteration can reach it, and the loop runs to the limit.
- Slow tails. As the example shows, the error can fall fast at first and then slowly; set the tolerance and the limit with care.
- Hinge joints. Reading angles off a 3D result for an arm with hinge joints is not valid unless the hinge constraints were applied in each pass.
- Coincident points. If a joint lands on its neighbor, the direction at L7 or L8 is not defined; choose one and keep the result valid.
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/fabrik/. The authors are listed in prov/W25J11.jsonl.
"""FABRIK (forward and backward reaching inverse kinematics) for an
unconstrained chain of points, after Aristidou and Lasenby (2011).
The chain is a list of joint positions p_0, ..., p_n (each a list of floats,
in any dimension) with link lengths d_1, ..., d_n, where d_i = |p_i - p_(i-1)|.
The base p_0 stays fixed and the end effector p_n should reach a target t.
- place(a, b, d) returns the point at distance d from a on the ray towards b.
- backward_pass and forward_pass are the two half steps.
- fabrik(points, lengths, target, ...) returns (points, errors, ok).
- planar_angles(points) turns a planar chain into relative joint angles,
so that the result can be checked by forward kinematics.
The module needs only the standard library.
"""
import math
def dist(a, b):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))
def place(a, b, d):
"""Return the point at distance d from a, on the ray from a towards b.
If b equals a, the direction is not defined; the first axis is used.
"""
r = dist(a, b)
if r == 0.0:
return [a[0] + d] + list(a[1:])
lam = d / r
return [(1.0 - lam) * x + lam * y for x, y in zip(a, b)]
def backward_pass(points, lengths, target):
"""Put the end effector on the target and pull the chain after it."""
n = len(lengths)
points[n] = list(target) # @line L7
for i in range(n - 1, -1, -1): # @line L7
points[i] = place(points[i + 1], points[i], lengths[i]) # @line L7
def forward_pass(points, lengths, base):
"""Put the first joint back on the base and push the chain from it."""
points[0] = list(base) # @line L8
for i in range(len(lengths)): # @line L8
points[i + 1] = place(points[i], points[i + 1], lengths[i]) # @line L8
def fabrik(points, lengths, target, eps=1e-10, max_iter=1000):
"""Return (points, errors, ok). errors[k] is |p_n - t| after k iterations.
If the target is out of reach, the chain is stretched along the line
from the base towards the target, and ok is False.
"""
points = [list(p) for p in points]
base = list(points[0]) # @line L1
n = len(lengths)
if dist(base, target) > sum(lengths): # @line L2
for i in range(n): # @line L3
points[i + 1] = place(points[i], target, lengths[i]) # @line L3
return points, [dist(points[n], target)], False # @line L4
errors = [dist(points[n], target)]
for _ in range(max_iter): # @line L5
if errors[-1] <= eps: # @line L6
return points, errors, True # @line L6
backward_pass(points, lengths, target) # @line L7
forward_pass(points, lengths, base) # @line L8
errors.append(dist(points[n], target))
return points, errors, errors[-1] <= eps # @line L9
def chain_from_angles(lengths, q):
"""The joint positions of a planar chain with relative angles q, base at the origin."""
pts = [[0.0, 0.0]]
a = 0.0
for length, t in zip(lengths, q):
a += t
x, y = pts[-1]
pts.append([x + length * math.cos(a), y + length * math.sin(a)])
return pts
def planar_angles(points):
"""Relative joint angles of a planar chain, each in (-pi, pi]."""
q, prev = [], 0.0
for a, b in zip(points, points[1:]):
ang = math.atan2(b[1] - a[1], b[0] - a[0])
q.append(math.remainder(ang - prev, 2.0 * math.pi))
prev = ang
return q
test_fabrik.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fabrik/. The authors are listed in prov/W25J11.jsonl.
"""Tests of FABRIK: the link lengths and the base after every pass, the
example of the page, the result turned into joint angles and checked by
forward kinematics, the 2R result against the closed form solutions, random
3D chains with targets in reach, the stretched chain for a target out of
reach, and the stall of a collinear start."""
import math
import random
from fabrik import backward_pass, chain_from_angles, dist, fabrik, forward_pass, planar_angles
def lengths_of(points):
return [dist(a, b) for a, b in zip(points, points[1:])]
def test_passes_keep_lengths_and_base():
rng = random.Random(1)
for _ in range(30):
n = rng.randint(2, 7)
pts = [[0.0, 0.0, 0.0]]
for _ in range(n):
pts.append([c + rng.uniform(-1.0, 1.0) for c in pts[-1]])
lengths = lengths_of(pts)
target = [rng.uniform(-2.0, 2.0) for _ in range(3)]
p = [list(x) for x in pts]
for _ in range(5):
backward_pass(p, lengths, target)
assert p[-1] == target
assert max(abs(a - b) for a, b in zip(lengths_of(p), lengths)) < 1e-12
forward_pass(p, lengths, pts[0])
assert p[0] == pts[0]
assert max(abs(a - b) for a, b in zip(lengths_of(p), lengths)) < 1e-12
def test_example_of_the_page():
lengths = [1.0, 0.8, 0.5]
pts = chain_from_angles(lengths, [0.3, 0.4, 0.5])
target = [1.2, 0.6]
assert abs(dist(pts[3], target) - 0.871173) < 1e-6
p = [list(x) for x in pts]
backward_pass(p, lengths, target)
assert max(abs(a - b) for a, b in zip(p[0], [0.066581, 0.022541])) < 1e-6
forward_pass(p, lengths, [0.0, 0.0])
assert max(abs(a - b) for a, b in zip(p[3], [1.142549, 0.568550])) < 1e-6
p, errors, ok = fabrik(pts, lengths, target)
assert ok and len(errors) - 1 == 232
assert abs(errors[1] - 0.065496) < 1e-6
assert all(b <= a for a, b in zip(errors, errors[1:]))
assert abs(errors[200] / errors[199] - 0.9007) < 1e-4
q = planar_angles(p)
assert max(abs(a - b) for a, b in zip(q, [0.377886, -0.104655, 2.838020])) < 1e-6
# Forward kinematics of the angles gives back the points.
for a, b in zip(chain_from_angles(lengths, q), p):
assert dist(a, b) < 1e-12
assert dist(chain_from_angles(lengths, q)[3], target) < 1e-10
def test_two_link_against_the_closed_form():
rng = random.Random(2)
for _ in range(40):
l1, l2 = rng.uniform(0.5, 1.5), rng.uniform(0.5, 1.5)
q_star = [rng.uniform(-math.pi, math.pi), rng.uniform(0.2, 2.9) * rng.choice((-1, 1))]
target = chain_from_angles([l1, l2], q_star)[2]
start = chain_from_angles([l1, l2], [rng.uniform(-math.pi, math.pi), rng.uniform(0.2, 2.9)])
p, errors, ok = fabrik(start, [l1, l2], target)
assert ok
q = planar_angles(p)
# The closed form: the two elbow solutions.
x, y = target
c2 = (x * x + y * y - l1 * l1 - l2 * l2) / (2.0 * l1 * l2)
sols = []
for s in (1.0, -1.0):
q2 = s * math.acos(max(-1.0, min(1.0, c2)))
q1 = math.atan2(y, x) - math.atan2(l2 * math.sin(q2), l1 + l2 * math.cos(q2))
sols.append([q1, q2])
assert min(max(abs(math.remainder(a - b, 2.0 * math.pi)) for a, b in zip(q, sol)) for sol in sols) < 1e-6
def test_random_chains_with_targets_in_reach():
rng = random.Random(3)
for _ in range(40):
n = rng.randint(3, 8)
pts = [[0.0, 0.0, 0.0]]
for _ in range(n):
pts.append([c + rng.uniform(-1.0, 1.0) for c in pts[-1]])
lengths = lengths_of(pts)
# A target in reach: the end of the same chain in another pose.
other = [[0.0, 0.0, 0.0]]
for d in lengths:
v = [rng.gauss(0.0, 1.0) for _ in range(3)]
nv = math.sqrt(sum(x * x for x in v))
other.append([c + d * x / nv for c, x in zip(other[-1], v)])
target = other[-1]
p, errors, ok = fabrik(pts, lengths, target, eps=1e-9, max_iter=20000)
assert ok
# The error never increases (Claim 4 of the proof page).
assert all(b <= a + 1e-15 for a, b in zip(errors, errors[1:]))
assert dist(p[-1], target) <= 1e-9 and p[0] == pts[0]
assert max(abs(a - b) for a, b in zip(lengths_of(p), lengths)) < 1e-9
def test_target_out_of_reach():
lengths = [1.0, 0.7, 0.4]
start = chain_from_angles(lengths, [0.4, 0.4, 0.4])
for target in ([3.0, 1.0], [-2.5, -0.5], [0.2, 2.4]):
p, errors, ok = fabrik(start, lengths, target)
assert not ok
d = math.hypot(*target)
assert abs(errors[-1] - (d - sum(lengths))) < 1e-12
q = planar_angles(p)
assert abs(math.remainder(q[0] - math.atan2(target[1], target[0]), 2.0 * math.pi)) < 1e-12
assert abs(q[1]) < 1e-12 and abs(q[2]) < 1e-12
def test_collinear_start_stalls():
# Every point stays on the x axis, where the end can only be at odd integers.
lengths = [1.0, 1.0, 1.0]
start = chain_from_angles(lengths, [0.0, 0.0, 0.0])
p, errors, ok = fabrik(start, lengths, [0.1, 0.0], max_iter=200)
assert not ok
assert all(abs(pt[1]) == 0.0 for pt in p)
assert abs(errors[-1] - 0.9) < 1e-12
# A small bend of the start removes the stall.
start = chain_from_angles(lengths, [0.0, 0.01, 0.0])
p, errors, ok = fabrik(start, lengths, [0.1, 0.0], max_iter=20000)
assert ok
History
Aristidou and Lasenby (2011) introduced FABRIK in Graphical Models as a fast heuristic for inverse kinematics that finds each joint position by locating a point on a line. They showed it on single chains, on chains with several end effectors and with joint limits, and compared it with Jacobian and coordinate descent methods. Aristidou, Chrysanthou and Lasenby (2016) extended it with model constraints for human figures and gave a proof of convergence for the unconstrained chain.
References
- Andreas Aristidou and Joan Lasenby, FABRIK: A fast, iterative solver for the Inverse Kinematics problem, Graphical Models 73(5), 243-260, 2011, Section 4 (the algorithm for a single chain)
- Andreas Aristidou, Yiorgos Chrysanthou and Joan Lasenby, Extending FABRIK with model constraints, Computer Animation and Virtual Worlds 27(1), 35-57, 2016, Section 3.3 (proof of convergence)
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 W25J11 Edit this page History Report an error Markdown