Algorithm Search⌘K

Algorithmadvanced

Shepperd's method

Also called quaternion from rotation matrix.

Converts a rotation matrix to a unit quaternion by taking the square root of the largest of the four squared components, so that every division is by a number of at least 2.

Time
Θ(1) worst
Space
Θ(1) extra
Where
n = the size of the matrix, fixed at n = 3
Properties
deterministicnot exactofflineiterative

Shepperd's method converts a 3 by 3 rotation matrix RR into the unit quaternion q=(w,x,y,z)q = (w, x, y, z) of the same rotation. Each of the four squares w2,x2,y2,z2w^2, x^2, y^2, z^2 is a linear function of the diagonal of RR, and each product of two components is a sum or a difference of two entries off the diagonal. The method takes the square root of the largest square, which is at least 1/41/4, and gets the other three components by division by four times that component. The simple formula that always divides by 4w4w fails for rotations by angles near π\pi, where ww is near zero; Shepperd's choice makes the result accurate in floating point for every rotation.

In plain words

A quaternion stores a turn as four numbers. A rotation matrix stores the same turn as nine numbers. From the matrix you can find the square of each of the four numbers by simple sums. You can also find the product of each pair of numbers. So you take one number as a square root, and you get the other three from the products by division. If the number you divide by is almost zero, the answer is bad. The method always takes the largest of the four numbers first, so the division is always safe. The quaternion and its negative give the same turn, so the method picks the sign that makes the first number not negative.

The problem

The input is a matrix R=(rij)R = (r_{ij}) 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 unit quaternion q=(w,x,y,z)q = (w, x, y, z) in the Hamilton convention, scalar first, such that RvR v is the vector part of q (0,v) q∗q\,(0, v)\,q^* for every v∈R3v \in \mathbb{R}^3. Both qq and −q-q are correct answers. The method returns the one with w≥0w \ge 0, which is unique when w>0w > 0, that is, when the rotation angle is less than π\pi.

For a unit quaternion, the rotation matrix is

R=(1−2(y2+z2)2(xy−wz)2(xz+wy)2(xy+wz)1−2(x2+z2)2(yz−wx)2(xz−wy)2(yz+wx)1−2(x2+y2)).R = \begin{pmatrix} 1 - 2(y^2 + z^2) & 2(xy - wz) & 2(xz + wy) \\ 2(xy + wz) & 1 - 2(x^2 + z^2) & 2(yz - wx) \\ 2(xz - wy) & 2(yz + wx) & 1 - 2(x^2 + y^2) \end{pmatrix}.

With t=r11+r22+r33t = r_{11} + r_{22} + r_{33} and w2+x2+y2+z2=1w^2 + x^2 + y^2 + z^2 = 1, this gives ten identities:

4w2=1+t,4x2=1+2r11−t,4y2=1+2r22−t,4z2=1+2r33−t,4w^2 = 1 + t, \quad 4x^2 = 1 + 2r_{11} - t, \quad 4y^2 = 1 + 2r_{22} - t, \quad 4z^2 = 1 + 2r_{33} - t,
4wx=r32−r23,4wy=r13−r31,4wz=r21−r12,4wx = r_{32} - r_{23}, \quad 4wy = r_{13} - r_{31}, \quad 4wz = r_{21} - r_{12},
4xy=r21+r12,4xz=r13+r31,4yz=r32+r23.4xy = r_{21} + r_{12}, \quad 4xz = r_{13} + r_{31}, \quad 4yz = r_{32} + r_{23}.

The algorithm

