Algorithmcore
Logarithm map of SO(3)
Also called matrix logarithm of a rotation.
Recovers the angle and axis of a 3D rotation matrix: theta by atan2 of the trace and the skew part, a series near 0, and the axis from the symmetric part near pi.
- Time
- Θ(1) worst
- Space
- Θ(1) extra
- Where
- n = the size of the matrix, fixed at n = 3
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The logarithm map of SO(3) takes a 3 by 3 rotation matrix and returns its exponential coordinates: a vector whose direction is the rotation axis and whose length is the rotation angle, so that . It inverts Rodrigues' rotation formula, which goes from axis and angle to the matrix. The axis-angle representation is the pair that both maps work with. The formulas are short, but the textbook form loses accuracy near and fails near . This page gives a version that is accurate in floating point at every angle, and proves it.
In plain words
Every turn of a solid object in space is a turn about one fixed line by some angle. A rotation matrix holds this turn in nine numbers. The logarithm finds the line and the angle again. The angle comes from the sum of the three diagonal numbers. The line comes from the differences of the numbers on the two sides of the diagonal. When the angle is very small, the line hardly matters, and a short series avoids a division by zero. When the angle is close to a half turn, the differences are almost zero and full of rounding noise. Then the line comes from the sums of the numbers on the two sides of the diagonal, which are large there. A half turn about a line is the same as a half turn about the reversed line, so at exactly a half turn there are two correct answers.
The problem
The input is a matrix in the special orthogonal group SO(3), so and . The output is a vector with and . Here is the skew-symmetric matrix of , so , and is the matrix exponential. We write with a unit axis and the angle . For the answer is unique. At both are answers. At the answer is , and the axis is undefined.
The algorithm
The algorithm uses three facts that follow from Rodrigues' formula :
The map is the inverse of : it reads the vector from a skew-symmetric matrix . The two thresholds are and .
SO3-LOG(R) ▷ R in SO(3); returns w = θ ω̂ with θ in [0, π]- 1
c ← (tr R - 1) / 2, clamped to [-1, 1] ▷ c = cos θ - 2
s ← vee(R - Rᵀ) / 2 ▷ s = sin θ · ω̂ - 3
θ ← atan2(|s|, c) - 4
if θ < δ₀ then ▷ R is close to I - 5
return (1 + θ²/6 + 7θ⁴/360) · s ▷ the series of θ / sin θ - 6
if θ ≤ π - δ_π then - 7
return (θ / |s|) · s - 8
B ← (R + Rᵀ) / 2 - c I ▷ B = (1 - c) ω̂ ω̂ᵀ - 9
k ← the index of the largest diagonal entry B_kk - 10
ω̂ ← column k of B, divided by its length - 11
if ω̂ · s < 0 then ω̂ ← -ω̂ ▷ at θ = π both signs are valid - 12
return θ ω̂
Lines L1 and L2 read and from . Line L3 takes the angle from both of them with atan2, and not from the cosine alone with arccos. Line L5 handles small angles, where the exact factor would be at . Line L7 is the general case. Lines L8 to L12 handle angles near , where is short and its direction is not reliable. The matrix is a multiple of , so each of its columns is a multiple of . Line L9 picks the column with the largest diagonal entry, which has , so it is far from zero. Line L11 takes the sign from , which still points the right way when .
Example
Take the rotation by about the axis , which moves to , to and to :
- Line L1: , so .
- Line L2: , and .
- Line L3: .
- Line L7: .
So the axis is and the angle is rad, or 120 degrees.
A second example takes the half turn about the axis, . Line L1 gives and line L2 gives , so line L3 gives . The textbook formula is here. Line L8 gives , line L9 picks , and line L10 gives . Line L11 makes no change because , and the output is . The vector is also correct.
The table shows a measurement on IEEE double precision with the implementation of this page. The axis is , and is computed from by Rodrigues' formula. The textbook method is the three-case method: gives , gives , and else and . The columns give the largest absolute error.
| by arccos | by atan2 | by the textbook method | by SO3-LOG | |
|---|---|---|---|---|
| 1.0e-9 | 0 | 8.6e-10 | 0 | |
| 4.4e-11 | 0 | 1.1e-22 | 1.1e-22 | |
| 7.8e-15 | 0 | 1.1e-19 | 1.1e-19 | |
| 1.1e-16 | 1.1e-16 | 0 | 0 | |
| 6.6e-13 | 0 | 1.8e-9 | 0 | |
| 4.4e-11 | 4.4e-16 | 1.2e-4 | 1.1e-16 | |
| 1.0e-9 | 0 | 1.1e-9 | 2.2e-16 |
At the trace rounds to exactly 3, so the textbook method returns . At its angle is wrong in the fifth digit, but the error cancels in , because is flat near 0. Near the division by makes the textbook error grow, and at the trace rounds to exactly , so the method returns the half turn.
Correctness
Every rotation is for a unit and some ; this is Euler's rotation theorem together with Rodrigues' formula. The three identities above then give and , and since on , line L3 returns exactly. Line L7 returns . Line L5 differs from the exact factor by a relative amount of about , which is below for . In lines L8 to L12, column of is , so line L10 gives , and line L11 fixes the sign when . At both signs give the same . The proof below also shows that the answer is unique when , and gives first-order error estimates in floating point.
Proof: SO3-LOG returns exponential coordinates of the input rotationfull
We use the notation of the page. For a unit vector , is its skew-symmetric matrix, so . Two facts about are used again and again. First, , which follows from for a unit . Second, and .
The proof is in exact arithmetic. The last section gives first-order error estimates for floating point.
Every rotation has exponential coordinates
Lemma 1. Let . Then there are a unit vector and an angle with .
Proof. Because , we have . With this gives , where the last step uses that the matrix has the odd size 3. So , and there is a unit vector with . Choose unit vectors and such that is a right-handed orthonormal basis. keeps lengths and angles, so it maps the plane spanned by and to itself, and on this plane it is an orthogonal map. In the basis , is block diagonal with the block for , so the determinant of this map is , and it is a plane rotation by some angle : and . If , replace by , by and by ; the basis stays right-handed and the two formulas stay true. Now set and . The matrix gives , because . It gives , because and . In the same way . So and agree on a basis, and . The formula for is the closed form of the matrix exponential (see the page on Rodrigues' rotation formula).
Lemma 2. Let with a unit and . Then (a) ; (b) ; (c) .
Proof. is skew-symmetric and is symmetric. So the skew part of is , which is (b), and the symmetric part is . Insert in the symmetric part to get , which is (c). The trace of is , which is (a).
The main result
Theorem. Let and let be the output of SO3-LOG. If the branch of line L7 or line L12 returns, then and . If the branch of line L5 returns, then with and . For the output is the only vector with and . For there are exactly two such vectors, , and the output is one of them.
Proof. By Lemma 1, write with a unit and .
Lines L1 to L3. By Lemma 2(a), line L1 computes , so the clamp has no effect in exact arithmetic. By Lemma 2(b), the vector of line L2 is . Because on , we have . The function with returns the angle in whose cosine and sine are proportional to and with a positive factor. With and that angle is , so line L3 recovers exactly.
Line L5, for . If , then and the output is , and . If , the exact answer is . The Taylor series of is , with only positive coefficients, so line L5 uses a value below the true ratio by . For this relative difference is below , far below the unit roundoff of double precision. So in floating point line L5 gives the same result as the exact ratio.
Line L7, for . Here , so and . Then and .
Lines L8 to L12, for . Here , so . By Lemma 2(c), the matrix of line L8 is . Its diagonal entries are . Because , the largest of them, chosen in line L9, has . Column of is , a nonzero multiple of . So line L10 sets with . If , then with . Line L11 flips the sign when , so after line L11 , and line L12 returns . If , then and line L11 does nothing. The output is . Since and , the formula of Lemma 1 gives . So both signs give .
Uniqueness. Let with , and write when . By Lemma 2(a), , and the cosine is one to one on , so . If , then . If , Lemma 2(b) gives with , so and . If , Lemma 2(c) gives , so . Both signs occur, as shown above.
Floating point
This section gives first-order estimates in the floating-point model with unit roundoff . It is not a full rounding error analysis. Assume that the input is a rotation whose entries have absolute errors of order .
The angle. The trace and the skew part then have absolute errors of order . An error in changes by about , and near by up to , because . So the textbook formula can lose about half of the digits near and near . The two arguments of atan2 have errors of order , and the gradient of has length , which is close to 1 here. So line L3 gives with an absolute error of order for every .
The axis. In line L7 the axis is , and an absolute error of order in gives an axis error of order . This is large only near , where the axis has little effect on , and near . At the switch , the error is about . In lines L8 to L10, the column of has length and an absolute error of order , so the axis has an error of order . Line L11 uses only the sign of . For that sign is right as long as is larger than the error in ; when it is not, is within a few units of roundoff of , where both signs give rotations that agree with to within a few units of roundoff.
The tests of the page check these estimates: the error of the output is below for small angles, below near , and the textbook formula loses accuracy where the estimates say it does.
Complexity
The input has a fixed size, so the time and the space are . The general case uses about 25 floating-point operations, one square root and one atan2. The branch near adds about 35 operations and a second square root. There is no loop and no iteration.
A general routine for the logarithm of an matrix uses operations per step, with several square roots of matrices. The closed form above needs none of that, because it uses the structure of SO(3).
Properties
- Inverse of the exponential. On the open ball , the logarithm is the inverse of , and it is smooth there.
- A jump at . On the set of rotations by , the output can jump between and . No continuous logarithm exists on all of SO(3).
- Range. A rotation by an angle about comes back as the rotation by about .
- Accuracy. The angle has an absolute error of the order of the unit roundoff at every angle, because both arguments of atan2 have such an error and the gradient of atan2 has length about 1 here.
- Exact zero. gives exactly, with no division.
Variants and improvements
- The textbook three-case method. Lynch and Park give the method with arccos and two exact tests, and . In the case they give the axis from a nonzero column of , which is at . Lines L8 to L10 extend this idea to angles near , and the table shows why that matters.
- Through a unit quaternion. Convert to a unit quaternion with Shepperd's method, then use and . Shepperd's method picks the largest of four candidates in the same way as line L9. See unit quaternion rotation.
- The plane. In SO(2), the logarithm is , with no special cases.
- SE(3). The logarithm of a rigid motion uses this map for the rotation part, then solves for the translation part. See the exponential map of SE(3).
When to use it
Use the logarithm to measure the difference of two rotations as an angle and an axis: is the rotation that takes to , in the body frame of . Attitude controllers use it as the error signal. The residuals of pose graph optimization and the error states of the error-state Kalman filter use it to map rotations to vectors. It is the base of uncertainty on Lie groups, rotation averaging and spherical linear interpolation, where moves from to at constant angular speed.
Pitfalls
- arccos near 0 and . The slope of arccos is infinite at , so an error in gives an angle error up to . Use atan2 of both the sine and the cosine.
- Exact equality tests. A computed rotation is almost never exactly and almost never has a trace of exactly . Use a threshold, and choose it so that both branches are accurate where they meet.
- Arguments out of range. Rounding can make slightly larger than 1 or smaller than . Then arccos raises an error or returns NaN. Clamp .
- The sign at . Code that compares two logarithms near must accept both signs. A trajectory of rotations that passes through angle gets a jump in ; unwrap it by continuity if you need a smooth curve.
- A matrix that is not a rotation. After many products, drifts away from SO(3). The formulas then give a wrong answer without a warning. Orthonormalize first, for example with the Gram-Schmidt process or the singular value decomposition.
- The order of the vee map. The vector of is . A swap of two indices gives the axis with a wrong sign.
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
so3_logarithm_map.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/so3-logarithm-map/. The authors are listed in prov/7X28ZK.jsonl.
"""Logarithm map of SO(3), written out in full.
so3_log(R) returns the exponential coordinates w = omega_hat * theta of a
rotation matrix R, with theta in [0, pi], so that exp([w]) = R. It reads
cos(theta) from the trace and sin(theta) omega_hat from the skew part, and
takes theta = atan2(sin, cos). It has three branches:
* theta < SMALL_THETA: w = s * theta / sin(theta), with the ratio taken from
its Taylor series, so that R = I gives w = 0 and not 0 / 0.
* SMALL_THETA <= theta <= pi - NEAR_PI: w = s * theta / |s|.
* theta > pi - NEAR_PI: the skew part is small and has a large relative
error, so the axis comes from the symmetric part of R, and only its sign
comes from the skew part.
log_textbook(R) is the three-case method as it is usually printed (arccos of
the trace, and the special cases R = I and trace(R) = -1). It is here to
show the loss of accuracy that the branches above avoid.
Matrices are lists of rows. Vectors are lists.
"""
import math
# Below this angle, theta / sin(theta) is replaced by 1 + t^2/6 + 7 t^4/360.
# The first omitted term is 31 t^6 / 15120, below 3e-21 here, so the series
# is exact to the last bit. The closed form theta / |s| is also accurate
# down to tiny angles, because theta comes from atan2; the series is only
# there so that R = I gives w = 0 without a division by zero.
SMALL_THETA = 1e-3
# Above pi - NEAR_PI, the axis comes from the symmetric part of R. At the
# switch, the skew part has |s| = sin(theta), near 1e-2, so its rounding
# error of about 1e-16 gives an axis error of about 1e-14 in either branch.
NEAR_PI = 1e-2
def _norm(x):
return math.sqrt(sum(a * a for a in x))
def so3_log(r):
"""Return w = omega_hat * theta with exp([w]) = r and theta = |w| in [0, pi].
r must be a rotation matrix. At theta = pi, both w and -w are valid.
Near pi, the sign comes from the skew part s; if s is exactly zero, the
component of w with the largest magnitude is positive.
"""
c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0 # @line L1
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] # @line L2
sn = _norm(s)
theta = math.atan2(sn, c) # @line L3
if theta < SMALL_THETA: # @line L4
t2 = theta * theta
return [(1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0) * x for x in s] # @line L5
if theta <= math.pi - NEAR_PI: # @line L6
return [theta / sn * x for x in s] # @line L7
# b = (r + r^T) / 2 - c I = (1 - c) omega_hat omega_hat^T.
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)] # @line L8
# Column k of b is (1 - c) omega_k omega_hat. With the largest diagonal
# entry, omega_k^2 >= 1/3, so the column is far from zero.
k = max(range(3), key=lambda i: b[i][i]) # @line L9
col = [b[i][k] for i in range(3)]
n = _norm(col)
axis = [x / n for x in col] # @line L10
if sum(a * x for a, x in zip(axis, s)) < 0.0: # @line L11
axis = [-a for a in axis]
return [theta * a for a in axis] # @line L12
def axis_angle(r):
"""Return (omega_hat, theta) for a rotation matrix r.
omega_hat is None when theta = 0, because every axis is valid there.
"""
w = so3_log(r)
theta = _norm(w)
if theta == 0.0:
return None, 0.0
return [x / theta for x in w], theta
def log_textbook(r):
"""Return w by the three-case method with arccos, for comparison only.
(a) r = I gives w = 0. (b) trace(r) = -1 gives theta = pi and the axis
from a column of r + I. (c) Otherwise theta = arccos((trace(r) - 1) / 2)
and [omega_hat] = (r - r^T) / (2 sin(theta)). The tests are exact
equality tests, as in the printed method.
"""
tr = r[0][0] + r[1][1] + r[2][2]
if tr == 3.0:
return [0.0, 0.0, 0.0]
if tr == -1.0:
k = max(range(3), key=lambda i: r[i][i])
col = [r[i][k] + (1.0 if i == k else 0.0) for i in range(3)]
n = _norm(col)
return [math.pi * x / n for x in col]
theta = math.acos(max(-1.0, min(1.0, (tr - 1.0) / 2.0)))
f = theta / (2.0 * math.sin(theta))
return [f * (r[2][1] - r[1][2]), f * (r[0][2] - r[2][0]), f * (r[1][0] - r[0][1])]
test_so3_logarithm_map.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/so3-logarithm-map/. The authors are listed in prov/7X28ZK.jsonl.
"""Tests of the logarithm map of SO(3).
The reference exponential is the power series of the matrix exponential,
summed to 60 terms, which is independent of Rodrigues' formula. The second
reference is rbm.so3_log, the shared helper.
"""
import math
import random
import rbm
from so3_logarithm_map import NEAR_PI, SMALL_THETA, axis_angle, log_textbook, so3_log
def series_exp(w, terms=60):
"""exp([w]) as the sum of [w]^k / k! for k < terms."""
k = [[0.0, -w[2], w[1]], [w[2], 0.0, -w[0]], [-w[1], w[0], 0.0]]
out = [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
term = [row[:] for row in out]
for n in range(1, terms):
term = [[sum(term[i][m] * k[m][j] for m in range(3)) / n for j in range(3)] for i in range(3)]
out = [[out[i][j] + term[i][j] for j in range(3)] for i in range(3)]
return out
def unit(rng):
while True:
v = [rng.gauss(0.0, 1.0) for _ in range(3)]
n = math.sqrt(sum(x * x for x in v))
if n > 1e-3:
return [x / n for x in v]
def vdiff(a, b):
return max(abs(x - y) for x, y in zip(a, b))
def mdiff(a, b):
return max(abs(a[i][j] - b[i][j]) for i in range(3) for j in range(3))
def test_check_value():
r = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
w = so3_log(r)
axis, theta = axis_angle(r)
assert abs(theta - 2.0943951) < 1e-7
assert abs(theta - 2.0 * math.pi / 3.0) < 1e-15
assert vdiff(axis, [1.0 / math.sqrt(3.0)] * 3) < 1e-15
assert vdiff(w, [2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3) < 1e-15
assert mdiff(series_exp(w), r) < 1e-14
def test_simple_rotations():
assert so3_log(rbm.eye(3)) == [0.0, 0.0, 0.0]
assert axis_angle(rbm.eye(3)) == (None, 0.0)
assert vdiff(so3_log(rbm.rot_z(math.pi / 2.0)), [0.0, 0.0, math.pi / 2.0]) < 1e-15
assert vdiff(so3_log(rbm.rot_x(-0.3)), [-0.3, 0.0, 0.0]) < 1e-15
# A rotation by 3 pi / 2 about z is a rotation by pi / 2 about -z.
assert vdiff(so3_log(rbm.rot_z(1.5 * math.pi)), [0.0, 0.0, -math.pi / 2.0]) < 1e-15
def test_round_trip_against_power_series():
rng = random.Random(11)
for _ in range(300):
w0 = [rng.uniform(0.0, math.pi) * x for x in unit(rng)]
r = series_exp(w0)
w = so3_log(r)
assert vdiff(w, w0) < 1e-12
assert mdiff(series_exp(w), r) < 1e-13
assert math.sqrt(sum(x * x for x in w)) <= math.pi
def test_exp_of_log_for_any_rotation():
rng = random.Random(12)
for _ in range(200):
# Angles beyond pi map back into [0, pi] with the opposite axis.
w0 = [rng.uniform(0.0, 3.0 * math.pi) * x for x in unit(rng)]
r = series_exp(w0, terms=90)
w = so3_log(r)
assert math.sqrt(sum(x * x for x in w)) <= math.pi + 1e-15
assert mdiff(series_exp(w), r) < 1e-12
def test_agrees_with_helper():
rng = random.Random(13)
thetas = [0.0, 1e-12, 1e-6, SMALL_THETA, 1e-2, 0.5, 2.0, math.pi - 0.02, math.pi - 1e-3, math.pi - 1e-8]
for th in thetas:
for _ in range(20):
r = rbm.so3_exp([th * x for x in unit(rng)])
assert vdiff(so3_log(r), rbm.so3_log(r)) < 1e-14
def test_small_angles():
rng = random.Random(14)
for th in (1e-300, 1e-16, 1e-12, 1e-8, SMALL_THETA * (1.0 - 1e-9), SMALL_THETA * (1.0 + 1e-9), 3e-3):
for _ in range(20):
w0 = [th * x for x in unit(rng)]
w = so3_log(series_exp(w0))
assert vdiff(w, w0) <= 1e-14 * th
def test_near_pi():
rng = random.Random(15)
for d in (0.1, NEAR_PI * (1.0 - 1e-9), NEAR_PI * (1.0 + 1e-9), 1e-4, 1e-8, 1e-12):
for _ in range(20):
w0 = [(math.pi - d) * x for x in unit(rng)]
w = so3_log(series_exp(w0))
assert vdiff(w, w0) < 1e-12
def test_angle_pi_has_two_answers():
rng = random.Random(16)
for _ in range(50):
u = unit(rng)
# R = 2 u u^T - I is the rotation by pi about u, built exactly.
r = [[2.0 * u[i] * u[j] - (1.0 if i == j else 0.0) for j in range(3)] for i in range(3)]
w = so3_log(r)
good = [math.pi * x for x in u]
assert min(vdiff(w, good), vdiff(w, [-x for x in good])) < 1e-12
assert mdiff(series_exp(w), r) < 1e-12
# The rotation by pi about x: the skew part is exactly zero.
w = so3_log([[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]])
assert w == [math.pi, 0.0, 0.0]
def test_textbook_method_loses_accuracy():
axis = [2.0 / 7.0, 3.0 / 7.0, 6.0 / 7.0]
# In the middle range both methods are accurate.
w0 = [1.0 * a for a in axis]
r = series_exp(w0)
assert vdiff(log_textbook(r), w0) < 1e-14
assert vdiff(so3_log(r), w0) < 1e-14
# Near 0, arccos of a number near 1 loses half of the digits.
w0 = [1e-9 * a for a in axis]
r = series_exp(w0)
assert vdiff(log_textbook(r), w0) > 1e-3 * 1e-9
assert vdiff(so3_log(r), w0) <= 1e-14 * 1e-9
# Near pi, the skew part is small and the division by sin(theta) fails.
w0 = [(math.pi - 1e-6) * a for a in axis]
r = series_exp(w0)
assert vdiff(log_textbook(r), w0) > 1e-6
assert vdiff(so3_log(r), w0) < 1e-14
History
Rodrigues published the formula for a rotation in terms of its axis and angle in 1840, and the trace and skew relations that the logarithm uses follow from it. Murray, Li and Sastry (1994) gave the arccos and skew formulas in their treatment of exponential coordinates for rotation, and Lynch and Park (2017) gave the three-case algorithm with the special cases and in Section 3.2.3. The use of atan2 and of the symmetric part near is common practice in numerical libraries for Lie groups; Sola, Deray and Atchuthan (2018) survey these maps for state estimation.
References
- Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 3, Section 3.2.3 (exponential coordinates of rotation and the matrix logarithm of a rotation, with the cases theta = 0 and theta = pi)
- Richard M. Murray, Zexiang Li and S. Shankar Sastry, A Mathematical Introduction to Robotic Manipulation, CRC Press, 1994, Chapter 2, Section 2.2 (exponential coordinates for rotation)
- Joan Sola, Jeremie Deray and Dinesh Atchuthan, A micro Lie theory for state estimation in robotics, 2018, the exponential and logarithm maps of SO(3) in the examples of the paper
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 7X28ZK Edit this page History Report an error Markdown