trajopt
 All Classes Namespaces Files Functions Variables Typedefs Pages
quat_ops.hpp
1 #pragma once
2 #include <Eigen/Dense>
3 using namespace Eigen;
4 
5 
6 inline Vector4d quatMult(const Vector4d& q1, const Vector4d& q2) {
7  return Vector4d(
8  q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3],
9  q1[0] * q2[1] + q1[1] * q2[0] + q1[2] * q2[3] - q1[3] * q2[2],
10  q1[0] * q2[2] + q1[2] * q2[0] + q1[3] * q2[1] - q1[1] * q2[3],
11  q1[0] * q2[3] + q1[3] * q2[0] + q1[1] * q2[2] - q1[2] * q2[1]);
12 }
13 
14 inline Vector4d quatExp(const Vector3d& r) {
15  // see http://www.lce.hut.fi/~ssarkka/pub/quat.pdf
16  double normr = r.norm();
17  if (normr > 1e-10) {
18  Vector4d q;
19  q(0) = cos(normr / 2);
20  q.bottomRows(3) = (r/normr) * sin(normr/2);
21  return q;
22  }
23  else {
24  Vector4d out(1,0,0,0);
25  out.bottomRows(3) += r;
26  out.normalize();
27  return out;
28  }
29 }
30 
31 inline Vector3d quatLog(const Vector4d& q) {
32  if (1-q[0] >= 1e-10) {
33  Vector3d v = q.bottomRows(3);
34  double s = q(0);
35  Vector3d out = (acos(s) / v.norm()) * v;
36  return out;
37  }
38  else {
39  return 2*q.bottomRows(3);
40  }
41 }
42 
43 inline Vector4d quatInv(const Vector4d& q) {
44  Vector4d qinv = q;
45  qinv.bottomRows(3) *= -1;
46  return qinv;
47 }
48 
49 
50 inline VectorXd quatRotate(const Vector4d& q, const Vector3d& p) {
51  Vector4d pquat;
52  pquat(0) = 0;
53  pquat.bottomRows(3) = p;
54  return quatMult(q, quatMult(pquat, quatInv(q)));
55 }