Algorithm Search⌘K

Algorithmcore

Exponential map of SE(3)

Also called exponential coordinates of rigid motion.

Turns a screw axis S and a distance theta into the rigid motion exp([S] theta) in closed form: Rodrigues' formula for the rotation and a matrix G(theta) for the translation.

Time
Θ(1) worst
Space
Θ(1) extra
Where
n = the size of the matrix, fixed at n = 4
Properties
deterministicofflineiterative
Origin
Roger W. Brockett, 1984

The exponential map of SE(3) takes a twist, a 6-vector that describes a velocity of a rigid body, and returns the rigid motion that the body makes when it keeps this velocity for one unit of time. The result is a 4 by 4 homogeneous transformation matrix in the special Euclidean group SE(3). It is the matrix exponential of a 4×44 \times 4 matrix of a special form, and that form gives a closed formula with one sine and one cosine, with no series and no general matrix routine. The rotation part is Rodrigues' formula; the translation part needs one more matrix, G(θ)G(\theta). Geometrically, every result is a screw motion: a rotation about a fixed line and a translation along the same line. The map is the building block of the product of exponentials formula for robot arms.

In plain words

Think of a nut on a bolt. When you turn the nut, it turns about the axis of the bolt, and it also moves along the axis. The bolt axis, the amount of travel per turn, and the angle of the turn together fix where the nut ends up. A twist holds the same three things as six numbers. The exponential map takes these six numbers and gives the final position and orientation of the body, as a table of numbers that a computer can multiply. When there is no turn, the body slides along a straight line, and the map is a plain shift. When the angle is very small, the general formula would divide small numbers by small numbers, so a short series is used.

The problem

We use the conventions of Lynch and Park. A twist is V=(ω,v)∈R6\mathcal{V} = (\omega, v) \in \mathbb{R}^6, with the angular part first, and its matrix is

[V]=([ω]v00)∈R4×4,[\mathcal{V}] = \begin{pmatrix} [\omega] & v \\ 0 & 0 \end{pmatrix} \in \mathbb{R}^{4 \times 4},

where [ω][\omega] is the skew-symmetric matrix of ω\omega. A screw axis is a twist S=(ω,v)S = (\omega, v) with ∣ω∣=1|\omega| = 1, or with ω=0\omega = 0 and ∣v∣=1|v| = 1. A rigid-body twist is a screw axis times a speed, so we can write it as Sθ˙S\dot\theta.

Problem 1: given a screw axis SS and a number θ\theta, compute T=e[S]θ∈SE(3)T = e^{[S]\theta} \in SE(3). For a revolute motion, θ\theta is an angle in radians; for a prismatic motion (ω=0\omega = 0), it is a distance in meters.

Problem 2: given any vector of exponential coordinates ξ=(w,u)∈R6\xi = (w, u) \in \mathbb{R}^6, compute e[ξ]e^{[\xi]}. If w≠0w \ne 0, then ξ=Sθ\xi = S\theta with θ=∣w∣\theta = |w| and S=ξ/θS = \xi/\theta.

The inverse problem, the logarithm, is: given T∈SE(3)T \in SE(3), find ξ\xi with e[ξ]=Te^{[\xi]} = T.

The algorithm

EXP-SCREW solves Problem 1. EXP-COORDS solves Problem 2 and calls EXP-SCREW, unless the angle is below the threshold δ=10−2\delta = 10^{-2}.

  1. EXP-SCREW(S, θ) ▷ S = (ω, v) a screw axis
  2. 1(ω, v) ← S
  3. 2if ω = 0 then ▷ prismatic: |v| = 1
  4. 3return [[I, v θ], [0, 1]] ▷ a translation by v θ
  5. 4K ← [ω]
  6. 5R ← I + sin θ · K + (1 - cos θ) · K² ▷ Rodrigues' formula
  7. 6G ← I θ + (1 - cos θ) · K + (θ - sin θ) · K²
  8. 7p ← G v
  9. 8return [[R, p], [0, 1]]
  1. EXP-COORDS(ξ) ▷ ξ = (w, u), any 6-vector
  2. E1 (w, u) ← ξ
  3. E2 θ ← |w|
  4. E3 if θ ≥ δ then
  5. E4 return EXP-SCREW(ξ / θ, θ)
  6. E5 a ← 1 - θ²/6 + θ⁴/120 ; b ← 1/2 - θ²/24 + θ⁴/720 ; c ← 1/6 - θ²/120 + θ⁴/5040
  7. E6 K ← [w]
  8. E7 return [[I + a K + b K², (I + b K + c K²) u], [0, 1]]

Line L3 is the case of a pure translation. Lines L5 and L6 come from the power series of e[S]θe^{[S]\theta}, as the correctness section shows. In EXP-COORDS, aa, bb and cc are the Taylor polynomials of sin⁡θ/θ\sin\theta/\theta, (1−cos⁡θ)/θ2(1 - \cos\theta)/\theta^2 and (θ−sin⁡θ)/θ3(\theta - \sin\theta)/\theta^3. With these factors the result is the same matrix as in EXP-SCREW, but nothing is divided by θ\theta, so θ=0\theta = 0 is no special case.

The logarithm reverses the steps. First take w=log⁡Rw = \log R with the logarithm map of SO(3), and θ=∣w∣\theta = |w|. Then u=(I−12[w]+d [w]2) pu = (I - \tfrac12 [w] + d\,[w]^2)\, p with d=(1−θ2cot⁡θ2)/θ2d = (1 - \tfrac{\theta}{2}\cot\tfrac{\theta}{2})/\theta^2, and d=1/12+θ2/720+θ4/30240d = 1/12 + \theta^2/720 + \theta^4/30240 for small θ\theta. This matrix is the inverse of the matrix I+b[w]+c[w]2I + b[w] + c[w]^2 in line E7. In the form of Lynch and Park, with a unit ω^\hat\omega, G(θ)−1=1θI−12[ω^]+(1θ−12cot⁡θ2)[ω^]2G(\theta)^{-1} = \tfrac{1}{\theta} I - \tfrac12 [\hat\omega] + \big(\tfrac{1}{\theta} - \tfrac12\cot\tfrac{\theta}{2}\big)[\hat\omega]^2, and v=G(θ)−1pv = G(\theta)^{-1} p. If R=IR = I, then w=0w = 0 and the motion is a translation: S=(0,p/∣p∣)S = (0, p/|p|) and θ=∣p∣\theta = |p|.

Example

