Algorithm Search⌘K

Algorithmcore

Analytic two-bone inverse kinematics

Also called two-bone IK, limb IK.

Solves an arm or leg with two bones in closed form. The law of cosines gives the angle at the root and the bend, and a pole vector selects the plane and the side of the middle joint.

Time
O(1) solve
Space
O(1) extra
Properties
deterministicexactonlineiterative

Analytic two-bone inverse kinematics puts the end of a limb with two bones, such as an arm (shoulder, elbow, wrist) or a leg (hip, knee, ankle), on a target point. The three joints form a triangle with the sides l1l_1 and l2l_2 (the bones) and dd (the distance from the root to the target). The law of cosines gives its angles:

cos⁡α=l12+d2−l222l1d,cos⁡β=l12+l22−d22l1l2,\cos\alpha = \frac{l_1^2 + d^2 - l_2^2}{2 l_1 d}, \qquad \cos\beta = \frac{l_1^2 + l_2^2 - d^2}{2 l_1 l_2},

where α\alpha is the angle at the root between the bone and the line to the target, and β\beta is the inner angle at the middle joint. The triangle can turn about the line from the root to the target, so a pole vector, a point that the animator places in front of the knee or behind the elbow, selects the plane and the side. The answer is a closed form with a fixed cost, so it is the standard limb solver of game engines and animation rigs, used for foot planting on uneven ground, hands on props, and footskate cleanup.

In plain words

Your arm has two bones of fixed length. To touch a point, the shoulder, the elbow and the hand make a triangle whose three sides you know: the upper arm, the forearm, and the distance from the shoulder to the point. A triangle with known sides has known angles, so you get the bend of the elbow and the angle at the shoulder at once, with no search. The same triangle can still swing around the line from the shoulder to the point, so you also say where the elbow should point. If the point is too far, the arm is stretched straight toward it. If it is too near, the arm is folded as far as it goes.

The problem

The input is the root position aa, the target tt, the bone lengths l1,l2>0l_1, l_2 > 0, and a pole point pp. The output is the middle joint ee and the end ff with ∣e−a∣=l1|e - a| = l_1 and ∣f−e∣=l2|f - e| = l_2, such that f=tf = t when the target is reachable, and ee lies in the plane of aa, tt and pp, on the side of pp. The target is reachable if and only if ∣l1−l2∣≤d≤l1+l2|l_1 - l_2| \le d \le l_1 + l_2 for d=∣t−a∣d = |t - a|; this is the workspace of the limb. For other targets the end goes to the reachable point nearest to tt on the ray from aa through tt. It is the two-link case of the inverse kinematics problem. The robotics pages use a world with zz up, and this page uses yy up; the method does not depend on the up axis, because the pole gives the plane.

The algorithm

  1. TWO-BONE-IK(a, t, l₁, l₂, p) ▷ root, target, bone lengths, pole
  2. 1v ← t - a; d ← |v| ▷ fail if d = 0
  3. 2d ← clamp(d, |l₁ - l₂|, l₁ + l₂) ▷ the reachable distances
  4. 3x ← v / |v| ▷ the unit direction to the target
  5. 4y ← normalize((p - a) - ((p - a) · x) x) ▷ the pole direction, orthogonal to x
  6. 5cos α ← (l₁² + d² - l₂²) / (2 l₁ d); sin α ← √(1 - cos² α)
  7. 6e ← a + l₁ (cos α x + sin α y) ▷ the middle joint
  8. 7f ← a + d x ▷ the end, on the line to the target
  9. 8return e, f

Line L2 clamps the distance, so an unreachable target still gives a valid limb. Line L4 removes the part of the pole along xx, so xx and yy are orthonormal and span the bending plane. Line L5 is the law of cosines; the code computes sin⁡α\sin\alpha by the product form of Heron's formula, which is exactly 0 for a straight limb, where 1−cos⁡2α\sqrt{1 - \cos^2\alpha} loses half the digits. The bend of the middle joint relative to the straight limb is θ2=π−β\theta_2 = \pi - \beta. A rig then turns each bone from its current direction to e−ae - a and to f−ef - e, with forward kinematics over the skeleton for the joints below.

In the plane, with the root at the origin and the joint angles of the planar 2R arm, the same triangle gives the textbook form

cos⁡θ2=x2+y2−l12−l222l1l2,θ1=atan2⁡(y,x)−atan2⁡(l2sin⁡θ2, l1+l2cos⁡θ2),\cos\theta_2 = \frac{x^2 + y^2 - l_1^2 - l_2^2}{2 l_1 l_2}, \qquad \theta_1 = \operatorname{atan2}(y, x) - \operatorname{atan2}(l_2 \sin\theta_2,\ l_1 + l_2\cos\theta_2),

with θ2≥0\theta_2 \ge 0 for one elbow solution and θ2≤0\theta_2 \le 0 for the other.

Example