The four squares grow in the same order as the four numbers t,r11,r22,r33t, r_{11}, r_{22}, r_{33}, because, for example, 4w2−4x2=2(t−r11)4w^2 - 4x^2 = 2(t - r_{11}) and 4x2−4y2=2(r11−r22)4x^2 - 4y^2 = 2(r_{11} - r_{22}). So line L2 finds the largest square without computing all four.

  1. SHEPPERD(R) ▷ R in SO(3); returns q = (w, x, y, z) with w ≥ 0
  2. 1t ← r₁₁ + r₂₂ + r₃₃
  3. 2k ← the index of the largest of (t, r₁₁, r₂₂, r₃₃), from 0 to 3
  4. 3if k = 0 then ▷ w² is the largest square
  5. 4w ← √(1 + t) / 2
  6. 5(x, y, z) ← (r₃₂ - r₂₃, r₁₃ - r₃₁, r₂₁ - r₁₂) / (4w)
  7. 6else if k = 1 then ▷ x² is the largest square
  8. 7x ← √(1 + 2r₁₁ - t) / 2
  9. 8(w, y, z) ← (r₃₂ - r₂₃, r₂₁ + r₁₂, r₁₃ + r₃₁) / (4x)
  10. 9else if k = 2 then ▷ y² is the largest square
  11. 10y ← √(1 + 2r₂₂ - t) / 2
  12. 11(w, x, z) ← (r₁₃ - r₃₁, r₂₁ + r₁₂, r₃₂ + r₂₃) / (4y)
  13. 12else ▷ z² is the largest square
  14. 13z ← √(1 + 2r₃₃ - t) / 2
  15. 14(w, x, y) ← (r₂₁ - r₁₂, r₁₃ + r₃₁, r₃₂ + r₂₃) / (4z)
  16. 15if w < 0 then q ← -q ▷ q and -q are the same rotation
  17. 16return q = (w, x, y, z)

Lines L4, L7, L10 and L13 are the square identities, each solved for one component with the positive root. Lines L5, L8, L11 and L14 are the product identities, each divided by four times the component that is already known. Line L15 picks one of the two signs.

Example

Take the rotation by 170 degrees about the axis (2,3,6)/7(2, 3, 6)/7. Its exact quaternion is (cos⁡85°,sin⁡85°⋅(2,3,6)/7)=(0.0871557,0.2846271,0.4269406,0.8538812)(\cos 85°, \sin 85° \cdot (2, 3, 6)/7) = (0.0871557, 0.2846271, 0.4269406, 0.8538812). Rodrigues' formula gives, to 7 digits,

R=(−0.82278260.09419640.56049600.3918790−0.62025120.67949930.41165470.77872680.4734184).R = \begin{pmatrix} -0.8227826 & 0.0941964 & 0.5604960 \\ 0.3918790 & -0.6202512 & 0.6794993 \\ 0.4116547 & 0.7787268 & 0.4734184 \end{pmatrix}.
  • Line L1: t=−0.9696155t = -0.9696155.
  • Line L2: the largest of (−0.9696155,−0.8227826,−0.6202512,0.4734184)(-0.9696155, -0.8227826, -0.6202512, 0.4734184) is r33r_{33}, so k=3k = 3. The four squares are 4w2=0.03038454w^2 = 0.0303845, 4x2=0.32405034x^2 = 0.3240503, 4y2=0.72911314y^2 = 0.7291131 and 4z2=2.91645234z^2 = 2.9164523.
  • Line L13: z=2.9164523/2=0.8538812z = \sqrt{2.9164523}/2 = 0.8538812, and 4z=3.41552474z = 3.4155247.
  • Line L14: w=(0.3918790−0.0941964)/3.4155247=0.0871557w = (0.3918790 - 0.0941964)/3.4155247 = 0.0871557, x=(0.5604960+0.4116547)/3.4155247=0.2846271x = (0.5604960 + 0.4116547)/3.4155247 = 0.2846271, and y=(0.7787268+0.6794993)/3.4155247=0.4269406y = (0.7787268 + 0.6794993)/3.4155247 = 0.4269406.
  • Line L15: w>0w > 0, so the sign stays.

The result agrees with the exact quaternion in all 7 digits.

Two short checks use the values of the area. For Rz(π/2)R_z(\pi/2), t=1t = 1 and r33=1r_{33} = 1; line L2 takes the first of the two equal values, k=0k = 0, and lines L4 and L5 give w=1/2w = 1/\sqrt2 and (x,y,z)=(0,0,2)/(4/2)(x, y, z) = (0, 0, 2)/(4/\sqrt2), so q=(0.70711,0,0,0.70711)q = (0.70711, 0, 0, 0.70711). For the rotation by π\pi about xx, R=diag⁡(1,−1,−1)R = \operatorname{diag}(1, -1, -1), t=−1t = -1 and k=1k = 1. Line L7 gives x=1+2+1/2=1x = \sqrt{1 + 2 + 1}/2 = 1, line L8 gives w=y=z=0w = y = z = 0, and the output is q=(0,1,0,0)q = (0, 1, 0, 0). The formula that always divides by 4w4w divides by zero here.

