想使用gtsam进行非线性优化Vector1,发现并不能利用历史数据。
代码如下:
#include <gtsam/base/Vector.h>
#include <gtsam/nonlinear/NonlinearFactor.h>
#include <gtsam/geometry/Point3.h>
#include <gtsam/geometry/Pose2.h>
#include <gtsam/linear/NoiseModel.h>
#include <gtsam/inference/Key.h>
#include <gtsam/nonlinear/GaussNewtonOptimizer.h>
#include <gtsam/geometry/Rot2.h>
#include <gtsam/geometry/Rot3.h>
#include <gtsam/geometry/Pose3.h>
#include <gtsam/slam/PriorFactor.h>
#include <gtsam/slam/BetweenFactor.h>
#include <gtsam/navigation/GPSFactor.h>
#include <gtsam/navigation/ImuFactor.h>
#include <gtsam/navigation/CombinedImuFactor.h>
#include <gtsam/nonlinear/NonlinearFactorGraph.h>
#include <gtsam/nonlinear/LevenbergMarquardtOptimizer.h>
#include <gtsam/nonlinear/Marginals.h>
#include <gtsam/nonlinear/Values.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/nonlinear/ISAM2.h>
#include <GeographicLib/Geocentric.hpp>
#include <GeographicLib/LocalCartesian.hpp>
#include <GeographicLib/Geoid.hpp>
#include <math.h>
#include <vector>
#include <iostream>
#include <ctime>
#include<stdlib.h>
#include<time.h>
#include <gtsam/nonlinear/DoglegOptimizer.h>
#include <random>
#include <Eigen/Dense>
using namespace std;
using namespace gtsam;
using namespace boost;
class UnaryFactor : public gtsam::NoiseModelFactor1<gtsam::Vector1>
{
double world;
public:
using NoiseModelFactor1<gtsam::Vector1>::evaluateError;
typedef std::shared_ptr<UnaryFactor> shared_ptr;
gtsam::Vector1 anchor;
UnaryFactor(gtsam::Key j, const SharedNoiseModel &model, double p)
: NoiseModelFactor1<gtsam::Vector1>(model, j), world(p) {}
virtual ~UnaryFactor() {}
gtsam::Vector evaluateError(const Vector1 &anchor, boost::optional<Matrix &> H = boost::none) const
{
gtsam::Vector1 residual;
gtsam::Matrix Jacobin = gtsam::Matrix::Zero(1, 1);
double r;
r = world + anchor[0];
residual << r;
Jacobin << 1;
if (H)
{
(*H) = Jacobin;
}
return residual;
};
};
NonlinearFactorGraph graph;
gtsam::Values initialyaw;
ISAM2Params parameters;
ISAM2 isam(parameters);
using gtsam::symbol_shorthand::X;
void optimizeGraph(int &k)
{
const double sig = 0.1;
std::random_device rd;
std::default_random_engine generator_(rd());
std::normal_distribution<double> noise(0, sig);
double jjj2 = k + 10 + noise(generator_);
double world=k - jjj2;
cout << "world:" << world << endl;
graph.emplace_shared<UnaryFactor>(X(k), noiseModel::Isotropic::Sigma(1, sig), world);
initialyaw.insert(X(k),Vector1(8));
}
int main()
{
for (int k = 0; k < 20; ++k)
{
optimizeGraph(k);
cout << "k:" << k << endl;
}
isam.update(graph, initialyaw);
isam.update();
Values isamCurrentEstimate = isam.calculateEstimate();
gtsam::Vector1 matX0 = isamCurrentEstimate.at<Vector1>(X(1));
cout << "Result for X: " << matX0[0] << endl;
initialyaw.clear();
return 0;
}
anchor真实值应为10,每次优化的时候,只使用了单次优化的数据。(isam优化器和LM 高斯牛顿都尝试过)
目前想要实现的是,第K次优化,优化的数据是1-K次的数据,循环写入尝试过,有没有其他更好的方法