Take l1=l2=1l_1 = l_2 = 1, the root at the origin and the target (1,1,0)(1, 1, 0). Then d=2d = \sqrt2, cos⁡α=(1+2−1)/(22)=1/2\cos\alpha = (1 + 2 - 1)/(2\sqrt2) = 1/\sqrt2, so α=π/4\alpha = \pi/4, and cos⁡β=(1+1−2)/2=0\cos\beta = (1 + 1 - 2)/2 = 0, so the elbow angle is β=π/2\beta = \pi/2.

pole pp yy elbow ee planar angles (θ1,θ2)(\theta_1, \theta_2)
(2,−1,0)(2, -1, 0) (1,−1,0)/2(1, -1, 0)/\sqrt2 (1,0,0)(1, 0, 0) (0,π/2)(0, \pi/2)
(−1,2,0)(-1, 2, 0) (−1,1,0)/2(-1, 1, 0)/\sqrt2 (0,1,0)(0, 1, 0) (π/2,−π/2)(\pi/2, -\pi/2)

These are the two solutions of the 2R arm on the inverse kinematics page. For the target (3,0,0)(3, 0, 0), d=3d = 3 is clamped to 2, cos⁡α=1\cos\alpha = 1, and the limb is straight: e=(1,0,0)e = (1, 0, 0) and f=(2,0,0)f = (2, 0, 0), pointing at the target.

Correctness

The proofs are in proofs/correctness.md; they are proved properties of the closed form in exact arithmetic.

  • After line L2, dd, l1l_1 and l2l_2 satisfy the triangle inequalities, so ∣cos⁡α∣≤1|\cos\alpha| \le 1 and the triangle exists.
  • ∣e−a∣=l1|e - a| = l_1, because xx and yy are orthonormal.
  • ∣f−e∣=l2|f - e| = l_2, by the law of cosines in the triangle a,e,fa, e, f.
  • If the target is reachable, the clamp does nothing and f=tf = t.
  • If d>l1+l2d > l_1 + l_2, then cos⁡α=1\cos\alpha = 1, and ee and ff lie on the ray from aa to tt: the straight limb points at the target.
  • e−ae - a is a combination of xx and yy with sin⁡α≥0\sin\alpha \ge 0, so ee is in the plane of aa, tt and pp, on the side of pp.
Proof: Two-bone IK keeps the bone lengths, reaches every reachable target, and stretches toward an unreachable onefull

We use the notation of the page. The arithmetic is exact, l1,l2>0l_1, l_2 > 0, and t≠at \ne a. Let d0=∣t−a∣d_0 = |t - a| be the distance before line L2 and dd the distance after it.

The triangle exists

Lemma 1. After line L2, ∣l1−l2∣≤d≤l1+l2|l_1 - l_2| \le d \le l_1 + l_2 and −1≤cos⁡α≤1-1 \le \cos\alpha \le 1.

Proof. The clamp gives the first claim. If d=0d = 0, then l1=l2l_1 = l_2; the code sets cos⁡α=1\cos\alpha = 1, and the claims below hold with f=af = a. Otherwise cos⁡α≤1\cos\alpha \le 1 is l12+d2−l22≤2l1dl_1^2 + d^2 - l_2^2 \le 2 l_1 d, that is (l1−d)2≤l22(l_1 - d)^2 \le l_2^2, that is ∣l1−d∣≤l2|l_1 - d| \le l_2, which follows from d≥l1−l2d \ge l_1 - l_2 and d≤l1+l2d \le l_1 + l_2. cos⁡α≥−1\cos\alpha \ge -1 is (l1+d)2≥l22(l_1 + d)^2 \ge l_2^2, which follows from d≥l2−l1d \ge l_2 - l_1. □\square

So sin⁡α=1−cos⁡2α\sin\alpha = \sqrt{1 - \cos^2\alpha} is real and nonnegative.

Bone lengths

Lemma 2. xx and yy of lines L3 and L4 are orthonormal.

Proof. ∣x∣=1|x| = 1 by line L3. Let w=(p−a)−((p−a)⋅x) xw = (p - a) - ((p - a)\cdot x)\,x; then w⋅x=(p−a)⋅x−(p−a)⋅x=0w \cdot x = (p - a)\cdot x - (p - a)\cdot x = 0, and y=w/∣w∣y = w / |w| for w≠0w \ne 0. □\square

Lemma 3. ∣e−a∣=l1|e - a| = l_1 and ∣f−e∣=l2|f - e| = l_2.

Proof. By line L6 and Lemma 2, ∣e−a∣2=l12(cos⁡2α+sin⁡2α)=l12|e - a|^2 = l_1^2 (\cos^2\alpha + \sin^2\alpha) = l_1^2. By line L7, f−e=(d−l1cos⁡α) x−l1sin⁡α yf - e = (d - l_1\cos\alpha)\,x - l_1 \sin\alpha\, y, so ∣f−e∣2=d2−2dl1cos⁡α+l12=d2−(l12+d2−l22)+l12=l22|f - e|^2 = d^2 - 2 d l_1 \cos\alpha + l_1^2 = d^2 - (l_1^2 + d^2 - l_2^2) + l_1^2 = l_2^2 by line L5. □\square