The table is a measurement in IEEE double precision with the implementation of this page. The axis is (2,3,6)/7(2, 3, 6)/7, RR comes from Rodrigues' formula, and the error is the largest component error against the exact quaternion, up to the sign.

angle error of the formula that divides by 4w4w error of SHEPPERD
π−10−1\pi - 10^{-1} 1.7e-14 1.1e-16
π−10−3\pi - 10^{-3} 5.2e-10 2.2e-16
π−10−5\pi - 10^{-5} 9.2e-7 2.2e-16
π−10−7\pi - 10^{-7} 3.5e-2 1.1e-16
π−10−9\pi - 10^{-9} division by zero 2.2e-16

At π−10−9\pi - 10^{-9}, 1+t1 + t rounds to 0, and the simple formula has nothing left to divide by.

Correctness

The ten identities follow from the matrix of qq by direct expansion and from w2+x2+y2+z2=1w^2 + x^2 + y^2 + z^2 = 1. The four numbers 4w2,4x2,4y2,4z24w^2, 4x^2, 4y^2, 4z^2 sum to 4, so the largest one is at least 1, and the component that line L2 selects has an absolute value of at least 1/21/2. The square root in that branch is of a number of at least 1, so it is defined, and the divisor is at least 2. The branch returns that component with a positive sign and the other three from the product identities, which gives one of ±q\pm q; both are the same rotation, and line L15 picks the one with w≥0w \ge 0. Every unit quaternion gives a rotation, and every rotation has a unit quaternion by Euler's rotation theorem, so there is always a qq to find. The proof gives the details and a first-order error bound in floating point.

Proof: SHEPPERD returns a unit quaternion of the input rotationfull

We use the notation of the page. A quaternion is q=(w,x,y,z)q = (w, x, y, z) in the Hamilton convention, scalar first, with ij=kij = k. For a unit quaternion qq, the map v↦v \mapsto the vector part of q (0,v) q∗q\,(0, v)\,q^* is linear, and its matrix R(q)R(q) is

R(q)=(w2+x2−y2−z22(xy−wz)2(xz+wy)2(xy+wz)w2−x2+y2−z22(yz−wx)2(xz−wy)2(yz+wx)w2−x2−y2+z2).R(q) = \begin{pmatrix} w^2 + x^2 - y^2 - z^2 & 2(xy - wz) & 2(xz + wy) \\ 2(xy + wz) & w^2 - x^2 + y^2 - z^2 & 2(yz - wx) \\ 2(xz - wy) & 2(yz + wx) & w^2 - x^2 - y^2 + z^2 \end{pmatrix}.

With w2+x2+y2+z2=1w^2 + x^2 + y^2 + z^2 = 1, the diagonal entries become the form 1−2(y2+z2)1 - 2(y^2 + z^2) and so on that the page uses. The proof is first in exact arithmetic, and the last section gives a first-order error bound in floating point.

Every rotation has a unit quaternion

Lemma 1. For every R∈SO(3)R \in SO(3) there is a unit quaternion qq with R(q)=RR(q) = R, and the unit quaternions with this property are exactly qq and −q-q.

