Algorithmcore
Spherical linear interpolation
Also called slerp, quaternion slerp.
Interpolates two unit quaternions along the shorter great arc between them, which turns a body about one fixed axis at constant angular speed from the first orientation to the second.
- Time
- Θ(1) worst
- Space
- Θ(1) extra
- Where
- n = the number of quaternion components, fixed at n = 4
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
Spherical linear interpolation, or slerp, takes two unit quaternions and and a number , and returns the point at the fraction of the great arc from to on the unit sphere of :
where is the angle between and as vectors of . As rotations, the result turns the body from the first orientation to the second about one fixed axis at a constant angular speed. Shoemake brought the method to computer animation in 1985, and it is the standard way to interpolate orientations in graphics and robotics.
In plain words
You have two orientations of a body and you want the ones in between. A unit quaternion is a point on a sphere in four dimensions, and each orientation is such a point. Slerp walks along the shortest circle on that sphere from the first point to the second, at a steady pace. For the body, this means one steady turn about one fixed line. Each orientation has two points on the sphere, opposite to each other. If you pick the wrong one, the body turns the long way round, so slerp first picks the point that is nearer. When the two points are almost equal, a plain straight line between them, pushed back onto the sphere, is as good and avoids a division by zero.
The problem
The input is two unit quaternions and , in the Hamilton convention with the scalar first, and a number , usually in . They stand for the rotations and , with equal to the vector part of . The output is a unit quaternion such that , , and
where is the logarithm map of SO(3) with . So is the rotation followed by the fraction of the relative rotation , about the axis in the frame of .
The algorithm
The algorithm takes the angle from atan2, , which is accurate at every angle. This is the angle of the isosceles triangle with sides and : the chord and the sum . The threshold is .
SLERP(q₀, q₁, t) ▷ unit quaternions; returns the point at t on the short arc- 1
d ← q₀ · q₁ ▷ the dot product in R⁴, d = cos Ω - 2
if d < 0 then - 3
q₁ ← -q₁ ▷ the same rotation, on the near side of the sphere - 4
Ω ← 2 atan2(|q₁ - q₀|, |q₁ + q₀|) ▷ the angle between q₀ and q₁, in [0, π/2] - 5
if Ω < δ then ▷ the two points almost agree - 6
q ← (1 - t) q₀ + t q₁ - 7
return q / |q| - 8
a ← sin((1 - t) Ω) / sin Ω - 9
b ← sin(t Ω) / sin Ω - 10
return a q₀ + b q₁
Lines L1 to L3 choose the sign of that makes the arc short. Line L4 computes the angle of the arc. Lines L6 and L7 are the normalized linear interpolation, used only for tiny arcs. Lines L8 to L10 are the slerp formula.
Example
Interpolate from the identity to the rotation by 90 degrees about , , at .
- Line L1: , so line L3 is not used.
- Line L4: and , so .
- Lines L8 and L9: and .
- Line L10: .
This is , the rotation by 22.5 degrees about , which is one quarter of 90 degrees, as it must be. The normalized linear interpolation of lines L6 and L7 at the same gives , the rotation by 21.598 degrees, so it does not move at a constant speed.
The sign test matters for rotations that are near each other but have quaternions far apart. Take the rotations by 170 degrees and by degrees about , with and . The two rotations differ by only 20 degrees, but . Without line L3, the midpoint would be proportional to , which is the identity: the body would turn back through 0 degrees, the long way of 340 degrees. With line L3, becomes , degrees, and the midpoint is , the rotation by 180 degrees, halfway along the short way.
As a check with the matrix form, the midpoint between the identity and , the rotation by about , is . Its logarithm is , the rotation by about the same axis.
Correctness
After lines L1 to L3, , so , and the relative rotation turns by the angle about the unit axis . Write , where is a unit vector of orthogonal to . Then the great arc is , and substituting gives the formula of lines L8 to L10. Left multiplication by is an isometry of that maps to and to , so the arc is also . The factor is the rotation by about , which is with . For , the normalized linear interpolation lies on the same arc, and its angle differs from by at most about , which is below . The proof gives the details.
Proof: SLERP returns the point at the fraction t of the short arcfull
We use the notation of the page. Quaternions are in the Hamilton convention, scalar first, and we treat them also as vectors of with the usual dot product and length. For unit quaternions, , and left or right multiplication by a unit quaternion is a linear isometry of . A unit quaternion gives the rotation with equal to the vector part of , and , .
The sign test
Lemma 1. After lines L1 to L3, , and is a quaternion of the same rotation as the input .
Proof. If , line L3 replaces by , and . Since , the rotation does not change.
The angle
Lemma 2. Let and be unit vectors with , . Then , , and line L4 returns . After Lemma 1, .
Proof. , which is or . Both square roots are of numbers that are not negative, and , so . If , then .
The arc formula
Lemma 3. Let . The great circle arc from to with constant speed, , is
and the angle between and is .
Proof. Put . Then and . So and are orthonormal, and . The great circle in their plane is , with and , and . Substituting gives
and the first coefficient is by the subtraction formula of the sine.
So lines L8 to L10 return when .
The power form and the rotations
Lemma 4. Let and . Then for a unit , and . The rotation is with .
Proof. The scalar part of is , and has length 1, so its vector part has length . Let be the left multiplication by . is a linear isometry, and . The isometry maps the great arc from to , which is by Lemma 3, to the great arc from to with the same parameter, which is . The unit quaternion is the rotation by about , which is by Rodrigues' formula. So . At , , and , so is a value of the logarithm of ; it is the only value when .
The same proof with for shows that , defined as , is the power used in the formula .
The branch for small angles
Lemma 5. Let and . The point of lines L6 and L7 lies on the great arc from to , at an angle from with .
Proof. If , then and lines L6 and L7 return , which is . Otherwise, with the orthonormal of Lemma 3, . For and both coefficients are not negative and not both zero, so the normalized point is with . The Taylor expansion in is . The cubic has the largest absolute value on , at , which gives the bound.
With , the bound is about , far below the unit roundoff.
Conclusion
Theorem. For unit quaternions , and , SLERP returns the point at the fraction of the shorter great arc from to the quaternion with a dot product that is not negative, exactly when and within the bound of Lemma 5 when . Its rotation is , and it moves at the constant angular speed about a fixed axis.
Proof. Lemma 1 fixes the sign, Lemma 2 gives the angle, and Lemmas 3 and 5 give the two branches. Lemma 4 gives the rotation form. By Lemma 3, equal steps of give equal arc angles, and by Lemma 4 the rotation angle of is , about the fixed axis in the frame of .
Complexity
One call takes time and space in the real RAM: one dot product, two norms of 4-vectors, one atan2, three sines and about 30 additions and multiplications. To evaluate many values of for the same pair, compute lines L1 to L4 and once; each further point then costs two sines and 8 multiplications.
Properties
- Constant angular speed. The arc angle grows linearly in , so the body turns at the constant rate per unit of about a fixed axis. Since and , both the body and the space angular velocity are constant, equal to and .
- Shortest path. The curve is a geodesic of SO(3) with its usual metric, the one that measures the angle of . After the sign test, it is the shortest such path between the two rotations, of length .
- Symmetry. , up to the sign that line L3 chooses.
- Independence of frames. For unit quaternions and , . So the path does not depend on the choice of the world frame or of the body frame.
- Unit length. The output has length 1 in exact arithmetic. In floating point its length is within a few units of the roundoff of 1.
- Only two points. Slerp of a sequence of keyframes, one segment at a time, has a jump in the angular velocity at each key. The curve is continuous, but not smooth.
Variants and improvements
- Normalized linear interpolation (nlerp). Lines L6 and L7 alone. The path is the same arc, but the speed is not constant; the angle error at is about . Nlerp is cheaper and is commutative when blending several rotations with weights.
- The matrix form. with Rodrigues' formula and the logarithm map gives the same rotations without quaternions. It costs more, and it needs care near the angle .
- Curves through many keys. Shoemake built Bezier curves on the sphere by the de Casteljau construction of a Bezier curve, with slerp in place of the linear interpolation. Spline schemes of this kind give a smooth angular velocity at the keys.
- Rigid motions. Screw linear interpolation does the same for a rotation and a translation together with a dual quaternion, and moves along a screw axis.
- Time scaling. To start and stop with zero angular speed, replace by a time scaling , such as the cubic . The axis stays fixed and only the speed along the arc changes.
When to use it
Use slerp to move a body or a camera between two orientations: keyframe animation, the orientation part of a straight-line motion of an end effector, and the interpolation of a measured attitude between two time stamps of a sensor. It also gives the midpoint of two rotations, which is the simplest case of rotation averaging. Convert the end orientations from matrices with Shepperd's method. To follow a measured angular velocity instead of a fixed end point, integrate the quaternion kinematic equation.
Pitfalls
- The long way round. Without the sign test of line L2, two close rotations can have quaternions with a negative dot product, and the body then turns by up to 360 degrees minus the right angle.
- arccos of the dot product. loses about half of the digits when is close to 1, so a tiny arc gets an angle error of about . The atan2 form of line L4 avoids this.
- Division by . At the formula is . Use the linear branch below a small threshold.
- Interpolating Euler angles. Linear interpolation of Euler angles or roll-pitch-yaw angles gives a path that changes its axis, depends on the angle convention, and can swing wildly near gimbal lock.
- Mixed conventions. Lines L8 to L10 use only sums and dot products in , so they work in the JPL convention (scalar last, ) as well. The power form and the conversion to a matrix use the quaternion product, which differs between the conventions. Do not mix the two in one computation.
- Angles of half a turn. If the two rotations differ by exactly , the two short paths in opposite directions have the same length, and a small change of the input switches between them.
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
# 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
spherical_linear_interpolation.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spherical-linear-interpolation/. The authors are listed in prov/BJ0DKQ.jsonl.
"""Spherical linear interpolation (slerp) of unit quaternions.
Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z).
slerp(q0, q1, t) returns the point at the fraction t of the great arc from
q0 to q1 on the unit sphere of R^4:
slerp(q0, q1, t) = sin((1 - t) W) / sin(W) q0 + sin(t W) / sin(W) q1,
where W is the angle between q0 and q1 in R^4. This equals q0 (q0* q1)^t.
If q0 . q1 < 0, q1 is replaced by -q1 first. Both give the same rotation,
and the replacement makes the arc the short one, so the rotation turns by
at most pi. W comes from atan2 of |q1 - q0| and |q1 + q0|, which is
accurate at every angle. For W below SMALL_ANGLE, the normalized linear
interpolation is used. Its point lies on the same arc, at an angle that
differs from t W by -t (1 - t) (1 - 2 t) W^3 / 6 to leading order, which is
at most about 0.016 W^3.
slerp_power(q0, q1, t) is the second method: q0 (q0* q1)^t with the power
taken through the axis and the angle. It is here for the tests.
"""
import math
# Below this angle (in radians, on the sphere of R^4), slerp is replaced by
# the normalized linear interpolation. Its error there is below 2e-20.
SMALL_ANGLE = 1e-6
def _norm(q):
return math.sqrt(sum(a * a for a in q))
def slerp(q0, q1, t):
"""Return the unit quaternion at the fraction t of the short arc from q0 to q1."""
d = sum(a * b for a, b in zip(q0, q1)) # @line L1
if d < 0.0: # @line L2
q1 = [-a for a in q1] # @line L3
a = _norm([y - x for x, y in zip(q0, q1)])
b = _norm([y + x for x, y in zip(q0, q1)])
big_w = 2.0 * math.atan2(a, b) # @line L4
if big_w < SMALL_ANGLE: # @line L5
q = [(1.0 - t) * x + t * y for x, y in zip(q0, q1)] # @line L6
n = _norm(q)
return [x / n for x in q] # @line L7
s = math.sin(big_w)
c0 = math.sin((1.0 - t) * big_w) / s # @line L8
c1 = math.sin(t * big_w) / s # @line L9
return [c0 * x + c1 * y for x, y in zip(q0, q1)] # @line L10
def _mul(q, r):
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_pow(q, t):
"""Return q^t for a unit quaternion q = (cos h, sin h u) with q[0] >= 0.
q^t = (cos(t h), sin(t h) u), with h = atan2(|v|, w) in [0, pi / 2].
For q = (1, 0, 0, 0) the result is (1, 0, 0, 0).
"""
v = q[1:]
s = _norm(v)
if s == 0.0:
return [1.0, 0.0, 0.0, 0.0]
h = math.atan2(s, q[0])
f = math.sin(t * h) / s
return [math.cos(t * h)] + [f * x for x in v]
def slerp_power(q0, q1, t):
"""Return q0 (q0* q1)^t, after the sign flip of q1 for the short arc."""
if sum(a * b for a, b in zip(q0, q1)) < 0.0:
q1 = [-a for a in q1]
rel = _mul([q0[0], -q0[1], -q0[2], -q0[3]], q1)
return _mul(q0, quat_pow(rel, t))
test_spherical_linear_interpolation.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spherical-linear-interpolation/. The authors are listed in prov/BJ0DKQ.jsonl.
"""Tests of spherical linear interpolation.
The references are the power form q0 (q0* q1)^t, and the matrix form
R0 exp(t log(R0^T R1)) built from the shared helper rbm (so3_exp, so3_log
and quat_to_rot), which does not use quaternions for the interpolation.
"""
import math
import random
import rbm
from spherical_linear_interpolation import SMALL_ANGLE, slerp, slerp_power
def unit(rng, n=4):
while True:
v = [rng.gauss(0.0, 1.0) for _ in range(n)]
s = math.sqrt(sum(x * x for x in v))
if s > 1e-3:
return [x / s for x in v]
def mdiff(a, b):
return max(abs(a[i][j] - b[i][j]) for i in range(3) for j in range(3))
def qdiff(p, q):
return max(abs(a - b) for a, b in zip(p, q))
def angle_between(p, q):
"""The rotation angle of p* q, in [0, pi], up to the sign of q."""
a = math.sqrt(sum((x - y) ** 2 for x, y in zip(p, q)))
b = math.sqrt(sum((x + y) ** 2 for x, y in zip(p, q)))
return 4.0 * math.atan2(min(a, b), max(a, b))
def test_quarter_turn_about_z():
q0 = [1.0, 0.0, 0.0, 0.0]
q1 = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], math.pi / 2.0)
assert qdiff(q1, [0.70711, 0.0, 0.0, 0.70711]) < 1e-5
for t in (0.0, 0.25, 0.5, 0.75, 1.0):
want = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], t * math.pi / 2.0)
assert qdiff(slerp(q0, q1, t), want) < 1e-15
q = slerp(q0, q1, 0.25)
assert abs(q[0] - 0.98079) < 1e-5 and abs(q[3] - 0.19509) < 1e-5
def test_end_points():
rng = random.Random(1)
for _ in range(200):
q0, q1 = unit(rng), unit(rng)
assert qdiff(slerp(q0, q1, 0.0), q0) < 1e-15
sign = 1.0 if sum(a * b for a, b in zip(q0, q1)) >= 0.0 else -1.0
assert qdiff(slerp(q0, q1, 1.0), [sign * x for x in q1]) < 1e-15
def test_against_power_form_and_matrix_form():
rng = random.Random(2)
for _ in range(200):
q0, q1 = unit(rng), unit(rng)
r0, r1 = rbm.quat_to_rot(q0), rbm.quat_to_rot(q1)
w = rbm.so3_log(rbm.mul(rbm.transpose(r0), r1))
if math.sqrt(sum(x * x for x in w)) > math.pi - 1e-3:
continue
for t in (0.1, 0.3, 0.5, 0.9):
q = slerp(q0, q1, t)
assert abs(sum(a * a for a in q) - 1.0) < 1e-14
assert qdiff(q, slerp_power(q0, q1, t)) < 1e-13
want = rbm.mul(r0, rbm.so3_exp([t * x for x in w]))
assert mdiff(rbm.quat_to_rot(q), want) < 1e-12
def test_constant_angular_speed():
rng = random.Random(3)
for _ in range(50):
q0, q1 = unit(rng), unit(rng)
total = angle_between(q0, q1)
steps = 10
pts = [slerp(q0, q1, k / steps) for k in range(steps + 1)]
for a, b in zip(pts, pts[1:]):
assert abs(angle_between(a, b) - total / steps) < 1e-12
def test_one_fixed_axis():
# Every intermediate rotation differs from q0 by a turn about one axis.
rng = random.Random(4)
for _ in range(50):
q0, q1 = unit(rng), unit(rng)
r0 = rbm.quat_to_rot(q0)
axes = []
for t in (0.2, 0.5, 0.8):
r = rbm.quat_to_rot(slerp(q0, q1, t))
w = rbm.so3_log(rbm.mul(rbm.transpose(r0), r))
n = math.sqrt(sum(x * x for x in w))
axes.append([x / n for x in w])
for a in axes[1:]:
assert qdiff(a, axes[0]) < 1e-10
def test_sign_flip_takes_the_short_arc():
qa = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], math.radians(170.0))
qb = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], math.radians(-170.0))
assert sum(a * b for a, b in zip(qa, qb)) < 0.0
mid = slerp(qa, qb, 0.5)
# The short way from 170 to 190 degrees passes 180 degrees.
assert qdiff(mid, [0.0, 0.0, 0.0, 1.0]) < 1e-15
# The same rotations with the sign of qb changed give the same path.
assert qdiff(slerp(qa, [-x for x in qb], 0.5), mid) < 1e-15
def test_small_angles():
rng = random.Random(5)
for scale in (1e-3, 1e-6, 0.5e-6, 1e-9, 1e-12, 0.0):
for _ in range(50):
q0 = unit(rng)
u = unit(rng, 3)
q1 = rbm.quat_mul(q0, rbm.quat_from_axis_angle(u, scale))
for t in (0.0, 0.3, 1.0):
want = rbm.quat_mul(q0, rbm.quat_from_axis_angle(u, t * scale)) if scale > 0.0 else q0
q = slerp(q0, q1, t)
assert qdiff(q, want) < 1e-15
assert abs(sum(a * a for a in q) - 1.0) < 1e-15
assert SMALL_ANGLE == 1e-6
def test_check_value_through_matrices():
# Halfway from I to the rotation by 2 pi / 3 about (1, 1, 1) / sqrt(3).
q = slerp([1.0, 0.0, 0.0, 0.0], [0.5, 0.5, 0.5, 0.5], 0.5)
w = rbm.so3_log(rbm.quat_to_rot(q))
assert max(abs(x - math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-14
assert abs(q[0] - math.sqrt(3.0) / 2.0) < 1e-15
History
Shoemake (1985) introduced slerp to computer animation in his SIGGRAPH paper on quaternion curves. He compared it with the interpolation of Euler angles, and built smooth curves through many keyframes with slerp in a Bezier construction. The formula for a point on a great arc is older and comes from spherical geometry. Sola (2017) gives the equivalent forms and the form on the arc in in the Hamilton convention.
References
- Ken Shoemake, Animating rotation with quaternion curves, Computer Graphics (Proceedings of SIGGRAPH 1985) 19(3), 245-254, 1985, the whole paper (the slerp formula, the comparison with Euler angle interpolation, and quaternion Bezier curves built from slerp)
- Joan Sola, Quaternion kinematics for the error-state Kalman filter, 2017, Section 2.7 (spherical linear interpolation, equation 127: q(t) = q0 (q0* q1)^t, and the form on the 4D arc)
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 BJ0DKQ Edit this page History Report an error Markdown