Reaching the target

Lemma 4. If ∣l1−l2∣≤d0≤l1+l2|l_1 - l_2| \le d_0 \le l_1 + l_2, then f=tf = t.

Proof. The clamp leaves d=d0d = d_0, and f=a+d0(t−a)/d0=tf = a + d_0 (t - a)/d_0 = t. □\square

Lemma 5. If d0>l1+l2d_0 > l_1 + l_2, then e=a+l1xe = a + l_1 x and f=a+(l1+l2)xf = a + (l_1 + l_2) x: the limb is straight and points at the target.

Proof. Then d=l1+l2d = l_1 + l_2, and cos⁡α=l12+(l1+l2)2−l222l1(l1+l2)=2l12+2l1l22l1(l1+l2)=1\cos\alpha = \frac{l_1^2 + (l_1 + l_2)^2 - l_2^2}{2 l_1 (l_1 + l_2)} = \frac{2 l_1^2 + 2 l_1 l_2}{2 l_1 (l_1 + l_2)} = 1, so sin⁡α=0\sin\alpha = 0. □\square

Of all the points that the end can reach, which are the points at a distance in [∣l1−l2∣,l1+l2][|l_1 - l_2|, l_1 + l_2] from aa, the point a+(l1+l2) xa + (l_1 + l_2)\,x is the nearest to tt, because the distance from tt to a point at the distance rr from aa is at least ∣d0−r∣|d_0 - r|, with equality on the ray toward tt. The same argument gives the nearest point a+∣l1−l2∣ xa + |l_1 - l_2|\, x for d0<∣l1−l2∣d_0 < |l_1 - l_2|.

The plane and the side

Lemma 6. ee lies in the plane through aa spanned by xx and p−ap - a, and (e−a)⋅w≥0(e - a) \cdot w \ge 0.

Proof. e−a=l1(cos⁡α x+sin⁡α y)e - a = l_1(\cos\alpha\,x + \sin\alpha\,y), and yy is a combination of xx and p−ap - a. (e−a)⋅w=l1sin⁡α ∣w∣≥0(e - a)\cdot w = l_1 \sin\alpha\, |w| \ge 0, by Lemma 2 and sin⁡α≥0\sin\alpha \ge 0. □\square

The planar closed form

Lemma 7. For a reachable (x,y)≠(0,0)(x, y) \ne (0, 0) in the plane, θ2=±arccos⁡x2+y2−l12−l222l1l2\theta_2 = \pm\arccos\frac{x^2 + y^2 - l_1^2 - l_2^2}{2 l_1 l_2} and θ1=atan2⁡(y,x)−atan2⁡(l2sin⁡θ2,l1+l2cos⁡θ2)\theta_1 = \operatorname{atan2}(y, x) - \operatorname{atan2}(l_2 \sin\theta_2, l_1 + l_2 \cos\theta_2) satisfy l1(cos⁡θ1,sin⁡θ1)+l2(cos⁡(θ1+θ2),sin⁡(θ1+θ2))=(x,y)l_1(\cos\theta_1, \sin\theta_1) + l_2(\cos(\theta_1 + \theta_2), \sin(\theta_1 + \theta_2)) = (x, y).

Proof. In complex numbers the left side is eiθ1(l1+l2eiθ2)e^{i\theta_1}(l_1 + l_2 e^{i\theta_2}). Its length squared is l12+l22+2l1l2cos⁡θ2=x2+y2l_1^2 + l_2^2 + 2 l_1 l_2 \cos\theta_2 = x^2 + y^2, by the choice of θ2\theta_2. Its argument is θ1+arg⁡(l1+l2eiθ2)=atan2⁡(y,x)\theta_1 + \arg(l_1 + l_2 e^{i\theta_2}) = \operatorname{atan2}(y, x), by the choice of θ1\theta_1. Two complex numbers with the same length and the same argument are equal. □\square

For l1=l2=1l_1 = l_2 = 1 and (x,y)=(1,1)(x, y) = (1, 1), cos⁡θ2=0\cos\theta_2 = 0. For θ2=π/2\theta_2 = \pi/2, θ1=π/4−atan2⁡(1,1)=0\theta_1 = \pi/4 - \operatorname{atan2}(1, 1) = 0, and for θ2=−π/2\theta_2 = -\pi/2, θ1=π/4+π/4=π/2\theta_1 = \pi/4 + \pi/4 = \pi/2. These are the check values (0,π/2)(0, \pi/2) and (π/2,−π/2)(\pi/2, -\pi/2), and the inner elbow angle is β=π−∣θ2∣=π/2\beta = \pi - |\theta_2| = \pi/2.