Proof. By Euler's rotation theorem, R=e[ω^]θR = e^{[\hat\omega]\theta} for a unit axis ω^\hat\omega and an angle θ∈[0,π]\theta \in [0, \pi]. Put q=(cos⁡θ2,sin⁡θ2 ω^)q = (\cos\frac\theta2, \sin\frac\theta2\,\hat\omega). Expanding R(q)R(q) with c=cos⁡θ2c = \cos\frac\theta2, s=sin⁡θ2s = \sin\frac\theta2 and the identities c2−s2=cos⁡θc^2 - s^2 = \cos\theta, 2cs=sin⁡θ2cs = \sin\theta and 2s2=1−cos⁡θ2s^2 = 1 - \cos\theta gives R(q)=cos⁡θ I+sin⁡θ [ω^]+(1−cos⁡θ)ω^ω^TR(q) = \cos\theta\, I + \sin\theta\,[\hat\omega] + (1 - \cos\theta)\hat\omega\hat\omega^{\mathsf T}, which is Rodrigues' formula, so R(q)=RR(q) = R. The entries of R(q)R(q) are quadratic in qq, so R(−q)=R(q)R(-q) = R(q). Conversely, suppose R(p)=R(q)R(p) = R(q) for unit pp and qq. Then R(p∗q)=R(p)TR(q)=IR(p^* q) = R(p)^{\mathsf T} R(q) = I, because RR of a product is the product of the matrices and R(p∗)=R(p)TR(p^*) = R(p)^{\mathsf T}. Write p∗q=(a,b)p^* q = (a, b) with b∈R3b \in \mathbb{R}^3. From the diagonal of R(a,b)=IR(a, b) = I and a2+∣b∣2=1a^2 + |b|^2 = 1 we get b12=b22=b32b_1^2 = b_2^2 = b_3^2 and 1−2(b22+b32)=11 - 2(b_2^2 + b_3^2) = 1, so b=0b = 0 and a=±1a = \pm 1. Hence q=±pq = \pm p. □\square

The ten identities

Lemma 2. Let qq be a unit quaternion and R=R(q)R = R(q), with t=r11+r22+r33t = r_{11} + r_{22} + r_{33}. Then

4w2=1+t,4x2=1+2r11−t,4y2=1+2r22−t,4z2=1+2r33−t,4w^2 = 1 + t, \quad 4x^2 = 1 + 2r_{11} - t, \quad 4y^2 = 1 + 2r_{22} - t, \quad 4z^2 = 1 + 2r_{33} - t,
4wx=r32−r23,4wy=r13−r31,4wz=r21−r12,4xy=r21+r12,4xz=r13+r31,4yz=r32+r23.4wx = r_{32} - r_{23}, \quad 4wy = r_{13} - r_{31}, \quad 4wz = r_{21} - r_{12}, \quad 4xy = r_{21} + r_{12}, \quad 4xz = r_{13} + r_{31}, \quad 4yz = r_{32} + r_{23}.

Proof. From the first form of R(q)R(q), t=3w2−x2−y2−z2=4w2−1t = 3w^2 - x^2 - y^2 - z^2 = 4w^2 - 1. Also r11=w2+x2−y2−z2r_{11} = w^2 + x^2 - y^2 - z^2, so 1+2r11−t=(w2+x2+y2+z2)+2(w2+x2−y2−z2)−(3w2−x2−y2−z2)=4x21 + 2r_{11} - t = (w^2 + x^2 + y^2 + z^2) + 2(w^2 + x^2 - y^2 - z^2) - (3w^2 - x^2 - y^2 - z^2) = 4x^2. The cases of yy and zz are the same with the indices moved. The six product identities come from the sums and the differences of the symmetric pairs of entries: for example r32−r23=2(yz+wx)−2(yz−wx)=4wxr_{32} - r_{23} = 2(yz + wx) - 2(yz - wx) = 4wx and r21+r12=2(xy+wz)+2(xy−wz)=4xyr_{21} + r_{12} = 2(xy + wz) + 2(xy - wz) = 4xy. □\square

Line L2 picks the largest square

Lemma 3. The index kk of line L2 is the index of a largest number among w2,x2,y2,z2w^2, x^2, y^2, z^2, and this number is at least 1/41/4.

Proof. By Lemma 2, 4w2−4x2=2(t−r11)4w^2 - 4x^2 = 2(t - r_{11}), 4x2−4y2=2(r11−r22)4x^2 - 4y^2 = 2(r_{11} - r_{22}), 4y2−4z2=2(r22−r33)4y^2 - 4z^2 = 2(r_{22} - r_{33}), and in the same way 4w2−4y2=2(t−r22)4w^2 - 4y^2 = 2(t - r_{22}), 4w2−4z2=2(t−r33)4w^2 - 4z^2 = 2(t - r_{33}) and 4x2−4z2=2(r11−r33)4x^2 - 4z^2 = 2(r_{11} - r_{33}). So the map (t,r11,r22,r33)↦(4w2,4x2,4y2,4z2)(t, r_{11}, r_{22}, r_{33}) \mapsto (4w^2, 4x^2, 4y^2, 4z^2) keeps the order of every pair, and the largest entry of one list has the same index as the largest entry of the other. The four squares sum to 1, so the largest is at least 1/41/4. □\square

