Skip to main content

tiny_solver/manifold/
so3.rs

1use std::{num::NonZero, ops::Mul};
2
3use nalgebra as na;
4
5use super::{AutoDiffManifold, Manifold};
6
7pub struct SO3<T: na::RealField> {
8    qx: T,
9    qy: T,
10    qz: T,
11    qw: T,
12}
13
14impl<T: na::RealField> SO3<T> {
15    /// [x, y, z, w]
16    pub fn from_vec(xyzw: na::DVectorView<T>) -> Self {
17        SO3 {
18            qx: xyzw[0].clone(),
19            qy: xyzw[1].clone(),
20            qz: xyzw[2].clone(),
21            qw: xyzw[3].clone(),
22        }
23    }
24    pub fn from_xyzw(x: T, y: T, z: T, w: T) -> Self {
25        SO3 {
26            qx: x,
27            qy: y,
28            qz: z,
29            qw: w,
30        }
31    }
32    pub fn identity() -> Self {
33        SO3 {
34            qx: T::zero(),
35            qy: T::zero(),
36            qz: T::zero(),
37            qw: T::one(),
38        }
39    }
40
41    pub fn exp(xi: na::DVectorView<T>) -> Self {
42        let mut xyzw = na::Vector4::zeros();
43
44        let theta2 = xi.norm_squared();
45
46        if theta2 < T::from_f64(1e-6).unwrap() {
47            // Taylor series of cos(theta / 2) and sin(theta / 2) / theta. Below this
48            // threshold, the next terms are under f64 precision.
49            let theta4 = theta2.clone() * theta2.clone();
50            xyzw.w = T::one() - theta2.clone() / T::from_f64(8.0).unwrap()
51                + theta4.clone() / T::from_f64(384.0).unwrap();
52            let tmp = T::from_f64(0.5).unwrap() - theta2 / T::from_f64(48.0).unwrap()
53                + theta4 / T::from_f64(3840.0).unwrap();
54            xyzw.x = xi[0].clone() * tmp.clone();
55            xyzw.y = xi[1].clone() * tmp.clone();
56            xyzw.z = xi[2].clone() * tmp;
57        } else {
58            let theta = theta2.sqrt();
59            let half_theta = theta.clone() * T::from_f64(0.5).unwrap();
60            xyzw.w = half_theta.clone().cos();
61
62            let omega = xi / theta;
63            // Not sqrt(1 - w^2): that drops the sign of sin(theta / 2) above 2 pi.
64            let sin_theta_half = half_theta.sin();
65            xyzw.x = omega[0].clone() * sin_theta_half.clone();
66            xyzw.y = omega[1].clone() * sin_theta_half.clone();
67            xyzw.z = omega[2].clone() * sin_theta_half;
68        }
69
70        SO3::from_vec(xyzw.as_view())
71    }
72
73    pub fn log(&self) -> na::DVector<T> {
74        const EPS: f64 = 1e-6;
75        let ivec = na::dvector![self.qx.clone(), self.qy.clone(), self.qz.clone()];
76
77        let squared_n = ivec.norm_squared();
78        let w = self.qw.clone();
79
80        let near_zero = squared_n.le(&T::from_f64(EPS * EPS).unwrap());
81
82        let w_sq = w.clone() * w.clone();
83        let t0 = T::from_f64(2.0).unwrap() / w.clone()
84            - T::from_f64(2.0 / 3.0).unwrap() * squared_n.clone() / (w_sq * w.clone());
85
86        let n = squared_n.sqrt();
87
88        let sign = T::from_f64(-1.0)
89            .unwrap()
90            .select(w.le(&T::zero()), T::one());
91        let atan_nbyw = sign.clone() * n.clone().atan2(sign * w);
92
93        let t = T::from_f64(2.0).unwrap() * atan_nbyw / n;
94
95        let two_atan_nbyd_by_n = t0.select(near_zero, t);
96
97        ivec * two_atan_nbyd_by_n
98    }
99
100    pub fn hat(xi: na::VectorView3<T>) -> na::Matrix3<T> {
101        let mut xi_hat = na::Matrix3::zeros();
102        xi_hat[(0, 1)] = -xi[2].clone();
103        xi_hat[(0, 2)] = xi[1].clone();
104        xi_hat[(1, 0)] = xi[2].clone();
105        xi_hat[(1, 2)] = -xi[0].clone();
106        xi_hat[(2, 0)] = -xi[1].clone();
107        xi_hat[(2, 1)] = xi[0].clone();
108
109        xi_hat
110    }
111
112    pub fn to_vec(&self) -> na::Vector4<T> {
113        na::Vector4::new(
114            self.qx.clone(),
115            self.qy.clone(),
116            self.qz.clone(),
117            self.qw.clone(),
118        )
119    }
120    pub fn to_dvec(&self) -> na::DVector<T> {
121        na::dvector![
122            self.qx.clone(),
123            self.qy.clone(),
124            self.qz.clone(),
125            self.qw.clone(),
126        ]
127    }
128    pub fn cast<U: na::RealField + simba::scalar::SupersetOf<T>>(&self) -> SO3<U> {
129        SO3::from_vec(self.to_vec().cast().as_view())
130    }
131    pub fn inverse(&self) -> Self {
132        SO3 {
133            qx: -self.qx.clone(),
134            qy: -self.qy.clone(),
135            qz: -self.qz.clone(),
136            qw: self.qw.clone(),
137        }
138    }
139    pub fn compose(&self, rhs: &Self) -> Self {
140        let x0 = self.qx.clone();
141        let y0 = self.qy.clone();
142        let z0 = self.qz.clone();
143        let w0 = self.qw.clone();
144
145        let x1 = rhs.qx.clone();
146        let y1 = rhs.qy.clone();
147        let z1 = rhs.qz.clone();
148        let w1 = rhs.qw.clone();
149
150        // Compute the product of the two quaternions, term by term
151        let qx = w0.clone() * x1.clone() + x0.clone() * w1.clone() + y0.clone() * z1.clone()
152            - z0.clone() * y1.clone();
153        let qy = w0.clone() * y1.clone() - x0.clone() * z1.clone()
154            + y0.clone() * w1.clone()
155            + z0.clone() * x1.clone();
156        let qz = w0.clone() * z1.clone() + x0.clone() * y1.clone() - y0.clone() * x1.clone()
157            + z0.clone() * w1.clone();
158        let qw = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
159        // println!("q {}", self.to_vec());
160        SO3 { qx, qy, qz, qw }
161    }
162}
163
164impl<T: na::RealField> Mul for SO3<T> {
165    type Output = Self;
166
167    fn mul(self, rhs: Self) -> Self::Output {
168        self.compose(&rhs)
169    }
170}
171impl<T: na::RealField> Mul for &SO3<T> {
172    type Output = SO3<T>;
173
174    fn mul(self, rhs: Self) -> Self::Output {
175        self.compose(rhs)
176    }
177}
178
179impl<T: na::RealField> Mul<na::VectorView3<'_, T>> for &SO3<T> {
180    type Output = na::Vector3<T>;
181
182    fn mul(self, rhs: na::VectorView3<'_, T>) -> Self::Output {
183        let qv = SO3::from_xyzw(rhs[0].clone(), rhs[1].clone(), rhs[2].clone(), T::zero());
184        let inv = self.inverse();
185        let v_rot: SO3<T> = (self * &qv) * inv;
186        na::Vector3::new(v_rot.qx, v_rot.qy, v_rot.qz)
187    }
188}
189
190#[derive(Debug, Clone)]
191pub struct QuaternionManifold;
192impl<T: na::RealField> AutoDiffManifold<T> for QuaternionManifold {
193    fn plus(
194        &self,
195        x: nalgebra::DVectorView<T>,
196        delta: nalgebra::DVectorView<T>,
197    ) -> nalgebra::DVector<T> {
198        let d: SO3<T> = SO3::exp(delta);
199        let x_s03: SO3<T> = SO3::from_xyzw(x[0].clone(), x[1].clone(), x[2].clone(), x[3].clone());
200        let x_plus = x_s03 * d;
201        na::dvector![
202            x_plus.qx.clone(),
203            x_plus.qy.clone(),
204            x_plus.qz.clone(),
205            x_plus.qw.clone(),
206        ]
207    }
208
209    fn minus(
210        &self,
211        y: nalgebra::DVectorView<T>,
212        x: nalgebra::DVectorView<T>,
213    ) -> nalgebra::DVector<T> {
214        let y_so3 = SO3::from_vec(y);
215        let x_so3_inv = SO3::from_vec(x).inverse();
216        let x_inv_y_log = (x_so3_inv * y_so3).log();
217        na::dvector![
218            x_inv_y_log[0].clone(),
219            x_inv_y_log[1].clone(),
220            x_inv_y_log[2].clone()
221        ]
222    }
223}
224impl Manifold for QuaternionManifold {
225    fn tangent_size(&self) -> NonZero<usize> {
226        NonZero::new(3).unwrap()
227    }
228}