Complexity

The method uses a fixed number of arithmetic operations and two square roots, so it costs O(1)O(1) time and O(1)O(1) space per limb. A character with four limbs needs four calls per frame.

Properties

  • Closed form, deterministic, with no iteration and no convergence test.
  • For a reachable target in a fixed plane there are exactly two solutions when ∣l1−l2∣<d<l1+l2|l_1 - l_2| < d < l_1 + l_2, and the pole picks one; at the two limits they merge.
  • The result is continuous in the target and the pole, except where the pole lies on the line from the root to the target.
  • Near full extension, α\alpha changes fast: dα/ddd\alpha / dd tends to infinity as dd tends to l1+l2l_1 + l_2, so the middle joint can snap when a target moves near the limit.

Variants and improvements

  • Longer chains. FABRIK, cyclic coordinate descent and the Jacobian transpose method handle chains of any length by iteration. A common rig solves a three bone leg by a two-bone solve and a fixed foot angle.
  • Soft limits. Many rigs ease dd toward l1+l2l_1 + l_2 with a smooth function to hide the snap near full extension. This is a tuning, with no source on this page.
  • Stretch. Some rigs scale the bones when the target is out of reach, instead of the clamp of line L2.
  • Joint limits and twist. The pole sets the plane, but not the twist of the end bone; the end orientation is set separately, for example to match the ground normal under a foot.
  • Style. Style based IK learns the choice among solutions from motion data.

When to use it

Use it for any arm or leg with a hinge in the middle when the end must reach a point exactly: foot contact, hand contact, aiming, and cleanup of foot sliding. For spines, tails, tentacles and other long chains, use an iterative solver.

Pitfalls

  • Target at the root. If d=0d = 0, there is no direction xx; the code raises an error. With l1=l2l_1 = l_2 every direction is a solution.
  • Pole on the line. If p−ap - a is parallel to xx, line L4 divides by zero. The code then picks a fixed direction orthogonal to xx; a rig should keep the pole away from the line.
  • Clamping only cos⁡α\cos\alpha. Clamping the cosine to [−1,1][-1, 1] without clamping dd keeps the joint angles valid, but the end no longer lies on the line to the target. Clamp dd first.
  • Mixed conventions. The planar angles θ1\theta_1 and θ2\theta_2 are relative: θ2\theta_2 is measured from the direction of the first bone. Joint angles of a rig may use the inner angle β\beta instead.
  • Bone lengths from the pose. Take l1l_1 and l2l_2 from the bind pose, not from the current animated pose, or the limb drifts when the animation scales a bone.

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.

anim.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.

Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
  left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
  with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
  rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""

import math

# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6


# ---------------------------------------------------------------- vectors


def add(a, b):
    """Return a + b."""
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    """Return a - b."""
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    """Return s a for a number s."""
    return tuple(s * x for x in a)


def dot(a, b):
    """Return the dot product of a and b."""
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    """Return the cross product of two 3D 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 cross2(a, b):
    """Return the scalar 2D cross product a_x b_y - a_y b_x."""
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    """Return the Euclidean length of a."""
    return math.sqrt(sum(x * x for x in a))


def normalize(a):
    """Return a / |a|. Raise ValueError for the zero vector."""
    n = norm(a)
    if n == 0.0:
        raise ValueError("cannot normalize the zero vector")
    return tuple(x / n for x in a)


def lerp(a, b, t):
    """Return (1 - t) a + t b."""
    return tuple((1 - t) * x + t * y for x, y in zip(a, b))


# ---------------------------------------------------------------- matrices


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None)."""
    if m is None:
        m = n
    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 mul(a, b):
    """Return the matrix product a b."""
    bt = list(zip(*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 vector a x as a tuple."""
    return tuple(sum(p * q for p, q in zip(row, x)) for row in a)


def transpose(a):
    """Return the transpose of a."""
    return [list(col) for col in zip(*a)]


def _lu(a):
    """Gaussian elimination with partial pivoting on a copy of a square a.

    Return (lu, perm, sign), or None if a pivot is exactly zero.
    """
    n = len(a)
    lu = [list(map(float, row)) for row in a]
    perm = list(range(n))
    sign = 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if lu[p][k] == 0.0:
            return None
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        piv = lu[k][k]
        for i in range(k + 1, n):
            f = lu[i][k] / piv
            lu[i][k] = f
            if f != 0.0:
                rk = lu[k]
                ri = lu[i]
                for j in range(k + 1, n):
                    ri[j] -= f * rk[j]
    return lu, perm, sign


def det(a):
    """Return the determinant of a square matrix."""
    n = len(a)
    if n == 1:
        return a[0][0]
    if n == 2:
        return a[0][0] * a[1][1] - a[0][1] * a[1][0]
    if n == 3:
        return (
            a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
            - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
            + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
        )
    r = _lu(a)
    if r is None:
        return 0.0
    lu, _, sign = r
    d = sign
    for i in range(n):
        d *= lu[i][i]
    return d


def _lu_solve(lu, perm, b):
    n = len(lu)
    y = [float(b[perm[i]]) for i in range(n)]
    for i in range(n):
        s = y[i]
        row = lu[i]
        for j in range(i):
            s -= row[j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        row = lu[i]
        for j in range(i + 1, n):
            s -= row[j] * y[j]
        y[i] = s / row[i]
    return y


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (returns a list) or a matrix given as a list of rows
    (returns a list of rows, one column of x per column of b).
    Raise ValueError if a is singular.
    """
    r = _lu(a)
    if r is None:
        raise ValueError("singular matrix")
    lu, perm, _ = r
    if len(b) > 0 and isinstance(b[0], (list, tuple)):
        cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
        return [list(row) for row in zip(*cols)]
    return _lu_solve(lu, perm, b)


def inv(a):
    """Return the inverse of a square matrix. Raise ValueError if singular."""
    return solve(a, eye(len(a)))


# ---------------------------------------------------------------- polar decomposition


def rot2(theta):
    """Return the 2 by 2 rotation matrix by the angle theta."""
    c, s = math.cos(theta), math.sin(theta)
    return [[c, -s], [s, c]]


def _frob(a):
    return math.sqrt(sum(x * x for row in a for x in row))


def _sym_eig3(s):
    """Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).

    Return (values, vectors), where vectors[k] is the unit eigenvector of
    values[k].
    """
    a = [list(map(float, row)) for row in s]
    v = eye(3)
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            sn = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p] = c * akp - sn * akq
                a[k][q] = sn * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k] = c * apk - sn * aqk
                a[q][k] = sn * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p] = c * vkp - sn * vkq
                v[k][q] = sn * vkp + c * vkq
    values = [a[i][i] for i in range(3)]
    vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
    return values, vectors