The branch returns plus or minus q

Theorem. For every R∈SO(3)R \in SO(3), SHEPPERD returns a unit quaternion pp with R(p)=RR(p) = R and pw≥0p_w \ge 0.

Proof. Let qq be a unit quaternion with R(q)=RR(q) = R (Lemma 1), and let kk be the index of line L2. Write c0,c1,c2,c3c_0, c_1, c_2, c_3 for w,x,y,zw, x, y, z. Replace qq by −q-q if needed so that ck>0c_k > 0; this is possible because ck2≥1/4c_k^2 \ge 1/4 by Lemma 3. The branch of index kk computes 4ck2/2=∣ck∣=ck\sqrt{4c_k^2}/2 = |c_k| = c_k by the square identity of Lemma 2, and the radicand is at least 1, so the root is defined. It then divides three product sums by 4ck≥24c_k \ge 2, and by the product identities of Lemma 2 each quotient is 4ckcj/(4ck)=cj4c_k c_j / (4c_k) = c_j. So the branch returns exactly qq. Line L15 replaces qq by −q-q if w<0w < 0. In both cases the output pp is ±q\pm q, so it has length 1, R(p)=R(q)=RR(p) = R(q) = R, and pw≥0p_w \ge 0. □\square

Uniqueness. If the rotation angle is less than π\pi, then w=cos⁡θ2>0w = \cos\frac\theta2 > 0, and by Lemma 1 only one of ±q\pm q has w≥0w \ge 0. At the angle π\pi, w=0w = 0, and the output is the one of ±q\pm q whose component kk is positive.

Floating point

Let the entries of the input have absolute errors at most ε\varepsilon, with ε\varepsilon small, and ignore the rounding of the few operations of the method, which adds terms of the order of the unit roundoff uu. The selected square S=4ck2S = 4c_k^2 is a sum of four entries with coefficients ±1\pm 1 (for example 1+2r11−t=1+r11−r22−r331 + 2r_{11} - t = 1 + r_{11} - r_{22} - r_{33}), so its error is at most 3ε3\varepsilon. The derivative of S/2\sqrt S / 2 is 1/(4S)=1/(8ck)1/(4\sqrt S) = 1/(8c_k), and ck≥1/2c_k \ge 1/2, so the error of ckc_k is at most 3ε/43\varepsilon/4 to first order. Each other component is cj=N/(4ck)c_j = N/(4c_k), where the numerator NN has an error of at most 2ε2\varepsilon. To first order,

∣δcj∣≤∣δN∣4ck+∣cj∣ ∣δck∣ck≤2ε2+2⋅3ε4=5ε2.|\delta c_j| \le \frac{|\delta N|}{4c_k} + \frac{|c_j|\,|\delta c_k|}{c_k} \le \frac{2\varepsilon}{2} + 2 \cdot \frac{3\varepsilon}{4} = \frac{5\varepsilon}{2}.

So every component has an error of at most 52ε+O(u)\frac52\varepsilon + O(u), for every rotation.

For comparison, the formula that always uses k=0k = 0 has δw≤3ε/(8w)\delta w \le 3\varepsilon/(8w) and ∣δcj∣≈∣cj∣ δw/w|\delta c_j| \approx |c_j|\,\delta w / w, which is about 3ε/(8w2)3\varepsilon/(8w^2) when ∣cj∣|c_j| is close to 1. At the angle π−d\pi - d, w=sin⁡d2≈d/2w = \sin\frac d2 \approx d/2, so the error grows like 3ε/(2d2)3\varepsilon/(2d^2). With ε\varepsilon of the order of u≈1.1⋅10−16u \approx 1.1 \cdot 10^{-16}, this is the u/d2u/d^2 growth of the table on the page.

Complexity

The input has a fixed size, so time and space are Θ(1)\Theta(1). The method uses 3 comparisons, one square root, about 10 additions and 4 divisions (or one division and 3 multiplications). It uses no trigonometric function. The route through the logarithm map and the axis and angle needs an atan2, a sine and a cosine, and has its own branches near 00 and π\pi.