Take the screw axis S=(ω,v)S = (\omega, v) with ω=(0,0,1)\omega = (0, 0, 1) and v=(1,0,0)v = (1, 0, 0), and θ=π/2\theta = \pi/2.

  • Line L4: K=[ω]K = [\omega], and K2=diag⁡(−1,−1,0)K^2 = \operatorname{diag}(-1, -1, 0).
  • Line L5: with sin⁡θ=1\sin\theta = 1 and cos⁡θ=0\cos\theta = 0, R=I+K+K2=Rz(π/2)=(0−10100001)R = I + K + K^2 = R_z(\pi/2) = \begin{pmatrix} 0 & -1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1 \end{pmatrix}.
  • Line L6: G=π2I+K+(π2−1)K2G = \tfrac{\pi}{2} I + K + (\tfrac{\pi}{2} - 1) K^2.
  • Line L7: π2v=(π/2,0,0)\tfrac{\pi}{2} v = (\pi/2, 0, 0), Kv=ω×v=(0,1,0)K v = \omega \times v = (0, 1, 0), and K2v=(−1,0,0)K^2 v = (-1, 0, 0). So p=(π/2−(π/2−1), 1, 0)=(1,1,0)p = (\pi/2 - (\pi/2 - 1),\ 1,\ 0) = (1, 1, 0).

So T=e[S]π/2T = e^{[S]\pi/2} turns the body by 90 degrees about the vertical and moves its origin to (1,1,0)(1, 1, 0) m. The geometry explains this. A screw axis with a unit ω\omega and pitch hh through the point qq is S=(ω,−ω×q+hω)S = (\omega, -\omega \times q + h\omega). Here h=ω⋅v=0h = \omega \cdot v = 0, and −ω×q=(1,0,0)-\omega \times q = (1, 0, 0) for q=(0,1,0)q = (0, 1, 0). So the motion is a pure rotation by 90 degrees about the vertical line through (0,1,0)(0, 1, 0). That rotation takes the origin, which is 1 m from the line in the −y-y direction, to the point 1 m from the line in the +x+x direction, which is (1,1,0)(1, 1, 0).

With a pitch of h=0.1h = 0.1 m/rad about the same line, S=(0,0,1,1,0,0.1)S = (0, 0, 1, 1, 0, 0.1), and θ=π\theta = \pi, the implementation gives R=Rz(π)R = R_z(\pi) and p=(0,2,0.3141593)p = (0, 2, 0.3141593). The origin turns half way around the line to (0,2)(0, 2) and rises by hθ=0.1πh\theta = 0.1\pi.

A prismatic axis S=(0,0,0,0,0,1)S = (0, 0, 0, 0, 0, 1) with θ=0.5\theta = 0.5 m gives the translation p=(0,0,0.5)p = (0, 0, 0.5) and R=IR = I.

The logarithm of the first TT returns ξ=(0,0,π/2,π/2,0,0)=Sθ\xi = (0, 0, \pi/2, \pi/2, 0, 0) = S\theta, the input.

Correctness

By induction, [S]k=([ω]k[ω]k−1v00)[S]^k = \begin{pmatrix} [\omega]^k & [\omega]^{k-1} v \\ 0 & 0 \end{pmatrix} for k≥1k \ge 1. So the power series of e[S]θe^{[S]\theta} has the upper left block e[ω]θe^{[\omega]\theta} and the upper right block (∑k≥1θkk![ω]k−1)v\big(\sum_{k \ge 1} \frac{\theta^k}{k!}[\omega]^{k-1}\big) v. If ω=0\omega = 0, only the term k=1k = 1 is left, which gives line L3. If ∣ω∣=1|\omega| = 1, then [ω]3=−[ω][\omega]^3 = -[\omega], so the powers of [ω][\omega] repeat with a sign. Collecting the odd and the even powers gives the series of sin⁡θ\sin\theta and 1−cos⁡θ1 - \cos\theta in the rotation block, which is line L5. It gives the series of 1−cos⁡θ1 - \cos\theta and θ−sin⁡θ\theta - \sin\theta in GG, which is line L6. For EXP-COORDS, the three series alternate with decreasing terms when θ<1\theta < 1, so the truncation errors of line E5 are below θ6/5040\theta^6/5040, which is below 3⋅10−163 \cdot 10^{-16} for θ<10−2\theta < 10^{-2}. The proof below gives all steps, and also proves that the matrix of the logarithm is the inverse of GG.

Proof: EXP-SCREW and EXP-COORDS compute the exponential of a twistfull

We use the notation of the page. For S=(ω,v)S = (\omega, v) with ω,v∈R3\omega, v \in \mathbb{R}^3, the 4×44 \times 4 matrix of SS is

[S]=([ω]v00),[S] = \begin{pmatrix} [\omega] & v \\ 0 & 0 \end{pmatrix},

where [ω][\omega] is the skew-symmetric matrix of ω\omega. The exponential of a square matrix AA is the series eA=∑k≥0Ak/k!e^A = \sum_{k \ge 0} A^k / k!, which converges absolutely for every AA (see the page on the matrix exponential). The proof is in exact arithmetic, in the real RAM.

Powers of a twist matrix

Lemma 1. For every k≥1k \ge 1,

[S]k=([ω]k[ω]k−1v00).[S]^k = \begin{pmatrix} [\omega]^k & [\omega]^{k-1} v \\ 0 & 0 \end{pmatrix}.

Proof. For k=1k = 1 this is the definition, with [ω]0=I[\omega]^0 = I. If it holds for kk, then

[S]k+1=[S]k[S]=([ω]k[ω]k−1v00)([ω]v00)=([ω]k+1[ω]kv00).[S]^{k+1} = [S]^k [S] = \begin{pmatrix} [\omega]^k & [\omega]^{k-1} v \\ 0 & 0 \end{pmatrix} \begin{pmatrix} [\omega] & v \\ 0 & 0 \end{pmatrix} = \begin{pmatrix} [\omega]^{k+1} & [\omega]^k v \\ 0 & 0 \end{pmatrix}.

□\square

Lemma 2. If ∣ω∣=1|\omega| = 1, then [ω]3=−[ω][\omega]^3 = -[\omega]. So for j≥1j \ge 1, [ω]2j+1=(−1)j[ω][\omega]^{2j+1} = (-1)^j [\omega] and [ω]2j+2=(−1)j[ω]2[\omega]^{2j+2} = (-1)^j [\omega]^2.

Proof. For every xx, [ω]2x=ω×(ω×x)=ω(ω⋅x)−x[\omega]^2 x = \omega \times (\omega \times x) = \omega(\omega \cdot x) - x, because ∣ω∣=1|\omega| = 1. So [ω]2=ωωT−I[\omega]^2 = \omega\omega^{\mathsf T} - I, and [ω]3=[ω]ωωT−[ω]=−[ω][\omega]^3 = [\omega]\omega\omega^{\mathsf T} - [\omega] = -[\omega], because [ω]ω=ω×ω=0[\omega]\omega = \omega \times \omega = 0. The other two formulas follow by induction on jj. □\square