def polar(f, tol=1e-14, max_iter=100):
    """Return (R, S) with F = R S, det R = +1 and S symmetric.

    2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
    the rotation that maximizes trace(R^T F), and S = R^T F.
    3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
    the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
    is above 1e-2. It stops when the relative change in the Frobenius norm is
    at most tol, or after max_iter steps. The iteration gives the orthogonal
    polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
    eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
    If det F > 0, S is symmetric positive definite. If det F < 0, S is
    symmetric with one negative eigenvalue. Raise ValueError for a singular
    3 by 3 F.
    """
    n = len(f)
    if n == 2:
        theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
        r = rot2(theta)
        s = mul(transpose(r), f)
        s01 = 0.5 * (s[0][1] + s[1][0])
        s[0][1] = s[1][0] = s01
        return r, s
    if n != 3:
        raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
    x = [list(map(float, row)) for row in f]
    change = float("inf")
    for _ in range(max_iter):
        xi = inv(x)
        if change > 1e-2:
            g = math.sqrt(_frob(xi) / _frob(x))
        else:
            g = 1.0
        xit = transpose(xi)
        y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
        change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
        x = y
        if change <= tol:
            break
    u = x
    s = mul(transpose(u), f)
    s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    if det(u) < 0.0:
        values, vectors = _sym_eig3(s)
        k = min(range(3), key=lambda i: values[i])
        v = vectors[k]
        h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
        u = mul(u, h)
        s = mul(h, s)
        s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    return u, s


# ---------------------------------------------------------------- quaternions


def q_mul(p, q):
    """Return the Hamilton product p q."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    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 q_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return (q[0], -q[1], -q[2], -q[3])


def q_dot(p, q):
    """Return the dot product of p and q as vectors of R^4."""
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]


def q_normalize(q):
    """Return q / |q|."""
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("cannot normalize the zero quaternion")
    return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)


def q_from_axis_angle(axis, angle):
    """Return the unit quaternion of the rotation by angle about axis (any length)."""
    u = normalize(axis)
    s = math.sin(0.5 * angle)
    return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])


def q_to_mat3(q):
    """Return the 3 by 3 rotation matrix of a unit quaternion."""
    w, x, y, z = q
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
    ]


def q_rotate(q, v):
    """Return the vector part of q (0, v) q* for a unit quaternion q."""
    r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
    return (r[1], r[2], r[3])


def q_log(q):
    """Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).

    For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
    phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
    """
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("log of the zero quaternion")
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    lw = math.log(n)
    if vn == 0.0:
        return (lw, 0.0, 0.0, 0.0)
    phi = math.atan2(vn, q[0])
    f = phi / vn
    return (lw, f * q[1], f * q[2], f * q[3])


def q_exp(q):
    """Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    ew = math.exp(q[0])
    if vn == 0.0:
        return (ew, 0.0, 0.0, 0.0)
    f = ew * math.sin(vn) / vn
    return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])


