LocalizationExample.cpp
Go to the documentation of this file.
1 /* ----------------------------------------------------------------------------
2 
3  * GTSAM Copyright 2010, Georgia Tech Research Corporation,
4  * Atlanta, Georgia 30332-0415
5  * All Rights Reserved
6  * Authors: Frank Dellaert, et al. (see THANKS for the full author list)
7 
8  * See LICENSE for the license information
9 
10  * -------------------------------------------------------------------------- */
11 
26 // We will use Pose2 variables (x, y, theta) to represent the robot positions
27 #include <gtsam/geometry/Pose2.h>
28 
29 // We will use simple integer Keys to refer to the robot poses.
30 #include <gtsam/inference/Key.h>
31 
32 // As in OdometryExample.cpp, we use a BetweenFactor to model odometry measurements.
34 
35 // We add all facors to a Nonlinear Factor Graph, as our factors are nonlinear.
37 
38 // The nonlinear solvers within GTSAM are iterative solvers, meaning they linearize the
39 // nonlinear functions around an initial linearization point, then solve the linear system
40 // to update the linearization point. This happens repeatedly until the solver converges
41 // to a consistent set of variable values. This requires us to specify an initial guess
42 // for each variable, held in a Values container.
43 #include <gtsam/nonlinear/Values.h>
44 
45 // Finally, once all of the factors have been added to our factor graph, we will want to
46 // solve/optimize to graph to find the best (Maximum A Posteriori) set of variable values.
47 // GTSAM includes several nonlinear optimizers to perform this step. Here we will use the
48 // standard Levenberg-Marquardt solver
50 
51 // Once the optimized values have been calculated, we can also calculate the marginal covariance
52 // of desired variables
54 
55 using namespace std;
56 using namespace gtsam;
57 
58 // Before we begin the example, we must create a custom unary factor to implement a
59 // "GPS-like" functionality. Because standard GPS measurements provide information
60 // only on the position, and not on the orientation, we cannot use a simple prior to
61 // properly model this measurement.
62 //
63 // The factor will be a unary factor, affect only a single system variable. It will
64 // also use a standard Gaussian noise model. Hence, we will derive our new factor from
65 // the NoiseModelFactor1.
67 
68 class UnaryFactor: public NoiseModelFactor1<Pose2> {
69  // The factor will hold a measurement consisting of an (X,Y) location
70  // We could this with a Point2 but here we just use two doubles
71  double mx_, my_;
72 
73  public:
75  typedef boost::shared_ptr<UnaryFactor> shared_ptr;
76 
77  // The constructor requires the variable key, the (X, Y) measurement value, and the noise model
78  UnaryFactor(Key j, double x, double y, const SharedNoiseModel& model):
79  NoiseModelFactor1<Pose2>(model, j), mx_(x), my_(y) {}
80 
81  ~UnaryFactor() override {}
82 
83  // Using the NoiseModelFactor1 base class there are two functions that must be overridden.
84  // The first is the 'evaluateError' function. This function implements the desired measurement
85  // function, returning a vector of errors when evaluated at the provided variable value. It
86  // must also calculate the Jacobians for this measurement function, if requested.
87  Vector evaluateError(const Pose2& q, boost::optional<Matrix&> H = boost::none) const override {
88  // The measurement function for a GPS-like measurement h(q) which predicts the measurement (m) is h(q) = q, q = [qx qy qtheta]
89  // The error is then simply calculated as E(q) = h(q) - m:
90  // error_x = q.x - mx
91  // error_y = q.y - my
92  // Node's orientation reflects in the Jacobian, in tangent space this is equal to the right-hand rule rotation matrix
93  // H = [ cos(q.theta) -sin(q.theta) 0 ]
94  // [ sin(q.theta) cos(q.theta) 0 ]
95  const Rot2& R = q.rotation();
96  if (H) (*H) = (gtsam::Matrix(2, 3) << R.c(), -R.s(), 0.0, R.s(), R.c(), 0.0).finished();
97  return (Vector(2) << q.x() - mx_, q.y() - my_).finished();
98  }
99 
100  // The second is a 'clone' function that allows the factor to be copied. Under most
101  // circumstances, the following code that employs the default copy constructor should
102  // work fine.
104  return boost::static_pointer_cast<gtsam::NonlinearFactor>(
106 
107  // Additionally, we encourage you the use of unit testing your custom factors,
108  // (as all GTSAM factors are), in which you would need an equals and print, to satisfy the
109  // GTSAM_CONCEPT_TESTABLE_INST(T) defined in Testable.h, but these are not needed below.
110 }; // UnaryFactor
111 
112 
113 int main(int argc, char** argv) {
114  // 1. Create a factor graph container and add factors to it
116 
117  // 2a. Add odometry factors
118  // For simplicity, we will use the same noise model for each odometry factor
119  auto odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1));
120  // Create odometry (Between) factors between consecutive poses
121  graph.emplace_shared<BetweenFactor<Pose2> >(1, 2, Pose2(2.0, 0.0, 0.0), odometryNoise);
122  graph.emplace_shared<BetweenFactor<Pose2> >(2, 3, Pose2(2.0, 0.0, 0.0), odometryNoise);
123 
124  // 2b. Add "GPS-like" measurements
125  // We will use our custom UnaryFactor for this.
126  auto unaryNoise =
127  noiseModel::Diagonal::Sigmas(Vector2(0.1, 0.1)); // 10cm std on x,y
128  graph.emplace_shared<UnaryFactor>(1, 0.0, 0.0, unaryNoise);
129  graph.emplace_shared<UnaryFactor>(2, 2.0, 0.0, unaryNoise);
130  graph.emplace_shared<UnaryFactor>(3, 4.0, 0.0, unaryNoise);
131  graph.print("\nFactor Graph:\n"); // print
132 
133  // 3. Create the data structure to hold the initialEstimate estimate to the solution
134  // For illustrative purposes, these have been deliberately set to incorrect values
135  Values initialEstimate;
136  initialEstimate.insert(1, Pose2(0.5, 0.0, 0.2));
137  initialEstimate.insert(2, Pose2(2.3, 0.1, -0.2));
138  initialEstimate.insert(3, Pose2(4.1, 0.1, 0.1));
139  initialEstimate.print("\nInitial Estimate:\n"); // print
140 
141  // 4. Optimize using Levenberg-Marquardt optimization. The optimizer
142  // accepts an optional set of configuration parameters, controlling
143  // things like convergence criteria, the type of linear system solver
144  // to use, and the amount of information displayed during optimization.
145  // Here we will use the default set of parameters. See the
146  // documentation for the full set of parameters.
147  LevenbergMarquardtOptimizer optimizer(graph, initialEstimate);
148  Values result = optimizer.optimize();
149  result.print("Final Result:\n");
150 
151  // 5. Calculate and print marginal covariances for all variables
152  Marginals marginals(graph, result);
153  cout << "x1 covariance:\n" << marginals.marginalCovariance(1) << endl;
154  cout << "x2 covariance:\n" << marginals.marginalCovariance(2) << endl;
155  cout << "x3 covariance:\n" << marginals.marginalCovariance(3) << endl;
156 
157  return 0;
158 }
noiseModel::Diagonal::shared_ptr odometryNoise
Scalar * y
virtual const Values & optimize()
double y() const
get y
Definition: Pose2.h:218
Eigen::Vector3d Vector3
Definition: Vector.h:43
A non-templated config holding any types of Manifold-group elements.
Factor Graph consisting of non-linear factors.
gtsam::NonlinearFactor::shared_ptr clone() const override
noiseModel::Diagonal::shared_ptr model
void insert(Key j, const Value &val)
Definition: Values.cpp:140
noiseModel::Diagonal::shared_ptr unaryNoise
Eigen::MatrixXd Matrix
Definition: base/Matrix.h:43
Rot2 R(Rot2::fromAngle(0.1))
Definition: Half.h:150
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
NonlinearFactorGraph graph
~UnaryFactor() override
IsDerived< DERIVEDFACTOR > emplace_shared(Args &&...args)
Emplace a shared pointer to factor of given type.
Definition: FactorGraph.h:172
Eigen::VectorXd Vector
Definition: Vector.h:38
Values result
boost::shared_ptr< This > shared_ptr
const Rot2 & rotation() const
rotation
Definition: Pose2.h:233
A nonlinear optimizer that uses the Levenberg-Marquardt trust-region scheme.
EIGEN_DEVICE_FUNC const Scalar & q
Vector evaluateError(const Pose2 &q, boost::optional< Matrix & > H=boost::none) const override
double s() const
Definition: Rot2.h:199
traits
Definition: chartTesting.h:28
void print(const std::string &str="", const KeyFormatter &keyFormatter=DefaultKeyFormatter) const
Definition: Values.cpp:77
void print(const std::string &str="NonlinearFactorGraph: ", const KeyFormatter &keyFormatter=DefaultKeyFormatter) const override
double x() const
get x
Definition: Pose2.h:215
Eigen::Vector2d Vector2
Definition: Vector.h:42
Non-linear factor base classes.
UnaryFactor(Key j, double x, double y, const SharedNoiseModel &model)
Matrix marginalCovariance(Key variable) const
Definition: Marginals.cpp:129
int main(int argc, char **argv)
boost::shared_ptr< UnaryFactor > shared_ptr
shorthand for a smart pointer to a factor
A class for computing marginals in a NonlinearFactorGraph.
double c() const
Definition: Rot2.h:194
2D Pose
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 x
Eigen::Matrix< double, Eigen::Dynamic, 1 > Vector
std::uint64_t Key
Integer nonlinear key type.
Definition: types.h:61
Marginals marginals(graph, result)
std::ptrdiff_t j
noiseModel::Base::shared_ptr SharedNoiseModel
Definition: NoiseModel.h:734


gtsam
Author(s):
autogenerated on Sat May 8 2021 02:42:34