The closed form

Theorem 1. Let S=(ω,v)S = (\omega, v) and θ∈R\theta \in \mathbb{R}.

(a) If ∣ω∣=1|\omega| = 1, then

e[S]θ=(RG(θ)v01),R=I+sin⁡θ [ω]+(1−cos⁡θ)[ω]2,G(θ)=Iθ+(1−cos⁡θ)[ω]+(θ−sin⁡θ)[ω]2.e^{[S]\theta} = \begin{pmatrix} R & G(\theta) v \\ 0 & 1 \end{pmatrix}, \quad R = I + \sin\theta\,[\omega] + (1 - \cos\theta)[\omega]^2, \quad G(\theta) = I\theta + (1 - \cos\theta)[\omega] + (\theta - \sin\theta)[\omega]^2.

(b) If ω=0\omega = 0, then

e[S]θ=(Ivθ01).e^{[S]\theta} = \begin{pmatrix} I & v\theta \\ 0 & 1 \end{pmatrix}.

Proof. By Lemma 1,

e[S]θ=I4+∑k≥1θkk!([ω]k[ω]k−1v00)=(e[ω]θ(∑k≥1θkk![ω]k−1)v01).e^{[S]\theta} = I_4 + \sum_{k \ge 1} \frac{\theta^k}{k!} \begin{pmatrix} [\omega]^k & [\omega]^{k-1} v \\ 0 & 0 \end{pmatrix} = \begin{pmatrix} e^{[\omega]\theta} & \left(\sum_{k \ge 1} \frac{\theta^k}{k!}[\omega]^{k-1}\right) v \\ 0 & 1 \end{pmatrix}.

Both series converge absolutely, so we may split and regroup them.

Case (b). If ω=0\omega = 0, then [ω]0=I[\omega]^0 = I and [ω]k=0[\omega]^k = 0 for k≥1k \ge 1. The upper left block is II, and only the term k=1k = 1 of the second series is left, which gives θv\theta v.

Case (a). The upper left block e[ω]θe^{[\omega]\theta} is RR by Rodrigues' formula; we repeat the short proof. Split the series of e[ω]θe^{[\omega]\theta} into the term k=0k = 0, the odd terms and the even terms with k≥2k \ge 2, and use Lemma 2:

e[ω]θ=I+(∑j≥0(−1)jθ2j+1(2j+1)!)[ω]+(∑j≥0(−1)jθ2j+2(2j+2)!)[ω]2=I+sin⁡θ [ω]+(1−cos⁡θ)[ω]2.e^{[\omega]\theta} = I + \Big(\sum_{j \ge 0} \frac{(-1)^j \theta^{2j+1}}{(2j+1)!}\Big)[\omega] + \Big(\sum_{j \ge 0} \frac{(-1)^j \theta^{2j+2}}{(2j+2)!}\Big)[\omega]^2 = I + \sin\theta\,[\omega] + (1 - \cos\theta)[\omega]^2.

For the second series, write G(θ)=∑k≥1θkk![ω]k−1G(\theta) = \sum_{k \ge 1} \frac{\theta^k}{k!}[\omega]^{k-1}. The term k=1k = 1 is IθI\theta. The terms with k−1=2j+1k - 1 = 2j + 1 odd give ∑j≥0(−1)jθ2j+2(2j+2)![ω]=(1−cos⁡θ)[ω]\sum_{j \ge 0} \frac{(-1)^j \theta^{2j+2}}{(2j+2)!}[\omega] = (1 - \cos\theta)[\omega]. The terms with k−1=2j+2k - 1 = 2j + 2 even and at least 2 give ∑j≥0(−1)jθ2j+3(2j+3)![ω]2=(θ−sin⁡θ)[ω]2\sum_{j \ge 0} \frac{(-1)^j \theta^{2j+3}}{(2j+3)!}[\omega]^2 = (\theta - \sin\theta)[\omega]^2. So G(θ)=Iθ+(1−cos⁡θ)[ω]+(θ−sin⁡θ)[ω]2G(\theta) = I\theta + (1 - \cos\theta)[\omega] + (\theta - \sin\theta)[\omega]^2. □\square

EXP-SCREW

Corollary 2. If SS is a screw axis, that is ∣ω∣=1|\omega| = 1, or ω=0\omega = 0 and ∣v∣=1|v| = 1, then EXP-SCREW(S,θ)(S, \theta) returns e[S]θe^{[S]\theta}.

Proof. Line L1 splits SS. If ω=0\omega = 0, line L3 returns the matrix of Theorem 1(b). Else ∣ω∣=1|\omega| = 1, lines L4 to L7 compute RR, G(θ)G(\theta) and p=G(θ)vp = G(\theta) v of Theorem 1(a), and line L8 returns the matrix of Theorem 1(a). The implementation checks the hypothesis on SS with a tolerance of 10−910^{-9} and raises an error if it fails. □\square

The result is in SE(3). RR is a rotation, because R=e[ω]θR = e^{[\omega]\theta}, det⁡eA=etr⁡A=1\det e^{A} = e^{\operatorname{tr} A} = 1 for the trace-free A=[ω]θA = [\omega]\theta, and (e[ω]θ)T=e−[ω]θ=(e[ω]θ)−1(e^{[\omega]\theta})^{\mathsf T} = e^{-[\omega]\theta} = (e^{[\omega]\theta})^{-1}.

EXP-COORDS

Theorem 3. For every ξ=(w,u)∈R6\xi = (w, u) \in \mathbb{R}^6, let θ=∣w∣\theta = |w|. If θ≥δ\theta \ge \delta or θ=0\theta = 0, EXP-COORDS(ξ)(\xi) returns e[ξ]e^{[\xi]}. If 0<θ<δ0 < \theta < \delta, it returns e[ξ]e^{[\xi]} with each of the three scalar factors changed by a relative amount below 3⋅10−163 \cdot 10^{-16}.

Proof. If θ≥δ>0\theta \ge \delta > 0, let S=ξ/θS = \xi / \theta. Then S=(w/θ,u/θ)S = (w/\theta, u/\theta) has a unit angular part, so it is a screw axis, and [ξ]=[S]θ[\xi] = [S]\theta. Line E4 returns e[S]θ=e[ξ]e^{[S]\theta} = e^{[\xi]} by Corollary 2.

If θ<δ\theta < \delta, put K=[w]=θ[ω^]K = [w] = \theta[\hat\omega] when θ>0\theta > 0. Theorem 1(a) with ω^=w/θ\hat\omega = w/\theta and v=u/θv = u/\theta gives

