Algorithm Search⌘K

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

The logarithm map of SO(3) takes a 3 by 3 rotation matrix RR and returns its exponential coordinates: a vector w=θω^w = \theta\hat\omega whose direction ω^\hat\omega is the rotation axis and whose length θ∈[0,π]\theta \in [0, \pi] is the rotation angle, so that e[w]=Re^{[w]} = R. 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 θ=0\theta = 0 and fails near θ=π\theta = \pi. 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 RR in the special orthogonal group SO(3), so RTR=IR^{\mathsf T} R = I and det⁡R=1\det R = 1. The output is a vector w∈R3w \in \mathbb{R}^3 with ∣w∣≤π|w| \le \pi and e[w]=Re^{[w]} = R. Here [w][w] is the skew-symmetric matrix of ww, so [w]x=w×x[w] x = w \times x, and e[w]e^{[w]} is the matrix exponential. We write w=θω^w = \theta\hat\omega with a unit axis ω^\hat\omega and the angle θ=∣w∣\theta = |w|. For θ<π\theta < \pi the answer is unique. At θ=π\theta = \pi both ±πω^\pm\pi\hat\omega are answers. At θ=0\theta = 0 the answer is w=0w = 0, and the axis is undefined.

The algorithm

The algorithm uses three facts that follow from Rodrigues' formula R=I+sin⁡θ [ω^]+(1−cos⁡θ)[ω^]2R = I + \sin\theta\,[\hat\omega] + (1 - \cos\theta)[\hat\omega]^2:

tr⁡R=1+2cos⁡θ,12(R−RT)=sin⁡θ [ω^],12(R+RT)−cos⁡θ I=(1−cos⁡θ) ω^ω^T.\operatorname{tr} R = 1 + 2\cos\theta, \qquad \tfrac12 (R - R^{\mathsf T}) = \sin\theta\,[\hat\omega], \qquad \tfrac12 (R + R^{\mathsf T}) - \cos\theta\, I = (1 - \cos\theta)\,\hat\omega\hat\omega^{\mathsf T}.

The map vee⁡\operatorname{vee} is the inverse of [⋅][\cdot]: it reads the vector (m32,m13,m21)(m_{32}, m_{13}, m_{21}) from a skew-symmetric matrix mm. The two thresholds are δ0=10−3\delta_0 = 10^{-3} and δπ=10−2\delta_\pi = 10^{-2}.

  1. SO3-LOG(R) ▷ R in SO(3); returns w = θ ω̂ with θ in [0, π]
  2. 1c ← (tr R - 1) / 2, clamped to [-1, 1] ▷ c = cos θ
  3. 2s ← vee(R - Rᵀ) / 2 ▷ s = sin θ · ω̂
  4. 3θ ← atan2(|s|, c)
  5. 4if θ < δ₀ then ▷ R is close to I
  6. 5return (1 + θ²/6 + 7θ⁴/360) · s ▷ the series of θ / sin θ
  7. 6if θ ≤ π - δ_π then
  8. 7return (θ / |s|) · s
  9. 8B ← (R + Rᵀ) / 2 - c I ▷ B = (1 - c) ω̂ ω̂ᵀ
  10. 9k ← the index of the largest diagonal entry B_kk
  11. 10ω̂ ← column k of B, divided by its length
  12. 11if ω̂ · s < 0 then ω̂ ← -ω̂ ▷ at θ = π both signs are valid
  13. 12return θ ω̂

Lines L1 and L2 read cos⁡θ\cos\theta and sin⁡θ ω^\sin\theta\,\hat\omega from RR. 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 θ/sin⁡θ\theta / \sin\theta would be 0/00/0 at θ=0\theta = 0. Line L7 is the general case. Lines L8 to L12 handle angles near π\pi, where ss is short and its direction is not reliable. The matrix BB is a multiple of ω^ω^T\hat\omega\hat\omega^{\mathsf T}, so each of its columns is a multiple of ω^\hat\omega. Line L9 picks the column with the largest diagonal entry, which has ωk2≥1/3\omega_k^2 \ge 1/3, so it is far from zero. Line L11 takes the sign from ss, which still points the right way when θ<π\theta < \pi.