def slerp(q0, q1, t):
    """Spherical linear interpolation of unit quaternions on the short arc.

    If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
    comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
    normalized linear interpolation is returned. See
    robotics/rigid-body-motion/spherical-linear-interpolation.
    """
    if q_dot(q0, q1) < 0.0:
        q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
    a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
    b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
    w = 2.0 * math.atan2(a, b)
    if w < SLERP_SMALL_ANGLE:
        return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
    s = math.sin(w)
    c0 = math.sin((1 - t) * w) / s
    c1 = math.sin(t * w) / s
    return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))


def q_from_mat3(r):
    """Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.

    Shepperd's method: take the largest of the trace, r00, r11 and r22, and
    divide by the component that it gives. See
    robotics/rigid-body-motion/shepperd-method.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
    if k == 0:
        w = math.sqrt(1.0 + t) / 2.0
        f = 4.0 * w
        q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
    elif k == 1:
        x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
        f = 4.0 * x
        q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
    elif k == 2:
        y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
        f = 4.0 * y
        q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
    else:
        z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
        f = 4.0 * z
        q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
    if q[0] < 0.0:
        q = (-q[0], -q[1], -q[2], -q[3])
    return q


# ---------------------------------------------------------------- transforms


def make_T(r, t):
    """Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
    d = len(t)
    m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
    m.append([0.0] * d + [1.0])
    return m


def T_mul(a, b):
    """Return the product a b of two homogeneous transforms."""
    return mul(a, b)


def T_inv(m):
    """Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].

    The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
    """
    d = len(m) - 1
    a = [row[:d] for row in m[:d]]
    t = [m[i][d] for i in range(d)]
    ai = inv(a)
    ti = matvec(ai, t)
    return make_T(ai, tuple(-x for x in ti))


def T_apply(m, p):
    """Apply a homogeneous transform to a point p and return a tuple."""
    d = len(m) - 1
    return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))


# ---------------------------------------------------------------- derivatives


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
two_bone_inverse_kinematics.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-bone-inverse-kinematics/. The authors are listed in prov/9Q6NF0.jsonl.
"""Analytic two-bone inverse kinematics with a pole vector.

A limb has the root a (shoulder or hip), the middle joint e (elbow or knee)
and the end f (wrist or ankle), with the bone lengths l1 = |e - a| and
l2 = |f - e|. Given a target t and a pole point p, the method:

1. clamps the distance d = |t - a| to [|l1 - l2|, l1 + l2];
2. finds the angle alpha at the root by the law of cosines;
3. puts the middle joint in the plane of a, t and p, on the side of p.

The end reaches t exactly when |l1 - l2| <= d <= l1 + l2. Otherwise it goes
to the reachable point nearest to t on the ray from a toward t, so an
unreachable far target gives the straight limb pointing at it.

planar_two_bone is the closed form of the planar 2R arm (joint angles
theta1 and theta2, both elbow solutions); it is the reference of the tests.
"""

import math

from anim import add, cross, dot, norm, normalize, scale, sub


def clamp(x, lo, hi):
    return lo if x < lo else hi if x > hi else x


def _orthogonal(x):
    """Return a unit vector orthogonal to the unit vector x (a fixed choice)."""
    k = min(range(3), key=lambda i: abs(x[i]))
    e = tuple(1.0 if i == k else 0.0 for i in range(3))
    return normalize(cross(cross(x, e), x))


def two_bone_ik(a, t, l1, l2, pole):
    """Return (e, f), the middle joint and the end of the limb.

    a: root position; t: target; l1, l2: bone lengths (positive);
    pole: a point that selects the bending plane and side.
    Raise ValueError if t = a (no direction to reach for).
    If the pole lies on the line through a and t, a fixed orthogonal
    direction is used instead.
    """
    v = sub(t, a)  # @line L1
    d = norm(v)
    if d == 0.0:
        raise ValueError("the target is at the root")
    dc = clamp(d, abs(l1 - l2), l1 + l2)  # @line L2
    x = scale(v, 1.0 / d)  # @line L3
    w = sub(pole, a)
    w = sub(w, scale(x, dot(w, x)))  # @line L4
    y = normalize(w) if norm(w) > 1e-12 * max(1.0, norm(sub(pole, a))) else _orthogonal(x)
    if dc == 0.0:
        ca, sa = 1.0, 0.0  # l1 = l2 and the limb folds onto itself
    else:
        ca = clamp((l1 * l1 + dc * dc - l2 * l2) / (2.0 * l1 * dc), -1.0, 1.0)  # @line L5
        # sin(alpha) by the product form of Heron's formula: it is exactly 0
        # for the straight limb, where sqrt(1 - ca^2) would give about 1e-8
        h2 = (dc + l1 + l2) * (l1 + l2 - dc) * (dc - l1 + l2) * (dc + l1 - l2)
        sa = min(1.0, math.sqrt(max(0.0, h2)) / (2.0 * l1 * dc))
    e = add(a, scale(add(scale(x, ca), scale(y, sa)), l1))  # @line L6
    f = add(a, scale(x, dc))  # @line L7
    return e, f  # @line L8


