/* ************************************************************************* */ TEST( StereoFactor, singlePoint) { NonlinearFactorGraph graph; graph.add(NonlinearEquality<Pose3>(X(1), camera1)); StereoPoint2 measurement(320, 320.0-50, 240); // arguments: measurement, sigma, cam#, measurement #, K, baseline (m) graph.add(GenericStereoFactor<Pose3, Point3>(measurement, model, X(1), L(1), K)); // Create a configuration corresponding to the ground truth Values values; values.insert(X(1), camera1); // add camera at z=6.25m looking towards origin Point3 l1(0, 0, 0); values.insert(L(1), l1); // add point at origin; GaussNewtonOptimizer optimizer(graph, values); // We expect the initial to be zero because config is the ground truth DOUBLES_EQUAL(0.0, optimizer.error(), 1e-9); // Iterate once, and the config should not have changed optimizer.iterate(); DOUBLES_EQUAL(0.0, optimizer.error(), 1e-9); // Complete solution optimizer.optimize(); DOUBLES_EQUAL(0.0, optimizer.error(), 1e-6); }
int main(const int argc, const char *argv[]) { // Read graph from file string g2oFile; if (argc < 2) g2oFile = findExampleDataFile("noisyToyGraph.txt"); else g2oFile = argv[1]; NonlinearFactorGraph::shared_ptr graph; Values::shared_ptr initial; boost::tie(graph, initial) = readG2o(g2oFile); // Add prior on the pose having index (key) = 0 NonlinearFactorGraph graphWithPrior = *graph; noiseModel::Diagonal::shared_ptr priorModel = // noiseModel::Diagonal::Variances((Vector(3) << 1e-6, 1e-6, 1e-8)); graphWithPrior.add(PriorFactor<Pose2>(0, Pose2(), priorModel)); graphWithPrior.print(); std::cout << "Computing LAGO estimate" << std::endl; Values estimateLago = lago::initialize(graphWithPrior); std::cout << "done!" << std::endl; if (argc < 3) { estimateLago.print("estimateLago"); } else { const string outputFile = argv[2]; std::cout << "Writing results to file: " << outputFile << std::endl; writeG2o(*graph, estimateLago, outputFile); std::cout << "done! " << std::endl; } return 0; }
//************************************************************************* TEST (EssentialMatrixFactor2, extraMinimization) { // Additional test with camera moving in positive X direction // We start with a factor graph and add constraints to it // Noise sigma is 1, assuming pixel measurements NonlinearFactorGraph graph; for (size_t i = 0; i < data.number_tracks(); i++) graph.add(EssentialMatrixFactor2(100, i, pA(i), pB(i), model2, K)); // Check error at ground truth Values truth; truth.insert(100, trueE); for (size_t i = 0; i < data.number_tracks(); i++) { Point3 P1 = data.tracks[i].p; truth.insert(i, double(baseline / P1.z())); } EXPECT_DOUBLES_EQUAL(0, graph.error(truth), 1e-8); // Optimize LevenbergMarquardtParams parameters; // parameters.setVerbosity("ERROR"); LevenbergMarquardtOptimizer optimizer(graph, truth, parameters); Values result = optimizer.optimize(); // Check result EssentialMatrix actual = result.at<EssentialMatrix>(100); EXPECT(assert_equal(trueE, actual, 1e-1)); for (size_t i = 0; i < data.number_tracks(); i++) EXPECT_DOUBLES_EQUAL(truth.at<double>(i), result.at<double>(i), 1e-1); // Check error at result EXPECT_DOUBLES_EQUAL(0, graph.error(result), 1e-4); }
//************************************************************************* TEST (EssentialMatrixFactor3, minimization) { // As before, we start with a factor graph and add constraints to it NonlinearFactorGraph graph; for (size_t i = 0; i < 5; i++) // but now we specify the rotation bRc graph.add(EssentialMatrixFactor3(100, i, pA(i), pB(i), cRb, model2)); // Check error at ground truth Values truth; truth.insert(100, bodyE); for (size_t i = 0; i < 5; i++) { Point3 P1 = data.tracks[i].p; truth.insert(i, double(baseline / P1.z())); } EXPECT_DOUBLES_EQUAL(0, graph.error(truth), 1e-8); // Optimize LevenbergMarquardtParams parameters; // parameters.setVerbosity("ERROR"); LevenbergMarquardtOptimizer optimizer(graph, truth, parameters); Values result = optimizer.optimize(); // Check result EssentialMatrix actual = result.at<EssentialMatrix>(100); EXPECT(assert_equal(bodyE, actual, 1e-1)); for (size_t i = 0; i < 5; i++) EXPECT_DOUBLES_EQUAL(truth.at<double>(i), result.at<double>(i), 1e-1); // Check error at result EXPECT_DOUBLES_EQUAL(0, graph.error(result), 1e-4); }
/* ************************************************************************* */ TEST( dataSet, readG2oTukey) { const string g2oFile = findExampleDataFile("pose2example"); NonlinearFactorGraph::shared_ptr actualGraph; Values::shared_ptr actualValues; bool is3D = false; boost::tie(actualGraph, actualValues) = readG2o(g2oFile, is3D, KernelFunctionTypeTUKEY); noiseModel::Diagonal::shared_ptr baseModel = noiseModel::Diagonal::Precisions((Vector(3) << 44.721360, 44.721360, 30.901699)); SharedNoiseModel model = noiseModel::Robust::Create(noiseModel::mEstimator::Tukey::Create(4.6851), baseModel); NonlinearFactorGraph expectedGraph; expectedGraph.add(BetweenFactor<Pose2>(0, 1, Pose2(1.030390, 0.011350, -0.081596), model)); expectedGraph.add(BetweenFactor<Pose2>(1, 2, Pose2(1.013900, -0.058639, -0.220291), model)); expectedGraph.add(BetweenFactor<Pose2>(2, 3, Pose2(1.027650, -0.007456, -0.043627), model)); expectedGraph.add(BetweenFactor<Pose2>(3, 4, Pose2(-0.012016, 1.004360, 1.560229), model)); expectedGraph.add(BetweenFactor<Pose2>(4, 5, Pose2(1.016030, 0.014565, -0.030930), model)); expectedGraph.add(BetweenFactor<Pose2>(5, 6, Pose2(1.023890, 0.006808, -0.007452), model)); expectedGraph.add(BetweenFactor<Pose2>(6, 7, Pose2(0.957734, 0.003159, 0.082836), model)); expectedGraph.add(BetweenFactor<Pose2>(7, 8, Pose2(-1.023820, -0.013668, -3.084560), model)); expectedGraph.add(BetweenFactor<Pose2>(8, 9, Pose2(1.023440, 0.013984, -0.127624), model)); expectedGraph.add(BetweenFactor<Pose2>(9,10, Pose2(1.003350, 0.022250, -0.195918), model)); expectedGraph.add(BetweenFactor<Pose2>(5, 9, Pose2(0.033943, 0.032439, 3.073637), model)); expectedGraph.add(BetweenFactor<Pose2>(3,10, Pose2(0.044020, 0.988477, -1.553511), model)); EXPECT(assert_equal(expectedGraph,*actualGraph,1e-5)); }
/* ************************************************************************** */ TEST(JointLimitFactorPose2Vector, optimization_2) { // over down limit // settings noiseModel::Gaussian::shared_ptr cost_model = noiseModel::Isotropic::Sigma(5, 0.001); noiseModel::Gaussian::shared_ptr prior_model = noiseModel::Isotropic::Sigma(5, 1000); Key qkey = Symbol('x', 0); Vector5 dlimit = (Vector5() << 0, 0, 0, -5.0, -10.0).finished(); Vector5 ulimit = (Vector5() << 0, 0, 0, 5, 10.0).finished(); Vector5 thresh = (Vector5() << 0, 0, 0, 2.0, 2.0).finished(); Pose2Vector conf(Pose2(1, -2, 3), Vector2(-10.0, -10.0)); NonlinearFactorGraph graph; graph.add(JointLimitFactorPose2Vector(qkey, cost_model, dlimit, ulimit, thresh)); graph.add(PriorFactor<Pose2Vector>(qkey, conf, prior_model)); Values init_values; init_values.insert(qkey, conf); GaussNewtonParams parameters; parameters.setVerbosity("ERROR"); parameters.setAbsoluteErrorTol(1e-12); GaussNewtonOptimizer optimizer(graph, init_values, parameters); optimizer.optimize(); Values results = optimizer.values(); Vector conf_limit = (Vector(2) << -3.0, -8.0).finished(); EXPECT(assert_equal(conf_limit, results.at<Pose2Vector>(qkey).configuration(), 1e-6)); }
/* ************************************************************************* */ void NonlinearISAM::update(const NonlinearFactorGraph& newFactors, const Values& initialValues) { if(newFactors.size() > 0) { // Reorder and relinearize every reorderInterval updates if(reorderInterval_ > 0 && ++reorderCounter_ >= reorderInterval_) { reorder_relinearize(); reorderCounter_ = 0; } factors_.push_back(newFactors); // Linearize new factors and insert them // TODO: optimize for whole config? linPoint_.insert(initialValues); // Augment ordering // TODO: allow for ordering constraints within the new variables // FIXME: should just loop over new values BOOST_FOREACH(const NonlinearFactorGraph::sharedFactor& factor, newFactors) BOOST_FOREACH(Key key, factor->keys()) ordering_.tryInsert(key, ordering_.nVars()); // will do nothing if already present boost::shared_ptr<GaussianFactorGraph> linearizedNewFactors = newFactors.linearize(linPoint_, ordering_); // Update ISAM isam_.update(*linearizedNewFactors); } }
/* ************************************************************************* */ TEST ( NonlinearEquality, allow_error_optimize_with_factors ) { // create a hard constraint Symbol key1('x',1); Pose2 feasible1(1.0, 2.0, 3.0); // initialize away from the ideal Values init; Pose2 initPose(0.0, 2.0, 3.0); init.insert(key1, initPose); double error_gain = 500.0; PoseNLE nle(key1, feasible1, error_gain); // create a soft prior that conflicts PosePrior prior(key1, initPose, noiseModel::Isotropic::Sigma(3, 0.1)); // add to a graph NonlinearFactorGraph graph; graph.add(nle); graph.add(prior); // optimize Ordering ordering; ordering.push_back(key1); Values actual = LevenbergMarquardtOptimizer(graph, init, ordering).optimize(); // verify Values expected; expected.insert(key1, feasible1); EXPECT(assert_equal(expected, actual)); }
/* ************************************************************************* */ TEST ( NonlinearEquality, allow_error_optimize ) { Symbol key1('x',1); Pose2 feasible1(1.0, 2.0, 3.0); double error_gain = 500.0; PoseNLE nle(key1, feasible1, error_gain); // add to a graph NonlinearFactorGraph graph; graph.add(nle); // initialize away from the ideal Pose2 initPose(0.0, 2.0, 3.0); Values init; init.insert(key1, initPose); // optimize Ordering ordering; ordering.push_back(key1); Values result = LevenbergMarquardtOptimizer(graph, init, ordering).optimize(); // verify Values expected; expected.insert(key1, feasible1); EXPECT(assert_equal(expected, result)); }
/* ************************************************************************* */ TEST(DoglegOptimizer, Iterate) { // really non-linear factor graph NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph(); // config far from minimum Point2 x0(3,0); Values config; config.insert(X(1), x0); double Delta = 1.0; for(size_t it=0; it<10; ++it) { GaussianBayesNet gbn = *fg.linearize(config)->eliminateSequential(); // Iterate assumes that linear error = nonlinear error at the linearization point, and this should be true double nonlinearError = fg.error(config); double linearError = GaussianFactorGraph(gbn).error(config.zeroVectors()); DOUBLES_EQUAL(nonlinearError, linearError, 1e-5); // cout << "it " << it << ", Delta = " << Delta << ", error = " << fg->error(*config) << endl; VectorValues dx_u = gbn.optimizeGradientSearch(); VectorValues dx_n = gbn.optimize(); DoglegOptimizerImpl::IterationResult result = DoglegOptimizerImpl::Iterate(Delta, DoglegOptimizerImpl::SEARCH_EACH_ITERATION, dx_u, dx_n, gbn, fg, config, fg.error(config)); Delta = result.Delta; EXPECT(result.f_error < fg.error(config)); // Check that error decreases Values newConfig(config.retract(result.dx_d)); config = newConfig; DOUBLES_EQUAL(fg.error(config), result.f_error, 1e-5); // Check that error is correctly filled in } }
/* ************************************************************************** */ TEST(GaussianPriorWorkspacePoseArm, optimization) { noiseModel::Gaussian::shared_ptr cost_model = noiseModel::Isotropic::Sigma(6, 0.1); Vector a = (Vector(2) << 1, 1).finished(); Vector alpha = (Vector(2) << 0, 0).finished(); Vector d = (Vector(2) << 0, 0).finished(); ArmModel arm = ArmModel(Arm(2, a, alpha, d), BodySphereVector()); Pose3 des = Pose3(Rot3(), Point3(2, 0, 0)); Key qkey = Symbol('x', 0); Vector q = (Vector(2) << 0, 0).finished(); Vector qinit = (Vector(2) << M_PI/2, M_PI/2).finished(); NonlinearFactorGraph graph; graph.add(GaussianPriorWorkspacePoseArm(qkey, arm, 1, des, cost_model)); Values init_values; init_values.insert(qkey, qinit); LevenbergMarquardtParams parameters; parameters.setVerbosity("ERROR"); parameters.setAbsoluteErrorTol(1e-12); LevenbergMarquardtOptimizer optimizer(graph, init_values, parameters); optimizer.optimize(); Values results = optimizer.values(); EXPECT_DOUBLES_EQUAL(0, graph.error(results), 1e-3); EXPECT(assert_equal(q, results.at<Vector>(qkey), 1e-3)); }
/* ************************************************************************* */ TEST( testNonlinearEqualityConstraint, unary_simple_optimization ) { // create a single-node graph with a soft and hard constraint to // ensure that the hard constraint overrides the soft constraint Point2 truth_pt(1.0, 2.0); Symbol key('x',1); double mu = 10.0; eq2D::UnaryEqualityConstraint::shared_ptr constraint( new eq2D::UnaryEqualityConstraint(truth_pt, key, mu)); Point2 badPt(100.0, -200.0); simulated2D::Prior::shared_ptr factor( new simulated2D::Prior(badPt, soft_model, key)); NonlinearFactorGraph graph; graph.push_back(constraint); graph.push_back(factor); Values initValues; initValues.insert(key, badPt); // verify error values EXPECT(constraint->active(initValues)); Values expected; expected.insert(key, truth_pt); EXPECT(constraint->active(expected)); EXPECT_DOUBLES_EQUAL(0.0, constraint->error(expected), tol); Values actual = LevenbergMarquardtOptimizer(graph, initValues).optimize(); EXPECT(assert_equal(expected, actual, tol)); }
//************************************************************************* TEST (EssentialMatrixFactor2, minimization) { // Here we want to optimize for E and inverse depths at the same time // We start with a factor graph and add constraints to it // Noise sigma is 1cm, assuming metric measurements NonlinearFactorGraph graph; for (size_t i = 0; i < 5; i++) graph.add(EssentialMatrixFactor2(100, i, pA(i), pB(i), model2)); // Check error at ground truth Values truth; truth.insert(100, trueE); for (size_t i = 0; i < 5; i++) { Point3 P1 = data.tracks[i].p; truth.insert(i, double(baseline / P1.z())); } EXPECT_DOUBLES_EQUAL(0, graph.error(truth), 1e-8); // Optimize LevenbergMarquardtParams parameters; // parameters.setVerbosity("ERROR"); LevenbergMarquardtOptimizer optimizer(graph, truth, parameters); Values result = optimizer.optimize(); // Check result EssentialMatrix actual = result.at<EssentialMatrix>(100); EXPECT(assert_equal(trueE, actual, 1e-1)); for (size_t i = 0; i < 5; i++) EXPECT_DOUBLES_EQUAL(truth.at<double>(i), result.at<double>(i), 1e-1); // Check error at result EXPECT_DOUBLES_EQUAL(0, graph.error(result), 1e-4); }
int main(int argc, char* argv[]) { // parse options and read BAL file SfM_data db = preamble(argc, argv); // Build graph using conventional GeneralSFMFactor NonlinearFactorGraph graph; for (size_t j = 0; j < db.number_tracks(); j++) { BOOST_FOREACH (const SfM_Measurement& m, db.tracks[j].measurements) { size_t i = m.first; Point2 z = m.second; Pose3_ camTnav_(C(i)); Cal3Bundler_ calibration_(K(i)); Point3_ nav_point_(P(j)); graph.addExpressionFactor( gNoiseModel, z, uncalibrate(calibration_, // now using transform_from !!!: project(transform_from(camTnav_, nav_point_)))); } } Values initial; size_t i = 0, j = 0; BOOST_FOREACH (const SfM_Camera& camera, db.cameras) { initial.insert(C(i), camera.pose().inverse()); // inverse !!! initial.insert(K(i), camera.calibration()); i += 1; } BOOST_FOREACH (const SfM_Track& track, db.tracks) initial.insert(P(j++), track.p); bool separateCalibration = true; return optimize(db, graph, initial, separateCalibration); }
/******************************************************************************* * Camera: f = 1, Image: 100x100, center: 50, 50.0 * Pose (ground truth): (Xw, -Yw, -Zw, [0,0,2.0]') * Known landmarks: * 3D Points: (10,10,0) (-10,10,0) (-10,-10,0) (10,-10,0) * Perfect measurements: * 2D Point: (55,45) (45,45) (45,55) (55,55) *******************************************************************************/ int main(int argc, char* argv[]) { /* read camera intrinsic parameters */ Cal3_S2::shared_ptr calib(new Cal3_S2(1, 1, 0, 50, 50)); /* 1. create graph */ NonlinearFactorGraph graph; /* 2. add factors to the graph */ // add measurement factors SharedDiagonal measurementNoise = Diagonal::Sigmas((Vector(2) << 0.5, 0.5)); boost::shared_ptr<ResectioningFactor> factor; graph.push_back( boost::make_shared<ResectioningFactor>(measurementNoise, X(1), calib, Point2(55, 45), Point3(10, 10, 0))); graph.push_back( boost::make_shared<ResectioningFactor>(measurementNoise, X(1), calib, Point2(45, 45), Point3(-10, 10, 0))); graph.push_back( boost::make_shared<ResectioningFactor>(measurementNoise, X(1), calib, Point2(45, 55), Point3(-10, -10, 0))); graph.push_back( boost::make_shared<ResectioningFactor>(measurementNoise, X(1), calib, Point2(55, 55), Point3(10, -10, 0))); /* 3. Create an initial estimate for the camera pose */ Values initial; initial.insert(X(1), Pose3(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(0, 0, 2))); /* 4. Optimize the graph using Levenberg-Marquardt*/ Values result = LevenbergMarquardtOptimizer(graph, initial).optimize(); result.print("Final result:\n"); return 0; }
/* ************************************************************************* */ NonlinearFactorGraph planarSLAMGraph() { NonlinearFactorGraph graph; // Prior on pose x1 at the origin. Pose2 prior(0.0, 0.0, 0.0); auto priorNoise = noiseModel::Diagonal::Sigmas(Vector3(0.3, 0.3, 0.1)); graph.add(PriorFactor<Pose2>(x1, prior, priorNoise)); // Two odometry factors Pose2 odometry(2.0, 0.0, 0.0); auto odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1)); graph.add(BetweenFactor<Pose2>(x1, x2, odometry, odometryNoise)); graph.add(BetweenFactor<Pose2>(x2, x3, odometry, odometryNoise)); // Add Range-Bearing measurements to two different landmarks auto measurementNoise = noiseModel::Diagonal::Sigmas(Vector2(0.1, 0.2)); Rot2 bearing11 = Rot2::fromDegrees(45), bearing21 = Rot2::fromDegrees(90), bearing32 = Rot2::fromDegrees(90); double range11 = std::sqrt(4.0 + 4.0), range21 = 2.0, range32 = 2.0; graph.add(BearingRangeFactor<Pose2, Point2>(x1, l1, bearing11, range11, measurementNoise)); graph.add(BearingRangeFactor<Pose2, Point2>(x2, l1, bearing21, range21, measurementNoise)); graph.add(BearingRangeFactor<Pose2, Point2>(x3, l2, bearing32, range32, measurementNoise)); return graph; }
/* ************************************************************************** */ TEST(GoalFactorArm, optimization_1) { // use optimization to solve inverse kinematics noiseModel::Gaussian::shared_ptr cost_model = noiseModel::Isotropic::Sigma(3, 0.1); // 2 link simple example Vector a = (Vector(2) << 1, 1).finished(); Vector alpha = (Vector(2) << 0, 0).finished(); Vector d = (Vector(2) << 0, 0).finished(); Arm arm(2, a, alpha, d); Point3 goal(1.414213562373095, 1.414213562373095, 0); Key qkey = Symbol('x', 0); Vector q = (Vector(2) << M_PI/4.0, 0).finished(); Vector qinit = (Vector(2) << 0, 0).finished(); NonlinearFactorGraph graph; graph.add(GoalFactorArm(qkey, cost_model, arm, goal)); Values init_values; init_values.insert(qkey, qinit); LevenbergMarquardtParams parameters; parameters.setVerbosity("ERROR"); parameters.setAbsoluteErrorTol(1e-12); LevenbergMarquardtOptimizer optimizer(graph, init_values, parameters); optimizer.optimize(); Values results = optimizer.values(); EXPECT_DOUBLES_EQUAL(0, graph.error(results), 1e-3); EXPECT(assert_equal(q, results.at<Vector>(qkey), 1e-3)); }
/* ************************************************************************* */ TEST( ConcurrentIncrementalSmootherDL, synchronize_1 ) { // Create a set of optimizer parameters ISAM2Params parameters; parameters.optimizationParams = ISAM2DoglegParams(); // parameters.maxIterations = 1; // Create a Concurrent Batch Smoother ConcurrentIncrementalSmoother smoother(parameters); // Create a simple separator *from* the filter NonlinearFactorGraph smootherFactors, filterSumarization; Values smootherValues, filterSeparatorValues; filterSeparatorValues.insert(1, Pose3().compose(poseError)); filterSeparatorValues.insert(2, filterSeparatorValues.at<Pose3>(1).compose(poseOdometry).compose(poseError)); filterSumarization.push_back(LinearContainerFactor(PriorFactor<Pose3>(1, poseInitial, noisePrior).linearize(filterSeparatorValues), filterSeparatorValues)); filterSumarization.push_back(LinearContainerFactor(BetweenFactor<Pose3>(1, 2, poseOdometry, noiseOdometery).linearize(filterSeparatorValues), filterSeparatorValues)); // Create expected values: the smoother output will be empty for this case NonlinearFactorGraph expectedSmootherSummarization; Values expectedSmootherSeparatorValues; NonlinearFactorGraph actualSmootherSummarization; Values actualSmootherSeparatorValues; smoother.presync(); smoother.getSummarizedFactors(actualSmootherSummarization, actualSmootherSeparatorValues); smoother.synchronize(smootherFactors, smootherValues, filterSumarization, filterSeparatorValues); smoother.postsync(); // Check CHECK(assert_equal(expectedSmootherSummarization, actualSmootherSummarization, 1e-6)); CHECK(assert_equal(expectedSmootherSeparatorValues, actualSmootherSeparatorValues, 1e-6)); // Update the smoother smoother.update(); // Check the factor graph. It should contain only the filter-provided factors NonlinearFactorGraph expectedFactorGraph = filterSumarization; NonlinearFactorGraph actualFactorGraph = smoother.getFactors(); CHECK(assert_equal(expectedFactorGraph, actualFactorGraph, 1e-6)); // Check the optimized value of smoother state NonlinearFactorGraph allFactors; allFactors.push_back(filterSumarization); Values allValues; allValues.insert(filterSeparatorValues); Values expectedValues = BatchOptimize(allFactors, allValues,1); Values actualValues = smoother.calculateEstimate(); CHECK(assert_equal(expectedValues, actualValues, 1e-6)); // Check the linearization point. The separator should remain identical to the filter provided values Values expectedLinearizationPoint = filterSeparatorValues; Values actualLinearizationPoint = smoother.getLinearizationPoint(); CHECK(assert_equal(expectedLinearizationPoint, actualLinearizationPoint, 1e-6)); }
/* ************************************************************************* */ TEST(Marginals, order) { NonlinearFactorGraph fg; fg += PriorFactor<Pose2>(0, Pose2(), noiseModel::Unit::Create(3)); fg += BetweenFactor<Pose2>(0, 1, Pose2(1,0,0), noiseModel::Unit::Create(3)); fg += BetweenFactor<Pose2>(1, 2, Pose2(1,0,0), noiseModel::Unit::Create(3)); fg += BetweenFactor<Pose2>(2, 3, Pose2(1,0,0), noiseModel::Unit::Create(3)); Values vals; vals.insert(0, Pose2()); vals.insert(1, Pose2(1,0,0)); vals.insert(2, Pose2(2,0,0)); vals.insert(3, Pose2(3,0,0)); vals.insert(100, Point2(0,1)); vals.insert(101, Point2(1,1)); fg += BearingRangeFactor<Pose2,Point2>(0, 100, vals.at<Pose2>(0).bearing(vals.at<Point2>(100)), vals.at<Pose2>(0).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(0, 101, vals.at<Pose2>(0).bearing(vals.at<Point2>(101)), vals.at<Pose2>(0).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(1, 100, vals.at<Pose2>(1).bearing(vals.at<Point2>(100)), vals.at<Pose2>(1).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(1, 101, vals.at<Pose2>(1).bearing(vals.at<Point2>(101)), vals.at<Pose2>(1).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(2, 100, vals.at<Pose2>(2).bearing(vals.at<Point2>(100)), vals.at<Pose2>(2).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(2, 101, vals.at<Pose2>(2).bearing(vals.at<Point2>(101)), vals.at<Pose2>(2).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(3, 100, vals.at<Pose2>(3).bearing(vals.at<Point2>(100)), vals.at<Pose2>(3).range(vals.at<Point2>(100)), noiseModel::Unit::Create(2)); fg += BearingRangeFactor<Pose2,Point2>(3, 101, vals.at<Pose2>(3).bearing(vals.at<Point2>(101)), vals.at<Pose2>(3).range(vals.at<Point2>(101)), noiseModel::Unit::Create(2)); Marginals marginals(fg, vals); KeySet set = fg.keys(); FastVector<Key> keys(set.begin(), set.end()); JointMarginal joint = marginals.jointMarginalCovariance(keys); LONGS_EQUAL(3, (long)joint(0,0).rows()); LONGS_EQUAL(3, (long)joint(1,1).rows()); LONGS_EQUAL(3, (long)joint(2,2).rows()); LONGS_EQUAL(3, (long)joint(3,3).rows()); LONGS_EQUAL(2, (long)joint(100,100).rows()); LONGS_EQUAL(2, (long)joint(101,101).rows()); }
/* ************************************************************************* */ int main (int argc, char* argv[]) { // Find default file, but if an argument is given, try loading a file string filename = findExampleDataFile("dubrovnik-3-7-pre"); if (argc>1) filename = string(argv[1]); // Load the SfM data from file SfM_data mydata; assert(readBAL(filename, mydata)); cout << boost::format("read %1% tracks on %2% cameras\n") % mydata.number_tracks() % mydata.number_cameras(); // Create a factor graph NonlinearFactorGraph graph; // We share *one* noiseModel between all projection factors noiseModel::Isotropic::shared_ptr noise = noiseModel::Isotropic::Sigma(2, 1.0); // one pixel in u and v // Add measurements to the factor graph size_t j = 0; BOOST_FOREACH(const SfM_Track& track, mydata.tracks) { BOOST_FOREACH(const SfM_Measurement& m, track.measurements) { size_t i = m.first; Point2 uv = m.second; graph.push_back(MyFactor(uv, noise, C(i), P(j))); // note use of shorthand symbols C and P } j += 1; } // Add a prior on pose x1. This indirectly specifies where the origin is. // and a prior on the position of the first landmark to fix the scale graph.push_back(PriorFactor<SfM_Camera>(C(0), mydata.cameras[0], noiseModel::Isotropic::Sigma(9, 0.1))); graph.push_back(PriorFactor<Point3> (P(0), mydata.tracks[0].p, noiseModel::Isotropic::Sigma(3, 0.1))); // Create initial estimate Values initial; size_t i = 0; j = 0; BOOST_FOREACH(const SfM_Camera& camera, mydata.cameras) initial.insert(C(i++), camera); BOOST_FOREACH(const SfM_Track& track, mydata.tracks) initial.insert(P(j++), track.p); /* Optimize the graph and print results */ Values result; try { LevenbergMarquardtParams params; params.setVerbosity("ERROR"); LevenbergMarquardtOptimizer lm(graph, initial, params); result = lm.optimize(); } catch (exception& e) { cout << e.what(); } cout << "final error: " << graph.error(result) << endl; return 0; }
/* ************************************************************************* */ int main(int argc, char* argv[]) { // Define the camera calibration parameters Cal3_S2::shared_ptr K(new Cal3_S2(50.0, 50.0, 0.0, 50.0, 50.0)); // Define the camera observation noise model noiseModel::Isotropic::shared_ptr measurementNoise = noiseModel::Isotropic::Sigma(2, 1.0); // one pixel in u and v // Create the set of ground-truth landmarks vector<Point3> points = createPoints(); // Create the set of ground-truth poses vector<Pose3> poses = createPoses(); // Create a factor graph NonlinearFactorGraph graph; // Add a prior on pose x1. This indirectly specifies where the origin is. noiseModel::Diagonal::shared_ptr poseNoise = noiseModel::Diagonal::Sigmas((Vector(6) << Vector3::Constant(0.3), Vector3::Constant(0.1))); // 30cm std on x,y,z 0.1 rad on roll,pitch,yaw graph.push_back(PriorFactor<Pose3>(Symbol('x', 0), poses[0], poseNoise)); // add directly to graph // Simulated measurements from each camera pose, adding them to the factor graph for (size_t i = 0; i < poses.size(); ++i) { for (size_t j = 0; j < points.size(); ++j) { SimpleCamera camera(poses[i], *K); Point2 measurement = camera.project(points[j]); graph.push_back(GenericProjectionFactor<Pose3, Point3, Cal3_S2>(measurement, measurementNoise, Symbol('x', i), Symbol('l', j), K)); } } // Because the structure-from-motion problem has a scale ambiguity, the problem is still under-constrained // Here we add a prior on the position of the first landmark. This fixes the scale by indicating the distance // between the first camera and the first landmark. All other landmark positions are interpreted using this scale. noiseModel::Isotropic::shared_ptr pointNoise = noiseModel::Isotropic::Sigma(3, 0.1); graph.push_back(PriorFactor<Point3>(Symbol('l', 0), points[0], pointNoise)); // add directly to graph graph.print("Factor Graph:\n"); // Create the data structure to hold the initial estimate to the solution // Intentionally initialize the variables off from the ground truth Values initialEstimate; for (size_t i = 0; i < poses.size(); ++i) initialEstimate.insert(Symbol('x', i), poses[i].compose(Pose3(Rot3::rodriguez(-0.1, 0.2, 0.25), Point3(0.05, -0.10, 0.20)))); for (size_t j = 0; j < points.size(); ++j) initialEstimate.insert(Symbol('l', j), points[j].compose(Point3(-0.25, 0.20, 0.15))); initialEstimate.print("Initial Estimates:\n"); /* Optimize the graph and print results */ Values result = DoglegOptimizer(graph, initialEstimate).optimize(); result.print("Final results:\n"); return 0; }
/* ************************************************************************* */ int main(int argc, char* argv[]) { // Create the set of ground-truth vector<Point3> points = createPoints(); vector<Pose3> poses = createPoses(); // Create the factor graph NonlinearFactorGraph graph; // Add a prior on pose x1. noiseModel::Diagonal::shared_ptr poseNoise = noiseModel::Diagonal::Sigmas((Vector(6) << Vector3::Constant(0.3), Vector3::Constant(0.1)).finished()); // 30cm std on x,y,z 0.1 rad on roll,pitch,yaw graph.push_back(PriorFactor<Pose3>(Symbol('x', 0), poses[0], poseNoise)); // Simulated measurements from each camera pose, adding them to the factor graph Cal3_S2 K(50.0, 50.0, 0.0, 50.0, 50.0); noiseModel::Isotropic::shared_ptr measurementNoise = noiseModel::Isotropic::Sigma(2, 1.0); for (size_t i = 0; i < poses.size(); ++i) { for (size_t j = 0; j < points.size(); ++j) { SimpleCamera camera(poses[i], K); Point2 measurement = camera.project(points[j]); // The only real difference with the Visual SLAM example is that here we use a // different factor type, that also calculates the Jacobian with respect to calibration graph.push_back(GeneralSFMFactor2<Cal3_S2>(measurement, measurementNoise, Symbol('x', i), Symbol('l', j), Symbol('K', 0))); } } // Add a prior on the position of the first landmark. noiseModel::Isotropic::shared_ptr pointNoise = noiseModel::Isotropic::Sigma(3, 0.1); graph.push_back(PriorFactor<Point3>(Symbol('l', 0), points[0], pointNoise)); // add directly to graph // Add a prior on the calibration. noiseModel::Diagonal::shared_ptr calNoise = noiseModel::Diagonal::Sigmas((Vector(5) << 500, 500, 0.1, 100, 100).finished()); graph.push_back(PriorFactor<Cal3_S2>(Symbol('K', 0), K, calNoise)); // Create the initial estimate to the solution // now including an estimate on the camera calibration parameters Values initialEstimate; initialEstimate.insert(Symbol('K', 0), Cal3_S2(60.0, 60.0, 0.0, 45.0, 45.0)); for (size_t i = 0; i < poses.size(); ++i) initialEstimate.insert(Symbol('x', i), poses[i].compose(Pose3(Rot3::Rodrigues(-0.1, 0.2, 0.25), Point3(0.05, -0.10, 0.20)))); for (size_t j = 0; j < points.size(); ++j) initialEstimate.insert<Point3>(Symbol('l', j), points[j] + Point3(-0.25, 0.20, 0.15)); /* Optimize the graph and print results */ Values result = DoglegOptimizer(graph, initialEstimate).optimize(); result.print("Final results:\n"); return 0; }
gtsam::NonlinearFactorGraph Matcher2D::findLocalLoopClosure( const PoseD slam_pose, LaserScan2D& scan) { NonlinearFactorGraph graph; #if 0 // get looped index vector<LoopResult2d> loop_result; loop_result = this->findLoopClosure(scan); // perform small EM only after init if (local_smallEM_.flag_init) { for (size_t i = 0; i < loop_result.size(); i++) { Pose2 relpose = loop_result[i].delta_pose; pair<size_t, size_t> relidx = make_pair(loop_result[i].loop_idx, pose_count_); // inlier if (pose_count_ - loop_result[i].loop_idx > setting_.local_loop_interval && local_smallEM_.perform(relpose, relidx, curr_values_, isam_.getFactorsUnsafe())) { cout << "local loop detected! " << endl; cout << "robot_" << ID_ << ": [" << loop_result[i].loop_idx << ", " << pose_count_ << "]" << endl; cout << "Press Enter to continue ... " << endl; cin.ignore(1); // matched: insert between robot factor graph.push_back(BetweenFactor<Pose2>(Symbol(ID_, loop_result[i].loop_idx), Symbol(ID_, pose_count_), relpose, setting_.loop_default_model)); } } } else { // only init small EM after certain count if (local_measure_poses_.size() >= setting_.local_loop_count_smallEM) { local_smallEM_.init(local_measure_poses_, local_measure_index_, Pose2()); local_measure_poses_.clear(); local_measure_index_.clear(); // insert in local cache } else { for (size_t i = 0; i < loop_result.size(); i++) { local_measure_poses_.push_back(loop_result[i].delta_pose); local_measure_index_.push_back(make_pair(loop_result[i].loop_idx, pose_count_)); } } } #endif return graph; }
int main(int argc, char** argv) { // 1. Create a factor graph container and add factors to it NonlinearFactorGraph graph; // 2a. Add a prior on the first pose, setting it to the origin // A prior factor consists of a mean and a noise model (covariance matrix) Pose2 prior(0.0, 0.0, 0.0); // prior at origin noiseModel::Diagonal::shared_ptr priorNoise = noiseModel::Diagonal::Sigmas(Vector_(3, 0.3, 0.3, 0.1)); graph.add(PriorFactor<Pose2>(1, prior, priorNoise)); // 2b. Add odometry factors // For simplicity, we will use the same noise model for each odometry factor noiseModel::Diagonal::shared_ptr odometryNoise = noiseModel::Diagonal::Sigmas(Vector_(3, 0.2, 0.2, 0.1)); // Create odometry (Between) factors between consecutive poses graph.add(BetweenFactor<Pose2>(1, 2, Pose2(2.0, 0.0, M_PI_2), odometryNoise)); graph.add(BetweenFactor<Pose2>(2, 3, Pose2(2.0, 0.0, M_PI_2), odometryNoise)); graph.add(BetweenFactor<Pose2>(3, 4, Pose2(2.0, 0.0, M_PI_2), odometryNoise)); graph.add(BetweenFactor<Pose2>(4, 5, Pose2(2.0, 0.0, M_PI_2), odometryNoise)); // 2c. Add the loop closure constraint // This factor encodes the fact that we have returned to the same pose. In real systems, // these constraints may be identified in many ways, such as appearance-based techniques // with camera images. // We will use another Between Factor to enforce this constraint, with the distance set to zero, noiseModel::Diagonal::shared_ptr model = noiseModel::Diagonal::Sigmas(Vector_(3, 0.2, 0.2, 0.1)); graph.add(BetweenFactor<Pose2>(5, 1, Pose2(0.0, 0.0, 0.0), model)); graph.print("\nFactor Graph:\n"); // print // 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, 1.1)); initialEstimate.insert(3, Pose2(2.1, 1.9, 2.8)); initialEstimate.insert(4, Pose2(-.3, 2.5, 4.2)); initialEstimate.insert(5, Pose2(0.1,-0.7, 5.8)); initialEstimate.print("\nInitial Estimate:\n"); // print // 4. Single Step Optimization using Levenberg-Marquardt LevenbergMarquardtParams parameters; parameters.verbosity = NonlinearOptimizerParams::ERROR; parameters.verbosityLM = LevenbergMarquardtParams::LAMBDA; parameters.linearSolverType = SuccessiveLinearizationParams::CONJUGATE_GRADIENT; { parameters.iterativeParams = boost::make_shared<SubgraphSolverParameters>(); LevenbergMarquardtOptimizer optimizer(graph, initialEstimate, parameters); Values result = optimizer.optimize(); result.print("Final Result:\n"); cout << "subgraph solver final error = " << graph.error(result) << endl; } return 0; }
int main(int argc, char** argv) { // 1. Create a factor graph container and add factors to it NonlinearFactorGraph graph; // 2a. Add odometry factors // For simplicity, we will use the same noise model for each odometry factor noiseModel::Diagonal::shared_ptr odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1)); // Create odometry (Between) factors between consecutive poses graph.add(BetweenFactor<Pose2>(1, 2, Pose2(2.0, 0.0, 0.0), odometryNoise)); graph.add(BetweenFactor<Pose2>(2, 3, Pose2(2.0, 0.0, 0.0), odometryNoise)); // 2b. Add "GPS-like" measurements // We will use our custom UnaryFactor for this. noiseModel::Diagonal::shared_ptr unaryNoise = noiseModel::Diagonal::Sigmas(Vector2(0.1, 0.1)); // 10cm std on x,y graph.add(boost::make_shared<UnaryFactor>(1, 0.0, 0.0, unaryNoise)); graph.add(boost::make_shared<UnaryFactor>(2, 2.0, 0.0, unaryNoise)); graph.add(boost::make_shared<UnaryFactor>(3, 4.0, 0.0, unaryNoise)); graph.print("\nFactor Graph:\n"); // print // 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 // 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"); // 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; return 0; }
/* ************************************************************************* */ TEST( dataSet, readG2o3D) { const string g2oFile = findExampleDataFile("pose3example"); NonlinearFactorGraph::shared_ptr actualGraph; Values::shared_ptr actualValues; bool is3D = true; boost::tie(actualGraph, actualValues) = readG2o(g2oFile, is3D); Values expectedValues; Rot3 R0 = Rot3::quaternion(1.000000, 0.000000, 0.000000, 0.000000 ); Point3 p0 = Point3(0.000000, 0.000000, 0.000000); expectedValues.insert(0, Pose3(R0, p0)); Rot3 R1 = Rot3::quaternion(0.854230, 0.190253, 0.283162, -0.392318 ); Point3 p1 = Point3(1.001367, 0.015390, 0.004948); expectedValues.insert(1, Pose3(R1, p1)); Rot3 R2 = Rot3::quaternion(0.421446, -0.351729, -0.597838, 0.584174 ); Point3 p2 = Point3(1.993500, 0.023275, 0.003793); expectedValues.insert(2, Pose3(R2, p2)); Rot3 R3 = Rot3::quaternion(0.067024, 0.331798, -0.200659, 0.919323); Point3 p3 = Point3(2.004291, 1.024305, 0.018047); expectedValues.insert(3, Pose3(R3, p3)); Rot3 R4 = Rot3::quaternion(0.765488, -0.035697, -0.462490, 0.445933); Point3 p4 = Point3(0.999908, 1.055073, 0.020212); expectedValues.insert(4, Pose3(R4, p4)); EXPECT(assert_equal(expectedValues,*actualValues,1e-5)); noiseModel::Diagonal::shared_ptr model = noiseModel::Diagonal::Precisions((Vector(6) << 10000.0,10000.0,10000.0,10000.0,10000.0,10000.0)); NonlinearFactorGraph expectedGraph; Point3 p01 = Point3(1.001367, 0.015390, 0.004948); Rot3 R01 = Rot3::quaternion(0.854230, 0.190253, 0.283162, -0.392318 ); expectedGraph.add(BetweenFactor<Pose3>(0, 1, Pose3(R01,p01), model)); Point3 p12 = Point3(0.523923, 0.776654, 0.326659); Rot3 R12 = Rot3::quaternion(0.105373 , 0.311512, 0.656877, -0.678505 ); expectedGraph.add(BetweenFactor<Pose3>(1, 2, Pose3(R12,p12), model)); Point3 p23 = Point3(0.910927, 0.055169, -0.411761); Rot3 R23 = Rot3::quaternion(0.568551 , 0.595795, -0.561677, 0.079353 ); expectedGraph.add(BetweenFactor<Pose3>(2, 3, Pose3(R23,p23), model)); Point3 p34 = Point3(0.775288, 0.228798, -0.596923); Rot3 R34 = Rot3::quaternion(0.542221 , -0.592077, 0.303380, -0.513226 ); expectedGraph.add(BetweenFactor<Pose3>(3, 4, Pose3(R34,p34), model)); Point3 p14 = Point3(-0.577841, 0.628016, -0.543592); Rot3 R14 = Rot3::quaternion(0.327419 , -0.125250, -0.534379, 0.769122 ); expectedGraph.add(BetweenFactor<Pose3>(1, 4, Pose3(R14,p14), model)); Point3 p30 = Point3(-0.623267, 0.086928, 0.773222); Rot3 R30 = Rot3::quaternion(0.083672 , 0.104639, 0.627755, 0.766795 ); expectedGraph.add(BetweenFactor<Pose3>(3, 0, Pose3(R30,p30), model)); EXPECT(assert_equal(expectedGraph,*actualGraph,1e-5)); }
int main(const int argc, const char *argv[]) { // Read graph from file string g2oFile; if (argc < 2) g2oFile = findExampleDataFile("pose3example.txt"); else g2oFile = argv[1]; NonlinearFactorGraph::shared_ptr graph; Values::shared_ptr initial; bool is3D = true; boost::tie(graph, initial) = readG2o(g2oFile, is3D); // Add prior on the first key NonlinearFactorGraph graphWithPrior = *graph; noiseModel::Diagonal::shared_ptr priorModel = // noiseModel::Diagonal::Variances((Vector(6) << 1e-6, 1e-6, 1e-6, 1e-4, 1e-4, 1e-4)); Key firstKey = 0; BOOST_FOREACH(const Values::ConstKeyValuePair& key_value, *initial) { std::cout << "Adding prior to g2o file " << std::endl; firstKey = key_value.key; graphWithPrior.add(PriorFactor<Pose3>(firstKey, Pose3(), priorModel)); break; } std::cout << "Initializing Pose3 - Riemannian gradient" << std::endl; bool useGradient = true; Values initialization = InitializePose3::initialize(graphWithPrior, *initial, useGradient); std::cout << "done!" << std::endl; std::cout << "initial error=" <<graph->error(*initial)<< std::endl; std::cout << "initialization error=" <<graph->error(initialization)<< std::endl; if (argc < 3) { initialization.print("initialization"); } else { const string outputFile = argv[2]; std::cout << "Writing results to file: " << outputFile << std::endl; writeG2o(*graph, initialization, outputFile); std::cout << "done! " << std::endl; } return 0; }
/* ********************************************************************* */ TEST (testNonlinearEqualityConstraint, map_warp ) { // get a graph NonlinearFactorGraph graph; // keys Symbol x1('x',1), x2('x',2); Symbol l1('l',1), l2('l',2); // constant constraint on x1 Point2 pose1(1.0, 1.0); graph.add(eq2D::UnaryEqualityConstraint(pose1, x1)); SharedDiagonal sigma = noiseModel::Isotropic::Sigma(1,0.1); // measurement from x1 to l1 Point2 z1(0.0, 5.0); graph.add(simulated2D::Measurement(z1, sigma, x1, l1)); // measurement from x2 to l2 Point2 z2(-4.0, 0.0); graph.add(simulated2D::Measurement(z2, sigma, x2, l2)); // equality constraint between l1 and l2 graph.add(eq2D::PointEqualityConstraint(l1, l2)); // create an initial estimate Values initialEstimate; initialEstimate.insert(x1, Point2( 1.0, 1.0)); initialEstimate.insert(l1, Point2( 1.0, 6.0)); initialEstimate.insert(l2, Point2(-4.0, 0.0)); // starting with a separate reference frame initialEstimate.insert(x2, Point2( 0.0, 0.0)); // other pose starts at origin // optimize Values actual = LevenbergMarquardtOptimizer(graph, initialEstimate).optimize(); Values expected; expected.insert(x1, Point2(1.0, 1.0)); expected.insert(l1, Point2(1.0, 6.0)); expected.insert(l2, Point2(1.0, 6.0)); expected.insert(x2, Point2(5.0, 6.0)); CHECK(assert_equal(expected, actual, tol)); }
/* ************************************************************************* */ bool check_smoother(const NonlinearFactorGraph& fullgraph, const Values& fullinit, const IncrementalFixedLagSmoother& smoother, const Key& key) { GaussianFactorGraph linearized = *fullgraph.linearize(fullinit); VectorValues delta = linearized.optimize(); Values fullfinal = fullinit.retract(delta); Point2 expected = fullfinal.at<Point2>(key); Point2 actual = smoother.calculateEstimate<Point2>(key); return assert_equal(expected, actual); }
int main(int argc, char** argv) { // Create an empty nonlinear factor graph NonlinearFactorGraph graph; // Add a prior on the first pose, setting it to the origin // A prior factor consists of a mean and a noise model (covariance matrix) Pose2 priorMean(0.0, 0.0, 0.0); // prior at origin noiseModel::Diagonal::shared_ptr priorNoise = noiseModel::Diagonal::Sigmas(Vector3(0.3, 0.3, 0.1)); graph.add(PriorFactor<Pose2>(1, priorMean, priorNoise)); // Add odometry factors Pose2 odometry(2.0, 0.0, 0.0); // For simplicity, we will use the same noise model for each odometry factor noiseModel::Diagonal::shared_ptr odometryNoise = noiseModel::Diagonal::Sigmas(Vector3(0.2, 0.2, 0.1)); // Create odometry (Between) factors between consecutive poses graph.add(BetweenFactor<Pose2>(1, 2, odometry, odometryNoise)); graph.add(BetweenFactor<Pose2>(2, 3, odometry, odometryNoise)); graph.print("\nFactor Graph:\n"); // print // Create the data structure to hold the initialEstimate estimate to the solution // For illustrative purposes, these have been deliberately set to incorrect values Values initial; initial.insert(1, Pose2(0.5, 0.0, 0.2)); initial.insert(2, Pose2(2.3, 0.1, -0.2)); initial.insert(3, Pose2(4.1, 0.1, 0.1)); initial.print("\nInitial Estimate:\n"); // print // optimize using Levenberg-Marquardt optimization Values result = LevenbergMarquardtOptimizer(graph, initial).optimize(); result.print("Final Result:\n"); // Calculate and print marginal covariances for all variables cout.precision(2); 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; return 0; }