Example

Take the rotation by 2π/32\pi/3 about the axis (1,1,1)/3(1, 1, 1)/\sqrt3, which moves xx to yy, yy to zz and zz to xx:

R=(001100010).R = \begin{pmatrix} 0 & 0 & 1 \\ 1 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}.
  • Line L1: tr⁡R=0\operatorname{tr} R = 0, so c=−1/2c = -1/2.
  • Line L2: s=12(r32−r23, r13−r31, r21−r12)=(1/2,1/2,1/2)s = \tfrac12 (r_{32} - r_{23},\ r_{13} - r_{31},\ r_{21} - r_{12}) = (1/2, 1/2, 1/2), and ∣s∣=3/2=0.8660254|s| = \sqrt3/2 = 0.8660254.
  • Line L3: θ=atan2⁡(0.8660254,−0.5)=2π/3=2.0943951\theta = \operatorname{atan2}(0.8660254, -0.5) = 2\pi/3 = 2.0943951.
  • Line L7: w=(2.0943951/0.8660254)⋅(1/2,1/2,1/2)=(1.2091996,1.2091996,1.2091996)w = (2.0943951 / 0.8660254) \cdot (1/2, 1/2, 1/2) = (1.2091996, 1.2091996, 1.2091996).

So the axis is (1,1,1)/3(1, 1, 1)/\sqrt3 and the angle is 2.09439512.0943951 rad, or 120 degrees.

A second example takes the half turn about the xx axis, R=diag⁡(1,−1,−1)R = \operatorname{diag}(1, -1, -1). Line L1 gives c=−1c = -1 and line L2 gives s=0s = 0, so line L3 gives θ=atan2⁡(0,−1)=π\theta = \operatorname{atan2}(0, -1) = \pi. The textbook formula [ω^]=(R−RT)/(2sin⁡θ)[\hat\omega] = (R - R^{\mathsf T}) / (2\sin\theta) is 0/00/0 here. Line L8 gives B=diag⁡(2,0,0)B = \operatorname{diag}(2, 0, 0), line L9 picks k=1k = 1, and line L10 gives ω^=(1,0,0)\hat\omega = (1, 0, 0). Line L11 makes no change because ω^⋅s=0\hat\omega \cdot s = 0, and the output is w=(π,0,0)w = (\pi, 0, 0). The vector (−π,0,0)(-\pi, 0, 0) is also correct.

The table shows a measurement on IEEE double precision with the implementation of this page. The axis is (2,3,6)/7(2, 3, 6)/7, and RR is computed from w=θω^w = \theta\hat\omega by Rodrigues' formula. The textbook method is the three-case method: R=IR = I gives w=0w = 0, tr⁡R=−1\operatorname{tr} R = -1 gives θ=π\theta = \pi, and else θ=arccos⁡c\theta = \arccos c and [ω^]=(R−RT)/(2sin⁡θ)[\hat\omega] = (R - R^{\mathsf T})/(2\sin\theta). The columns give the largest absolute error.

θ\theta θ\theta by arccos θ\theta by atan2 ww by the textbook method ww by SO3-LOG
10−910^{-9} 1.0e-9 0 8.6e-10 0
10−610^{-6} 4.4e-11 0 1.1e-22 1.1e-22
10−310^{-3} 7.8e-15 0 1.1e-19 1.1e-19
11 1.1e-16 1.1e-16 0 0
π−10−3\pi - 10^{-3} 6.6e-13 0 1.8e-9 0
π−10−6\pi - 10^{-6} 4.4e-11 4.4e-16 1.2e-4 1.1e-16
π−10−9\pi - 10^{-9} 1.0e-9 0 1.1e-9 2.2e-16