Properties

  • Accuracy. For a rotation matrix with rounding errors of the order of the unit roundoff uu in its entries, every output component has an absolute error of order uu, at every angle. The formula that divides by 4w4w has an error of order u/d2u / d^2 at the angle π−d\pi - d, as the table shows.
  • No special cases. No branch tests for the identity or for the angle π\pi. The rotations by π\pi about xx, yy and zz use the branches k=1,2,3k = 1, 2, 3, and the identity uses k=0k = 0.
  • Uniqueness. With line L15, the output is unique for every rotation by an angle less than π\pi. At the angle π\pi, w=0w = 0 and both qq and −q-q have w=0w = 0; the output is then the one with a positive component kk.
  • Continuity. All four branches compute the same qq in exact arithmetic, so the switch between branches does not make a jump. The only jump is the sign flip of line L15 at the angle π\pi, which no continuous choice can avoid.
  • Input that is not orthogonal. If RR is close to a rotation, the output is close to the quaternion of that rotation, but its length is not exactly 1. Normalize it if the length matters.

Variants and improvements

  • Normalization at the end. Divide qq by its length. This costs one more square root and makes the output a unit quaternion even when RR is slightly off SO(3).
  • The sign of a time series. For a sequence of rotations, as in a recorded trajectory, choose the sign of each quaternion so that its dot product with the previous one is positive, and not by w≥0w \ge 0. This keeps the sequence continuous, which spherical linear interpolation and filters need.
  • The eigenvector method. Build the 4 by 4 symmetric matrix of the Davenport q-method from RR and take the eigenvector of its largest eigenvalue. This gives the quaternion of a nearby rotation for a matrix that is far from orthogonal, at the cost of an eigenvalue problem.
  • Through the logarithm. Compute θω^\theta\hat\omega with the logarithm map of SO(3), then q=(cos⁡θ2,sin⁡θ2 ω^)q = (\cos\frac\theta2, \sin\frac\theta2\,\hat\omega). This needs trigonometric functions, and it must handle the angle π\pi with its own branch.
  • The JPL convention. Some attitude papers write the quaternion with the scalar last and with ij=−kij = -k. In that convention the signs of the three differences in lines L5, L8, L11 and L14 change. Convert at the interface, and do not mix the two.

When to use it

Use the method whenever a rotation matrix must become a quaternion: after forward kinematics, from the output of a camera pose or a point set alignment such as the Kabsch algorithm, or to store attitude in a filter state. It is the standard step before spherical linear interpolation, before an integration of the quaternion kinematic equation, and before rotation averaging methods that work on quaternions.

Pitfalls

  • The formula that divides by 4w4w. It is the first one in many books, and it is correct, but only for angles well below π\pi. Its error grows as u/d2u/d^2 near π−d\pi - d, and it divides by zero at π\pi. This is a loss of accuracy by cancellation in 1+t1 + t.
  • A transposed matrix. If RR maps world coordinates to body coordinates, the method returns the conjugate quaternion. Check which way the matrix maps before you convert.
  • Equal values in line L2. Ties are harmless: any branch with the largest square works, because its component is at least 1/21/2.
  • Comparing quaternions. Two correct results can differ in sign. Compare q1q_1 and q2q_2 by min⁡(∣q1−q2∣,∣q1+q2∣)\min(|q_1 - q_2|, |q_1 + q_2|), or compare the matrices.
  • A matrix that is not a rotation. A reflection (det⁡R=−1\det R = -1) also gives four numbers, but they mean nothing. Check det⁡R\det R when the input is not trusted.

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
shepperd_method.py 68 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shepperd-method/. The authors are listed in prov/DK6ZQE.jsonl.
"""Shepperd's method: the unit quaternion of a rotation matrix.

Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z),
and q acts on a vector v by (0, R v) = q (0, v) q*. For such a q,

    4 w^2 = 1 + t           4 w x = r32 - r23     4 x y = r21 + r12
    4 x^2 = 1 + 2 r11 - t   4 w y = r13 - r31     4 x z = r13 + r31
    4 y^2 = 1 + 2 r22 - t   4 w z = r21 - r12     4 y z = r32 + r23
    4 z^2 = 1 + 2 r33 - t

where t = r11 + r22 + r33 is the trace (indices from 1 in the comments,
from 0 in the code). The four squares sum to 4, so the largest one is at
least 1. Shepperd's method takes the square root of the largest one, and
gets the other three components from the off-diagonal sums and differences,
divided by four times that component, which is at least 2.

shepperd(R) is the method. quat_textbook(R) is the method that always
divides by 4 w; it is here to show the loss of accuracy near the angle pi.

Matrices are lists of rows. Vectors and quaternions are lists.
"""

