• 014 gtsam/examples/LocalizationExample.cpp


    一、include files

    /**
     * A simple 2D pose slam example with "GPS" measurements
     *  - The robot moves forward 2 meter each iteration
     *  - The robot initially faces along the X axis (horizontal, to the right in 2D)
     *  - We have full odometry between pose
     *  - We have "GPS-like" measurements implemented with a custom factor
     */
    
    // We will use Pose2 variables (x, y, theta) to represent the robot positions
    #include 
    
    // We will use simple integer Keys to refer to the robot poses.
    #include 
    
    // As in OdometryExample.cpp, we use a BetweenFactor to model odometry measurements.
    #include 
    
    // We add all facors to a Nonlinear Factor Graph, as our factors are nonlinear.
    #include 
    
    // The nonlinear solvers within GTSAM are iterative solvers, meaning they linearize the
    // nonlinear functions around an initial linearization point, then solve the linear system
    // to update the linearization point. This happens repeatedly until the solver converges
    // to a consistent set of variable values. This requires us to specify an initial guess
    // for each variable, held in a Values container.
    #include 
    
    // Finally, once all of the factors have been added to our factor graph, we will want to
    // solve/optimize to graph to find the best (Maximum A Posteriori) set of variable values.
    // GTSAM includes several nonlinear optimizers to perform this step. Here we will use the
    // standard Levenberg-Marquardt solver
    #include 
    
    // Once the optimized values have been calculated, we can also calculate the marginal covariance
    // of desired variables
    #include 
    
    using namespace std;
    using namespace gtsam;
    
    // Before we begin the example, we must create a custom unary factor to implement a
    // "GPS-like" functionality. Because standard GPS measurements provide information
    // only on the position, and not on the orientation, we cannot use a simple prior to
    // properly model this measurement.
    //
    // The factor will be a unary factor, affect only a single system variable. It will
    // also use a standard Gaussian noise model. Hence, we will derive our new factor from
    // the NoiseModelFactor1.
    #include 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    GTSAM中的非线性求解器是迭代求解器,这意味着它们在初始线性化点周围线性化非线性函数,然后求解线性系统以更新线性化点。这会重复发生,直到解算器收敛到一组一致的变量值。这要求我们为保存在Values容器中的每个变量指定一个初始猜测。
      给定一个起始的初值很重要
     
     
    最后,一旦所有因子都添加到我们的因子图中,我们将需要对图进行求解/优化,以找到最佳(最大后验)变量值集。
    GTSAM包括几个非线性优化器来执行此步骤。这里我们将使用标准的Levenberg-Marquardt解算器

    二、一元因子

    class UnaryFactor: public NoiseModelFactor1<Pose2> {
      // The factor will hold a measurement consisting of an (X,Y) location
      // We could this with a Point2 but here we just use two doubles
      double mx_, my_;
    
     public:
      /// shorthand for a smart pointer to a factor
      typedef boost::shared_ptr<UnaryFactor> shared_ptr;
    
      // The constructor requires the variable key, the (X, Y) measurement value, and the noise model
      UnaryFactor(Key j, double x, double y, const SharedNoiseModel& model):
        NoiseModelFactor1<Pose2>(model, j), mx_(x), my_(y) {}
    
      ~UnaryFactor() override {}
    
      // Using the NoiseModelFactor1 base class there are two functions that must be overridden.
      // The first is the 'evaluateError' function. This function implements the desired measurement
      // function, returning a vector of errors when evaluated at the provided variable value. It
      // must also calculate the Jacobians for this measurement function, if requested.
      Vector evaluateError(const Pose2& q, boost::optional<Matrix&> H = boost::none) const override {
        // The measurement function for a GPS-like measurement h(q) which predicts the measurement (m) is h(q) = q, q = [qx qy qtheta]
        // The error is then simply calculated as E(q) = h(q) - m:
        // error_x = q.x - mx
        // error_y = q.y - my
        // Node's orientation reflects in the Jacobian, in tangent space this is equal to the right-hand rule rotation matrix
        // H =  [ cos(q.theta)  -sin(q.theta) 0 ]
        //      [ sin(q.theta)   cos(q.theta) 0 ]
        const Rot2& R = q.rotation();
        if (H) (*H) = (gtsam::Matrix(2, 3) << R.c(), -R.s(), 0.0, R.s(), R.c(), 0.0).finished();
        return (Vector(2) << q.x() - mx_, q.y() - my_).finished();
      }
    
      // The second is a 'clone' function that allows the factor to be copied. Under most
      // circumstances, the following code that employs the default copy constructor should
      // work fine.
      gtsam::NonlinearFactor::shared_ptr clone() const override {
        return boost::static_pointer_cast<gtsam::NonlinearFactor>(
            gtsam::NonlinearFactor::shared_ptr(new UnaryFactor(*this))); }
    
      // Additionally, we encourage you the use of unit testing your custom factors,
      // (as all GTSAM factors are), in which you would need an equals and print, to satisfy the
      // GTSAM_CONCEPT_TESTABLE_INST(T) defined in Testable.h, but these are not needed below.
    };  // UnaryFactor
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    雅克比:
    [ c o s ( q θ ) − s i n ( q θ ) 0 s i n ( q θ ) c o s ( q θ ) 0 ]

    [cos(qθ)sin(qθ)0sin(qθ)cos(qθ)0]" role="presentation">[cos(qθ)sin(qθ)0sin(qθ)cos(qθ)0]
    [cos(qθ)sin(qθ)sin(qθ)cos(qθ)00]

    三、main function

    构建因子图

      // 1. Create a factor graph container and add factors to it
      NonlinearFactorGraph graph;
    
    • 1
    • 2

    添加里程计因子

      // 2a. Add odometry factors
      // For simplicity, we will use the same noise model for each odometry factor
      auto odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1));
      // Create odometry (Between) factors between consecutive poses
      graph.emplace_shared<BetweenFactor<Pose2> >(1, 2, Pose2(2.0, 0.0, 0.0), odometryNoise);
      graph.emplace_shared<BetweenFactor<Pose2> >(2, 3, Pose2(2.0, 0.0, 0.0), odometryNoise);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    添加自定义因子

      // 2b. Add "GPS-like" measurements
      // We will use our custom UnaryFactor for this.
      auto unaryNoise =
          noiseModel::Diagonal::Sigmas(Vector2(0.1, 0.1));  // 10cm std on x,y
      graph.emplace_shared<UnaryFactor>(1, 0.0, 0.0, unaryNoise);
      graph.emplace_shared<UnaryFactor>(2, 2.0, 0.0, unaryNoise);
      graph.emplace_shared<UnaryFactor>(3, 4.0, 0.0, unaryNoise);
      graph.print("\nFactor Graph:\n");  // print
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    创造Values进行初值的存储

      // 3. Create the data structure to hold the initialEstimate estimate to the solution
      // For illustrative purposes, these have been deliberately set to incorrect values
      Values initialEstimate;
      initialEstimate.insert(1, Pose2(0.5, 0.0, 0.2));
      initialEstimate.insert(2, Pose2(2.3, 0.1, -0.2));
      initialEstimate.insert(3, Pose2(4.1, 0.1, 0.1));
      initialEstimate.print("\nInitial Estimate:\n");  // print
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    进行优化
    使用Levenberg-Marquardt优化进行优化。优化器接受一组可选的配置参数,控制收敛标准、要使用的线性系统解算器类型以及优化过程中显示的信息量。这里我们将使用默认的参数集。有关整套参数,请参见文档。

      // 4. Optimize using Levenberg-Marquardt optimization. The optimizer
      // accepts an optional set of configuration parameters, controlling
      // things like convergence criteria, the type of linear system solver
      // to use, and the amount of information displayed during optimization.
      // Here we will use the default set of parameters.  See the
      // documentation for the full set of parameters.
      LevenbergMarquardtOptimizer optimizer(graph, initialEstimate);
      Values result = optimizer.optimize();
      result.print("Final Result:\n");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    获取边际概率

      // 5. Calculate and print marginal covariances for all variables
      Marginals marginals(graph, result);
      cout << "x1 covariance:\n" << marginals.marginalCovariance(1) << endl;
      cout << "x2 covariance:\n" << marginals.marginalCovariance(2) << endl;
      cout << "x3 covariance:\n" << marginals.marginalCovariance(3) << endl;
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    记录一次非常麻烦的调试
    C++提高编程
    Qt教程 — 3.1 深入了解Qt 控件:Buttons按钮
    破除“数据孤岛”新策略:Data Fabric(数据编织)和逻辑数据平台
    系统开发系列 之MyEclipse创建WebService详细教程和调用教程(spring框架+maven+CXF框架)
    【C++】构造函数与析构函数概念简介 ( 构造函数和析构函数引入 | 构造函数定义与调用 | 析构函数定义与调用 | 代码示例 )
    Nvidia-docker运行错误- Nvidia-docker : Unknown runtime specified nvidia
    做分析用什么工具
    数据结构初阶——排序
    STM32 USB虚拟串口
  • 原文地址:https://blog.csdn.net/weixin_43848456/article/details/127672368