e[ξ]=(I+aK+bK2(I+bK+cK2) u01),a=sin⁡θθ, b=1−cos⁡θθ2, c=θ−sin⁡θθ3.e^{[\xi]} = \begin{pmatrix} I + a K + b K^2 & (I + b K + c K^2)\, u \\ 0 & 1 \end{pmatrix}, \quad a = \frac{\sin\theta}{\theta},\ b = \frac{1 - \cos\theta}{\theta^2},\ c = \frac{\theta - \sin\theta}{\theta^3}.

Indeed, sin⁡θ [ω^]=aK\sin\theta\,[\hat\omega] = a K, (1−cos⁡θ)[ω^]2=bK2(1 - \cos\theta)[\hat\omega]^2 = b K^2, and G(θ)v=(Iθ+(1−cos⁡θ)[ω^]+(θ−sin⁡θ)[ω^]2) u/θ=(I+bK+cK2) uG(\theta) v = (I\theta + (1 - \cos\theta)[\hat\omega] + (\theta - \sin\theta)[\hat\omega]^2)\, u/\theta = (I + b K + c K^2)\, u. The same formula also holds for θ=0\theta = 0, where K=0K = 0 and the result is the translation by uu, as in Theorem 1(b). Line E5 replaces aa, bb and cc by their Taylor polynomials of degree 4 in θ\theta. The three series alternate, and their terms decrease in size for θ<1\theta < 1, so the error of each truncation is below the first omitted term: θ6/5040\theta^6/5040, θ6/40320\theta^6/40320 and θ6/362880\theta^6/362880. For θ<δ=10−2\theta < \delta = 10^{-2} these are below 2⋅10−162 \cdot 10^{-16}, and relative to a≈1a \approx 1, b≈1/2b \approx 1/2 and c≈1/6c \approx 1/6 they are below 3⋅10−163 \cdot 10^{-16}. Lines E6 and E7 then compute the matrix above. □\square

The inverse map

Theorem 4. Let T=(Rp01)T = \begin{pmatrix} R & p \\ 0 & 1 \end{pmatrix} with R∈SO(3)R \in SO(3), and let ww be a vector with e[w]=Re^{[w]} = R and θ=∣w∣<2π\theta = |w| < 2\pi, for example the output of the SO(3) logarithm, which has θ≤π\theta \le \pi. Then the unique uu with e[(w,u)]=Te^{[(w, u)]} = T is u=(I−12[w]+d [w]2) pu = (I - \tfrac12 [w] + d\,[w]^2)\, p, where d=(1−θ2cot⁡θ2)/θ2d = (1 - \tfrac{\theta}{2}\cot\tfrac{\theta}{2}) / \theta^2 for θ>0\theta > 0, and d=1/12d = 1/12 for θ=0\theta = 0.

Proof. By the proof of Theorem 3, the translation part of e[(w,u)]e^{[(w, u)]} is MuM u with M=I+bK+cK2M = I + b K + c K^2 and K=[w]K = [w]. We show that N=I−12K+dK2N = I - \tfrac12 K + d K^2 is the inverse of MM. If θ=0\theta = 0, then K=0K = 0 and M=N=IM = N = I. Else write K=θ[ω^]K = \theta[\hat\omega] with the unit vector ω^=w/θ\hat\omega = w/\theta. Both MM and NN are polynomials in KK. KK maps the line of ω^\hat\omega to 0 and maps the plane orthogonal to ω^\hat\omega to itself, so we can check MN=IM N = I on the line and on the plane separately. On the line of ω^\hat\omega, Kω^=0K\hat\omega = 0, so Mω^=Nω^=ω^M\hat\omega = N\hat\omega = \hat\omega. On the orthogonal plane, KK acts as θJ\theta J, where Jx=ω^×xJ x = \hat\omega \times x is the rotation by π/2\pi/2 about ω^\hat\omega, with J2=−IJ^2 = -I. Identify this plane with the complex numbers, so that JJ is multiplication by ii. Then MM acts as the number m=1+b θi−c θ2=sin⁡θθ+i 1−cos⁡θθ=eiθ−1iθm = 1 + b\,\theta i - c\,\theta^2 = \frac{\sin\theta}{\theta} + i\,\frac{1 - \cos\theta}{\theta} = \frac{e^{i\theta} - 1}{i\theta}. And NN acts as n=1−θ2i−d θ2=hcot⁡h−ihn = 1 - \tfrac{\theta}{2} i - d\,\theta^2 = h\cot h - i h, with h=θ/2h = \theta/2. Now eiθ−1=eih(eih−e−ih)=2isin⁡h eihe^{i\theta} - 1 = e^{ih}(e^{ih} - e^{-ih}) = 2i\sin h\, e^{ih}, so m=sin⁡hheihm = \frac{\sin h}{h} e^{ih}. And n=hsin⁡h(cos⁡h−isin⁡h)=hsin⁡he−ihn = \frac{h}{\sin h}(\cos h - i\sin h) = \frac{h}{\sin h} e^{-ih}. So mn=1m n = 1, and MN=IM N = I on the plane. Hence N=M−1N = M^{-1}, for 0<θ<2π0 < \theta < 2\pi, where sin⁡h≠0\sin h \ne 0.

So Mu=pM u = p has the unique solution u=Npu = N p. The rotation part of e[(w,u)]e^{[(w, u)]} is e[w]=Re^{[w]} = R, so e[(w,u)]=Te^{[(w, u)]} = T. □\square

At θ=π\theta = \pi the rotation logarithm has two values ±πω^\pm\pi\hat\omega, and each of them gives one uu by Theorem 4. For θ\theta near 0, the implementation uses the series d=1/12+θ2/720+θ4/30240d = 1/12 + \theta^2/720 + \theta^4/30240, the start of the Taylor series of (1−hcot⁡h)/θ2(1 - h\cot h)/\theta^2.

Complexity

The input has a fixed size, so the time and the space are Θ(1)\Theta(1) in the real RAM. EXP-SCREW computes one sine and one cosine, one 3×33 \times 3 product K2K^2 (27 multiplications), two combinations of II, KK and K2K^2, and one product GvG v. That is fewer than 150 floating-point operations. The cost does not depend on θ\theta.

The product of exponentials formula for an arm with nn joints calls the map nn times and multiplies nn matrices of size 4×44 \times 4, so forward kinematics costs Θ(n)\Theta(n) operations.