def bend_angle(l1, l2, d):
    """Return the bend theta2 = pi - beta of the middle joint for the distance d."""
    dc = clamp(d, abs(l1 - l2), l1 + l2)
    cb = clamp((l1 * l1 + l2 * l2 - dc * dc) / (2.0 * l1 * l2), -1.0, 1.0)
    return math.pi - math.acos(cb)


def planar_two_bone(x, y, l1, l2, elbow=1):
    """Closed form of the planar 2R arm: return (theta1, theta2).

    elbow = +1 gives theta2 >= 0, elbow = -1 gives theta2 <= 0. The target
    must be reachable.
    """
    c2 = (x * x + y * y - l1 * l1 - l2 * l2) / (2.0 * l1 * l2)
    if c2 < -1.0 - 1e-12 or c2 > 1.0 + 1e-12:
        raise ValueError("the target is not reachable")
    th2 = elbow * math.acos(clamp(c2, -1.0, 1.0))
    th1 = math.atan2(y, x) - math.atan2(l2 * math.sin(th2), l1 + l2 * math.cos(th2))
    return th1, th2


def planar_fk(th1, th2, l1, l2):
    """Forward kinematics of the planar 2R arm: return (elbow, end)."""
    e = (l1 * math.cos(th1), l1 * math.sin(th1))
    f = (e[0] + l2 * math.cos(th1 + th2), e[1] + l2 * math.sin(th1 + th2))
    return e, f
test_two_bone_inverse_kinematics.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/two-bone-inverse-kinematics/. The authors are listed in prov/9Q6NF0.jsonl.
"""Tests of analytic two-bone IK.

They check the 2R check values, that forward kinematics of the result
reaches a reachable target within 1e-9 and keeps the bone lengths, that an
unreachable far target gives the straight limb pointing at it, that a near
target gives the folded limb, that the pole selects the plane and the side,
and that the 3D solution equals the planar closed form.
"""

import math
import random

import pytest

import anim
from two_bone_inverse_kinematics import (
    bend_angle,
    planar_fk,
    planar_two_bone,
    two_bone_ik,
)


def close(a, b, tol):
    return all(abs(x - y) <= tol for x, y in zip(a, b))


def rand_vec(rng, s=1.0):
    return tuple(rng.uniform(-s, s) for _ in range(3))


def test_check_values():
    th = planar_two_bone(1.0, 1.0, 1.0, 1.0, elbow=1)
    assert close(th, (0.0, math.pi / 2), 1e-12)
    th = planar_two_bone(1.0, 1.0, 1.0, 1.0, elbow=-1)
    assert close(th, (math.pi / 2, -math.pi / 2), 1e-12)
    assert abs(bend_angle(1.0, 1.0, math.sqrt(2.0)) - math.pi / 2) <= 1e-12
    # the 3D solver with the pole on the side of +x - y gives the elbow (1, 0, 0)
    e, f = two_bone_ik((0.0, 0.0, 0.0), (1.0, 1.0, 0.0), 1.0, 1.0, (2.0, -1.0, 0.0))
    assert close(e, (1.0, 0.0, 0.0), 1e-12) and close(f, (1.0, 1.0, 0.0), 1e-12)
    e, f = two_bone_ik((0.0, 0.0, 0.0), (1.0, 1.0, 0.0), 1.0, 1.0, (-1.0, 2.0, 0.0))
    assert close(e, (0.0, 1.0, 0.0), 1e-12)


def test_reachable_targets_and_lengths():
    rng = random.Random(1)
    for _ in range(500):
        a = rand_vec(rng, 2.0)
        l1, l2 = rng.uniform(0.2, 2.0), rng.uniform(0.2, 2.0)
        lo, hi = abs(l1 - l2), l1 + l2
        d = rng.uniform(lo + 1e-6, hi - 1e-6)
        t = anim.add(a, anim.scale(anim.normalize(rand_vec(rng)), d))
        e, f = two_bone_ik(a, t, l1, l2, anim.add(a, rand_vec(rng, 3.0)))
        assert close(f, t, 1e-9)
        assert abs(anim.norm(anim.sub(e, a)) - l1) <= 1e-9
        assert abs(anim.norm(anim.sub(f, e)) - l2) <= 1e-9


def test_planar_fk_of_ik():
    rng = random.Random(2)
    for _ in range(500):
        l1, l2 = rng.uniform(0.2, 2.0), rng.uniform(0.2, 2.0)
        d = rng.uniform(abs(l1 - l2) + 1e-6, l1 + l2 - 1e-6)
        phi = rng.uniform(-math.pi, math.pi)
        x, y = d * math.cos(phi), d * math.sin(phi)
        for elbow in (1, -1):
            th1, th2 = planar_two_bone(x, y, l1, l2, elbow)
            _, f = planar_fk(th1, th2, l1, l2)
            assert close(f, (x, y), 1e-9)


