testLieGroupEKF.cpp
Go to the documentation of this file.
1 /* ----------------------------------------------------------------------------
2  * GTSAM Copyright 2010, Georgia Tech Research Corporation,
3  * Atlanta, Georgia 30332-0415
4  * All Rights Reserved
5  * Authors: Frank Dellaert, et al. (see THANKS for the full author list)
6  *
7  * See LICENSE for the license information
8  * -------------------------------------------------------------------------- */
9 
18 #include <gtsam/base/Testable.h>
20 #include <gtsam/geometry/Rot3.h>
23 
24 using namespace gtsam;
25 
26 // Duplicate the dynamics function in GEKF_Rot3Example
27 namespace exampleSO3 {
28  static constexpr double k = 0.5;
30  // φ = Logmap(R), Dφ = ∂φ/∂δR
31  Matrix3 D_phi;
32  Vector3 phi = Rot3::Logmap(X, D_phi);
33  // zero out yaw
34  phi[2] = 0.0;
35  D_phi.row(2).setZero();
36 
37  if (H) *H = -k * D_phi; // ∂(–kφ)/∂δR
38  return -k * phi; // xi ∈ 𝔰𝔬(3)
39  }
40 } // namespace exampleSO3
41 
42 TEST(GroupeEKF, DynamicsJacobian) {
43  // Construct a nontrivial state and IMU input
44  Rot3 R = Rot3::RzRyRx(0.1, -0.2, 0.3);
45 
46  // Analytic Jacobian
47  Matrix3 actualH;
48  exampleSO3::dynamics(R, actualH);
49 
50  // Numeric Jacobian w.r.t. the state X
51  auto f = [&](const Rot3& X_) { return exampleSO3::dynamics(X_); };
52  Matrix3 expectedH = numericalDerivative11<Vector3, Rot3>(f, R);
53 
54  // Compare
55  EXPECT(assert_equal(expectedH, actualH));
56 }
57 
58 TEST(GroupeEKF, PredictNumericState) {
59  // GIVEN
60  Rot3 R0 = Rot3::RzRyRx(0.2, -0.1, 0.3);
61  Matrix3 P0 = Matrix3::Identity() * 0.2;
62  double dt = 0.1;
63 
64  // Analytic Jacobian
65  Matrix3 actualH;
66  LieGroupEKF<Rot3> ekf0(R0, P0);
67  ekf0.predictMean(exampleSO3::dynamics, dt, actualH);
68 
69  // wrap predict into a state->state functor (mapping on SO(3))
70  auto g = [&](const Rot3& R) -> Rot3 {
71  LieGroupEKF<Rot3> ekf(R, P0);
72  return ekf.predictMean(exampleSO3::dynamics, dt);
73  };
74 
75  // numeric Jacobian of g at R0
76  Matrix3 expectedH = numericalDerivative11<Rot3, Rot3>(g, R0);
77 
78  EXPECT(assert_equal(expectedH, actualH));
79 }
80 
81 TEST(GroupeEKF, StateAndControl) {
82  auto f = [](const Rot3& X, const Vector2& dummy_u,
84  return exampleSO3::dynamics(X, H);
85  };
86 
87  // GIVEN
88  Rot3 R0 = Rot3::RzRyRx(0.2, -0.1, 0.3);
89  Matrix3 P0 = Matrix3::Identity() * 0.2;
90  Vector2 dummy_u(1, 2);
91  double dt = 0.1;
92  Matrix3 Q = Matrix3::Zero();
93 
94  // Analytic Jacobian
95  Matrix3 actualH;
96  LieGroupEKF<Rot3> ekf0(R0, P0);
97  ekf0.predictMean(f, dummy_u, dt, actualH);
98 
99  // wrap predict into a state->state functor (mapping on SO(3))
100  auto g = [&](const Rot3& R) -> Rot3 {
101  LieGroupEKF<Rot3> ekf(R, P0);
102  return ekf.predictMean(f, dummy_u, dt, Q);
103  };
104 
105  // numeric Jacobian of g at R0
106  Matrix3 expectedH = numericalDerivative11<Rot3, Rot3>(g, R0);
107 
108  EXPECT(assert_equal(expectedH, actualH));
109 }
110 
111 // Namespace for dynamic Matrix LieGroupEKF test
113  // Constant tangent vector for dynamics (same as "velocityTangent" in IEKF test)
114  const Vector kFixedVelocityTangent = (Vector(4) << 0.5, 0.1, -0.1, -0.5).finished();
115 
116  // Dynamics function: xi = f(X, H_X)
117  // Returns a constant tangent vector, so Df_DX = 0.
118  // H_X is D(xi)/D(X_local), where X_local is the tangent space perturbation of X.
120  if (H_X) {
121  size_t state_dim = X.size();
122  size_t tangent_dim = kFixedVelocityTangent.size();
123  // Ensure Jacobian dimensions are consistent even if state or tangent is 0-dim
124  H_X->setZero(tangent_dim, state_dim);
125  }
126  return kFixedVelocityTangent;
127  }
128 
129  // Measurement function h(X, H)
130  double h(const Matrix& p, OptionalJacobian<-1, -1> H = {}) {
131  // Specialized for a 2x2 matrix!
132  if (p.rows() != 2 || p.cols() != 2) {
133  throw std::invalid_argument("Matrix must be 2x2.");
134  }
135  if (H) {
136  H->resize(1, p.size());
137  *H << 1.0, 0.0, 0.0, 1.0; // d(trace)/dp00, d(trace)/dp01, d(trace)/dp10, d(trace)/dp11
138  }
139  return p(0, 0) + p(1, 1); // Trace of the matrix
140  }
141 } // namespace exampleLieGroupDynamicMatrix
142 
143 TEST(LieGroupEKF_DynamicMatrix, PredictAndUpdate) {
144  // --- Setup ---
145  Matrix p0Matrix = (Matrix(2, 2) << 1.0, 2.0, 3.0, 4.0).finished();
146  Matrix p0Covariance = I_4x4 * 0.01;
147  double dt = 0.1;
148  Matrix process_noise_Q = I_4x4 * 0.001;
149  Matrix measurement_noise_R = Matrix::Identity(1, 1) * 0.005;
150 
151  LieGroupEKF<Matrix> ekf(p0Matrix, p0Covariance);
152  EXPECT_LONGS_EQUAL(4, ekf.state().size());
153  EXPECT_LONGS_EQUAL(4, ekf.dimension());
154 
155  // --- Predict ---
156  // ekf.predict takes f(X, H_X), dt, process_noise_Q
157  ekf.predict(exampleLieGroupDynamicMatrix::f, dt, process_noise_Q);
158 
159  // Verification for Predict
160  // For f, Df_DXk = 0 (Jacobian of xi w.r.t X_local is Zero).
161  // State transition Jacobian A = Ad_Uinv + Dexp * Df_DXk * dt.
162  // For Matrix (VectorSpace): Ad_Uinv = I, Dexp = I.
163  // So, A = I + I * 0 * dt = I.
164  // Covariance update: P_next = A * P_current * A.transpose() + Q = I * P_current * I + Q = P_current + Q.
166  Matrix pCovariancePredictedExpected = p0Covariance + process_noise_Q;
167 
168  EXPECT(assert_equal(pPredictedExpected, ekf.state(), 1e-9));
169  EXPECT(assert_equal(pCovariancePredictedExpected, ekf.covariance(), 1e-9));
170 
171  // --- Update ---
172  Matrix pStateBeforeUpdate = ekf.state();
173  Matrix pCovarianceBeforeUpdate = ekf.covariance();
174 
175  double zTrue = exampleLieGroupDynamicMatrix::h(pStateBeforeUpdate);
176  double zObserved = zTrue - 0.03; // Simulated measurement with some error
177 
178  ekf.update(exampleLieGroupDynamicMatrix::h, zObserved, measurement_noise_R);
179 
180  // Verification for Update (Manual Kalman Steps)
181  Matrix H_update(1, 4); // Measurement Jacobian: 1x4 for 2x2 matrix, trace measurement
182  double zPredictionManual = exampleLieGroupDynamicMatrix::h(pStateBeforeUpdate, H_update);
183  // Innovation: y_tangent = traits<Measurement>::Local(prediction, observation)
184  // For double (scalar), Local(A,B) is B-A.
185  double innovationY_tangent = zObserved - zPredictionManual;
186  Matrix S_innovation_cov = H_update * pCovarianceBeforeUpdate * H_update.transpose() + measurement_noise_R;
187  Matrix K_gain = pCovarianceBeforeUpdate * H_update.transpose() * S_innovation_cov.inverse();
188  Vector deltaXiTangent = K_gain * innovationY_tangent; // Tangent space correction for Matrix state
189  Matrix pUpdatedExpected = traits<Matrix>::Retract(pStateBeforeUpdate, deltaXiTangent);
190  Matrix I_KH = I_4x4 - K_gain * H_update; // I_4x4 because state dimension is 4
191  Matrix pUpdatedCovarianceExpected = I_KH * pCovarianceBeforeUpdate * I_KH.transpose() + K_gain * measurement_noise_R * K_gain.transpose();
192 
193  EXPECT(assert_equal(pUpdatedExpected, ekf.state(), 1e-9));
194  EXPECT(assert_equal(pUpdatedCovarianceExpected, ekf.covariance(), 1e-9));
195 }
196 
197 int main() {
198  TestResult tr;
199  return TestRegistry::runAllTests(tr);
200 }
gtsam::OptionalJacobian< Eigen::Dynamic, Eigen::Dynamic >
Definition: OptionalJacobian.h:189
TestRegistry::runAllTests
static int runAllTests(TestResult &result)
Definition: TestRegistry.cpp:27
gtsam::LieGroupEKF::predictMean
G predictMean(Dynamics &&f, double dt, OptionalJacobian< Dim, Dim > A={}) const
Definition: LieGroupEKF.h:92
H
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy y set format x g set format y g set format x2 g set format y2 g set format z g set angles radians set nogrid set key title set key left top Right noreverse box linetype linewidth samplen spacing width set nolabel set noarrow set nologscale set logscale x set set pointsize set encoding default set nopolar set noparametric set set set set surface set nocontour set clabel set mapping cartesian set nohidden3d set cntrparam order set cntrparam linear set cntrparam levels auto set cntrparam points set size set set xzeroaxis lt lw set x2zeroaxis lt lw set yzeroaxis lt lw set y2zeroaxis lt lw set tics in set ticslevel set tics set mxtics default set mytics default set mx2tics default set my2tics default set xtics border mirror norotate autofreq set ytics border mirror norotate autofreq set ztics border nomirror norotate autofreq set nox2tics set noy2tics set timestamp bottom norotate set rrange[*:*] noreverse nowriteback set trange[*:*] noreverse nowriteback set urange[*:*] noreverse nowriteback set vrange[*:*] noreverse nowriteback set xlabel matrix size set x2label set timefmt d m y n H
Definition: gnuplot_common_settings.hh:74
e
Array< double, 1, 3 > e(1./3., 0.5, 2.)
EXPECT_LONGS_EQUAL
#define EXPECT_LONGS_EQUAL(expected, actual)
Definition: Test.h:154
Testable.h
Concept check for values that can be used in unit tests.
EXPECT
#define EXPECT(condition)
Definition: Test.h:150
TestHarness.h
exampleSO3
Definition: testLieGroupEKF.cpp:27
dt
const double dt
Definition: testVelocityConstraint.cpp:15
exampleLieGroupDynamicMatrix::kFixedVelocityTangent
const Vector kFixedVelocityTangent
Definition: testLieGroupEKF.cpp:114
gtsam::Matrix
Eigen::MatrixXd Matrix
Definition: base/Matrix.h:39
X
#define X
Definition: icosphere.cpp:20
gtsam::Vector3
Eigen::Vector3d Vector3
Definition: Vector.h:44
h
const double h
Definition: testSimpleHelicopter.cpp:19
gtsam::Vector
Eigen::VectorXd Vector
Definition: Vector.h:39
Rot3.h
3D rotation represented as a rotation matrix or quaternion
LieGroupEKF.h
Extended Kalman Filter derived class for Lie groups G.
simple::R0
static Rot3 R0
Definition: testInitializePose3.cpp:48
exampleLieGroupDynamicMatrix
Definition: testLieGroupEKF.cpp:112
numericalDerivative.h
Some functions to compute numerical derivatives.
gtsam::ManifoldEKF< G >::covariance
const Covariance & covariance() const
Definition: ManifoldEKF.h:111
gtsam::LieGroupEKF
Extended Kalman Filter on a Lie group G, derived from ManifoldEKF.
Definition: LieGroupEKF.h:49
gtsam::Rot3
Rot3 is a 3D rotation represented as a rotation matrix if the preprocessor symbol GTSAM_USE_QUATERNIO...
Definition: Rot3.h:58
gtsam::ManifoldEKF< G >::state
const G & state() const
Definition: ManifoldEKF.h:108
dynamics
Vector9 dynamics(const Vector6 &imu)
Left-invariant dynamics for NavState.
Definition: IEKF_NavstateExample.cpp:35
NavState.h
Navigation state composing of attitude, position, and velocity.
gtsam::LieGroupEKF::predict
void predict(Dynamics &&f, double dt, const Covariance &Q)
Definition: LieGroupEKF.h:129
gtsam::ManifoldEKF< G >::dimension
int dimension() const
Definition: ManifoldEKF.h:114
Vector2
Definition: test_operator_overloading.cpp:18
gtsam::ManifoldEKF< G >::update
void update(const Measurement &prediction, const Eigen::Matrix< double, traits< Measurement >::dimension, Dim > &H, const Measurement &z, const Eigen::Matrix< double, traits< Measurement >::dimension, traits< Measurement >::dimension > &R)
Definition: ManifoldEKF.h:152
g
void g(const string &key, int i)
Definition: testBTree.cpp:41
TestResult
Definition: TestResult.h:26
Eigen::Quaternion
The quaternion class used to represent 3D orientations and rotations.
Definition: ForwardDeclarations.h:293
gtsam
traits
Definition: ABC.h:17
gtsam::TEST
TEST(SmartFactorBase, Pinhole)
Definition: testSmartFactorBase.cpp:38
gtsam::traits
Definition: Group.h:36
gtsam::OptionalJacobian
Definition: OptionalJacobian.h:38
p
float * p
Definition: Tutorial_Map_using.cpp:9
gtsam::assert_equal
bool assert_equal(const Matrix &expected, const Matrix &actual, double tol)
Definition: Matrix.cpp:41
gtsam::Rot3::Logmap
static Vector3 Logmap(const Rot3 &R, OptionalJacobian< 3, 3 > H={})
Definition: Rot3M.cpp:161
exampleLieGroupDynamicMatrix::f
Vector f(const Matrix &X, OptionalJacobian< Eigen::Dynamic, Eigen::Dynamic > H_X={})
Definition: testLieGroupEKF.cpp:119
exampleLieGroupDynamicMatrix::h
double h(const Matrix &p, OptionalJacobian<-1, -1 > H={})
Definition: testLieGroupEKF.cpp:130
exampleSO3::dynamics
Vector3 dynamics(const Rot3 &X, OptionalJacobian< 3, 3 > H={})
Definition: testLieGroupEKF.cpp:29
P0
static double P0[5]
Definition: ndtri.c:59
gtsam::Rot3::RzRyRx
static Rot3 RzRyRx(double x, double y, double z, OptionalJacobian< 3, 1 > Hx={}, OptionalJacobian< 3, 1 > Hy={}, OptionalJacobian< 3, 1 > Hz={})
Rotations around Z, Y, then X axes as in http://en.wikipedia.org/wiki/Rotation_matrix,...
Definition: Rot3M.cpp:84
R
Rot2 R(Rot2::fromAngle(0.1))
main
int main()
Definition: testLieGroupEKF.cpp:197
k
static constexpr double k
Definition: GEKF_Rot3Example.cpp:31


gtsam
Author(s):
autogenerated on Wed May 28 2025 03:06:45