Properties

  • One parameter subgroups. e[S]θ1e[S]θ2=e[S](θ1+θ2)e^{[S]\theta_1} e^{[S]\theta_2} = e^{[S](\theta_1 + \theta_2)}, because [S]θ1[S]\theta_1 and [S]θ2[S]\theta_2 commute.
  • Derivative. ddθe[S]θ=[S]e[S]θ=e[S]θ[S]\frac{d}{d\theta} e^{[S]\theta} = [S] e^{[S]\theta} = e^{[S]\theta} [S]. So a body that moves along e[S]θ(t)e^{[S]\theta(t)} has the twist Sθ˙S\dot\theta, the same in the fixed frame and in the moving frame.
  • Surjective. Every T∈SE(3)T \in SE(3) is e[ξ]e^{[\xi]} for some ξ\xi; the logarithm above constructs one. This is the algebraic form of Chasles' theorem.
  • Not injective. Adding 2π2\pi to the angle of a revolute screw gives the same TT, and at a rotation angle of π\pi there are two logarithms.
  • Change of frame. Te[S]θT−1=e[AdTS]θT e^{[S]\theta} T^{-1} = e^{[\mathrm{Ad}_T S]\theta}, where AdT\mathrm{Ad}_T is the adjoint map.
  • Not a group morphism. In general e[ξ1]e[ξ2]≠e[ξ1+ξ2]e^{[\xi_1]} e^{[\xi_2]} \ne e^{[\xi_1 + \xi_2]}, because the two matrices do not commute.

Variants and improvements

  • Two separate exponentials. Some code computes R=e[w]R = e^{[w]} and takes p=up = u as the translation. That is a different map, the exponential of SO(3) times the translations, and it does not follow a screw motion. It is used in some filters; the two maps agree to first order only.
  • Dual quaternions. A dual quaternion stores the same rigid motion in 8 numbers, and its exponential is the same screw motion.
  • The plane. In SE(2), with ξ=(θ,ux,uy)\xi = (\theta, u_x, u_y), the translation is VuV u with V=1θ(sin⁡θ−(1−cos⁡θ)1−cos⁡θsin⁡θ)V = \frac{1}{\theta}\begin{pmatrix} \sin\theta & -(1 - \cos\theta) \\ 1 - \cos\theta & \sin\theta \end{pmatrix}.
  • Jacobians. Optimization on SE(3) needs the derivative of the exponential with respect to ξ\xi, the left or right Jacobian. Sola, Deray and Atchuthan give the closed forms; see uncertainty on Lie groups.

When to use it

Use the exponential map to compute the forward kinematics of an arm with the product of exponentials formula, to integrate a constant twist over a time step exactly, and to apply a small correction ξ\xi to a pose in pose graph optimization or a filter on SE(3), with T←Te[ξ]T \leftarrow T e^{[\xi]}. Use the logarithm to measure the error between two poses as a 6-vector. If you only need the composition of known poses, multiply the matrices directly with the pose compounding operators.

Pitfalls

  • The order of the twist. Lynch and Park put the angular part first; Murray, Li and Sastry put the linear part first. A mix of the two gives wrong results without a warning.
  • v is not the velocity of the body origin. In the twist (ω,v)(\omega, v) in the fixed frame, vv is the velocity of the body point that is at the origin of the fixed frame. For a rotation about a line through qq, v=−ω×qv = -\omega \times q, not 0.
  • A screw that is not normalized. EXP-SCREW needs ∣ω∣=1|\omega| = 1. If you pass a twist ξ\xi with ∣w∣≠1|w| \ne 1, use EXP-COORDS, which normalizes.
  • Small angles. The closed form (1−cos⁡θ)/θ2(1 - \cos\theta)/\theta^2 loses digits to cancellation when θ\theta is small; use the series below a threshold. The tests of the implementation check that the two branches agree to 10−1310^{-13} at the threshold 10−210^{-2} (a measurement, not a proof).
  • Integrating the translation separately. e[ξ]e^{[\xi]} is not the translation uu followed by the rotation e[w]e^{[w]}; the translation of e[ξ]e^{[\xi]} is GuG u, not uu.

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
se3_exponential_map.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/se3-exponential-map/. The authors are listed in prov/25FNCG.jsonl.
"""Exponential map of SE(3), written out in full.

A screw axis S = (omega, v) has |omega| = 1, or omega = 0 and |v| = 1.
exp_screw(S, theta) is the closed form of Lynch and Park, Modern Robotics,
Section 3.3.3. exp_coords(xi) takes general exponential coordinates
xi = S * theta, and uses a Taylor series when the rotation angle is small.
log_coords(T) is the inverse map, with theta in [0, pi].

Matrices are lists of rows. The 4x4 result is [[R, p], [0, 0, 0, 1]].
"""

import math

# Below this rotation angle, exp_coords and log_coords use Taylor series.
# The first omitted term of each series is of order theta^6, below 3e-16
# for theta < 1e-2. Above the threshold, exp_screw divides u by theta, and
# the rounding error of 1 - cos(theta) grows like 1e-16 |u| / theta, which
# is near 1e-14 |u| at the threshold.
SERIES_THETA = 1e-2


def _hat(w):
    return [[0.0, -w[2], w[1]], [w[2], 0.0, -w[0]], [-w[1], w[0], 0.0]]


def _mul3(a, b):
    return [[sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)] for i in range(3)]


def _comb(c0, c1, w, c2, w2):
    """Return c0 I + c1 w + c2 w2 for 3x3 matrices w and w2."""
    return [[(c0 if i == j else 0.0) + c1 * w[i][j] + c2 * w2[i][j] for j in range(3)] for i in range(3)]


def _pose(r, p):
    return [r[0] + [p[0]], r[1] + [p[1]], r[2] + [p[2]], [0.0, 0.0, 0.0, 1.0]]


def _apply(m, x):
    return [sum(m[i][k] * x[k] for k in range(3)) for i in range(3)]