import math


def shepperd(r):
    """Return the unit quaternion (w, x, y, z), with w >= 0, of the rotation r."""
    t = r[0][0] + r[1][1] + r[2][2]  # @line L1
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])  # @line L2
    if k == 0:  # @line L3
        w = math.sqrt(1.0 + t) / 2.0  # @line L4
        f = 4.0 * w
        q = [w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f]  # @line L5
    elif k == 1:  # @line L6
        x = math.sqrt(1.0 + 2.0 * r[0][0] - t) / 2.0  # @line L7
        f = 4.0 * x
        q = [(r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f]  # @line L8
    elif k == 2:  # @line L9
        y = math.sqrt(1.0 + 2.0 * r[1][1] - t) / 2.0  # @line L10
        f = 4.0 * y
        q = [(r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f]  # @line L11
    else:  # @line L12
        z = math.sqrt(1.0 + 2.0 * r[2][2] - t) / 2.0  # @line L13
        f = 4.0 * z
        q = [(r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z]  # @line L14
    if q[0] < 0.0:  # @line L15
        q = [-a for a in q]
    return q  # @line L16


def branch(r):
    """Return the index (0 for w, 1 for x, 2 for y, 3 for z) that line L2 picks."""
    t = r[0][0] + r[1][1] + r[2][2]
    return max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])


def quat_textbook(r):
    """Return the quaternion by the formula that always divides by 4 w.

    w = sqrt(1 + t) / 2, and x, y, z from the skew part. It fails at w = 0
    (a rotation by pi) and loses accuracy when w is small.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    w = math.sqrt(max(0.0, 1.0 + t)) / 2.0
    f = 4.0 * w
    return [w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f]
test_shepperd_method.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shepperd-method/. The authors are listed in prov/DK6ZQE.jsonl.
"""Tests of Shepperd's method.

The references are the shared helper rbm: quat_to_rot (quaternion to
matrix) for the round trip, and so3_log with quat_from_axis_angle as a
second, independent way from the matrix to the quaternion.
"""

import math
import random

import rbm
from shepperd_method import branch, quat_textbook, shepperd


def unit(rng, n=3):
    while True:
        v = [rng.gauss(0.0, 1.0) for _ in range(n)]
        s = math.sqrt(sum(x * x for x in v))
        if s > 1e-3:
            return [x / s for x in v]


def mdiff(a, b):
    return max(abs(a[i][j] - b[i][j]) for i in range(3) for j in range(3))


def qdiff(p, q):
    """Distance of two quaternions up to the sign, since q and -q agree."""
    return min(max(abs(a - b) for a, b in zip(p, q)), max(abs(a + b) for a, b in zip(p, q)))


def test_check_values():
    q = shepperd(rbm.rot_z(math.pi / 2.0))
    assert qdiff(q, [math.sqrt(0.5), 0.0, 0.0, math.sqrt(0.5)]) < 1e-15
    assert abs(q[0] - 0.70711) < 1e-5 and abs(q[3] - 0.70711) < 1e-5
    # The rotation by 2 pi / 3 about (1, 1, 1) / sqrt(3).
    q = shepperd([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
    assert q == [0.5, 0.5, 0.5, 0.5]
    # The rotation by pi about x: w = 0, and the x branch is used.
    r = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]]
    assert branch(r) == 1
    assert shepperd(r) == [0.0, 1.0, 0.0, 0.0]


def test_rotations_by_pi_about_each_axis():
    # The identity and the three half turns use the four branches.
    cases = [
        ([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], 0, [1.0, 0.0, 0.0, 0.0]),
        ([[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]], 1, [0.0, 1.0, 0.0, 0.0]),
        ([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]], 2, [0.0, 0.0, 1.0, 0.0]),
        ([[-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0]], 3, [0.0, 0.0, 0.0, 1.0]),
    ]
    for r, k, want in cases:
        assert branch(r) == k
        assert shepperd(r) == want


def test_all_four_branches_on_random_rotations():
    rng = random.Random(1)
    seen = [0, 0, 0, 0]
    for _ in range(2000):
        q0 = unit(rng, 4)
        r = rbm.quat_to_rot(q0)
        q = shepperd(r)
        seen[branch(r)] += 1
        assert abs(sum(a * a for a in q) - 1.0) < 1e-14
        assert q[0] >= 0.0
        assert qdiff(q, q0) < 1e-14
        assert mdiff(rbm.quat_to_rot(q), r) < 1e-14
    # Each branch is used for a fair share of uniform random rotations.
    assert min(seen) > 200


def test_branch_picks_the_largest_component():
    rng = random.Random(2)
    for _ in range(500):
        q0 = unit(rng, 4)
        k = branch(rbm.quat_to_rot(q0))
        # Ties are broken by rounding, so allow a tiny gap.
        assert abs(q0[k]) >= max(abs(a) for a in q0) - 1e-12
        assert abs(q0[k]) >= 0.5 - 1e-12


def test_against_log_and_axis_angle():
    rng = random.Random(3)
    for _ in range(300):
        axis = unit(rng)
        angle = rng.uniform(0.0, math.pi - 0.05)
        r = rbm.so3_exp([angle * a for a in axis])
        w = rbm.so3_log(r)
        th = math.sqrt(sum(x * x for x in w))
        ref = rbm.quat_from_axis_angle(w, th) if th > 0.0 else [1.0, 0.0, 0.0, 0.0]
        assert qdiff(shepperd(r), ref) < 1e-13


def test_half_turns_about_random_axes():
    rng = random.Random(4)
    for _ in range(300):
        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)]
        q = shepperd(r)
        assert qdiff(q, [0.0] + u) < 1e-15
        assert mdiff(rbm.quat_to_rot(q), r) < 1e-15


def test_near_pi_textbook_formula_fails():
    axis = [2.0 / 7.0, 3.0 / 7.0, 6.0 / 7.0]
    for d, bad in ((1e-3, 1e-10), (1e-5, 1e-7), (1e-7, 1e-3)):
        angle = math.pi - d
        r = rbm.so3_exp([angle * a for a in axis])
        ref = rbm.quat_from_axis_angle(axis, angle)
        assert qdiff(shepperd(r), ref) < 1e-15
        assert qdiff(quat_textbook(r), ref) > bad
    r = [[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]]
    try:
        quat_textbook(r)
    except ZeroDivisionError:
        pass
    else:
        raise AssertionError("the textbook formula should divide by zero at w = 0")


def test_matrix_with_small_error():
    # A rotation with entries rounded to 7 digits still gives a quaternion
    # within about 1e-7, and of length within 1e-6 of 1.
    rng = random.Random(5)
    for _ in range(200):
        q0 = unit(rng, 4)
        r = [[round(x, 7) for x in row] for row in rbm.quat_to_rot(q0)]
        q = shepperd(r)
        assert qdiff(q, q0) < 1e-6
        assert abs(math.sqrt(sum(a * a for a in q)) - 1.0) < 1e-6

History

Shepperd, at the Charles Stark Draper Laboratory, published the method in 1978 as a short engineering note in the Journal of Guidance and Control. The note gives the four candidate squares from the trace and the diagonal and selects the largest one to avoid a division by a small number. Lynch and Park (2017) print the formula that divides by 4w4w in Appendix B.3, together with the form of RR in terms of qq. Sola (2017) lists the conversions and compares the Hamilton and JPL conventions.

References

  1. S. W. Shepperd, Quaternion from rotation matrix, Journal of Guidance and Control 1(3), 223-224, 1978, the whole note (the four candidate squares from the trace and the diagonal, and the choice of the largest one)
  2. Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Appendix B, Section B.3 (unit quaternions, equations B.9 to B.12, with the formula that divides by 4 q0)
  3. Joan Sola, Quaternion kinematics for the error-state Kalman filter, 2017, Section 2.5 (rotation matrix and quaternion) and Section 3 (Hamilton and JPL conventions)

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