1个不稳定版本

0.2.0 2023年2月18日

#812 in 数学

Apache-2.0

53KB
1K SLoC

qrotate

qrotate crate提供了三维空间中点的3元素向量旋转的四元数表示。3元素向量可以使用Rust标准库类型,或来自ndarray crate的向量。





版权(c)2023 Steven Michael ([email protected])

概述


四元数旋转表示为乘法(*)操作,并可以应用于以下3D向量的表示,其中T是一个模板参数,匹配浮点类型,f32f64


[T; 3] 3元素固定大小数组
&[T; 3] 3元素固定大小数组的引用
&[T] 包含3个元素的切片
std::vec::Vec<T> 包含3个元素的标准库向量
&std::vec::Vec<T> 包含3个元素的标准库向量的引用
ndarray::Array1<'a, T> ndarray crate中从1D数组(启用ndarray功能)
ndarray::ArrayView1<'a, T> ndarray crate中1D数组的视图(启用ndarray功能)

四元数也可以通过乘法运算符(*)与其他四元数相乘,以表示旋转的连接。

上述操作也被定义为在通过四元数的引用使用时工作。

注意:此四元数表示使用“常规”四元数定义,当从轴和角度构建时,定义了围绕给定轴按给定角度的右手向量旋转。





示例


简单旋转

绕z轴旋转π/2的x轴单位向量

use std::f64::consts::PI;
let xhat = [1.0, 0.0, 0.0];
let yhat = qrotate::Quaternion::<f64>>rotz(PI / 2.0) * xhat
// yhat = [0.0, 1.0, 0.0];

连接旋转

首先绕z轴旋转π/2,然后绕y轴旋转π/3的x轴单位向量

use std::f64::consts::PI;
let xhat = [1.0, 0.0, 0.0];
let q1 = qrotate::Quaternion::<f64>::rotz(PI / 2.0);
let q2 = qrotate::Quaternion::<f64>::roty(PI / 3.0);
let result q2 * q1 * xhat

找到旋转两个向量的四元数

找到从xhat向量旋转到yhat向量的四元数

let xhat = [1.0, 0.0, 0.0];
let yhat = [0.0, 1.0, 0.0];
let q = qrotation::qv1tov2(&xhat, &yhat);

方向余弦矩阵

将四元数表示为方向余弦矩阵(DCM),它左乘向量以执行旋转,或表示为右乘2D(Nx3)列矩阵以执行旋转的方向余弦矩阵

use std::f64::consts::PI;
let q = qrotate::Quaternion::<f64>::rotz(PI / 2.0);

// get [[f64; 3]; 3] representation of quaternion as DCM
// that left-multiples row vector
let dcm = q.ldcm();

// Same thing, excpet DCM as ndarray::Array2<f64> 
let dcm_ndarr = q.ldcm_ndarr();

// Same thing, except DCM as ndarray::Array2<f64>
// that right-multiplies column vector
let dcm_ndarr = q.rdcm_ndarr();

将方向余弦矩阵(DCM)转换为四元数

use std::f64::consts::PI;
let q = qrotate::Quaternion::<f64>::rotz(PI / 2.0);

// get [[f64; 3]; 3] representation of quaternion as DCM
// that left-multiples row vector
let dcm = q.ldcm();

// Convert back to quaternion
let q2 = Quaternion::<f64>::from_ldcm(dcm);

轴,角度

将四元数转换为旋转轴和角度表示,以及反向转换

// Construct quaternion representing rotation about zhat axis by PI/2
let zhat = [0.0, 1.0, 0.0]
let theta = std::f64::consts::PI / 2.0;
let q = Quaternion::<f64>::from_axis_angle(zhat, theta);
// Result is same as zhat
let axis: [f64; 3] = q.axis();
// result is PI / 2.0
let angle: f64 = q.angle();

其他操作

以下是一些杂项操作

// Construct identity quaternion (no rotation)
let mut q = Quaternion::<f64>::identity();

// now rotate about y axis
q = Quaternion::<f64>::qroty(0.1) * q;

// Get conjugate
let qc = q.conjugate();

// Get quaternion norm (should be 1.0 most of the time)
let n = q.norm();

// Scale quaternion
q = q * 2.0;

// Get normalized version of quaternion
let qn = q.normalized();

// Normalize quaternion in place
q.normalize();

// Get vector elements of quaternion
let v: [f64; 3] = q.vector();

// Get scalar elements of quaternion
let w: f64 = q.scalar();

Python 绑定

通过启用 python 功能,该软件包还可以编译为 Python 库。该库提供了一个 "Quaternion" 类,可用于旋转 3 元素 NumPy 向量(以及 Nx3 NumPy "矩阵" 的每个元素)。上述许多函数在 Python 中也都有提供

依赖项

~1.3–7.5MB
~45K SLoC