At θ=10−9\theta = 10^{-9} the trace rounds to exactly 3, so the textbook method returns w=0w = 0. At θ=10−6\theta = 10^{-6} its angle is wrong in the fifth digit, but the error cancels in ww, because θ/sin⁡θ\theta / \sin\theta is flat near 0. Near π\pi the division by sin⁡θ\sin\theta makes the textbook error grow, and at π−10−9\pi - 10^{-9} the trace rounds to exactly −1-1, so the method returns the half turn.

Correctness

Every rotation is e[ω^]θe^{[\hat\omega]\theta} for a unit ω^\hat\omega and some θ∈[0,π]\theta \in [0, \pi]; this is Euler's rotation theorem together with Rodrigues' formula. The three identities above then give c=cos⁡θc = \cos\theta and s=sin⁡θ ω^s = \sin\theta\,\hat\omega, and since sin⁡θ≥0\sin\theta \ge 0 on [0,π][0, \pi], line L3 returns θ\theta exactly. Line L7 returns (θ/sin⁡θ)sin⁡θ ω^=θω^(\theta/\sin\theta)\sin\theta\,\hat\omega = \theta\hat\omega. Line L5 differs from the exact factor by a relative amount of about 31θ6/1512031\theta^6/15120, which is below 3⋅10−213 \cdot 10^{-21} for θ<δ0\theta < \delta_0. In lines L8 to L12, column kk of BB is (1−c) ωk ω^(1 - c)\,\omega_k\,\hat\omega, so line L10 gives ±ω^\pm\hat\omega, and line L11 fixes the sign when θ<π\theta < \pi. At θ=π\theta = \pi both signs give the same RR. The proof below also shows that the answer is unique when θ<π\theta < \pi, 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 ω^∈R3\hat\omega \in \mathbb{R}^3, [ω^][\hat\omega] is its skew-symmetric matrix, so [ω^]x=ω^×x[\hat\omega] x = \hat\omega \times x. Two facts about [ω^][\hat\omega] are used again and again. First, [ω^]2=ω^ω^T−I[\hat\omega]^2 = \hat\omega \hat\omega^{\mathsf T} - I, which follows from ω^×(ω^×x)=ω^(ω^⋅x)−x\hat\omega \times (\hat\omega \times x) = \hat\omega (\hat\omega \cdot x) - x for a unit ω^\hat\omega. Second, tr⁡[ω^]=0\operatorname{tr}[\hat\omega] = 0 and tr⁡[ω^]2=∣ω^∣2−3=−2\operatorname{tr}[\hat\omega]^2 = |\hat\omega|^2 - 3 = -2.

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 R∈SO(3)R \in SO(3). Then there are a unit vector ω^\hat\omega and an angle θ∈[0,π]\theta \in [0, \pi] with R=e[ω^]θ=I+sin⁡θ [ω^]+(1−cos⁡θ)[ω^]2R = e^{[\hat\omega]\theta} = I + \sin\theta\,[\hat\omega] + (1 - \cos\theta)[\hat\omega]^2.