def exp_screw(s, theta):
    """Return exp([S] theta) for a screw axis S = (omega, v) and a distance theta.

    Raise ValueError if S is not a screw axis: |omega| must be 1, or
    omega = 0 and |v| = 1, within 1e-9.
    """
    w, v = list(s[:3]), list(s[3:])  # @line L1
    nw = math.sqrt(sum(x * x for x in w))
    nv = math.sqrt(sum(x * x for x in v))
    if nw <= 1e-9:  # @line L2
        if abs(nv - 1.0) > 1e-9:
            raise ValueError("omega = 0 needs |v| = 1")
        return _pose([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [x * theta for x in v])  # @line L3
    if abs(nw - 1.0) > 1e-9:
        raise ValueError("omega must be a unit vector")
    k = _hat(w)  # @line L4
    k2 = _mul3(k, k)
    r = _comb(1.0, math.sin(theta), k, 1.0 - math.cos(theta), k2)  # @line L5
    g = _comb(theta, 1.0 - math.cos(theta), k, theta - math.sin(theta), k2)  # @line L6
    p = _apply(g, v)  # @line L7
    return _pose(r, p)  # @line L8


def exp_coords(xi):
    """Return exp([xi]) for exponential coordinates xi = (w, u) = S * theta.

    With theta = |w|: if theta >= SERIES_THETA, normalize and call
    exp_screw. If 0 < theta < SERIES_THETA, use the series
    R = I + a [w] + b [w]^2 and p = (I + b [w] + c [w]^2) u, where
    a = sin(theta) / theta, b = (1 - cos(theta)) / theta^2 and
    c = (theta - sin(theta)) / theta^3 are replaced by their Taylor series.
    If w = 0, the result is the translation by u.
    """
    w, u = list(xi[:3]), list(xi[3:])  # @line E1
    theta = math.sqrt(sum(x * x for x in w))  # @line E2
    if theta >= SERIES_THETA:  # @line E3
        return exp_screw([x / theta for x in xi], theta)  # @line E4
    t2 = theta * theta  # @line E5
    a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
    b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    k = _hat(w)  # @line E6
    k2 = _mul3(k, k)
    r = _comb(1.0, a, k, b, k2)
    p = _apply(_comb(1.0, b, k, c, k2), u)
    return _pose(r, p)  # @line E7


def log_coords(t):
    """Return xi = (w, u) with exp_coords(xi) = t and |w| in [0, pi].

    w is the logarithm of R (see the so3-logarithm-map page), and
    u = G^(-1) p with G^(-1) = I - [w] / 2 + d [w]^2 and
    d = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r = [row[:3] for row in t[:3]]
    p = [t[0][3], t[1][3], t[2][3]]
    c = max(-1.0, min(1.0, (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0))
    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 = math.sqrt(sum(x * x for x in s))
    theta = math.atan2(sn, c)
    if theta < SERIES_THETA:
        t2 = theta * theta
        w = [x * (1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0) for x in s]
    elif theta <= math.pi - 1e-2:
        w = [theta / sn * x for x in s]
    else:
        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)]
        k = max(range(3), key=lambda i: b[i][i])
        col = [b[i][k] for i in range(3)]
        ncol = math.sqrt(sum(x * x for x in col))
        axis = [x / ncol for x in col]
        if sum(x * y for x, y in zip(axis, s)) < 0.0:
            axis = [-x for x in axis]
        w = [theta * x for x in axis]
    if theta < SERIES_THETA:
        t2 = theta * theta
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = theta / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (theta * theta)
    k = _hat(w)
    gi = _comb(1.0, -0.5, k, d, _mul3(k, k))
    return w + _apply(gi, p)


def screw_axis(q, s_hat, h):
    """Return the screw axis (omega, -omega x q + h omega) of a rotation about
    the unit axis s_hat through the point q, with pitch h."""
    w = list(s_hat)
    wxq = [w[1] * q[2] - w[2] * q[1], w[2] * q[0] - w[0] * q[2], w[0] * q[1] - w[1] * q[0]]
    return w + [-a + h * b for a, b in zip(wxq, w)]
test_se3_exponential_map.py 285 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/se3-exponential-map/. The authors are listed in prov/25FNCG.jsonl.
"""Tests of the page code and of the shared helper rbm.py."""

import itertools
import math
import random

import pytest

import rbm
from se3_exponential_map import exp_coords, exp_screw, log_coords, screw_axis

TOL = 1e-12


def maxdiff(a, b):
    if a and isinstance(a[0], list):
        return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
    return max(abs(x - y) for x, y in zip(a, b))


def series_exp(m, terms=80):
    """Matrix exponential by its power series sum m^k / k!."""
    n = len(m)
    out = rbm.eye(n)
    term = rbm.eye(n)
    for k in range(1, terms):
        term = rbm.scale(rbm.mul(term, m), 1.0 / k)
        out = rbm.add(out, term)
    return out


def rand_unit(rng):
    while True:
        v = [rng.uniform(-1.0, 1.0) for _ in range(3)]
        n = rbm.norm(v)
        if 0.1 < n <= 1.0:
            return [x / n for x in v]


def rand_xi(rng, tmax=math.pi):
    w = rbm.scale(rand_unit(rng), rng.uniform(0.0, tmax))
    return w + [rng.uniform(-2.0, 2.0) for _ in range(3)]


def is_pose(t):
    r = [row[:3] for row in t[:3]]
    assert maxdiff(rbm.mul(rbm.transpose(r), r), rbm.eye(3)) < TOL
    assert abs(rbm.det(r) - 1.0) < TOL
    assert t[3] == [0.0, 0.0, 0.0, 1.0]


# ---------------------------------------------------------------- page code


def test_check_value():
    s = screw_axis([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], 0.0)
    assert maxdiff(s, [0.0, 0.0, 1.0, 1.0, 0.0, 0.0]) < TOL
    t = exp_screw(s, math.pi / 2.0)
    want = rbm.make_T(rbm.rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert maxdiff(t, want) < TOL
    assert maxdiff(exp_coords(rbm.scale(s, math.pi / 2.0)), want) < TOL


def test_against_power_series_and_helper():
    rng = random.Random(1)
    for _ in range(150):
        xi = rand_xi(rng)
        t = exp_coords(xi)
        is_pose(t)
        assert maxdiff(t, series_exp(rbm.hat6(xi))) < 1e-11
        assert maxdiff(t, rbm.se3_exp(xi)) < TOL


def test_prismatic_and_errors():
    t = exp_screw([0.0, 0.0, 0.0, 0.0, 0.6, 0.8], 2.5)
    assert maxdiff(t, rbm.make_T(rbm.eye(3), [0.0, 1.5, 2.0])) < TOL
    assert maxdiff(exp_coords([0.0, 0.0, 0.0, 1.0, -2.0, 3.0]), rbm.make_T(rbm.eye(3), [1.0, -2.0, 3.0])) == 0.0
    with pytest.raises(ValueError):
        exp_screw([0.0, 0.0, 2.0, 0.0, 0.0, 0.0], 1.0)
    with pytest.raises(ValueError):
        exp_screw([0.0, 0.0, 0.0, 0.0, 0.0, 2.0], 1.0)


def test_small_angles_are_continuous():
    rng = random.Random(2)
    for _ in range(50):
        xi = rand_xi(rng)
        for th in (0.1, 1e-2 * (1 + 1e-9), 1e-2 * (1 - 1e-9), 1e-4, 1e-6, 1e-9, 1e-14):
            w = rbm.scale(rbm.scale(xi[:3], 1.0 / rbm.norm(xi[:3])), th)
            x = w + xi[3:]
            want = series_exp(rbm.hat6(x), 30)
            assert maxdiff(exp_coords(x), want) < 1e-13
            assert maxdiff(rbm.se3_exp(x), want) < 1e-13
            assert maxdiff(rbm.so3_exp(w), series_exp(rbm.hat3(w), 30)) < 1e-15


def test_screw_motion_geometry():
    rng = random.Random(3)
    for _ in range(50):
        q = [rng.uniform(-2.0, 2.0) for _ in range(3)]
        s_hat = rand_unit(rng)
        h = rng.uniform(-1.0, 1.0)
        th = rng.uniform(-6.0, 6.0)
        t = exp_screw(screw_axis(q, s_hat, h), th)
        # a point on the axis moves along the axis by h theta
        assert maxdiff(rbm.T_apply(t, q), rbm.add(q, rbm.scale(s_hat, h * th))) < 1e-11
        # one-parameter subgroup
        a, b = rng.uniform(-3.0, 3.0), rng.uniform(-3.0, 3.0)
        s = screw_axis(q, s_hat, h)
        assert maxdiff(rbm.mul(exp_screw(s, a), exp_screw(s, b)), exp_screw(s, a + b)) < 1e-11


def test_derivative_is_twist():
    rng = random.Random(4)
    for _ in range(20):
        s = screw_axis([rng.uniform(-1, 1) for _ in range(3)], rand_unit(rng), rng.uniform(-1, 1))
        th = rng.uniform(-3.0, 3.0)
        h = 1e-6
        d = rbm.scale(rbm.sub(exp_screw(s, th + h), exp_screw(s, th - h)), 1.0 / (2 * h))
        assert maxdiff(d, rbm.mul(rbm.hat6(s), exp_screw(s, th))) < 1e-6


def test_log_round_trips():
    rng = random.Random(5)
    for _ in range(200):
        xi = rand_xi(rng, math.pi - 1e-6)
        if rbm.norm(xi[:3]) < 1e-3:
            continue
        assert maxdiff(log_coords(exp_coords(xi)), xi) < 1e-10
    for _ in range(100):
        t = exp_coords(rand_xi(rng, 3.0 * math.pi))
        x = log_coords(t)
        assert rbm.norm(x[:3]) <= math.pi + 1e-12
        assert maxdiff(exp_coords(x), t) < 1e-11
        assert maxdiff(x, rbm.se3_log(t)) < 1e-9
    for th in (0.0, 1e-9, 1e-5, math.pi - 1e-3, math.pi - 1e-7, math.pi):
        for _ in range(10):
            xi = rbm.scale(rand_unit(rng), th) + [rng.uniform(-2, 2) for _ in range(3)]
            t = exp_coords(xi)
            assert maxdiff(exp_coords(log_coords(t)), t) < 1e-10


# ---------------------------------------------------------------- helper rbm


def test_rbm_self_test():
    assert rbm.self_test()


def test_rbm_linear_algebra():
    rng = random.Random(6)
    for n in range(1, 6):
        for _ in range(20):
            a = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
            x = [rng.uniform(-1, 1) for _ in range(n)]
            b = rbm.matvec(a, x)
            assert maxdiff(rbm.matvec(a, rbm.solve(a, b)), b) < 1e-9
            assert maxdiff(rbm.mul(a, rbm.inv(a)), rbm.eye(n)) < 1e-8
            want = 0.0
            for perm in itertools.permutations(range(n)):
                sign = 1
                for i in range(n):
                    for j in range(i + 1, n):
                        if perm[i] > perm[j]:
                            sign = -sign
                prod = 1.0
                for i in range(n):
                    prod *= a[i][perm[i]]
                want += sign * prod
            assert abs(rbm.det(a) - want) < 1e-12
            spd = rbm.add(rbm.mul(a, rbm.transpose(a)), rbm.scale(rbm.eye(n), 0.1))
            low = rbm.cholesky(spd)
            assert all(low[i][j] == 0.0 for i in range(n) for j in range(i + 1, n))
            assert maxdiff(rbm.mul(low, rbm.transpose(low)), spd) < 1e-12
    with pytest.raises(ValueError):
        rbm.solve([[1.0, 2.0], [2.0, 4.0]], [1.0, 1.0])
    with pytest.raises(ValueError):
        rbm.cholesky([[1.0, 2.0], [2.0, 1.0]])
    assert rbm.det([[1.0, 2.0], [2.0, 4.0]]) == 0.0
    j = [[rng.uniform(-1, 1) for _ in range(5)] for _ in range(3)]
    jp = rbm.pinv_right(j)
    assert len(jp) == 5 and len(jp[0]) == 3
    assert maxdiff(rbm.mul(j, jp), rbm.eye(3)) < 1e-10
    assert rbm.zeros(2, 3) == [[0.0] * 3, [0.0] * 3]
    assert rbm.cross([1, 0, 0], [0, 1, 0]) == [0, 0, 1]
    assert rbm.dot([1, 2, 3], [4, 5, 6]) == 32
    assert rbm.norm([3.0, 4.0]) == 5.0
    assert rbm.sub([1, 2], [1, 1]) == [0, 1]
    m = rbm.solve([[2.0, 0.0], [0.0, 4.0]], [[2.0, 4.0], [4.0, 8.0]])
    assert m == [[1.0, 2.0], [1.0, 2.0]]


def test_rbm_hat_vee_and_rotations():
    rng = random.Random(7)
    for _ in range(50):
        a = [rng.uniform(-2, 2) for _ in range(3)]
        b = [rng.uniform(-2, 2) for _ in range(3)]
        assert maxdiff(rbm.matvec(rbm.hat3(a), b), rbm.cross(a, b)) < 1e-15
        assert rbm.vee3(rbm.hat3(a)) == a
        v = a + b
        assert rbm.vee6(rbm.hat6(v)) == v
        th = rng.uniform(-4, 4)
        assert maxdiff(rbm.rot_x(th), rbm.so3_exp([th, 0.0, 0.0])) < TOL
        assert maxdiff(rbm.rot_y(th), rbm.so3_exp([0.0, th, 0.0])) < TOL
        assert maxdiff(rbm.rot_z(th), rbm.so3_exp([0.0, 0.0, th])) < TOL
        r, p, y = (rng.uniform(-3, 3) for _ in range(3))
        want = rbm.mul(rbm.rot_z(y), rbm.mul(rbm.rot_y(p), rbm.rot_x(r)))
        assert maxdiff(rbm.rpy(r, p, y), want) < 1e-15
        w = rbm.scale(rand_unit(rng), rng.uniform(0.0, 3.0))
        rot = rbm.so3_exp(w)
        assert maxdiff(rot, series_exp(rbm.hat3(w))) < 1e-12
        assert maxdiff(rbm.mul(rbm.transpose(rot), rot), rbm.eye(3)) < TOL
        assert abs(rbm.det(rot) - 1.0) < TOL


def test_rbm_so3_log():
    rng = random.Random(8)
    for _ in range(200):
        w = rbm.scale(rand_unit(rng), rng.uniform(1e-3, math.pi - 1e-6))
        assert maxdiff(rbm.so3_log(rbm.so3_exp(w)), w) < 1e-10
    for th in (0.0, 1e-12, 1e-6, 1e-2 * (1 - 1e-9), 1e-2 * (1 + 1e-9), 0.5,math.pi - 0.02, math.pi - 1e-3, math.pi - 1e-8, math.pi):
        for _ in range(10):
            rot = rbm.so3_exp(rbm.scale(rand_unit(rng), th))
            w = rbm.so3_log(rot)
            assert rbm.norm(w) <= math.pi + 1e-15
            assert maxdiff(rbm.so3_exp(w), rot) < 1e-12
    w = rbm.so3_log(rbm.rot_x(math.pi))
    assert maxdiff(w, [math.pi, 0.0, 0.0]) < TOL
    assert rbm.so3_log(rbm.eye(3)) == [0.0, 0.0, 0.0]


def test_rbm_poses_and_adjoint():
    rng = random.Random(9)
    for _ in range(50):
        t1 = rbm.se3_exp(rand_xi(rng))
        t2 = rbm.se3_exp(rand_xi(rng))
        is_pose(t1)
        assert maxdiff(rbm.mul(t1, rbm.T_inv(t1)), rbm.eye(4)) < TOL
        x = [rng.uniform(-1, 1) for _ in range(3)]
        assert maxdiff(rbm.T_apply(t1, x), rbm.matvec(t1, x + [1.0])[:3]) < 1e-15
        a12 = rbm.adjoint(rbm.mul(t1, t2))
        assert maxdiff(a12, rbm.mul(rbm.adjoint(t1), rbm.adjoint(t2))) < 1e-11
        v = [rng.uniform(-1, 1) for _ in range(6)]
        lhs = rbm.mul(rbm.mul(t1, rbm.hat6(v)), rbm.T_inv(t1))
        assert maxdiff(lhs, rbm.hat6(rbm.matvec(rbm.adjoint(t1), v))) < 1e-11
        xi = rand_xi(rng, math.pi - 1e-6)
        if rbm.norm(xi[:3]) > 1e-3:
            assert maxdiff(rbm.se3_log(rbm.se3_exp(xi)), xi) < 1e-10
        assert maxdiff(rbm.se3_exp(rbm.se3_log(t1)), t1) < 1e-11


def test_rbm_quaternions():
    q = rbm.quat_from_axis_angle([0.0, 0.0, 1.0], math.pi / 2.0)
    assert maxdiff(q, [0.70711, 0.0, 0.0, 0.70711]) < 1e-5
    assert maxdiff(rbm.quat_to_rot(q), rbm.rot_z(math.pi / 2.0)) < TOL
    assert maxdiff(rbm.quat_from_axis_angle([1.0, 0.0, 0.0], math.pi), [0.0, 1.0, 0.0, 0.0]) < 1e-15
    assert rbm.quat_from_axis_angle([0.0, 0.0, 0.0], 0.0) == [1.0, 0.0, 0.0, 0.0]
    with pytest.raises(ValueError):
        rbm.quat_from_axis_angle([0.0, 0.0, 0.0], 1.0)
    rng = random.Random(10)
    for _ in range(50):
        a, b = rand_unit(rng), rand_unit(rng)
        ta, tb = rng.uniform(-4, 4), rng.uniform(-4, 4)
        qa = rbm.quat_from_axis_angle(rbm.scale(a, 2.5), ta)
        qb = rbm.quat_from_axis_angle(b, tb)
        ra = rbm.quat_to_rot(qa)
        assert maxdiff(ra, rbm.so3_exp(rbm.scale(a, ta))) < TOL
        assert maxdiff(rbm.quat_to_rot(rbm.quat_mul(qa, qb)), rbm.mul(ra, rbm.quat_to_rot(qb))) < TOL
        v = [rng.uniform(-1, 1) for _ in range(3)]
        rotated = rbm.quat_mul(rbm.quat_mul(qa, [0.0] + v), rbm.quat_conj(qa))
        assert abs(rotated[0]) < TOL
        assert maxdiff(rotated[1:], rbm.matvec(ra, v)) < TOL
        assert maxdiff(rbm.quat_to_rot(rbm.scale(qa, -3.0)), ra) < TOL


def test_rbm_num_jacobian():
    def f(x):
        return [math.sin(x[0]) * x[1], x[0] * x[0] + math.exp(x[1]), x[1]]

    x = [0.3, -0.7]
    want = [[math.cos(0.3) * -0.7, math.sin(0.3)], [0.6, math.exp(-0.7)], [0.0, 1.0]]
    assert maxdiff(rbm.num_jacobian(f, x, 1e-6), want) < 1e-8
    assert maxdiff(rbm.num_jacobian(f, x), want) < 1e-8

History

The screw theory of rigid motion goes back to Mozzi (1763) and Chasles (1830). Brockett (1984) used exponentials of twists to describe the kinematics of robot arms, the product of exponentials formula. Murray, Li and Sastry (1994) and Lynch and Park (2017) give the closed form of the exponential and its inverse in their textbooks. Lynch and Park note that, in the kinematics literature, exponential coordinates of rotation have also been called Euler-Rodrigues parameters.

References

  1. Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 3, Section 3.3.3 (exponential coordinates of rigid-body motions, the closed form of the exponential and the matrix logarithm of a rigid-body motion)
  2. Richard M. Murray, Zexiang Li and S. Shankar Sastry, A Mathematical Introduction to Robotic Manipulation, CRC Press, 1994, Chapter 2, Section 3.2 (exponential coordinates for rigid motion and twists); the book writes a twist with the linear part first
  3. Roger W. Brockett, Robotic manipulators and the product of exponentials formula, Mathematical Theory of Networks and Systems, Lecture Notes in Control and Information Sciences 58, Springer, 1984, 120-129, the whole paper (forward kinematics as a product of exponentials of twists)
  4. Joan Sola, Jeremie Deray and Dinesh Atchuthan, A micro Lie theory for state estimation in robotics, 2018, the exponential and logarithm maps of SE(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
  • a scene preset for the example