fix formatting for examples This is mostly just applying the existing clang format config, except: - Use NOLINT on overlong comment lines. - Wrap some sections in 'clang-format off' / 'clang format on'. - Manually split or join some multi-line strings. Change-Id: Ia1a40eeb92112e12c3a169309afe087af55b2f4f
diff --git a/.clang-format b/.clang-format index 3b22926..e28c3fd 100644 --- a/.clang-format +++ b/.clang-format
@@ -3,3 +3,4 @@ BinPackParameters: false PointerAlignment: Left DerivePointerAlignment: false +CommentPragmas: NOLINT.*
diff --git a/examples/bal_problem.cc b/examples/bal_problem.cc index 1ee3c81..ceac89a 100644 --- a/examples/bal_problem.cc +++ b/examples/bal_problem.cc
@@ -35,6 +35,7 @@ #include <fstream> #include <string> #include <vector> + #include "Eigen/Core" #include "ceres/rotation.h" #include "glog/logging.h" @@ -46,7 +47,7 @@ typedef Eigen::Map<Eigen::VectorXd> VectorRef; typedef Eigen::Map<const Eigen::VectorXd> ConstVectorRef; -template<typename T> +template <typename T> void FscanfOrDie(FILE* fptr, const char* format, T* value) { int num_scanned = fscanf(fptr, format, value); if (num_scanned != 1) { @@ -82,9 +83,8 @@ FscanfOrDie(fptr, "%d", &num_points_); FscanfOrDie(fptr, "%d", &num_observations_); - VLOG(1) << "Header: " << num_cameras_ - << " " << num_points_ - << " " << num_observations_; + VLOG(1) << "Header: " << num_cameras_ << " " << num_points_ << " " + << num_observations_; point_index_ = new int[num_observations_]; camera_index_ = new int[num_observations_]; @@ -97,7 +97,7 @@ FscanfOrDie(fptr, "%d", camera_index_ + i); FscanfOrDie(fptr, "%d", point_index_ + i); for (int j = 0; j < 2; ++j) { - FscanfOrDie(fptr, "%lf", observations_ + 2*i + j); + FscanfOrDie(fptr, "%lf", observations_ + 2 * i + j); } } @@ -119,7 +119,7 @@ quaternion_cursor += 4; original_cursor += 3; for (int j = 4; j < 10; ++j) { - *quaternion_cursor++ = *original_cursor++; + *quaternion_cursor++ = *original_cursor++; } } // Copy the rest of the points. @@ -127,7 +127,7 @@ *quaternion_cursor++ = *original_cursor++; } // Swap in the quaternion parameters. - delete []parameters_; + delete[] parameters_; parameters_ = quaternion_parameters; } } @@ -181,25 +181,25 @@ void BALProblem::WriteToPLYFile(const std::string& filename) const { std::ofstream of(filename.c_str()); - of << "ply" - << '\n' << "format ascii 1.0" - << '\n' << "element vertex " << num_cameras_ + num_points_ - << '\n' << "property float x" - << '\n' << "property float y" - << '\n' << "property float z" - << '\n' << "property uchar red" - << '\n' << "property uchar green" - << '\n' << "property uchar blue" - << '\n' << "end_header" << std::endl; + of << "ply" << '\n' + << "format ascii 1.0" << '\n' + << "element vertex " << num_cameras_ + num_points_ << '\n' + << "property float x" << '\n' + << "property float y" << '\n' + << "property float z" << '\n' + << "property uchar red" << '\n' + << "property uchar green" << '\n' + << "property uchar blue" << '\n' + << "end_header" << std::endl; // Export extrinsic data (i.e. camera centers) as green points. double angle_axis[3]; double center[3]; - for (int i = 0; i < num_cameras(); ++i) { + for (int i = 0; i < num_cameras(); ++i) { const double* camera = cameras() + camera_block_size() * i; CameraToAngleAxisAndCenter(camera, angle_axis, center); - of << center[0] << ' ' << center[1] << ' ' << center[2] - << " 0 255 0" << '\n'; + of << center[0] << ' ' << center[1] << ' ' << center[2] << " 0 255 0" + << '\n'; } // Export the structure (i.e. 3D Points) as white points. @@ -226,9 +226,8 @@ // c = -R't Eigen::VectorXd inverse_rotation = -angle_axis_ref; - AngleAxisRotatePoint(inverse_rotation.data(), - camera + camera_block_size() - 6, - center); + AngleAxisRotatePoint( + inverse_rotation.data(), camera + camera_block_size() - 6, center); VectorRef(center, 3) *= -1.0; } @@ -243,13 +242,10 @@ } // t = -R * c - AngleAxisRotatePoint(angle_axis, - center, - camera + camera_block_size() - 6); + AngleAxisRotatePoint(angle_axis, center, camera + camera_block_size() - 6); VectorRef(camera + camera_block_size() - 6, 3) *= -1.0; } - void BALProblem::Normalize() { // Compute the marginal median of the geometry. std::vector<double> tmp(num_points_); @@ -329,10 +325,10 @@ } BALProblem::~BALProblem() { - delete []point_index_; - delete []camera_index_; - delete []observations_; - delete []parameters_; + delete[] point_index_; + delete[] camera_index_; + delete[] observations_; + delete[] parameters_; } } // namespace examples
diff --git a/examples/bal_problem.h b/examples/bal_problem.h index e9a348e..81e8844 100644 --- a/examples/bal_problem.h +++ b/examples/bal_problem.h
@@ -65,20 +65,20 @@ const double translation_sigma, const double point_sigma); - int camera_block_size() const { return use_quaternions_ ? 10 : 9; } - int point_block_size() const { return 3; } - int num_cameras() const { return num_cameras_; } - int num_points() const { return num_points_; } - int num_observations() const { return num_observations_; } - int num_parameters() const { return num_parameters_; } - const int* point_index() const { return point_index_; } - const int* camera_index() const { return camera_index_; } - const double* observations() const { return observations_; } - const double* parameters() const { return parameters_; } - const double* cameras() const { return parameters_; } - double* mutable_cameras() { return parameters_; } + int camera_block_size() const { return use_quaternions_ ? 10 : 9; } + int point_block_size() const { return 3; } + int num_cameras() const { return num_cameras_; } + int num_points() const { return num_points_; } + int num_observations() const { return num_observations_; } + int num_parameters() const { return num_parameters_; } + const int* point_index() const { return point_index_; } + const int* camera_index() const { return camera_index_; } + const double* observations() const { return observations_; } + const double* parameters() const { return parameters_; } + const double* cameras() const { return parameters_; } + double* mutable_cameras() { return parameters_; } double* mutable_points() { - return parameters_ + camera_block_size() * num_cameras_; + return parameters_ + camera_block_size() * num_cameras_; } private:
diff --git a/examples/bundle_adjuster.cc b/examples/bundle_adjuster.cc index bd1281c..e7b154e 100644 --- a/examples/bundle_adjuster.cc +++ b/examples/bundle_adjuster.cc
@@ -64,6 +64,9 @@ #include "glog/logging.h" #include "snavely_reprojection_error.h" +// clang-format makes the gflags definitions too verbose +// clang-format off + DEFINE_string(input, "", "Input File name"); DEFINE_string(trust_region_strategy, "levenberg_marquardt", "Options are: levenberg_marquardt, dogleg."); @@ -74,7 +77,7 @@ "refine each successful trust region step."); DEFINE_string(blocks_for_inner_iterations, "automatic", "Options are: " - "automatic, cameras, points, cameras,points, points,cameras"); + "automatic, cameras, points, cameras,points, points,cameras"); DEFINE_string(linear_solver, "sparse_schur", "Options are: " "sparse_schur, dense_schur, iterative_schur, sparse_normal_cholesky, " @@ -100,8 +103,8 @@ DEFINE_bool(robustify, false, "Use a robust loss function."); DEFINE_double(eta, 1e-2, "Default value for eta. Eta determines the " - "accuracy of each linear solve of the truncated newton step. " - "Changing this parameter can affect solve performance."); + "accuracy of each linear solve of the truncated newton step. " + "Changing this parameter can affect solve performance."); DEFINE_int32(num_threads, 1, "Number of threads."); DEFINE_int32(num_iterations, 5, "Number of iterations."); @@ -126,6 +129,8 @@ DEFINE_string(final_ply, "", "Export the refined BAL file data as a PLY " "file."); +// clang-format on + namespace ceres { namespace examples { namespace { @@ -138,11 +143,11 @@ CHECK(StringToVisibilityClusteringType(FLAGS_visibility_clustering, &options->visibility_clustering_type)); CHECK(StringToSparseLinearAlgebraLibraryType( - FLAGS_sparse_linear_algebra_library, - &options->sparse_linear_algebra_library_type)); + FLAGS_sparse_linear_algebra_library, + &options->sparse_linear_algebra_library_type)); CHECK(StringToDenseLinearAlgebraLibraryType( - FLAGS_dense_linear_algebra_library, - &options->dense_linear_algebra_library_type)); + FLAGS_dense_linear_algebra_library, + &options->dense_linear_algebra_library_type)); options->use_explicit_schur_complement = FLAGS_explicit_schur_complement; options->use_mixed_precision_solves = FLAGS_mixed_precision_solves; options->max_num_refinement_iterations = FLAGS_max_num_refinement_iterations; @@ -162,31 +167,37 @@ LOG(INFO) << "Camera blocks for inner iterations"; options->inner_iteration_ordering.reset(new ParameterBlockOrdering); for (int i = 0; i < num_cameras; ++i) { - options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 0); + options->inner_iteration_ordering->AddElementToGroup( + cameras + camera_block_size * i, 0); } } else if (FLAGS_blocks_for_inner_iterations == "points") { LOG(INFO) << "Point blocks for inner iterations"; options->inner_iteration_ordering.reset(new ParameterBlockOrdering); for (int i = 0; i < num_points; ++i) { - options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 0); + options->inner_iteration_ordering->AddElementToGroup( + points + point_block_size * i, 0); } } else if (FLAGS_blocks_for_inner_iterations == "cameras,points") { LOG(INFO) << "Camera followed by point blocks for inner iterations"; options->inner_iteration_ordering.reset(new ParameterBlockOrdering); for (int i = 0; i < num_cameras; ++i) { - options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 0); + options->inner_iteration_ordering->AddElementToGroup( + cameras + camera_block_size * i, 0); } for (int i = 0; i < num_points; ++i) { - options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 1); + options->inner_iteration_ordering->AddElementToGroup( + points + point_block_size * i, 1); } } else if (FLAGS_blocks_for_inner_iterations == "points,cameras") { LOG(INFO) << "Point followed by camera blocks for inner iterations"; options->inner_iteration_ordering.reset(new ParameterBlockOrdering); for (int i = 0; i < num_cameras; ++i) { - options->inner_iteration_ordering->AddElementToGroup(cameras + camera_block_size * i, 1); + options->inner_iteration_ordering->AddElementToGroup( + cameras + camera_block_size * i, 1); } for (int i = 0; i < num_points; ++i) { - options->inner_iteration_ordering->AddElementToGroup(points + point_block_size * i, 0); + options->inner_iteration_ordering->AddElementToGroup( + points + point_block_size * i, 0); } } else if (FLAGS_blocks_for_inner_iterations == "automatic") { LOG(INFO) << "Choosing automatic blocks for inner iterations"; @@ -211,8 +222,7 @@ return; } - ceres::ParameterBlockOrdering* ordering = - new ceres::ParameterBlockOrdering; + ceres::ParameterBlockOrdering* ordering = new ceres::ParameterBlockOrdering; // The points come before the cameras. for (int i = 0; i < num_points; ++i) { @@ -266,14 +276,11 @@ CostFunction* cost_function; // Each Residual block takes a point and a camera as input and // outputs a 2 dimensional residual. - cost_function = - (FLAGS_use_quaternions) - ? SnavelyReprojectionErrorWithQuaternions::Create( - observations[2 * i + 0], - observations[2 * i + 1]) - : SnavelyReprojectionError::Create( - observations[2 * i + 0], - observations[2 * i + 1]); + cost_function = (FLAGS_use_quaternions) + ? SnavelyReprojectionErrorWithQuaternions::Create( + observations[2 * i + 0], observations[2 * i + 1]) + : SnavelyReprojectionError::Create( + observations[2 * i + 0], observations[2 * i + 1]); // If enabled use Huber's loss function. LossFunction* loss_function = FLAGS_robustify ? new HuberLoss(1.0) : NULL; @@ -289,9 +296,8 @@ if (FLAGS_use_quaternions && FLAGS_use_local_parameterization) { LocalParameterization* camera_parameterization = - new ProductParameterization( - new QuaternionParameterization(), - new IdentityParameterization(6)); + new ProductParameterization(new QuaternionParameterization(), + new IdentityParameterization(6)); for (int i = 0; i < bal_problem->num_cameras(); ++i) { problem->SetParameterization(cameras + camera_block_size * i, camera_parameterization); @@ -310,9 +316,8 @@ srand(FLAGS_random_seed); bal_problem.Normalize(); - bal_problem.Perturb(FLAGS_rotation_sigma, - FLAGS_translation_sigma, - FLAGS_point_sigma); + bal_problem.Perturb( + FLAGS_rotation_sigma, FLAGS_translation_sigma, FLAGS_point_sigma); BuildProblem(&bal_problem, &problem); Solver::Options options;
diff --git a/examples/circle_fit.cc b/examples/circle_fit.cc index e963988..c542475 100644 --- a/examples/circle_fit.cc +++ b/examples/circle_fit.cc
@@ -48,7 +48,7 @@ // consider instead of using this one. If you already have a decent guess, Ceres // can squeeze down the last bit of error. // -// [1] http://www.mathworks.com/matlabcentral/fileexchange/5557-circle-fit/content/circfit.m +// [1] http://www.mathworks.com/matlabcentral/fileexchange/5557-circle-fit/content/circfit.m // NOLINT #include <cstdio> #include <vector> @@ -65,8 +65,10 @@ using ceres::Solve; using ceres::Solver; -DEFINE_double(robust_threshold, 0.0, "Robust loss parameter. Set to 0 for " - "normal squared error (no robustification)."); +DEFINE_double(robust_threshold, + 0.0, + "Robust loss parameter. Set to 0 for normal squared error (no " + "robustification)."); // The cost for a single sample. The returned residual is related to the // distance of the point from the circle (passed in as x, y, m parameters). @@ -76,10 +78,11 @@ class DistanceFromCircleCost { public: DistanceFromCircleCost(double xx, double yy) : xx_(xx), yy_(yy) {} - template <typename T> bool operator()(const T* const x, - const T* const y, - const T* const m, // r = m^2 - T* residual) const { + template <typename T> + bool operator()(const T* const x, + const T* const y, + const T* const m, // r = m^2 + T* residual) const { // Since the radius is parameterized as m^2, unpack m to get r. T r = *m * *m; @@ -97,7 +100,7 @@ // distance in the metric sense (it has units distance^2) it produces more // robust fits when there are outliers. This is because the cost surface is // more convex. - residual[0] = r*r - xp*xp - yp*yp; + residual[0] = r * r - xp * xp - yp * yp; return true; } @@ -137,7 +140,7 @@ double xx, yy; int num_points = 0; while (scanf("%lf %lf\n", &xx, &yy) == 2) { - CostFunction *cost = + CostFunction* cost = new AutoDiffCostFunction<DistanceFromCircleCost, 1, 1, 1, 1>( new DistanceFromCircleCost(xx, yy)); problem.AddResidualBlock(cost, loss, &x, &y, &m);
diff --git a/examples/curve_fitting.cc b/examples/curve_fitting.cc index 3f577f8..fc7ff94 100644 --- a/examples/curve_fitting.cc +++ b/examples/curve_fitting.cc
@@ -34,8 +34,8 @@ using ceres::AutoDiffCostFunction; using ceres::CostFunction; using ceres::Problem; -using ceres::Solver; using ceres::Solve; +using ceres::Solver; // Data generated using the following octave code. // randn('seed', 23497); @@ -48,6 +48,7 @@ // data = [x', y_observed']; const int kNumObservations = 67; +// clang-format off const double data[] = { 0.000000e+00, 1.133898e+00, 7.500000e-02, 1.334902e+00, @@ -117,14 +118,13 @@ 4.875000e+00, 4.727863e+00, 4.950000e+00, 4.669206e+00, }; +// clang-format on struct ExponentialResidual { - ExponentialResidual(double x, double y) - : x_(x), y_(y) {} + ExponentialResidual(double x, double y) : x_(x), y_(y) {} - template <typename T> bool operator()(const T* const m, - const T* const c, - T* residual) const { + template <typename T> + bool operator()(const T* const m, const T* const c, T* residual) const { residual[0] = y_ - exp(m[0] * x_ + c[0]); return true; } @@ -146,7 +146,8 @@ new AutoDiffCostFunction<ExponentialResidual, 1, 1, 1>( new ExponentialResidual(data[2 * i], data[2 * i + 1])), NULL, - &m, &c); + &m, + &c); } Solver::Options options;
diff --git a/examples/denoising.cc b/examples/denoising.cc index a4bc4d2..61ea2c6 100644 --- a/examples/denoising.cc +++ b/examples/denoising.cc
@@ -261,7 +261,8 @@ } if (FLAGS_foe_file.empty()) { - std::cerr << "Please provide a Fields of Experts file name using -foe_file.\n"; + std::cerr << "Please provide a Fields of Experts file name using -foe_file." + "\n"; return 1; }
diff --git a/examples/ellipse_approximation.cc b/examples/ellipse_approximation.cc index 59894a2..74782f4 100644 --- a/examples/ellipse_approximation.cc +++ b/examples/ellipse_approximation.cc
@@ -37,6 +37,7 @@ #include <cmath> #include <vector> + #include "ceres/ceres.h" #include "glog/logging.h" @@ -53,6 +54,7 @@ const int kYRows = 212; const int kYCols = 2; +// clang-format off const double kYData[kYRows * kYCols] = { +3.871364e+00, +9.916027e-01, +3.864003e+00, +1.034148e+00, @@ -267,6 +269,7 @@ +3.870542e+00, +9.996121e-01, +3.865424e+00, +1.028474e+00 }; +// clang-format on ceres::ConstMatrixRef kY(kYData, kYRows, kYCols); class PointToLineSegmentContourCostFunction : public ceres::CostFunction { @@ -382,9 +385,8 @@ // Eigen::MatrixXd is column major so we define our own MatrixXd which is // row major. Eigen::VectorXd can be used directly. - typedef Eigen::Matrix<double, - Eigen::Dynamic, Eigen::Dynamic, - Eigen::RowMajor> MatrixXd; + typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> + MatrixXd; using Eigen::VectorXd; // `X` is the matrix of control points which make up the contour of line @@ -420,18 +422,18 @@ for (int i = 0; i < num_observations; ++i) { parameter_blocks[0] = &t[i]; problem.AddResidualBlock( - PointToLineSegmentContourCostFunction::Create(num_segments, kY.row(i)), - NULL, - parameter_blocks); + PointToLineSegmentContourCostFunction::Create(num_segments, kY.row(i)), + NULL, + parameter_blocks); } // Add regularization to minimize the length of the line segment contour. for (int i = 0; i < num_segments; ++i) { problem.AddResidualBlock( - EuclideanDistanceFunctor::Create(sqrt(regularization_weight)), - NULL, - X.data() + 2 * i, - X.data() + 2 * ((i + 1) % num_segments)); + EuclideanDistanceFunctor::Create(sqrt(regularization_weight)), + NULL, + X.data() + 2 * i, + X.data() + 2 * ((i + 1) % num_segments)); } ceres::Solver::Options options;
diff --git a/examples/fields_of_experts.cc b/examples/fields_of_experts.cc index 60d179a..7b7983e 100644 --- a/examples/fields_of_experts.cc +++ b/examples/fields_of_experts.cc
@@ -33,8 +33,8 @@ #include "fields_of_experts.h" -#include <fstream> #include <cmath> +#include <fstream> #include "pgm_image.h" @@ -80,14 +80,12 @@ const double sum = 1.0 + sq_norm * c; const double inv = 1.0 / sum; // 'sum' and 'inv' are always positive, assuming that 's' is. - rho[0] = alpha_ * log(sum); + rho[0] = alpha_ * log(sum); rho[1] = alpha_ * c * inv; - rho[2] = - alpha_ * c * c * inv * inv; + rho[2] = -alpha_ * c * c * inv * inv; } -FieldsOfExperts::FieldsOfExperts() - : size_(0), num_filters_(0) { -} +FieldsOfExperts::FieldsOfExperts() : size_(0), num_filters_(0) {} bool FieldsOfExperts::LoadFromFile(const std::string& filename) { std::ifstream foe_file(filename.c_str()); @@ -147,6 +145,5 @@ return new FieldsOfExpertsLoss(alpha_[alpha_index]); } - } // namespace examples } // namespace ceres
diff --git a/examples/fields_of_experts.h b/examples/fields_of_experts.h index 210ca69..d7f1a4a 100644 --- a/examples/fields_of_experts.h +++ b/examples/fields_of_experts.h
@@ -47,10 +47,9 @@ #include <iostream> #include <vector> -#include "ceres/loss_function.h" #include "ceres/cost_function.h" +#include "ceres/loss_function.h" #include "ceres/sized_cost_function.h" - #include "pgm_image.h" namespace ceres { @@ -78,7 +77,7 @@ // class FieldsOfExpertsLoss : public ceres::LossFunction { public: - explicit FieldsOfExpertsLoss(double alpha) : alpha_(alpha) { } + explicit FieldsOfExpertsLoss(double alpha) : alpha_(alpha) {} virtual void Evaluate(double, double*) const; private: @@ -97,19 +96,13 @@ bool LoadFromFile(const std::string& filename); // Side length of a square filter in this FoE. They are all of the same size. - int Size() const { - return size_; - } + int Size() const { return size_; } // Total number of pixels the filter covers. - int NumVariables() const { - return size_ * size_; - } + int NumVariables() const { return size_ * size_; } // Number of filters used by the FoE. - int NumFilters() const { - return num_filters_; - } + int NumFilters() const { return num_filters_; } // Creates a new cost function. The caller is responsible for deallocating the // memory. alpha_index specifies which filter is used in the cost function. @@ -119,12 +112,8 @@ ceres::LossFunction* NewLossFunction(int alpha_index) const; // Gets the delta pixel indices for all pixels in a patch. - const std::vector<int>& GetXDeltaIndices() const { - return x_delta_indices_; - } - const std::vector<int>& GetYDeltaIndices() const { - return y_delta_indices_; - } + const std::vector<int>& GetXDeltaIndices() const { return x_delta_indices_; } + const std::vector<int>& GetYDeltaIndices() const { return y_delta_indices_; } private: // The side length of a square filter.
diff --git a/examples/helloworld.cc b/examples/helloworld.cc index d5d546c..9e32fad 100644 --- a/examples/helloworld.cc +++ b/examples/helloworld.cc
@@ -78,7 +78,6 @@ Solve(options, &problem, &summary); std::cout << summary.BriefReport() << "\n"; - std::cout << "x : " << initial_x - << " -> " << x << "\n"; + std::cout << "x : " << initial_x << " -> " << x << "\n"; return 0; }
diff --git a/examples/helloworld_analytic_diff.cc b/examples/helloworld_analytic_diff.cc index 9dbbc76..6e120b5 100644 --- a/examples/helloworld_analytic_diff.cc +++ b/examples/helloworld_analytic_diff.cc
@@ -33,20 +33,21 @@ // Minimize 0.5 (10 - x)^2 using analytic jacobian matrix. #include <vector> + #include "ceres/ceres.h" #include "glog/logging.h" using ceres::CostFunction; -using ceres::SizedCostFunction; using ceres::Problem; -using ceres::Solver; +using ceres::SizedCostFunction; using ceres::Solve; +using ceres::Solver; // A CostFunction implementing analytically derivatives for the // function f(x) = 10 - x. class QuadraticCostFunction - : public SizedCostFunction<1 /* number of residuals */, - 1 /* size of first parameter */> { + : public SizedCostFunction<1 /* number of residuals */, + 1 /* size of first parameter */> { public: virtual ~QuadraticCostFunction() {} @@ -100,8 +101,7 @@ Solve(options, &problem, &summary); std::cout << summary.BriefReport() << "\n"; - std::cout << "x : " << initial_x - << " -> " << x << "\n"; + std::cout << "x : " << initial_x << " -> " << x << "\n"; return 0; }
diff --git a/examples/helloworld_numeric_diff.cc b/examples/helloworld_numeric_diff.cc index 0810f47..474adf3 100644 --- a/examples/helloworld_numeric_diff.cc +++ b/examples/helloworld_numeric_diff.cc
@@ -34,12 +34,12 @@ #include "ceres/ceres.h" #include "glog/logging.h" -using ceres::NumericDiffCostFunction; using ceres::CENTRAL; using ceres::CostFunction; +using ceres::NumericDiffCostFunction; using ceres::Problem; -using ceres::Solver; using ceres::Solve; +using ceres::Solver; // A cost functor that implements the residual r = 10 - x. struct CostFunctor { @@ -63,7 +63,7 @@ // Set up the only cost function (also known as residual). This uses // numeric differentiation to obtain the derivative (jacobian). CostFunction* cost_function = - new NumericDiffCostFunction<CostFunctor, CENTRAL, 1, 1> (new CostFunctor); + new NumericDiffCostFunction<CostFunctor, CENTRAL, 1, 1>(new CostFunctor); problem.AddResidualBlock(cost_function, NULL, &x); // Run the solver! @@ -73,7 +73,6 @@ Solve(options, &problem, &summary); std::cout << summary.BriefReport() << "\n"; - std::cout << "x : " << initial_x - << " -> " << x << "\n"; + std::cout << "x : " << initial_x << " -> " << x << "\n"; return 0; }
diff --git a/examples/libmv_bundle_adjuster.cc b/examples/libmv_bundle_adjuster.cc index 22bcf5b..b1eb220 100644 --- a/examples/libmv_bundle_adjuster.cc +++ b/examples/libmv_bundle_adjuster.cc
@@ -87,16 +87,17 @@ // There're existing problem files dumped from blender stored in folder // ../data/libmv-ba-problems. -#include <cstdio> #include <fcntl.h> + +#include <cstdio> #include <sstream> #include <string> #include <vector> #ifdef _MSC_VER -# include <io.h> -# define open _open -# define close _close +#include <io.h> +#define open _open +#define close _close typedef unsigned __int32 uint32_t; #else #include <stdint.h> @@ -121,8 +122,9 @@ using std::vector; DEFINE_string(input, "", "Input File name"); -DEFINE_string(refine_intrinsics, "", "Camera intrinsics to be refined. " - "Options are: none, radial."); +DEFINE_string(refine_intrinsics, + "", + "Camera intrinsics to be refined. Options are: none, radial."); namespace { @@ -134,7 +136,7 @@ // t is a translation vector representing its positions. struct EuclideanCamera { EuclideanCamera() : image(-1) {} - EuclideanCamera(const EuclideanCamera &c) : image(c.image), R(c.R), t(c.t) {} + EuclideanCamera(const EuclideanCamera& c) : image(c.image), R(c.R), t(c.t) {} int image; Mat3 R; @@ -147,7 +149,7 @@ // X represents the 3D position of the track. struct EuclideanPoint { EuclideanPoint() : track(-1) {} - EuclideanPoint(const EuclideanPoint &p) : track(p.track), X(p.X) {} + EuclideanPoint(const EuclideanPoint& p) : track(p.track), X(p.X) {} int track; Vec3 X; }; @@ -201,25 +203,24 @@ }; // Returns a pointer to the camera corresponding to a image. -EuclideanCamera *CameraForImage(vector<EuclideanCamera> *all_cameras, +EuclideanCamera* CameraForImage(vector<EuclideanCamera>* all_cameras, const int image) { if (image < 0 || image >= all_cameras->size()) { return NULL; } - EuclideanCamera *camera = &(*all_cameras)[image]; + EuclideanCamera* camera = &(*all_cameras)[image]; if (camera->image == -1) { return NULL; } return camera; } -const EuclideanCamera *CameraForImage( - const vector<EuclideanCamera> &all_cameras, - const int image) { +const EuclideanCamera* CameraForImage( + const vector<EuclideanCamera>& all_cameras, const int image) { if (image < 0 || image >= all_cameras.size()) { return NULL; } - const EuclideanCamera *camera = &all_cameras[image]; + const EuclideanCamera* camera = &all_cameras[image]; if (camera->image == -1) { return NULL; } @@ -227,7 +228,7 @@ } // Returns maximal image number at which marker exists. -int MaxImage(const vector<Marker> &all_markers) { +int MaxImage(const vector<Marker>& all_markers) { if (all_markers.size() == 0) { return -1; } @@ -240,12 +241,12 @@ } // Returns a pointer to the point corresponding to a track. -EuclideanPoint *PointForTrack(vector<EuclideanPoint> *all_points, +EuclideanPoint* PointForTrack(vector<EuclideanPoint>* all_points, const int track) { if (track < 0 || track >= all_points->size()) { return NULL; } - EuclideanPoint *point = &(*all_points)[track]; + EuclideanPoint* point = &(*all_points)[track]; if (point->track == -1) { return NULL; } @@ -266,7 +267,7 @@ union { unsigned char bytes[4]; uint32_t value; - } endian_test = { { 0, 1, 2, 3 } }; + } endian_test = {{0, 1, 2, 3}}; host_endian_type_ = endian_test.value; file_endian_type_ = host_endian_type_; } @@ -277,7 +278,7 @@ } } - bool OpenFile(const std::string &file_name) { + bool OpenFile(const std::string& file_name) { file_descriptor_ = open(file_name.c_str(), O_RDONLY | O_BINARY); if (file_descriptor_ < 0) { return false; @@ -306,6 +307,7 @@ } return value; } + private: static constexpr long int kLittleEndian = 0x03020100ul; static constexpr long int kBigEndian = 0x00010203ul; @@ -315,14 +317,17 @@ T SwitchEndian(const T value) const { if (sizeof(T) == 4) { unsigned int temp_value = static_cast<unsigned int>(value); + // clang-format off return ((temp_value >> 24)) | ((temp_value << 8) & 0x00ff0000) | ((temp_value >> 8) & 0x0000ff00) | ((temp_value << 24)); + // clang-format on } else if (sizeof(T) == 1) { return value; } else { - LOG(FATAL) << "Entered non-implemented part of endian switching function."; + LOG(FATAL) << "Entered non-implemented part of endian " + "switching function."; } } @@ -332,16 +337,14 @@ }; // Read 3x3 column-major matrix from the file -void ReadMatrix3x3(const EndianAwareFileReader &file_reader, - Mat3 *matrix) { +void ReadMatrix3x3(const EndianAwareFileReader& file_reader, Mat3* matrix) { for (int i = 0; i < 9; i++) { (*matrix)(i % 3, i / 3) = file_reader.Read<float>(); } } // Read 3-vector from file -void ReadVector3(const EndianAwareFileReader &file_reader, - Vec3 *vector) { +void ReadVector3(const EndianAwareFileReader& file_reader, Vec3* vector) { for (int i = 0; i < 3; i++) { (*vector)(i) = file_reader.Read<float>(); } @@ -364,12 +367,12 @@ // // Returns false if any kind of error happened during // reading. -bool ReadProblemFromFile(const std::string &file_name, +bool ReadProblemFromFile(const std::string& file_name, double camera_intrinsics[8], - vector<EuclideanCamera> *all_cameras, - vector<EuclideanPoint> *all_points, - bool *is_image_space, - vector<Marker> *all_markers) { + vector<EuclideanCamera>* all_cameras, + vector<EuclideanPoint>* all_points, + bool* is_image_space, + vector<Marker>* all_markers) { EndianAwareFileReader file_reader; if (!file_reader.OpenFile(file_name)) { return false; @@ -451,24 +454,24 @@ // camera coordinates (i.e. the principal point is at (0, 0)) to get image // coordinates in pixels. Templated for use with autodifferentiation. template <typename T> -inline void ApplyRadialDistortionCameraIntrinsics(const T &focal_length_x, - const T &focal_length_y, - const T &principal_point_x, - const T &principal_point_y, - const T &k1, - const T &k2, - const T &k3, - const T &p1, - const T &p2, - const T &normalized_x, - const T &normalized_y, - T *image_x, - T *image_y) { +inline void ApplyRadialDistortionCameraIntrinsics(const T& focal_length_x, + const T& focal_length_y, + const T& principal_point_x, + const T& principal_point_y, + const T& k1, + const T& k2, + const T& k3, + const T& p1, + const T& p2, + const T& normalized_x, + const T& normalized_y, + T* image_x, + T* image_y) { T x = normalized_x; T y = normalized_y; // Apply distortion to the normalized points to get (xd, yd). - T r2 = x*x + y*y; + T r2 = x * x + y * y; T r4 = r2 * r2; T r6 = r4 * r2; T r_coeff = 1.0 + k1 * r2 + k2 * r4 + k3 * r6; @@ -496,14 +499,14 @@ const T* const X, // Point coordinates 3x1. T* residuals) const { // Unpack the intrinsics. - const T& focal_length = intrinsics[OFFSET_FOCAL_LENGTH]; + const T& focal_length = intrinsics[OFFSET_FOCAL_LENGTH]; const T& principal_point_x = intrinsics[OFFSET_PRINCIPAL_POINT_X]; const T& principal_point_y = intrinsics[OFFSET_PRINCIPAL_POINT_Y]; - const T& k1 = intrinsics[OFFSET_K1]; - const T& k2 = intrinsics[OFFSET_K2]; - const T& k3 = intrinsics[OFFSET_K3]; - const T& p1 = intrinsics[OFFSET_P1]; - const T& p2 = intrinsics[OFFSET_P2]; + const T& k1 = intrinsics[OFFSET_K1]; + const T& k2 = intrinsics[OFFSET_K2]; + const T& k3 = intrinsics[OFFSET_K3]; + const T& p1 = intrinsics[OFFSET_P1]; + const T& p2 = intrinsics[OFFSET_P2]; // Compute projective coordinates: x = RX + t. T x[3]; @@ -526,9 +529,13 @@ focal_length, principal_point_x, principal_point_y, - k1, k2, k3, - p1, p2, - xn, yn, + k1, + k2, + k3, + p1, + p2, + xn, + yn, &predicted_x, &predicted_y); @@ -551,40 +558,41 @@ std::string bundling_message = ""; #define APPEND_BUNDLING_INTRINSICS(name, flag) \ - if (bundle_intrinsics & flag) { \ - if (!bundling_message.empty()) { \ - bundling_message += ", "; \ - } \ - bundling_message += name; \ - } (void)0 + if (bundle_intrinsics & flag) { \ + if (!bundling_message.empty()) { \ + bundling_message += ", "; \ + } \ + bundling_message += name; \ + } \ + (void)0 - APPEND_BUNDLING_INTRINSICS("f", BUNDLE_FOCAL_LENGTH); + APPEND_BUNDLING_INTRINSICS("f", BUNDLE_FOCAL_LENGTH); APPEND_BUNDLING_INTRINSICS("px, py", BUNDLE_PRINCIPAL_POINT); - APPEND_BUNDLING_INTRINSICS("k1", BUNDLE_RADIAL_K1); - APPEND_BUNDLING_INTRINSICS("k2", BUNDLE_RADIAL_K2); - APPEND_BUNDLING_INTRINSICS("p1", BUNDLE_TANGENTIAL_P1); - APPEND_BUNDLING_INTRINSICS("p2", BUNDLE_TANGENTIAL_P2); + APPEND_BUNDLING_INTRINSICS("k1", BUNDLE_RADIAL_K1); + APPEND_BUNDLING_INTRINSICS("k2", BUNDLE_RADIAL_K2); + APPEND_BUNDLING_INTRINSICS("p1", BUNDLE_TANGENTIAL_P1); + APPEND_BUNDLING_INTRINSICS("p2", BUNDLE_TANGENTIAL_P2); LOG(INFO) << "Bundling " << bundling_message << "."; } } // Print a message to the log containing all the camera intriniscs values. -void PrintCameraIntrinsics(const char *text, const double *camera_intrinsics) { +void PrintCameraIntrinsics(const char* text, const double* camera_intrinsics) { std::ostringstream intrinsics_output; intrinsics_output << "f=" << camera_intrinsics[OFFSET_FOCAL_LENGTH]; - intrinsics_output << - " cx=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_X] << - " cy=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_Y]; + intrinsics_output << " cx=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_X] + << " cy=" << camera_intrinsics[OFFSET_PRINCIPAL_POINT_Y]; -#define APPEND_DISTORTION_COEFFICIENT(name, offset) \ - { \ - if (camera_intrinsics[offset] != 0.0) { \ - intrinsics_output << " " name "=" << camera_intrinsics[offset]; \ - } \ - } (void)0 +#define APPEND_DISTORTION_COEFFICIENT(name, offset) \ + { \ + if (camera_intrinsics[offset] != 0.0) { \ + intrinsics_output << " " name "=" << camera_intrinsics[offset]; \ + } \ + } \ + (void)0 APPEND_DISTORTION_COEFFICIENT("k1", OFFSET_K1); APPEND_DISTORTION_COEFFICIENT("k2", OFFSET_K2); @@ -603,22 +611,21 @@ // Element with index i matches to a rotation+translation for // camera at image i. vector<Vec6> PackCamerasRotationAndTranslation( - const vector<Marker> &all_markers, - const vector<EuclideanCamera> &all_cameras) { + const vector<Marker>& all_markers, + const vector<EuclideanCamera>& all_cameras) { vector<Vec6> all_cameras_R_t; int max_image = MaxImage(all_markers); all_cameras_R_t.resize(max_image + 1); for (int i = 0; i <= max_image; i++) { - const EuclideanCamera *camera = CameraForImage(all_cameras, i); + const EuclideanCamera* camera = CameraForImage(all_cameras, i); if (!camera) { continue; } - ceres::RotationMatrixToAngleAxis(&camera->R(0, 0), - &all_cameras_R_t[i](0)); + ceres::RotationMatrixToAngleAxis(&camera->R(0, 0), &all_cameras_R_t[i](0)); all_cameras_R_t[i].tail<3>() = camera->t; } @@ -626,31 +633,29 @@ } // Convert cameras rotations fro mangle axis back to rotation matrix. -void UnpackCamerasRotationAndTranslation( - const vector<Marker> &all_markers, - const vector<Vec6> &all_cameras_R_t, - vector<EuclideanCamera> *all_cameras) { +void UnpackCamerasRotationAndTranslation(const vector<Marker>& all_markers, + const vector<Vec6>& all_cameras_R_t, + vector<EuclideanCamera>* all_cameras) { int max_image = MaxImage(all_markers); for (int i = 0; i <= max_image; i++) { - EuclideanCamera *camera = CameraForImage(all_cameras, i); + EuclideanCamera* camera = CameraForImage(all_cameras, i); if (!camera) { continue; } - ceres::AngleAxisToRotationMatrix(&all_cameras_R_t[i](0), - &camera->R(0, 0)); + ceres::AngleAxisToRotationMatrix(&all_cameras_R_t[i](0), &camera->R(0, 0)); camera->t = all_cameras_R_t[i].tail<3>(); } } -void EuclideanBundleCommonIntrinsics(const vector<Marker> &all_markers, +void EuclideanBundleCommonIntrinsics(const vector<Marker>& all_markers, const int bundle_intrinsics, const int bundle_constraints, - double *camera_intrinsics, - vector<EuclideanCamera> *all_cameras, - vector<EuclideanPoint> *all_points) { + double* camera_intrinsics, + vector<EuclideanCamera>* all_cameras, + vector<EuclideanPoint>* all_points) { PrintCameraIntrinsics("Original intrinsics: ", camera_intrinsics); ceres::Problem::Options problem_options; @@ -663,49 +668,50 @@ // Block for minimization has got the following structure: // <3 elements for angle-axis> <3 elements for translation> vector<Vec6> all_cameras_R_t = - PackCamerasRotationAndTranslation(all_markers, *all_cameras); + PackCamerasRotationAndTranslation(all_markers, *all_cameras); // Parameterization used to restrict camera motion for modal solvers. - ceres::SubsetParameterization *constant_transform_parameterization = NULL; + ceres::SubsetParameterization* constant_transform_parameterization = NULL; if (bundle_constraints & BUNDLE_NO_TRANSLATION) { - std::vector<int> constant_translation; + std::vector<int> constant_translation; - // First three elements are rotation, last three are translation. - constant_translation.push_back(3); - constant_translation.push_back(4); - constant_translation.push_back(5); + // First three elements are rotation, last three are translation. + constant_translation.push_back(3); + constant_translation.push_back(4); + constant_translation.push_back(5); - constant_transform_parameterization = + constant_transform_parameterization = new ceres::SubsetParameterization(6, constant_translation); } std::vector<OpenCVReprojectionError> errors; - std::vector<ceres::AutoDiffCostFunction<OpenCVReprojectionError, 2, 8, 6, 3>> costFunctions; + std::vector<ceres::AutoDiffCostFunction<OpenCVReprojectionError, 2, 8, 6, 3>> + costFunctions; errors.reserve(all_markers.size()); costFunctions.reserve(all_markers.size()); int num_residuals = 0; bool have_locked_camera = false; for (int i = 0; i < all_markers.size(); ++i) { - const Marker &marker = all_markers[i]; - EuclideanCamera *camera = CameraForImage(all_cameras, marker.image); - EuclideanPoint *point = PointForTrack(all_points, marker.track); + const Marker& marker = all_markers[i]; + EuclideanCamera* camera = CameraForImage(all_cameras, marker.image); + EuclideanPoint* point = PointForTrack(all_points, marker.track); if (camera == NULL || point == NULL) { continue; } // Rotation of camera denoted in angle axis followed with // camera translaiton. - double *current_camera_R_t = &all_cameras_R_t[camera->image](0); + double* current_camera_R_t = &all_cameras_R_t[camera->image](0); errors.emplace_back(marker.x, marker.y); costFunctions.emplace_back(&errors.back(), ceres::DO_NOT_TAKE_OWNERSHIP); problem.AddResidualBlock(&costFunctions.back(), - NULL, - camera_intrinsics, - current_camera_R_t, - &point->X(0)); + NULL, + camera_intrinsics, + current_camera_R_t, + &point->X(0)); // We lock the first camera to better deal with scene orientation ambiguity. if (!have_locked_camera) { @@ -739,23 +745,23 @@ std::vector<int> constant_intrinsics; #define MAYBE_SET_CONSTANT(bundle_enum, offset) \ - if (!(bundle_intrinsics & bundle_enum)) { \ - constant_intrinsics.push_back(offset); \ - } - MAYBE_SET_CONSTANT(BUNDLE_FOCAL_LENGTH, OFFSET_FOCAL_LENGTH); + if (!(bundle_intrinsics & bundle_enum)) { \ + constant_intrinsics.push_back(offset); \ + } + MAYBE_SET_CONSTANT(BUNDLE_FOCAL_LENGTH, OFFSET_FOCAL_LENGTH); MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_X); MAYBE_SET_CONSTANT(BUNDLE_PRINCIPAL_POINT, OFFSET_PRINCIPAL_POINT_Y); - MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K1, OFFSET_K1); - MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K2, OFFSET_K2); - MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P1, OFFSET_P1); - MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P2, OFFSET_P2); + MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K1, OFFSET_K1); + MAYBE_SET_CONSTANT(BUNDLE_RADIAL_K2, OFFSET_K2); + MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P1, OFFSET_P1); + MAYBE_SET_CONSTANT(BUNDLE_TANGENTIAL_P2, OFFSET_P2); #undef MAYBE_SET_CONSTANT // Always set K3 constant, it's not used at the moment. constant_intrinsics.push_back(OFFSET_K3); - ceres::SubsetParameterization *subset_parameterization = - new ceres::SubsetParameterization(8, constant_intrinsics); + ceres::SubsetParameterization* subset_parameterization = + new ceres::SubsetParameterization(8, constant_intrinsics); problem.SetParameterization(camera_intrinsics, subset_parameterization); } @@ -776,15 +782,14 @@ std::cout << "Final report:\n" << summary.FullReport(); // Copy rotations and translations back. - UnpackCamerasRotationAndTranslation(all_markers, - all_cameras_R_t, - all_cameras); + UnpackCamerasRotationAndTranslation( + all_markers, all_cameras_R_t, all_cameras); PrintCameraIntrinsics("Final intrinsics: ", camera_intrinsics); } } // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]);
diff --git a/examples/libmv_homography.cc b/examples/libmv_homography.cc index fe647da..55f3b70 100644 --- a/examples/libmv_homography.cc +++ b/examples/libmv_homography.cc
@@ -54,8 +54,8 @@ // homogeneous system of equations via singular value decomposition, giving an // algebraic solution for the homography, then solving for a final solution by // minimizing the symmetric transfer error in image space with Ceres (called the -// Gold Standard Solution in "Multiple View Geometry"). The routines are based on -// the routines from the Libmv library. +// Gold Standard Solution in "Multiple View Geometry"). The routines are based +// on the routines from the Libmv library. // // This example demonstrates custom exit criterion by having a callback check // for image-space error. @@ -69,7 +69,7 @@ typedef Eigen::VectorXd Vec; typedef Eigen::Matrix<double, 3, 3> Mat3; typedef Eigen::Matrix<double, 2, 1> Vec2; -typedef Eigen::Matrix<double, Eigen::Dynamic, 8> MatX8; +typedef Eigen::Matrix<double, Eigen::Dynamic, 8> MatX8; typedef Eigen::Vector3d Vec3; namespace { @@ -83,8 +83,7 @@ // Default settings for homography estimation which should be suitable // for a wide range of use cases. EstimateHomographyOptions() - : max_num_iterations(50), - expected_average_symmetric_distance(1e-16) {} + : max_num_iterations(50), expected_average_symmetric_distance(1e-16) {} // Maximal number of iterations for the refinement step. int max_num_iterations; @@ -107,9 +106,9 @@ // // Templated to be used with autodifferentiation. template <typename T> -void SymmetricGeometricDistanceTerms(const Eigen::Matrix<T, 3, 3> &H, - const Eigen::Matrix<T, 2, 1> &x1, - const Eigen::Matrix<T, 2, 1> &x2, +void SymmetricGeometricDistanceTerms(const Eigen::Matrix<T, 3, 3>& H, + const Eigen::Matrix<T, 2, 1>& x1, + const Eigen::Matrix<T, 2, 1>& x2, T forward_error[2], T backward_error[2]) { typedef Eigen::Matrix<T, 3, 1> Vec3; @@ -132,17 +131,13 @@ // // D(H * x1, x2)^2 + D(H^-1 * x2, x1)^2 // -double SymmetricGeometricDistance(const Mat3 &H, - const Vec2 &x1, - const Vec2 &x2) { +double SymmetricGeometricDistance(const Mat3& H, + const Vec2& x1, + const Vec2& x2) { Vec2 forward_error, backward_error; - SymmetricGeometricDistanceTerms<double>(H, - x1, - x2, - forward_error.data(), - backward_error.data()); - return forward_error.squaredNorm() + - backward_error.squaredNorm(); + SymmetricGeometricDistanceTerms<double>( + H, x1, x2, forward_error.data(), backward_error.data()); + return forward_error.squaredNorm() + backward_error.squaredNorm(); } // A parameterization of the 2D homography matrix that uses 8 parameters so @@ -154,24 +149,28 @@ // H = |d e f| // |g h 1| // -template<typename T = double> +template <typename T = double> class Homography2DNormalizedParameterization { public: typedef Eigen::Matrix<T, 8, 1> Parameters; // a, b, ... g, h typedef Eigen::Matrix<T, 3, 3> Parameterized; // H // Convert from the 8 parameters to a H matrix. - static void To(const Parameters &p, Parameterized *h) { + static void To(const Parameters& p, Parameterized* h) { + // clang-format off *h << p(0), p(1), p(2), p(3), p(4), p(5), p(6), p(7), 1.0; + // clang-format on } // Convert from a H matrix to the 8 parameters. - static void From(const Parameterized &h, Parameters *p) { + static void From(const Parameterized& h, Parameters* p) { + // clang-format off *p << h(0, 0), h(0, 1), h(0, 2), h(1, 0), h(1, 1), h(1, 2), h(2, 0), h(2, 1); + // clang-format on } }; @@ -194,11 +193,10 @@ // (a-x1*g)*y1 + (b-x1*h)*y2 + c-x1 = |0| // (-x2*a+x1*d)*y1 + (-x2*b+x1*e)*y2 + -x2*c+x1*f |0| // -bool Homography2DFromCorrespondencesLinearEuc( - const Mat &x1, - const Mat &x2, - Mat3 *H, - double expected_precision) { +bool Homography2DFromCorrespondencesLinearEuc(const Mat& x1, + const Mat& x2, + Mat3* H, + double expected_precision) { assert(2 == x1.rows()); assert(4 <= x1.cols()); assert(x1.rows() == x2.rows()); @@ -209,27 +207,27 @@ Mat b = Mat::Zero(n * 3, 1); for (int i = 0; i < n; ++i) { int j = 3 * i; - L(j, 0) = x1(0, i); // a - L(j, 1) = x1(1, i); // b - L(j, 2) = 1.0; // c + L(j, 0) = x1(0, i); // a + L(j, 1) = x1(1, i); // b + L(j, 2) = 1.0; // c L(j, 6) = -x2(0, i) * x1(0, i); // g L(j, 7) = -x2(0, i) * x1(1, i); // h - b(j, 0) = x2(0, i); // i + b(j, 0) = x2(0, i); // i ++j; - L(j, 3) = x1(0, i); // d - L(j, 4) = x1(1, i); // e - L(j, 5) = 1.0; // f + L(j, 3) = x1(0, i); // d + L(j, 4) = x1(1, i); // e + L(j, 5) = 1.0; // f L(j, 6) = -x2(1, i) * x1(0, i); // g L(j, 7) = -x2(1, i) * x1(1, i); // h - b(j, 0) = x2(1, i); // i + b(j, 0) = x2(1, i); // i // This ensures better stability // TODO(julien) make a lite version without this 3rd set ++j; - L(j, 0) = x2(1, i) * x1(0, i); // a - L(j, 1) = x2(1, i) * x1(1, i); // b - L(j, 2) = x2(1, i); // c + L(j, 0) = x2(1, i) * x1(0, i); // a + L(j, 1) = x2(1, i) * x1(1, i); // b + L(j, 2) = x2(1, i); // c L(j, 3) = -x2(0, i) * x1(0, i); // d L(j, 4) = -x2(0, i) * x1(1, i); // e L(j, 5) = -x2(0, i); // f @@ -244,11 +242,10 @@ // used for homography matrix refinement. class HomographySymmetricGeometricCostFunctor { public: - HomographySymmetricGeometricCostFunctor(const Vec2 &x, - const Vec2 &y) - : x_(x), y_(y) { } + HomographySymmetricGeometricCostFunctor(const Vec2& x, const Vec2& y) + : x_(x), y_(y) {} - template<typename T> + template <typename T> bool operator()(const T* homography_parameters, T* residuals) const { typedef Eigen::Matrix<T, 3, 3> Mat3; typedef Eigen::Matrix<T, 2, 1> Vec2; @@ -257,11 +254,7 @@ Vec2 x(T(x_(0)), T(x_(1))); Vec2 y(T(y_(0)), T(y_(1))); - SymmetricGeometricDistanceTerms<T>(H, - x, - y, - &residuals[0], - &residuals[2]); + SymmetricGeometricDistanceTerms<T>(H, x, y, &residuals[0], &residuals[2]); return true; } @@ -278,9 +271,10 @@ // points < 0.5px error). class TerminationCheckingCallback : public ceres::IterationCallback { public: - TerminationCheckingCallback(const Mat &x1, const Mat &x2, - const EstimateHomographyOptions &options, - Mat3 *H) + TerminationCheckingCallback(const Mat& x1, + const Mat& x2, + const EstimateHomographyOptions& options, + Mat3* H) : options_(options), x1_(x1), x2_(x2), H_(H) {} virtual ceres::CallbackReturnType operator()( @@ -293,9 +287,8 @@ // Calculate average of symmetric geometric distance. double average_distance = 0.0; for (int i = 0; i < x1_.cols(); i++) { - average_distance += SymmetricGeometricDistance(*H_, - x1_.col(i), - x2_.col(i)); + average_distance += + SymmetricGeometricDistance(*H_, x1_.col(i), x2_.col(i)); } average_distance /= x1_.cols(); @@ -307,17 +300,17 @@ } private: - const EstimateHomographyOptions &options_; - const Mat &x1_; - const Mat &x2_; - Mat3 *H_; + const EstimateHomographyOptions& options_; + const Mat& x1_; + const Mat& x2_; + Mat3* H_; }; bool EstimateHomography2DFromCorrespondences( - const Mat &x1, - const Mat &x2, - const EstimateHomographyOptions &options, - Mat3 *H) { + const Mat& x1, + const Mat& x2, + const EstimateHomographyOptions& options, + Mat3* H) { assert(2 == x1.rows()); assert(4 <= x1.cols()); assert(x1.rows() == x2.rows()); @@ -325,26 +318,23 @@ // Step 1: Algebraic homography estimation. // Assume algebraic estimation always succeeds. - Homography2DFromCorrespondencesLinearEuc(x1, - x2, - H, - EigenDouble::dummy_precision()); + Homography2DFromCorrespondencesLinearEuc( + x1, x2, H, EigenDouble::dummy_precision()); LOG(INFO) << "Estimated matrix after algebraic estimation:\n" << *H; // Step 2: Refine matrix using Ceres minimizer. ceres::Problem problem; for (int i = 0; i < x1.cols(); i++) { - HomographySymmetricGeometricCostFunctor - *homography_symmetric_geometric_cost_function = - new HomographySymmetricGeometricCostFunctor(x1.col(i), - x2.col(i)); + HomographySymmetricGeometricCostFunctor* + homography_symmetric_geometric_cost_function = + new HomographySymmetricGeometricCostFunctor(x1.col(i), x2.col(i)); problem.AddResidualBlock( - new ceres::AutoDiffCostFunction< - HomographySymmetricGeometricCostFunctor, - 4, // num_residuals - 9>(homography_symmetric_geometric_cost_function), + new ceres::AutoDiffCostFunction<HomographySymmetricGeometricCostFunctor, + 4, // num_residuals + 9>( + homography_symmetric_geometric_cost_function), NULL, H->data()); } @@ -369,9 +359,9 @@ return summary.IsSolutionUsable(); } -} // namespace libmv +} // namespace -int main(int argc, char **argv) { +int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); Mat x1(2, 100); @@ -382,9 +372,11 @@ Mat3 homography_matrix; // This matrix has been dumped from a Blender test file of plane tracking. + // clang-format off homography_matrix << 1.243715, -0.461057, -111.964454, 0.0, 0.617589, -192.379252, 0.0, -0.000983, 1.0; + // clang-format on Mat x2 = x1; for (int i = 0; i < x2.cols(); ++i) { @@ -405,7 +397,7 @@ EstimateHomography2DFromCorrespondences(x1, x2, options, &estimated_matrix); // Normalize the matrix for easier comparison. - estimated_matrix /= estimated_matrix(2 ,2); + estimated_matrix /= estimated_matrix(2, 2); std::cout << "Original matrix:\n" << homography_matrix << "\n"; std::cout << "Estimated matrix:\n" << estimated_matrix << "\n";
diff --git a/examples/more_garbow_hillstrom.cc b/examples/more_garbow_hillstrom.cc index 0dc8fbf..e39d23c 100644 --- a/examples/more_garbow_hillstrom.cc +++ b/examples/more_garbow_hillstrom.cc
@@ -50,24 +50,27 @@ // A problem is considered solved if of the log relative error of its // objective function is at least 4. - #include <cmath> #include <iostream> // NOLINT #include <sstream> // NOLINT #include <string> + #include "ceres/ceres.h" #include "gflags/gflags.h" #include "glog/logging.h" DEFINE_string(problem, "all", "Which problem to solve"); -DEFINE_bool(use_numeric_diff, false, - "Use numeric differentiation instead of automatic " - "differentiation."); -DEFINE_string(numeric_diff_method, "ridders", "When using numeric " - "differentiation, selects algorithm. Options are: central, " - "forward, ridders."); -DEFINE_int32(ridders_extrapolations, 3, "Maximal number of extrapolations in " - "Ridders' method."); +DEFINE_bool(use_numeric_diff, + false, + "Use numeric differentiation instead of automatic" + " differentiation."); +DEFINE_string(numeric_diff_method, + "ridders", + "When using numeric differentiation, selects algorithm. Options " + "are: central, forward, ridders."); +DEFINE_int32(ridders_extrapolations, + 3, + "Maximal number of extrapolations in Ridders' method."); namespace ceres { namespace examples { @@ -78,48 +81,48 @@ options->max_num_ridders_extrapolations = FLAGS_ridders_extrapolations; } -#define BEGIN_MGH_PROBLEM(name, num_parameters, num_residuals) \ - struct name { \ - static constexpr int kNumParameters = num_parameters; \ - static const double initial_x[kNumParameters]; \ - static const double lower_bounds[kNumParameters]; \ - static const double upper_bounds[kNumParameters]; \ - static const double constrained_optimal_cost; \ - static const double unconstrained_optimal_cost; \ - static CostFunction* Create() { \ - if (FLAGS_use_numeric_diff) { \ - ceres::NumericDiffOptions options; \ - SetNumericDiffOptions(&options); \ - if (FLAGS_numeric_diff_method == "central") { \ - return new NumericDiffCostFunction<name, \ - ceres::CENTRAL, \ - num_residuals, \ - num_parameters>( \ - new name, ceres::TAKE_OWNERSHIP, num_residuals, options); \ - } else if (FLAGS_numeric_diff_method == "forward") { \ - return new NumericDiffCostFunction<name, \ - ceres::FORWARD, \ - num_residuals, \ - num_parameters>( \ - new name, ceres::TAKE_OWNERSHIP, num_residuals, options); \ - } else if (FLAGS_numeric_diff_method == "ridders") { \ - return new NumericDiffCostFunction<name, \ - ceres::RIDDERS, \ - num_residuals, \ - num_parameters>( \ - new name, ceres::TAKE_OWNERSHIP, num_residuals, options); \ - } else { \ - LOG(ERROR) << "Invalid numeric diff method specified"; \ - return NULL; \ - } \ - } else { \ - return new AutoDiffCostFunction<name, \ - num_residuals, \ - num_parameters>(new name); \ - } \ - } \ - template <typename T> \ +#define BEGIN_MGH_PROBLEM(name, num_parameters, num_residuals) \ + struct name { \ + static constexpr int kNumParameters = num_parameters; \ + static const double initial_x[kNumParameters]; \ + static const double lower_bounds[kNumParameters]; \ + static const double upper_bounds[kNumParameters]; \ + static const double constrained_optimal_cost; \ + static const double unconstrained_optimal_cost; \ + static CostFunction* Create() { \ + if (FLAGS_use_numeric_diff) { \ + ceres::NumericDiffOptions options; \ + SetNumericDiffOptions(&options); \ + if (FLAGS_numeric_diff_method == "central") { \ + return new NumericDiffCostFunction<name, \ + ceres::CENTRAL, \ + num_residuals, \ + num_parameters>( \ + new name, ceres::TAKE_OWNERSHIP, num_residuals, options); \ + } else if (FLAGS_numeric_diff_method == "forward") { \ + return new NumericDiffCostFunction<name, \ + ceres::FORWARD, \ + num_residuals, \ + num_parameters>( \ + new name, ceres::TAKE_OWNERSHIP, num_residuals, options); \ + } else if (FLAGS_numeric_diff_method == "ridders") { \ + return new NumericDiffCostFunction<name, \ + ceres::RIDDERS, \ + num_residuals, \ + num_parameters>( \ + new name, ceres::TAKE_OWNERSHIP, num_residuals, options); \ + } else { \ + LOG(ERROR) << "Invalid numeric diff method specified"; \ + return NULL; \ + } \ + } else { \ + return new AutoDiffCostFunction<name, num_residuals, num_parameters>( \ + new name); \ + } \ + } \ + template <typename T> \ bool operator()(const T* const x, T* residual) const { +// clang-format off #define END_MGH_PROBLEM return true; } }; // NOLINT @@ -535,7 +538,10 @@ #undef BEGIN_MGH_PROBLEM #undef END_MGH_PROBLEM -template<typename TestProblem> bool Solve(bool is_constrained, int trial) { +// clang-format on + +template <typename TestProblem> +bool Solve(bool is_constrained, int trial) { double x[TestProblem::kNumParameters]; for (int i = 0; i < TestProblem::kNumParameters; ++i) { x[i] = pow(10, trial) * TestProblem::initial_x[i]; @@ -563,16 +569,14 @@ Solve(options, &problem, &summary); const double kMinLogRelativeError = 4.0; - const double log_relative_error = -std::log10( - std::abs(2.0 * summary.final_cost - optimal_cost) / - (optimal_cost > 0.0 ? optimal_cost : 1.0)); + const double log_relative_error = + -std::log10(std::abs(2.0 * summary.final_cost - optimal_cost) / + (optimal_cost > 0.0 ? optimal_cost : 1.0)); const bool success = log_relative_error >= kMinLogRelativeError; - LOG(INFO) << "Expected : " << optimal_cost - << " actual: " << 2.0 * summary.final_cost - << " " << success - << " in " << summary.total_time_in_seconds - << " seconds"; + LOG(INFO) << "Expected : " << optimal_cost + << " actual: " << 2.0 * summary.final_cost << " " << success + << " in " << summary.total_time_in_seconds << " seconds"; return success; } @@ -591,29 +595,29 @@ int constrained_successes = 0; std::stringstream ss; -#define UNCONSTRAINED_SOLVE(n) \ - ss << "Unconstrained Problem " << n << " : "; \ - if (FLAGS_problem == #n || FLAGS_problem == "all") { \ - unconstrained_problems += 3; \ - if (Solve<ceres::examples::TestProblem##n>(false, 0)) { \ - unconstrained_successes += 1; \ - ss << "Yes "; \ - } else { \ - ss << "No "; \ - } \ - if (Solve<ceres::examples::TestProblem##n>(false, 1)) { \ - unconstrained_successes += 1; \ - ss << "Yes "; \ - } else { \ - ss << "No "; \ - } \ - if (Solve<ceres::examples::TestProblem##n>(false, 2)) { \ - unconstrained_successes += 1; \ - ss << "Yes "; \ - } else { \ - ss << "No "; \ - } \ - } \ +#define UNCONSTRAINED_SOLVE(n) \ + ss << "Unconstrained Problem " << n << " : "; \ + if (FLAGS_problem == #n || FLAGS_problem == "all") { \ + unconstrained_problems += 3; \ + if (Solve<ceres::examples::TestProblem##n>(false, 0)) { \ + unconstrained_successes += 1; \ + ss << "Yes "; \ + } else { \ + ss << "No "; \ + } \ + if (Solve<ceres::examples::TestProblem##n>(false, 1)) { \ + unconstrained_successes += 1; \ + ss << "Yes "; \ + } else { \ + ss << "No "; \ + } \ + if (Solve<ceres::examples::TestProblem##n>(false, 2)) { \ + unconstrained_successes += 1; \ + ss << "Yes "; \ + } else { \ + ss << "No "; \ + } \ + } \ ss << std::endl; UNCONSTRAINED_SOLVE(1); @@ -636,22 +640,20 @@ UNCONSTRAINED_SOLVE(18); UNCONSTRAINED_SOLVE(19); - ss << "Unconstrained : " - << unconstrained_successes - << "/" + ss << "Unconstrained : " << unconstrained_successes << "/" << unconstrained_problems << std::endl; -#define CONSTRAINED_SOLVE(n) \ - ss << "Constrained Problem " << n << " : "; \ - if (FLAGS_problem == #n || FLAGS_problem == "all") { \ - constrained_problems += 1; \ - if (Solve<ceres::examples::TestProblem##n>(true, 0)) { \ - constrained_successes += 1; \ - ss << "Yes "; \ - } else { \ - ss << "No "; \ - } \ - } \ +#define CONSTRAINED_SOLVE(n) \ + ss << "Constrained Problem " << n << " : "; \ + if (FLAGS_problem == #n || FLAGS_problem == "all") { \ + constrained_problems += 1; \ + if (Solve<ceres::examples::TestProblem##n>(true, 0)) { \ + constrained_successes += 1; \ + ss << "Yes "; \ + } else { \ + ss << "No "; \ + } \ + } \ ss << std::endl; CONSTRAINED_SOLVE(3); @@ -664,10 +666,8 @@ CONSTRAINED_SOLVE(14); CONSTRAINED_SOLVE(16); CONSTRAINED_SOLVE(18); - ss << "Constrained : " - << constrained_successes - << "/" - << constrained_problems << std::endl; + ss << "Constrained : " << constrained_successes << "/" << constrained_problems + << std::endl; std::cout << ss.str(); return 0;
diff --git a/examples/nist.cc b/examples/nist.cc index a9a066e..937d6bd 100644 --- a/examples/nist.cc +++ b/examples/nist.cc
@@ -83,52 +83,70 @@ #include "glog/logging.h" DEFINE_bool(use_tiny_solver, false, "Use TinySolver instead of Ceres::Solver"); -DEFINE_string(nist_data_dir, "", "Directory containing the NIST non-linear" - "regression examples"); -DEFINE_string(minimizer, "trust_region", +DEFINE_string(nist_data_dir, + "", + "Directory containing the NIST non-linear regression examples"); +DEFINE_string(minimizer, + "trust_region", "Minimizer type to use, choices are: line_search & trust_region"); -DEFINE_string(trust_region_strategy, "levenberg_marquardt", +DEFINE_string(trust_region_strategy, + "levenberg_marquardt", "Options are: levenberg_marquardt, dogleg"); -DEFINE_string(dogleg, "traditional_dogleg", +DEFINE_string(dogleg, + "traditional_dogleg", "Options are: traditional_dogleg, subspace_dogleg"); -DEFINE_string(linear_solver, "dense_qr", "Options are: " - "sparse_cholesky, dense_qr, dense_normal_cholesky and" - "cgnr"); -DEFINE_string(preconditioner, "jacobi", "Options are: " - "identity, jacobi"); -DEFINE_string(line_search, "wolfe", +DEFINE_string(linear_solver, + "dense_qr", + "Options are: sparse_cholesky, dense_qr, dense_normal_cholesky " + "and cgnr"); +DEFINE_string(preconditioner, "jacobi", "Options are: identity, jacobi"); +DEFINE_string(line_search, + "wolfe", "Line search algorithm to use, choices are: armijo and wolfe."); -DEFINE_string(line_search_direction, "lbfgs", +DEFINE_string(line_search_direction, + "lbfgs", "Line search direction algorithm to use, choices: lbfgs, bfgs"); -DEFINE_int32(max_line_search_iterations, 20, +DEFINE_int32(max_line_search_iterations, + 20, "Maximum number of iterations for each line search."); -DEFINE_int32(max_line_search_restarts, 10, +DEFINE_int32(max_line_search_restarts, + 10, "Maximum number of restarts of line search direction algorithm."); -DEFINE_string(line_search_interpolation, "cubic", - "Degree of polynomial aproximation in line search, " - "choices are: bisection, quadratic & cubic."); -DEFINE_int32(lbfgs_rank, 20, +DEFINE_string(line_search_interpolation, + "cubic", + "Degree of polynomial aproximation in line search, choices are: " + "bisection, quadratic & cubic."); +DEFINE_int32(lbfgs_rank, + 20, "Rank of L-BFGS inverse Hessian approximation in line search."); -DEFINE_bool(approximate_eigenvalue_bfgs_scaling, false, +DEFINE_bool(approximate_eigenvalue_bfgs_scaling, + false, "Use approximate eigenvalue scaling in (L)BFGS line search."); -DEFINE_double(sufficient_decrease, 1.0e-4, +DEFINE_double(sufficient_decrease, + 1.0e-4, "Line search Armijo sufficient (function) decrease factor."); -DEFINE_double(sufficient_curvature_decrease, 0.9, +DEFINE_double(sufficient_curvature_decrease, + 0.9, "Line search Wolfe sufficient curvature decrease factor."); DEFINE_int32(num_iterations, 10000, "Number of iterations"); -DEFINE_bool(nonmonotonic_steps, false, "Trust region algorithm can use" - " nonmonotic steps"); +DEFINE_bool(nonmonotonic_steps, + false, + "Trust region algorithm can use nonmonotic steps"); DEFINE_double(initial_trust_region_radius, 1e4, "Initial trust region radius"); -DEFINE_bool(use_numeric_diff, false, +DEFINE_bool(use_numeric_diff, + false, "Use numeric differentiation instead of automatic " "differentiation."); -DEFINE_string(numeric_diff_method, "ridders", "When using numeric " - "differentiation, selects algorithm. Options are: central, " - "forward, ridders."); -DEFINE_double(ridders_step_size, 1e-9, "Initial step size for Ridders " - "numeric differentiation."); -DEFINE_int32(ridders_extrapolations, 3, "Maximal number of Ridders " - "extrapolations."); +DEFINE_string(numeric_diff_method, + "ridders", + "When using numeric differentiation, selects algorithm. Options " + "are: central, forward, ridders."); +DEFINE_double(ridders_step_size, + 1e-9, + "Initial step size for Ridders numeric differentiation."); +DEFINE_int32(ridders_extrapolations, + 3, + "Maximal number of Ridders extrapolations."); namespace ceres { namespace examples { @@ -149,7 +167,7 @@ void SplitStringUsingChar(const string& full, const char delim, vector<string>* result) { - std::back_insert_iterator< vector<string> > it(*result); + std::back_insert_iterator<vector<string> > it(*result); const char* p = full.data(); const char* end = p + full.size(); @@ -222,12 +240,12 @@ // Parse the remaining parameter lines. for (int parameter_id = 1; parameter_id < kNumParameters; ++parameter_id) { - GetAndSplitLine(ifs, &pieces); - // b2, b3, .... - for (int i = 0; i < kNumTries; ++i) { - initial_parameters_(i, parameter_id) = atof(pieces[i + 2].c_str()); - } - final_parameters_(0, parameter_id) = atof(pieces[2 + kNumTries].c_str()); + GetAndSplitLine(ifs, &pieces); + // b2, b3, .... + for (int i = 0; i < kNumTries; ++i) { + initial_parameters_(i, parameter_id) = atof(pieces[i + 2].c_str()); + } + final_parameters_(0, parameter_id) = atof(pieces[2 + kNumTries].c_str()); } // Certfied cost @@ -241,26 +259,28 @@ GetAndSplitLine(ifs, &pieces); // Response. for (int j = 0; j < kNumResponses; ++j) { - response_(i, j) = atof(pieces[j].c_str()); + response_(i, j) = atof(pieces[j].c_str()); } // Predictor variables. for (int j = 0; j < kNumPredictors; ++j) { - predictor_(i, j) = atof(pieces[j + kNumResponses].c_str()); + predictor_(i, j) = atof(pieces[j + kNumResponses].c_str()); } } } - Matrix initial_parameters(int start) const { return initial_parameters_.row(start); } // NOLINT - Matrix final_parameters() const { return final_parameters_; } - Matrix predictor() const { return predictor_; } - Matrix response() const { return response_; } - int predictor_size() const { return predictor_.cols(); } - int num_observations() const { return predictor_.rows(); } - int response_size() const { return response_.cols(); } - int num_parameters() const { return initial_parameters_.cols(); } - int num_starts() const { return initial_parameters_.rows(); } - double certified_cost() const { return certified_cost_; } + Matrix initial_parameters(int start) const { + return initial_parameters_.row(start); + } // NOLINT + Matrix final_parameters() const { return final_parameters_; } + Matrix predictor() const { return predictor_; } + Matrix response() const { return response_; } + int predictor_size() const { return predictor_.cols(); } + int num_observations() const { return predictor_.rows(); } + int response_size() const { return response_.cols(); } + int num_parameters() const { return initial_parameters_.cols(); } + int num_starts() const { return initial_parameters_.rows(); } + double certified_cost() const { return certified_cost_; } private: Matrix predictor_; @@ -270,21 +290,23 @@ double certified_cost_; }; -#define NIST_BEGIN(CostFunctionName) \ - struct CostFunctionName { \ - CostFunctionName(const double* const x, \ - const double* const y, \ - const int n) \ - : x_(x), y_(y), n_(n) {} \ - const double* x_; \ - const double* y_; \ - const int n_; \ - template <typename T> \ - bool operator()(const T* const b, T* residual) const { \ - for (int i = 0; i < n_; ++i) { \ - const T x(x_[i]); \ +#define NIST_BEGIN(CostFunctionName) \ + struct CostFunctionName { \ + CostFunctionName(const double* const x, \ + const double* const y, \ + const int n) \ + : x_(x), y_(y), n_(n) {} \ + const double* x_; \ + const double* y_; \ + const int n_; \ + template <typename T> \ + bool operator()(const T* const b, T* residual) const { \ + for (int i = 0; i < n_; ++i) { \ + const T x(x_[i]); \ residual[i] = y_[i] - ( +// clang-format off + #define NIST_END ); } return true; }}; // y = b1 * (b2+x)**(-1/b3) + e @@ -430,6 +452,8 @@ const int n_; }; +// clang-format on + static void SetNumericDiffOptions(ceres::NumericDiffOptions* options) { options->max_num_ridders_extrapolations = FLAGS_ridders_extrapolations; options->ridders_relative_initial_step_size = FLAGS_ridders_step_size; @@ -473,9 +497,9 @@ string JoinPath(const string& dirname, const string& basename) { #ifdef _WIN32 - static const char separator = '\\'; + static const char separator = '\\'; #else - static const char separator = '/'; + static const char separator = '/'; #endif // _WIN32 if ((!basename.empty() && basename[0] == separator) || dirname.empty()) { @@ -491,8 +515,7 @@ CostFunction* CreateCostFunction(const Matrix& predictor, const Matrix& response, const int num_observations) { - Model* model = - new Model(predictor.data(), response.data(), num_observations); + Model* model = new Model(predictor.data(), response.data(), num_observations); ceres::CostFunction* cost_function = NULL; if (FLAGS_use_numeric_diff) { ceres::NumericDiffOptions options; @@ -502,28 +525,19 @@ ceres::CENTRAL, ceres::DYNAMIC, num_parameters>( - model, - ceres::TAKE_OWNERSHIP, - num_observations, - options); + model, ceres::TAKE_OWNERSHIP, num_observations, options); } else if (FLAGS_numeric_diff_method == "forward") { cost_function = new NumericDiffCostFunction<Model, ceres::FORWARD, ceres::DYNAMIC, num_parameters>( - model, - ceres::TAKE_OWNERSHIP, - num_observations, - options); + model, ceres::TAKE_OWNERSHIP, num_observations, options); } else if (FLAGS_numeric_diff_method == "ridders") { cost_function = new NumericDiffCostFunction<Model, ceres::RIDDERS, ceres::DYNAMIC, num_parameters>( - model, - ceres::TAKE_OWNERSHIP, - num_observations, - options); + model, ceres::TAKE_OWNERSHIP, num_observations, options); } else { LOG(ERROR) << "Invalid numeric diff method specified"; return 0; @@ -572,8 +586,9 @@ int num_success = 0; for (int start = 0; start < nist_problem.num_starts(); ++start) { Matrix initial_parameters = nist_problem.initial_parameters(start); - ceres::CostFunction* cost_function = CreateCostFunction<Model, num_parameters>( - predictor, response, nist_problem.num_observations()); + ceres::CostFunction* cost_function = + CreateCostFunction<Model, num_parameters>( + predictor, response, nist_problem.num_observations()); double initial_cost; double final_cost; @@ -609,8 +624,8 @@ delete cost_function; } - const double log_relative_error = ComputeLRE(nist_problem.final_parameters(), - initial_parameters); + const double log_relative_error = + ComputeLRE(nist_problem.final_parameters(), initial_parameters); const int kMinNumMatchingDigits = 4; if (log_relative_error > kMinNumMatchingDigits) { ++num_success; @@ -629,7 +644,6 @@ return num_success; } - void SolveNISTProblems() { if (FLAGS_nist_data_dir.empty()) { LOG(FATAL) << "Must specify the directory containing the NIST problems";
diff --git a/examples/pgm_image.h b/examples/pgm_image.h index 1de8d67..3d2df63 100644 --- a/examples/pgm_image.h +++ b/examples/pgm_image.h
@@ -46,7 +46,7 @@ namespace ceres { namespace examples { -template<typename Real> +template <typename Real> class PGMImage { public: // Create an empty image @@ -63,9 +63,9 @@ // Get individual pixels Real* MutablePixel(int x, int y); - Real Pixel(int x, int y) const; + Real Pixel(int x, int y) const; Real* MutablePixelFromLinearIndex(int index); - Real PixelFromLinearIndex(int index) const; + Real PixelFromLinearIndex(int index) const; int LinearIndex(int x, int y) const; // Adds an image to another @@ -90,52 +90,51 @@ // --- IMPLEMENTATION -template<typename Real> +template <typename Real> PGMImage<Real>::PGMImage(int width, int height) - : height_(height), width_(width), data_(width*height, 0.0) { -} + : height_(height), width_(width), data_(width * height, 0.0) {} -template<typename Real> +template <typename Real> PGMImage<Real>::PGMImage(std::string filename) { if (!ReadFromFile(filename)) { height_ = 0; - width_ = 0; + width_ = 0; } } -template<typename Real> +template <typename Real> void PGMImage<Real>::Set(double constant) { for (int i = 0; i < data_.size(); ++i) { data_[i] = constant; } } -template<typename Real> +template <typename Real> int PGMImage<Real>::width() const { return width_; } -template<typename Real> +template <typename Real> int PGMImage<Real>::height() const { return height_; } -template<typename Real> +template <typename Real> int PGMImage<Real>::NumPixels() const { return width_ * height_; } -template<typename Real> +template <typename Real> Real* PGMImage<Real>::MutablePixel(int x, int y) { return MutablePixelFromLinearIndex(LinearIndex(x, y)); } -template<typename Real> +template <typename Real> Real PGMImage<Real>::Pixel(int x, int y) const { return PixelFromLinearIndex(LinearIndex(x, y)); } -template<typename Real> +template <typename Real> Real* PGMImage<Real>::MutablePixelFromLinearIndex(int index) { CHECK(index >= 0); CHECK(index < width_ * height_); @@ -143,22 +142,22 @@ return &data_[index]; } -template<typename Real> -Real PGMImage<Real>::PixelFromLinearIndex(int index) const { +template <typename Real> +Real PGMImage<Real>::PixelFromLinearIndex(int index) const { CHECK(index >= 0); CHECK(index < width_ * height_); CHECK(index < data_.size()); return data_[index]; } -template<typename Real> +template <typename Real> int PGMImage<Real>::LinearIndex(int x, int y) const { - return x + width_*y; + return x + width_ * y; } // Adds an image to another -template<typename Real> -void PGMImage<Real>::operator+= (const PGMImage<Real>& image) { +template <typename Real> +void PGMImage<Real>::operator+=(const PGMImage<Real>& image) { CHECK(data_.size() == image.data_.size()); for (int i = 0; i < data_.size(); ++i) { data_[i] += image.data_[i]; @@ -166,22 +165,22 @@ } // Adds a constant to an image -template<typename Real> -void PGMImage<Real>::operator+= (Real a) { +template <typename Real> +void PGMImage<Real>::operator+=(Real a) { for (int i = 0; i < data_.size(); ++i) { data_[i] += a; } } // Multiplies an image by a constant -template<typename Real> -void PGMImage<Real>::operator*= (Real a) { +template <typename Real> +void PGMImage<Real>::operator*=(Real a) { for (int i = 0; i < data_.size(); ++i) { data_[i] *= a; } } -template<typename Real> +template <typename Real> bool PGMImage<Real>::WriteToFile(std::string filename) const { std::ofstream outputfile(filename.c_str()); outputfile << "P2" << std::endl; @@ -191,7 +190,7 @@ outputfile << width_ << ' ' << height_ << " 255 " << std::endl; // Write data - int num_pixels = width_*height_; + int num_pixels = width_ * height_; for (int i = 0; i < num_pixels; ++i) { // Convert to integer by rounding when writing file outputfile << static_cast<int>(data_[i] + 0.5) << ' '; @@ -200,10 +199,10 @@ return bool(outputfile); // Returns true/false } -namespace { +namespace { // Helper function to read data from a text file, ignoring "#" comments. -template<typename T> +template <typename T> bool GetIgnoreComment(std::istream* in, T& t) { std::string word; bool ok; @@ -229,7 +228,7 @@ } } // namespace -template<typename Real> +template <typename Real> bool PGMImage<Real>::ReadFromFile(std::string filename) { std::ifstream inputfile(filename.c_str()); @@ -242,9 +241,9 @@ // Read the image header int two_fifty_five; - if (!GetIgnoreComment(&inputfile, width_) || + if (!GetIgnoreComment(&inputfile, width_) || !GetIgnoreComment(&inputfile, height_) || - !GetIgnoreComment(&inputfile, two_fifty_five) ) { + !GetIgnoreComment(&inputfile, two_fifty_five)) { return false; } // Assert that the number of grey levels is 255. @@ -253,7 +252,7 @@ } // Now read the data - int num_pixels = width_*height_; + int num_pixels = width_ * height_; data_.resize(num_pixels); if (ch2 == '2') { // Ascii file @@ -297,7 +296,7 @@ return true; } -template<typename Real> +template <typename Real> bool PGMImage<Real>::SetData(const std::vector<Real>& new_data) { // This function cannot change the dimensions if (new_data.size() != data_.size()) { @@ -307,7 +306,7 @@ return true; } -template<typename Real> +template <typename Real> const std::vector<Real>& PGMImage<Real>::data() const { return data_; } @@ -315,5 +314,4 @@ } // namespace examples } // namespace ceres - #endif // CERES_EXAMPLES_PGM_IMAGE_H_
diff --git a/examples/powell.cc b/examples/powell.cc index bbb63d5..c75ad24 100644 --- a/examples/powell.cc +++ b/examples/powell.cc
@@ -45,6 +45,7 @@ // Vol 7(1), March 1981. #include <vector> + #include "ceres/ceres.h" #include "gflags/gflags.h" #include "glog/logging.h" @@ -52,13 +53,12 @@ using ceres::AutoDiffCostFunction; using ceres::CostFunction; using ceres::Problem; -using ceres::Solver; using ceres::Solve; +using ceres::Solver; struct F1 { - template <typename T> bool operator()(const T* const x1, - const T* const x2, - T* residual) const { + template <typename T> + bool operator()(const T* const x1, const T* const x2, T* residual) const { // f1 = x1 + 10 * x2; residual[0] = x1[0] + 10.0 * x2[0]; return true; @@ -66,9 +66,8 @@ }; struct F2 { - template <typename T> bool operator()(const T* const x3, - const T* const x4, - T* residual) const { + template <typename T> + bool operator()(const T* const x3, const T* const x4, T* residual) const { // f2 = sqrt(5) (x3 - x4) residual[0] = sqrt(5.0) * (x3[0] - x4[0]); return true; @@ -76,9 +75,8 @@ }; struct F3 { - template <typename T> bool operator()(const T* const x2, - const T* const x3, - T* residual) const { + template <typename T> + bool operator()(const T* const x2, const T* const x3, T* residual) const { // f3 = (x2 - 2 x3)^2 residual[0] = (x2[0] - 2.0 * x3[0]) * (x2[0] - 2.0 * x3[0]); return true; @@ -86,47 +84,44 @@ }; struct F4 { - template <typename T> bool operator()(const T* const x1, - const T* const x4, - T* residual) const { + template <typename T> + bool operator()(const T* const x1, const T* const x4, T* residual) const { // f4 = sqrt(10) (x1 - x4)^2 residual[0] = sqrt(10.0) * (x1[0] - x4[0]) * (x1[0] - x4[0]); return true; } }; -DEFINE_string(minimizer, "trust_region", +DEFINE_string(minimizer, + "trust_region", "Minimizer type to use, choices are: line_search & trust_region"); int main(int argc, char** argv) { GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); - double x1 = 3.0; + double x1 = 3.0; double x2 = -1.0; - double x3 = 0.0; - double x4 = 1.0; + double x3 = 0.0; + double x4 = 1.0; Problem problem; // Add residual terms to the problem using the using the autodiff // wrapper to get the derivatives automatically. The parameters, x1 through // x4, are modified in place. - problem.AddResidualBlock(new AutoDiffCostFunction<F1, 1, 1, 1>(new F1), - NULL, - &x1, &x2); - problem.AddResidualBlock(new AutoDiffCostFunction<F2, 1, 1, 1>(new F2), - NULL, - &x3, &x4); - problem.AddResidualBlock(new AutoDiffCostFunction<F3, 1, 1, 1>(new F3), - NULL, - &x2, &x3); - problem.AddResidualBlock(new AutoDiffCostFunction<F4, 1, 1, 1>(new F4), - NULL, - &x1, &x4); + problem.AddResidualBlock( + new AutoDiffCostFunction<F1, 1, 1, 1>(new F1), NULL, &x1, &x2); + problem.AddResidualBlock( + new AutoDiffCostFunction<F2, 1, 1, 1>(new F2), NULL, &x3, &x4); + problem.AddResidualBlock( + new AutoDiffCostFunction<F3, 1, 1, 1>(new F3), NULL, &x2, &x3); + problem.AddResidualBlock( + new AutoDiffCostFunction<F4, 1, 1, 1>(new F4), NULL, &x1, &x4); Solver::Options options; - LOG_IF(FATAL, !ceres::StringToMinimizerType(FLAGS_minimizer, - &options.minimizer_type)) + LOG_IF( + FATAL, + !ceres::StringToMinimizerType(FLAGS_minimizer, &options.minimizer_type)) << "Invalid minimizer: " << FLAGS_minimizer << ", valid options are: trust_region and line_search."; @@ -134,21 +129,25 @@ options.linear_solver_type = ceres::DENSE_QR; options.minimizer_progress_to_stdout = true; + // clang-format off std::cout << "Initial x1 = " << x1 << ", x2 = " << x2 << ", x3 = " << x3 << ", x4 = " << x4 << "\n"; + // clang-format on // Run the solver! Solver::Summary summary; Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; + // clang-format off std::cout << "Final x1 = " << x1 << ", x2 = " << x2 << ", x3 = " << x3 << ", x4 = " << x4 << "\n"; + // clang-format on return 0; }
diff --git a/examples/random.h b/examples/random.h index 7b09b15..ace0711 100644 --- a/examples/random.h +++ b/examples/random.h
@@ -52,7 +52,7 @@ x1 = 2.0 * RandDouble() - 1.0; x2 = 2.0 * RandDouble() - 1.0; w = x1 * x1 + x2 * x2; - } while ( w >= 1.0 || w == 0.0 ); + } while (w >= 1.0 || w == 0.0); w = sqrt((-2.0 * log(w)) / w); return x1 * w;
diff --git a/examples/robot_pose_mle.cc b/examples/robot_pose_mle.cc index 83c0903..ab9a098 100644 --- a/examples/robot_pose_mle.cc +++ b/examples/robot_pose_mle.cc
@@ -125,8 +125,9 @@ // will be computed by a DynamicAutoDiffCostFunction since the number of // odoemtry observations will only be known at run time. -#include <cstdio> #include <math.h> + +#include <cstdio> #include <vector> #include "ceres/ceres.h" @@ -136,9 +137,9 @@ #include "random.h" using ceres::AutoDiffCostFunction; -using ceres::DynamicAutoDiffCostFunction; using ceres::CauchyLoss; using ceres::CostFunction; +using ceres::DynamicAutoDiffCostFunction; using ceres::LossFunction; using ceres::Problem; using ceres::Solve; @@ -147,17 +148,22 @@ using std::min; using std::vector; -DEFINE_double(corridor_length, 30.0, "Length of the corridor that the robot is " - "travelling down."); +DEFINE_double(corridor_length, + 30.0, + "Length of the corridor that the robot is travelling down."); -DEFINE_double(pose_separation, 0.5, "The distance that the robot traverses " - "between successive odometry updates."); +DEFINE_double(pose_separation, + 0.5, + "The distance that the robot traverses between successive " + "odometry updates."); -DEFINE_double(odometry_stddev, 0.1, "The standard deviation of " - "odometry error of the robot."); +DEFINE_double(odometry_stddev, + 0.1, + "The standard deviation of odometry error of the robot."); -DEFINE_double(range_stddev, 0.01, "The standard deviation of range readings of " - "the robot."); +DEFINE_double(range_stddev, + 0.01, + "The standard deviation of range readings of the robot."); // The stride length of the dynamic_autodiff_cost_function evaluator. static constexpr int kStride = 10; @@ -165,8 +171,8 @@ struct OdometryConstraint { typedef AutoDiffCostFunction<OdometryConstraint, 1, 1> OdometryCostFunction; - OdometryConstraint(double odometry_mean, double odometry_stddev) : - odometry_mean(odometry_mean), odometry_stddev(odometry_stddev) {} + OdometryConstraint(double odometry_mean, double odometry_stddev) + : odometry_mean(odometry_mean), odometry_stddev(odometry_stddev) {} template <typename T> bool operator()(const T* const odometry, T* residual) const { @@ -187,13 +193,14 @@ typedef DynamicAutoDiffCostFunction<RangeConstraint, kStride> RangeCostFunction; - RangeConstraint( - int pose_index, - double range_reading, - double range_stddev, - double corridor_length) : - pose_index(pose_index), range_reading(range_reading), - range_stddev(range_stddev), corridor_length(corridor_length) {} + RangeConstraint(int pose_index, + double range_reading, + double range_stddev, + double corridor_length) + : pose_index(pose_index), + range_reading(range_reading), + range_stddev(range_stddev), + corridor_length(corridor_length) {} template <typename T> bool operator()(T const* const* relative_poses, T* residuals) const { @@ -201,8 +208,8 @@ for (int i = 0; i <= pose_index; ++i) { global_pose += relative_poses[i][0]; } - residuals[0] = (global_pose + range_reading - corridor_length) / - range_stddev; + residuals[0] = + (global_pose + range_reading - corridor_length) / range_stddev; return true; } @@ -235,14 +242,14 @@ void SimulateRobot(vector<double>* odometry_values, vector<double>* range_readings) { - const int num_steps = static_cast<int>( - ceil(FLAGS_corridor_length / FLAGS_pose_separation)); + const int num_steps = + static_cast<int>(ceil(FLAGS_corridor_length / FLAGS_pose_separation)); // The robot starts out at the origin. double robot_location = 0.0; for (int i = 0; i < num_steps; ++i) { - const double actual_odometry_value = min( - FLAGS_pose_separation, FLAGS_corridor_length - robot_location); + const double actual_odometry_value = + min(FLAGS_pose_separation, FLAGS_corridor_length - robot_location); robot_location += actual_odometry_value; const double actual_range = FLAGS_corridor_length - robot_location; const double observed_odometry = @@ -263,11 +270,14 @@ robot_location += odometry_readings[i]; const double range_error = robot_location + range_readings[i] - FLAGS_corridor_length; - const double odometry_error = - FLAGS_pose_separation - odometry_readings[i]; + const double odometry_error = FLAGS_pose_separation - odometry_readings[i]; printf("%4d: %8.3f %8.3f %8.3f %8.3f %8.3f\n", - static_cast<int>(i), robot_location, odometry_readings[i], - range_readings[i], range_error, odometry_error); + static_cast<int>(i), + robot_location, + odometry_readings[i], + range_readings[i], + range_error, + odometry_error); } }
diff --git a/examples/robust_curve_fitting.cc b/examples/robust_curve_fitting.cc index 6186aa1..9b526c5 100644 --- a/examples/robust_curve_fitting.cc +++ b/examples/robust_curve_fitting.cc
@@ -43,6 +43,7 @@ // data = [x', y_observed']; const int kNumObservations = 67; +// clang-format off const double data[] = { 0.000000e+00, 1.133898e+00, 7.500000e-02, 1.334902e+00, @@ -112,21 +113,20 @@ 4.875000e+00, 4.727863e+00, 4.950000e+00, 4.669206e+00 }; +// clang-format on using ceres::AutoDiffCostFunction; -using ceres::CostFunction; using ceres::CauchyLoss; +using ceres::CostFunction; using ceres::Problem; using ceres::Solve; using ceres::Solver; struct ExponentialResidual { - ExponentialResidual(double x, double y) - : x_(x), y_(y) {} + ExponentialResidual(double x, double y) : x_(x), y_(y) {} - template <typename T> bool operator()(const T* const m, - const T* const c, - T* residual) const { + template <typename T> + bool operator()(const T* const m, const T* const c, T* residual) const { residual[0] = y_ - exp(m[0] * x_ + c[0]); return true; } @@ -147,9 +147,7 @@ CostFunction* cost_function = new AutoDiffCostFunction<ExponentialResidual, 1, 1, 1>( new ExponentialResidual(data[2 * i], data[2 * i + 1])); - problem.AddResidualBlock(cost_function, - new CauchyLoss(0.5), - &m, &c); + problem.AddResidualBlock(cost_function, new CauchyLoss(0.5), &m, &c); } Solver::Options options;
diff --git a/examples/rosenbrock.cc b/examples/rosenbrock.cc index 3f64f1c..1b9aef6 100644 --- a/examples/rosenbrock.cc +++ b/examples/rosenbrock.cc
@@ -53,7 +53,6 @@ virtual int NumParameters() const { return 2; } }; - int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); @@ -68,7 +67,7 @@ std::cout << summary.FullReport() << "\n"; std::cout << "Initial x: " << -1.2 << " y: " << 1.0 << "\n"; - std::cout << "Final x: " << parameters[0] - << " y: " << parameters[1] << "\n"; + std::cout << "Final x: " << parameters[0] << " y: " << parameters[1] + << "\n"; return 0; }
diff --git a/examples/sampled_function/sampled_function.cc b/examples/sampled_function/sampled_function.cc index 093276a..7dec42b 100644 --- a/examples/sampled_function/sampled_function.cc +++ b/examples/sampled_function/sampled_function.cc
@@ -35,23 +35,23 @@ #include "ceres/cubic_interpolation.h" #include "glog/logging.h" -using ceres::Grid1D; -using ceres::CubicInterpolator; using ceres::AutoDiffCostFunction; using ceres::CostFunction; +using ceres::CubicInterpolator; +using ceres::Grid1D; using ceres::Problem; -using ceres::Solver; using ceres::Solve; +using ceres::Solver; // A simple cost functor that interfaces an interpolated table of // values with automatic differentiation. struct InterpolatedCostFunctor { explicit InterpolatedCostFunctor( const CubicInterpolator<Grid1D<double> >& interpolator) - : interpolator_(interpolator) { - } + : interpolator_(interpolator) {} - template<typename T> bool operator()(const T* x, T* residuals) const { + template <typename T> + bool operator()(const T* x, T* residuals) const { interpolator_.Evaluate(*x, residuals); return true; }
diff --git a/examples/simple_bundle_adjuster.cc b/examples/simple_bundle_adjuster.cc index dec6cd6..8180d73 100644 --- a/examples/simple_bundle_adjuster.cc +++ b/examples/simple_bundle_adjuster.cc
@@ -52,10 +52,10 @@ delete[] parameters_; } - int num_observations() const { return num_observations_; } - const double* observations() const { return observations_; } - double* mutable_cameras() { return parameters_; } - double* mutable_points() { return parameters_ + 9 * num_cameras_; } + int num_observations() const { return num_observations_; } + const double* observations() const { return observations_; } + double* mutable_cameras() { return parameters_; } + double* mutable_points() { return parameters_ + 9 * num_cameras_; } double* mutable_camera_for_observation(int i) { return mutable_cameras() + camera_index_[i] * 9; @@ -85,7 +85,7 @@ FscanfOrDie(fptr, "%d", camera_index_ + i); FscanfOrDie(fptr, "%d", point_index_ + i); for (int j = 0; j < 2; ++j) { - FscanfOrDie(fptr, "%lf", observations_ + 2*i + j); + FscanfOrDie(fptr, "%lf", observations_ + 2 * i + j); } } @@ -96,8 +96,8 @@ } private: - template<typename T> - void FscanfOrDie(FILE *fptr, const char *format, T *value) { + template <typename T> + void FscanfOrDie(FILE* fptr, const char* format, T* value) { int num_scanned = fscanf(fptr, format, value); if (num_scanned != 1) { LOG(FATAL) << "Invalid UW data file."; @@ -139,14 +139,14 @@ // Compute the center of distortion. The sign change comes from // the camera model that Noah Snavely's Bundler assumes, whereby // the camera coordinate system has a negative z axis. - T xp = - p[0] / p[2]; - T yp = - p[1] / p[2]; + T xp = -p[0] / p[2]; + T yp = -p[1] / p[2]; // Apply second and fourth order radial distortion. const T& l1 = camera[7]; const T& l2 = camera[8]; - T r2 = xp*xp + yp*yp; - T distortion = 1.0 + r2 * (l1 + l2 * r2); + T r2 = xp * xp + yp * yp; + T distortion = 1.0 + r2 * (l1 + l2 * r2); // Compute final projected point position. const T& focal = camera[6]; @@ -165,7 +165,7 @@ static ceres::CostFunction* Create(const double observed_x, const double observed_y) { return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError, 2, 9, 3>( - new SnavelyReprojectionError(observed_x, observed_y))); + new SnavelyReprojectionError(observed_x, observed_y))); } double observed_x; @@ -195,9 +195,8 @@ // dimensional residual. Internally, the cost function stores the observed // image location and compares the reprojection against the observation. - ceres::CostFunction* cost_function = - SnavelyReprojectionError::Create(observations[2 * i + 0], - observations[2 * i + 1]); + ceres::CostFunction* cost_function = SnavelyReprojectionError::Create( + observations[2 * i + 0], observations[2 * i + 1]); problem.AddResidualBlock(cost_function, NULL /* squared loss */, bal_problem.mutable_camera_for_observation(i),
diff --git a/examples/slam/common/read_g2o.h b/examples/slam/common/read_g2o.h index 71b071c..fea32e9 100644 --- a/examples/slam/common/read_g2o.h +++ b/examples/slam/common/read_g2o.h
@@ -97,7 +97,9 @@ // where I_ij is the (i, j)-th entry of the information matrix for the // measurement. Only the upper-triangular part is stored. The measurement order // is the delta position followed by the delta orientation. -template <typename Pose, typename Constraint, typename MapAllocator, +template <typename Pose, + typename Constraint, + typename MapAllocator, typename VectorAllocator> bool ReadG2oFile(const std::string& filename, std::map<int, Pose, std::less<int>, MapAllocator>* poses,
diff --git a/examples/slam/pose_graph_2d/angle_local_parameterization.h b/examples/slam/pose_graph_2d/angle_local_parameterization.h index 428cccc..a81637c 100644 --- a/examples/slam/pose_graph_2d/angle_local_parameterization.h +++ b/examples/slam/pose_graph_2d/angle_local_parameterization.h
@@ -41,9 +41,9 @@ // [-pi to pi). class AngleLocalParameterization { public: - template <typename T> - bool operator()(const T* theta_radians, const T* delta_theta_radians, + bool operator()(const T* theta_radians, + const T* delta_theta_radians, T* theta_radians_plus_delta) const { *theta_radians_plus_delta = NormalizeAngle(*theta_radians + *delta_theta_radians); @@ -53,7 +53,8 @@ static ceres::LocalParameterization* Create() { return (new ceres::AutoDiffLocalParameterization<AngleLocalParameterization, - 1, 1>); + 1, + 1>); } };
diff --git a/examples/slam/pose_graph_2d/normalize_angle.h b/examples/slam/pose_graph_2d/normalize_angle.h index afd5df4..c215671 100644 --- a/examples/slam/pose_graph_2d/normalize_angle.h +++ b/examples/slam/pose_graph_2d/normalize_angle.h
@@ -44,7 +44,7 @@ // Use ceres::floor because it is specialized for double and Jet types. T two_pi(2.0 * M_PI); return angle_radians - - two_pi * ceres::floor((angle_radians + T(M_PI)) / two_pi); + two_pi * ceres::floor((angle_radians + T(M_PI)) / two_pi); } } // namespace examples
diff --git a/examples/slam/pose_graph_2d/pose_graph_2d.cc b/examples/slam/pose_graph_2d/pose_graph_2d.cc index 0d9b047..1172123 100644 --- a/examples/slam/pose_graph_2d/pose_graph_2d.cc +++ b/examples/slam/pose_graph_2d/pose_graph_2d.cc
@@ -71,7 +71,8 @@ for (std::vector<Constraint2d>::const_iterator constraints_iter = constraints.begin(); - constraints_iter != constraints.end(); ++constraints_iter) { + constraints_iter != constraints.end(); + ++constraints_iter) { const Constraint2d& constraint = *constraints_iter; std::map<int, Pose2d>::iterator pose_begin_iter = @@ -88,16 +89,19 @@ // Ceres will take ownership of the pointer. ceres::CostFunction* cost_function = PoseGraph2dErrorTerm::Create( constraint.x, constraint.y, constraint.yaw_radians, sqrt_information); - problem->AddResidualBlock( - cost_function, loss_function, &pose_begin_iter->second.x, - &pose_begin_iter->second.y, &pose_begin_iter->second.yaw_radians, - &pose_end_iter->second.x, &pose_end_iter->second.y, - &pose_end_iter->second.yaw_radians); + problem->AddResidualBlock(cost_function, + loss_function, + &pose_begin_iter->second.x, + &pose_begin_iter->second.y, + &pose_begin_iter->second.yaw_radians, + &pose_end_iter->second.x, + &pose_end_iter->second.y, + &pose_end_iter->second.yaw_radians); problem->SetParameterization(&pose_begin_iter->second.yaw_radians, - angle_local_parameterization); + angle_local_parameterization); problem->SetParameterization(&pose_end_iter->second.yaw_radians, - angle_local_parameterization); + angle_local_parameterization); } // The pose graph optimization problem has three DOFs that are not fully @@ -107,8 +111,7 @@ // internal damping which mitigate this issue, but it is better to properly // constrain the gauge freedom. This can be done by setting one of the poses // as constant so the optimizer cannot change it. - std::map<int, Pose2d>::iterator pose_start_iter = - poses->begin(); + std::map<int, Pose2d>::iterator pose_start_iter = poses->begin(); CHECK(pose_start_iter != poses->end()) << "There are no poses."; problem->SetParameterBlockConstant(&pose_start_iter->second.x); problem->SetParameterBlockConstant(&pose_start_iter->second.y); @@ -141,10 +144,11 @@ return false; } for (std::map<int, Pose2d>::const_iterator poses_iter = poses.begin(); - poses_iter != poses.end(); ++poses_iter) { + poses_iter != poses.end(); + ++poses_iter) { const std::map<int, Pose2d>::value_type& pair = *poses_iter; - outfile << pair.first << " " << pair.second.x << " " << pair.second.y - << ' ' << pair.second.yaw_radians << '\n'; + outfile << pair.first << " " << pair.second.x << " " << pair.second.y << ' ' + << pair.second.yaw_radians << '\n'; } return true; }
diff --git a/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h b/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h index 20656d2..5d404e3 100644 --- a/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h +++ b/examples/slam/pose_graph_2d/pose_graph_2d_error_term.h
@@ -59,15 +59,21 @@ // [-pi, pi). class PoseGraph2dErrorTerm { public: - PoseGraph2dErrorTerm(double x_ab, double y_ab, double yaw_ab_radians, + PoseGraph2dErrorTerm(double x_ab, + double y_ab, + double yaw_ab_radians, const Eigen::Matrix3d& sqrt_information) : p_ab_(x_ab, y_ab), yaw_ab_radians_(yaw_ab_radians), sqrt_information_(sqrt_information) {} template <typename T> - bool operator()(const T* const x_a, const T* const y_a, const T* const yaw_a, - const T* const x_b, const T* const y_b, const T* const yaw_b, + bool operator()(const T* const x_a, + const T* const y_a, + const T* const yaw_a, + const T* const x_b, + const T* const y_b, + const T* const yaw_b, T* residuals_ptr) const { const Eigen::Matrix<T, 2, 1> p_a(*x_a, *y_a); const Eigen::Matrix<T, 2, 1> p_b(*x_b, *y_b); @@ -75,8 +81,7 @@ Eigen::Map<Eigen::Matrix<T, 3, 1> > residuals_map(residuals_ptr); residuals_map.template head<2>() = - RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - - p_ab_.cast<T>(); + RotationMatrix2D(*yaw_a).transpose() * (p_b - p_a) - p_ab_.cast<T>(); residuals_map(2) = ceres::examples::NormalizeAngle( (*yaw_b - *yaw_a) - static_cast<T>(yaw_ab_radians_)); @@ -87,12 +92,14 @@ return true; } - static ceres::CostFunction* Create(double x_ab, double y_ab, + static ceres::CostFunction* Create(double x_ab, + double y_ab, double yaw_ab_radians, const Eigen::Matrix3d& sqrt_information) { - return (new ceres::AutoDiffCostFunction<PoseGraph2dErrorTerm, 3, 1, 1, 1, 1, - 1, 1>(new PoseGraph2dErrorTerm( - x_ab, y_ab, yaw_ab_radians, sqrt_information))); + return (new ceres:: + AutoDiffCostFunction<PoseGraph2dErrorTerm, 3, 1, 1, 1, 1, 1, 1>( + new PoseGraph2dErrorTerm( + x_ab, y_ab, yaw_ab_radians, sqrt_information))); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW
diff --git a/examples/slam/pose_graph_2d/types.h b/examples/slam/pose_graph_2d/types.h index 43e0ffe..3c13824 100644 --- a/examples/slam/pose_graph_2d/types.h +++ b/examples/slam/pose_graph_2d/types.h
@@ -50,9 +50,7 @@ double yaw_radians; // The name of the data type in the g2o file format. - static std::string name() { - return "VERTEX_SE2"; - } + static std::string name() { return "VERTEX_SE2"; } }; inline std::istream& operator>>(std::istream& input, Pose2d& pose) { @@ -77,17 +75,15 @@ Eigen::Matrix3d information; // The name of the data type in the g2o file format. - static std::string name() { - return "EDGE_SE2"; - } + static std::string name() { return "EDGE_SE2"; } }; inline std::istream& operator>>(std::istream& input, Constraint2d& constraint) { input >> constraint.id_begin >> constraint.id_end >> constraint.x >> - constraint.y >> constraint.yaw_radians >> - constraint.information(0, 0) >> constraint.information(0, 1) >> - constraint.information(0, 2) >> constraint.information(1, 1) >> - constraint.information(1, 2) >> constraint.information(2, 2); + constraint.y >> constraint.yaw_radians >> constraint.information(0, 0) >> + constraint.information(0, 1) >> constraint.information(0, 2) >> + constraint.information(1, 1) >> constraint.information(1, 2) >> + constraint.information(2, 2); // Set the lower triangular part of the information matrix. constraint.information(1, 0) = constraint.information(0, 1);
diff --git a/examples/slam/pose_graph_3d/pose_graph_3d.cc b/examples/slam/pose_graph_3d/pose_graph_3d.cc index 420d804..c54412d 100644 --- a/examples/slam/pose_graph_3d/pose_graph_3d.cc +++ b/examples/slam/pose_graph_3d/pose_graph_3d.cc
@@ -28,8 +28,8 @@ // // Author: vitus@google.com (Michael Vitus) -#include <iostream> #include <fstream> +#include <iostream> #include <string> #include "ceres/ceres.h" @@ -48,7 +48,8 @@ // Constructs the nonlinear least squares optimization problem from the pose // graph constraints. void BuildOptimizationProblem(const VectorOfConstraints& constraints, - MapOfPoses* poses, ceres::Problem* problem) { + MapOfPoses* poses, + ceres::Problem* problem) { CHECK(poses != NULL); CHECK(problem != NULL); if (constraints.empty()) { @@ -62,7 +63,8 @@ for (VectorOfConstraints::const_iterator constraints_iter = constraints.begin(); - constraints_iter != constraints.end(); ++constraints_iter) { + constraints_iter != constraints.end(); + ++constraints_iter) { const Constraint3d& constraint = *constraints_iter; MapOfPoses::iterator pose_begin_iter = poses->find(constraint.id_begin); @@ -78,7 +80,8 @@ ceres::CostFunction* cost_function = PoseGraph3dErrorTerm::Create(constraint.t_be, sqrt_information); - problem->AddResidualBlock(cost_function, loss_function, + problem->AddResidualBlock(cost_function, + loss_function, pose_begin_iter->second.p.data(), pose_begin_iter->second.q.coeffs().data(), pose_end_iter->second.p.data(), @@ -127,11 +130,16 @@ LOG(ERROR) << "Error opening the file: " << filename; return false; } - for (std::map<int, Pose3d, std::less<int>, + for (std::map<int, + Pose3d, + std::less<int>, Eigen::aligned_allocator<std::pair<const int, Pose3d> > >:: const_iterator poses_iter = poses.begin(); - poses_iter != poses.end(); ++poses_iter) { - const std::map<int, Pose3d, std::less<int>, + poses_iter != poses.end(); + ++poses_iter) { + const std::map<int, + Pose3d, + std::less<int>, Eigen::aligned_allocator<std::pair<const int, Pose3d> > >:: value_type& pair = *poses_iter; outfile << pair.first << " " << pair.second.p.transpose() << " "
diff --git a/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h b/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h index aca819e..c8def17 100644 --- a/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h +++ b/examples/slam/pose_graph_3d/pose_graph_3d_error_term.h
@@ -33,7 +33,6 @@ #include "Eigen/Core" #include "ceres/autodiff_cost_function.h" - #include "types.h" namespace ceres { @@ -75,8 +74,10 @@ : t_ab_measured_(t_ab_measured), sqrt_information_(sqrt_information) {} template <typename T> - bool operator()(const T* const p_a_ptr, const T* const q_a_ptr, - const T* const p_b_ptr, const T* const q_b_ptr, + bool operator()(const T* const p_a_ptr, + const T* const q_a_ptr, + const T* const p_b_ptr, + const T* const q_b_ptr, T* residuals_ptr) const { Eigen::Map<const Eigen::Matrix<T, 3, 1> > p_a(p_a_ptr); Eigen::Map<const Eigen::Quaternion<T> > q_a(q_a_ptr);
diff --git a/examples/slam/pose_graph_3d/types.h b/examples/slam/pose_graph_3d/types.h index 2142820..25f7ba2 100644 --- a/examples/slam/pose_graph_3d/types.h +++ b/examples/slam/pose_graph_3d/types.h
@@ -47,23 +47,23 @@ Eigen::Quaterniond q; // The name of the data type in the g2o file format. - static std::string name() { - return "VERTEX_SE3:QUAT"; - } + static std::string name() { return "VERTEX_SE3:QUAT"; } EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; inline std::istream& operator>>(std::istream& input, Pose3d& pose) { - input >> pose.p.x() >> pose.p.y() >> pose.p.z() >> pose.q.x() >> - pose.q.y() >> pose.q.z() >> pose.q.w(); + input >> pose.p.x() >> pose.p.y() >> pose.p.z() >> pose.q.x() >> pose.q.y() >> + pose.q.z() >> pose.q.w(); // Normalize the quaternion to account for precision loss due to // serialization. pose.q.normalize(); return input; } -typedef std::map<int, Pose3d, std::less<int>, +typedef std::map<int, + Pose3d, + std::less<int>, Eigen::aligned_allocator<std::pair<const int, Pose3d> > > MapOfPoses; @@ -83,9 +83,7 @@ Eigen::Matrix<double, 6, 6> information; // The name of the data type in the g2o file format. - static std::string name() { - return "EDGE_SE3:QUAT"; - } + static std::string name() { return "EDGE_SE3:QUAT"; } EIGEN_MAKE_ALIGNED_OPERATOR_NEW };
diff --git a/examples/snavely_reprojection_error.h b/examples/snavely_reprojection_error.h index 5e51eb4..eb39d23 100644 --- a/examples/snavely_reprojection_error.h +++ b/examples/snavely_reprojection_error.h
@@ -70,15 +70,14 @@ // Compute the center of distortion. The sign change comes from // the camera model that Noah Snavely's Bundler assumes, whereby // the camera coordinate system has a negative z axis. - const T xp = - p[0] / p[2]; - const T yp = - p[1] / p[2]; + const T xp = -p[0] / p[2]; + const T yp = -p[1] / p[2]; // Apply second and fourth order radial distortion. const T& l1 = camera[7]; const T& l2 = camera[8]; - const T r2 = xp*xp + yp*yp; - const T distortion = 1.0 + r2 * (l1 + l2 * r2); - + const T r2 = xp * xp + yp * yp; + const T distortion = 1.0 + r2 * (l1 + l2 * r2); // Compute final projected point position. const T& focal = camera[6]; @@ -97,7 +96,7 @@ static ceres::CostFunction* Create(const double observed_x, const double observed_y) { return (new ceres::AutoDiffCostFunction<SnavelyReprojectionError, 2, 9, 3>( - new SnavelyReprojectionError(observed_x, observed_y))); + new SnavelyReprojectionError(observed_x, observed_y))); } double observed_x; @@ -135,15 +134,15 @@ // Compute the center of distortion. The sign change comes from // the camera model that Noah Snavely's Bundler assumes, whereby // the camera coordinate system has a negative z axis. - const T xp = - p[0] / p[2]; - const T yp = - p[1] / p[2]; + const T xp = -p[0] / p[2]; + const T yp = -p[1] / p[2]; // Apply second and fourth order radial distortion. const T& l1 = camera[8]; const T& l2 = camera[9]; - const T r2 = xp*xp + yp*yp; - const T distortion = 1.0 + r2 * (l1 + l2 * r2); + const T r2 = xp * xp + yp * yp; + const T distortion = 1.0 + r2 * (l1 + l2 * r2); // Compute final projected point position. const T& focal = camera[7]; @@ -161,10 +160,13 @@ // the client code. static ceres::CostFunction* Create(const double observed_x, const double observed_y) { - return (new ceres::AutoDiffCostFunction< - SnavelyReprojectionErrorWithQuaternions, 2, 10, 3>( - new SnavelyReprojectionErrorWithQuaternions(observed_x, - observed_y))); + return ( + new ceres::AutoDiffCostFunction<SnavelyReprojectionErrorWithQuaternions, + 2, + 10, + 3>( + new SnavelyReprojectionErrorWithQuaternions(observed_x, + observed_y))); } double observed_x;