Proof. Because RRT=IR R^{\mathsf T} = I, we have R−I=R(I−RT)R - I = R(I - R^{\mathsf T}). With det⁡R=1\det R = 1 this gives det⁡(R−I)=det⁡((I−R)T)=det⁡(I−R)=−det⁡(R−I)\det(R - I) = \det((I - R)^{\mathsf T}) = \det(I - R) = -\det(R - I), where the last step uses that the matrix has the odd size 3. So det⁡(R−I)=0\det(R - I) = 0, and there is a unit vector uu with Ru=uR u = u. Choose unit vectors aa and b=u×ab = u \times a such that (u,a,b)(u, a, b) is a right-handed orthonormal basis. RR keeps lengths and angles, so it maps the plane spanned by aa and bb to itself, and on this plane it is an orthogonal 2×22 \times 2 map. In the basis (u,a,b)(u, a, b), RR is block diagonal with the block 11 for uu, so the determinant of this map is det⁡R=1\det R = 1, and it is a plane rotation by some angle φ∈(−π,π]\varphi \in (-\pi, \pi]: Ra=cos⁡φ a+sin⁡φ bR a = \cos\varphi\, a + \sin\varphi\, b and Rb=−sin⁡φ a+cos⁡φ bR b = -\sin\varphi\, a + \cos\varphi\, b. If φ<0\varphi < 0, replace uu by −u-u, bb by −b-b and φ\varphi by −φ-\varphi; the basis stays right-handed and the two formulas stay true. Now set ω^=u\hat\omega = u and θ=φ∈[0,π]\theta = \varphi \in [0, \pi]. The matrix E=I+sin⁡θ [u]+(1−cos⁡θ)[u]2E = I + \sin\theta\,[u] + (1 - \cos\theta)[u]^2 gives Eu=uE u = u, because [u]u=0[u] u = 0. It gives Ea=a+sin⁡θ b−(1−cos⁡θ)a=cos⁡θ a+sin⁡θ bE a = a + \sin\theta\, b - (1 - \cos\theta) a = \cos\theta\, a + \sin\theta\, b, because [u]a=u×a=b[u] a = u \times a = b and [u]2a=−a[u]^2 a = -a. In the same way Eb=−sin⁡θ a+cos⁡θ bE b = -\sin\theta\, a + \cos\theta\, b. So EE and RR agree on a basis, and E=RE = R. The formula for EE is the closed form of the matrix exponential e[u]θe^{[u]\theta} (see the page on Rodrigues' rotation formula). □\square

Lemma 2. Let R=e[ω^]θR = e^{[\hat\omega]\theta} with a unit ω^\hat\omega and θ∈[0,π]\theta \in [0, \pi]. Then (a) tr⁡R=1+2cos⁡θ\operatorname{tr} R = 1 + 2\cos\theta; (b) 12(R−RT)=sin⁡θ [ω^]\tfrac12 (R - R^{\mathsf T}) = \sin\theta\,[\hat\omega]; (c) 12(R+RT)−cos⁡θ I=(1−cos⁡θ) ω^ω^T\tfrac12 (R + R^{\mathsf T}) - \cos\theta\, I = (1 - \cos\theta)\,\hat\omega\hat\omega^{\mathsf T}.

Proof. [ω^][\hat\omega] is skew-symmetric and [ω^]2[\hat\omega]^2 is symmetric. So the skew part of RR is sin⁡θ [ω^]\sin\theta\,[\hat\omega], which is (b), and the symmetric part is I+(1−cos⁡θ)[ω^]2I + (1 - \cos\theta)[\hat\omega]^2. Insert [ω^]2=ω^ω^T−I[\hat\omega]^2 = \hat\omega\hat\omega^{\mathsf T} - I in the symmetric part to get cos⁡θ I+(1−cos⁡θ)ω^ω^T\cos\theta\, I + (1 - \cos\theta)\hat\omega\hat\omega^{\mathsf T}, which is (c). The trace of RR is 3+0+(1−cos⁡θ)(−2)=1+2cos⁡θ3 + 0 + (1 - \cos\theta)(-2) = 1 + 2\cos\theta, which is (a). □\square

The main result

Theorem. Let R∈SO(3)R \in SO(3) and let ww be the output of SO3-LOG(R)(R). If the branch of line L7 or line L12 returns, then e[w]=Re^{[w]} = R and ∣w∣∈[0,π]|w| \in [0, \pi]. If the branch of line L5 returns, then w=(1+ϵ) θω^w = (1 + \epsilon)\, \theta\hat\omega with e[θω^]=Re^{[\theta\hat\omega]} = R and 0≤ϵ<3⋅10−210 \le \epsilon < 3 \cdot 10^{-21}. For θ<π\theta < \pi the output is the only vector ww with ∣w∣≤π|w| \le \pi and e[w]=Re^{[w]} = R. For θ=π\theta = \pi there are exactly two such vectors, ±πω^\pm\pi\hat\omega, and the output is one of them.

Proof. By Lemma 1, write R=e[ω^]θR = e^{[\hat\omega]\theta} with a unit ω^\hat\omega and θ∈[0,π]\theta \in [0, \pi].

Lines L1 to L3. By Lemma 2(a), line L1 computes c=cos⁡θ∈[−1,1]c = \cos\theta \in [-1, 1], so the clamp has no effect in exact arithmetic. By Lemma 2(b), the vector of line L2 is s=sin⁡θ ω^s = \sin\theta\, \hat\omega. Because sin⁡θ≥0\sin\theta \ge 0 on [0,π][0, \pi], we have ∣s∣=sin⁡θ|s| = \sin\theta. The function atan2⁡(y,x)\operatorname{atan2}(y, x) with y≥0y \ge 0 returns the angle in [0,π][0, \pi] whose cosine and sine are proportional to xx and yy with a positive factor. With x=cos⁡θx = \cos\theta and y=sin⁡θy = \sin\theta that angle is θ\theta, so line L3 recovers θ\theta exactly.

Line L5, for θ<δ0\theta < \delta_0. If θ=0\theta = 0, then s=0s = 0 and the output is w=0w = 0, and e[0]=I=Re^{[0]} = I = R. If 0<θ<δ00 < \theta < \delta_0, the exact answer is w=(θ/sin⁡θ) s=θω^w = (\theta / \sin\theta)\, s = \theta\hat\omega. The Taylor series of θ/sin⁡θ\theta / \sin\theta is 1+θ2/6+7θ4/360+31θ6/15120+⋯1 + \theta^2/6 + 7\theta^4/360 + 31\theta^6/15120 + \cdots, with only positive coefficients, so line L5 uses a value below the true ratio by 31θ6/15120+O(θ8)31\theta^6/15120 + O(\theta^8). For θ<δ0=10−3\theta < \delta_0 = 10^{-3} this relative difference is below 3⋅10−213 \cdot 10^{-21}, far below the unit roundoff 2−53≈1.1⋅10−162^{-53} \approx 1.1 \cdot 10^{-16} of double precision. So in floating point line L5 gives the same result as the exact ratio.

Line L7, for δ0≤θ≤π−δπ\delta_0 \le \theta \le \pi - \delta_\pi. Here sin⁡θ>0\sin\theta > 0, so ∣s∣>0|s| > 0 and (θ/∣s∣) s=(θ/sin⁡θ)sin⁡θ ω^=θω^(\theta / |s|)\, s = (\theta / \sin\theta)\sin\theta\,\hat\omega = \theta\hat\omega. Then e[w]=e[ω^]θ=Re^{[w]} = e^{[\hat\omega]\theta} = R and ∣w∣=θ|w| = \theta.

Lines L8 to L12, for θ>π−δπ\theta > \pi - \delta_\pi. Here θ>π/2\theta > \pi/2, so 1−c>11 - c > 1. By Lemma 2(c), the matrix of line L8 is B=(1−c) ω^ω^TB = (1 - c)\,\hat\omega\hat\omega^{\mathsf T}. Its diagonal entries are Bii=(1−c) ωi2B_{ii} = (1 - c)\,\omega_i^2. Because ω12+ω22+ω32=1\omega_1^2 + \omega_2^2 + \omega_3^2 = 1, the largest of them, chosen in line L9, has ωk2≥1/3\omega_k^2 \ge 1/3. Column kk of BB is (1−c) ωk ω^(1 - c)\,\omega_k\,\hat\omega, a nonzero multiple of ω^\hat\omega. So line L10 sets ω^′=σω^\hat\omega' = \sigma\hat\omega with σ=sign⁡(ωk)∈{−1,+1}\sigma = \operatorname{sign}(\omega_k) \in \{-1, +1\}. If θ<π\theta < \pi, then ω^′⋅s=σsin⁡θ\hat\omega' \cdot s = \sigma\sin\theta with sin⁡θ>0\sin\theta > 0. Line L11 flips the sign when σ=−1\sigma = -1, so after line L11 ω^′=ω^\hat\omega' = \hat\omega, and line L12 returns θω^\theta\hat\omega. If θ=π\theta = \pi, then s=0s = 0 and line L11 does nothing. The output is πσω^\pi\sigma\hat\omega. Since sin⁡π=0\sin\pi = 0 and [−ω^]2=[ω^]2[-\hat\omega]^2 = [\hat\omega]^2, the formula of Lemma 1 gives e[−ω^]π=I+2[ω^]2=e[ω^]πe^{[-\hat\omega]\pi} = I + 2[\hat\omega]^2 = e^{[\hat\omega]\pi}. So both signs give RR.

Uniqueness. Let e[w′]=Re^{[w']} = R with ∣w′∣=θ′≤π|w'| = \theta' \le \pi, and write w′=θ′ω^′w' = \theta'\hat\omega' when θ′>0\theta' > 0. By Lemma 2(a), cos⁡θ′=c=cos⁡θ\cos\theta' = c = \cos\theta, and the cosine is one to one on [0,π][0, \pi], so θ′=θ\theta' = \theta. If θ=0\theta = 0, then w′=0=ww' = 0 = w. If 0<θ<π0 < \theta < \pi, Lemma 2(b) gives sin⁡θ [ω^′]=sin⁡θ [ω^]\sin\theta\,[\hat\omega'] = \sin\theta\,[\hat\omega] with sin⁡θ≠0\sin\theta \ne 0, so ω^′=ω^\hat\omega' = \hat\omega and w′=ww' = w. If θ=π\theta = \pi, Lemma 2(c) gives 2ω^′ω^′T=2ω^ω^T2\hat\omega'\hat\omega'^{\mathsf T} = 2\hat\omega\hat\omega^{\mathsf T}, so ω^′=±ω^\hat\omega' = \pm\hat\omega. Both signs occur, as shown above. □\square

Floating point

This section gives first-order estimates in the floating-point model with unit roundoff u=2−53u = 2^{-53}. It is not a full rounding error analysis. Assume that the input RR is a rotation whose entries have absolute errors of order uu.

The angle. The trace and the skew part then have absolute errors of order uu. An error δ\delta in cc changes arccos⁡c\arccos c by about δ/sin⁡θ\delta / \sin\theta, and near c=±1c = \pm 1 by up to 2δ\sqrt{2\delta}, because arccos⁡(1−δ)≈2δ\arccos(1 - \delta) \approx \sqrt{2\delta}. So the textbook formula θ=arccos⁡c\theta = \arccos c can lose about half of the digits near θ=0\theta = 0 and near θ=π\theta = \pi. The two arguments of atan2 have errors of order uu, and the gradient of atan2⁡(y,x)\operatorname{atan2}(y, x) has length 1/x2+y21 / \sqrt{x^2 + y^2}, which is close to 1 here. So line L3 gives θ\theta with an absolute error of order uu for every θ\theta.

The axis. In line L7 the axis is s/∣s∣s / |s|, and an absolute error of order uu in ss gives an axis error of order u/sin⁡θu / \sin\theta. This is large only near θ=0\theta = 0, where the axis has little effect on w=θω^w = \theta\hat\omega, and near θ=π\theta = \pi. At the switch θ=π−δπ\theta = \pi - \delta_\pi, the error is about u/sin⁡(10−2)≈10−14u / \sin(10^{-2}) \approx 10^{-14}. In lines L8 to L10, the column of BB has length (1−c)∣ωk∣≥1/3(1 - c)|\omega_k| \ge 1/\sqrt{3} and an absolute error of order uu, so the axis has an error of order uu. Line L11 uses only the sign of ω^′⋅s\hat\omega' \cdot s. For θ<π\theta < \pi that sign is right as long as sin⁡θ\sin\theta is larger than the error in ss; when it is not, θ\theta is within a few units of roundoff of π\pi, where both signs give rotations that agree with RR to within a few units of roundoff.

The tests of the page check these estimates: the error of the output is below 10−14θ10^{-14}\theta for small angles, below 10−1210^{-12} near π\pi, 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 Θ(1)\Theta(1). The general case uses about 25 floating-point operations, one square root and one atan2. The branch near π\pi adds about 35 operations and a second square root. There is no loop and no iteration.

A general routine for the logarithm of an n×nn \times n matrix uses O(n3)O(n^3) 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 ∣w∣<π|w| < \pi, the logarithm is the inverse of w↦e[w]w \mapsto e^{[w]}, and it is smooth there.
  • A jump at π\pi. On the set of rotations by π\pi, the output can jump between πω^\pi\hat\omega and −πω^-\pi\hat\omega. No continuous logarithm exists on all of SO(3).
  • Range. A rotation by an angle α∈(π,2π)\alpha \in (\pi, 2\pi) about ω^\hat\omega comes back as the rotation by 2π−α2\pi - \alpha about −ω^-\hat\omega.
  • 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. R=IR = I gives w=0w = 0 exactly, with no division.

Variants and improvements

  • The textbook three-case method. Lynch and Park give the method with arccos and two exact tests, R=IR = I and tr⁡R=−1\operatorname{tr} R = -1. In the case tr⁡R=−1\operatorname{tr} R = -1 they give the axis from a nonzero column of R+IR + I, which is 2ω^ω^T2\hat\omega\hat\omega^{\mathsf T} at θ=π\theta = \pi. Lines L8 to L10 extend this idea to angles near π\pi, and the table shows why that matters.
  • Through a unit quaternion. Convert RR to a unit quaternion q=(qw,qv)q = (q_w, q_v) with Shepperd's method, then use θ=2atan2⁡(∣qv∣,qw)\theta = 2\operatorname{atan2}(|q_v|, q_w) and ω^=qv/∣qv∣\hat\omega = q_v / |q_v|. 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 θ=atan2⁡(r21,r11)\theta = \operatorname{atan2}(r_{21}, r_{11}), 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: log⁡(R1TR2)\log(R_1^{\mathsf T} R_2) is the rotation that takes R1R_1 to R2R_2, in the body frame of R1R_1. 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 R1etlog⁡(R1TR2)R_1 e^{t \log(R_1^{\mathsf T} R_2)} moves from R1R_1 to R2R_2 at constant angular speed.

Pitfalls

  • arccos near 0 and π\pi. The slope of arccos is infinite at ±1\pm 1, so an error δ\delta in cc gives an angle error up to 2δ\sqrt{2\delta}. Use atan2 of both the sine and the cosine.
  • Exact equality tests. A computed rotation is almost never exactly II and almost never has a trace of exactly −1-1. Use a threshold, and choose it so that both branches are accurate where they meet.
  • Arguments out of range. Rounding can make cc slightly larger than 1 or smaller than −1-1. Then arccos raises an error or returns NaN. Clamp cc.
  • The sign at π\pi. Code that compares two logarithms near π\pi must accept both signs. A trajectory of rotations that passes through angle π\pi gets a jump in ww; unwrap it by continuity if you need a smooth curve.
  • A matrix that is not a rotation. After many products, RR drifts away from SO(3). The formulas then give a wrong answer without a warning. Orthonormalize RR first, for example with the Gram-Schmidt process or the singular value decomposition.
  • The order of the vee map. The vector of [w][w] is (m32,m13,m21)(m_{32}, m_{13}, m_{21}). 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.

rbm.pyI0RawGitHub
# 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 θ=0\theta = 0 and θ=π\theta = \pi in Section 3.2.3. The use of atan2 and of the symmetric part near π\pi is common practice in numerical libraries for Lie groups; Sola, Deray and Atchuthan (2018) survey these maps for state estimation.

References

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • 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
  • a scene preset for the example