def test_unreachable_far_target_gives_straight_limb():
    rng = random.Random(3)
    for _ in range(200):
        a = rand_vec(rng)
        l1, l2 = rng.uniform(0.2, 2.0), rng.uniform(0.2, 2.0)
        u = anim.normalize(rand_vec(rng))
        t = anim.add(a, anim.scale(u, (l1 + l2) * rng.uniform(1.01, 3.0)))
        e, f = two_bone_ik(a, t, l1, l2, anim.add(a, rand_vec(rng, 3.0)))
        assert close(e, anim.add(a, anim.scale(u, l1)), 1e-9)
        assert close(f, anim.add(a, anim.scale(u, l1 + l2)), 1e-9)


def test_near_target_gives_folded_limb():
    a, t = (0.0, 0.0, 0.0), (0.1, 0.0, 0.0)
    e, f = two_bone_ik(a, t, 2.0, 1.0, (0.0, 1.0, 0.0))
    assert close(e, (2.0, 0.0, 0.0), 1e-12) and close(f, (1.0, 0.0, 0.0), 1e-12)
    e, f = two_bone_ik(a, t, 1.0, 2.0, (0.0, 1.0, 0.0))
    assert close(e, (-1.0, 0.0, 0.0), 1e-12) and close(f, (1.0, 0.0, 0.0), 1e-12)


def test_pole_selects_plane_and_side():
    rng = random.Random(4)
    for _ in range(300):
        a = rand_vec(rng)
        l1, l2 = rng.uniform(0.5, 1.5), rng.uniform(0.5, 1.5)
        d = rng.uniform(abs(l1 - l2) + 0.05, l1 + l2 - 0.05)
        x = anim.normalize(rand_vec(rng))
        t = anim.add(a, anim.scale(x, d))
        p = anim.add(a, rand_vec(rng, 3.0))
        e, _ = two_bone_ik(a, t, l1, l2, p)
        nrm = anim.cross(x, anim.sub(p, a))
        if anim.norm(nrm) < 1e-3:
            continue
        assert abs(anim.dot(anim.sub(e, a), anim.normalize(nrm))) <= 1e-9
        w = anim.sub(anim.sub(p, a), anim.scale(x, anim.dot(anim.sub(p, a), x)))
        assert anim.dot(anim.sub(e, a), w) >= 0.0


def test_3d_equals_planar_closed_form():
    rng = random.Random(5)
    for _ in range(300):
        l1, l2 = rng.uniform(0.2, 2.0), rng.uniform(0.2, 2.0)
        d = rng.uniform(abs(l1 - l2) + 1e-6, l1 + l2 - 1e-6)
        phi = rng.uniform(-math.pi, math.pi)
        x, y = d * math.cos(phi), d * math.sin(phi)
        th1, th2 = planar_two_bone(x, y, l1, l2, elbow=-1)
        e2, _ = planar_fk(th1, th2, l1, l2)
        # elbow = -1 bends clockwise, so the elbow is on the left of the target ray
        pole = (-math.sin(phi), math.cos(phi), 0.0)
        e, f = two_bone_ik((0.0, 0.0, 0.0), (x, y, 0.0), l1, l2, pole)
        assert close(e, (e2[0], e2[1], 0.0), 1e-9)
        assert abs(e[2]) <= 1e-12


def test_degenerate_inputs():
    with pytest.raises(ValueError):
        two_bone_ik((0.0, 0.0, 0.0), (0.0, 0.0, 0.0), 1.0, 1.0, (0.0, 1.0, 0.0))
    # a pole on the line through the root and the target still gives a valid limb
    e, f = two_bone_ik((0.0, 0.0, 0.0), (1.0, 0.0, 0.0), 1.0, 1.0, (5.0, 0.0, 0.0))
    assert close(f, (1.0, 0.0, 0.0), 1e-12)
    assert abs(anim.norm(e) - 1.0) <= 1e-12 and abs(anim.norm(anim.sub(f, e)) - 1.0) <= 1e-12
    with pytest.raises(ValueError):
        planar_two_bone(3.0, 0.0, 1.0, 1.0)

History

The closed form of the planar two-link arm comes from robotics, where it is the first example of analytic inverse kinematics, as in Lynch and Park (2017). Computer animation took it over for limbs, and Parent (2012) treats it with the other inverse kinematics methods for linkages. The pole vector is the control that animation tools added to choose the bending plane of a three dimensional limb.

References

  1. Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 6, Inverse Kinematics (the planar two-link arm and analytic inverse kinematics)
  2. Rick Parent, Computer Animation, Algorithms and Techniques, 3rd edition, Morgan Kaufmann, 2012, the chapter on kinematic linkages (inverse kinematics)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.solve
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example