An Interface to 'Ceres Solver' for Non-Linear Least Squares and Optimization

Provides an interface to the 'Ceres Solver' C++ library < https://github.com/ceres-solver/ceres-solver>. 'Ceres Solver' is an open source library for modeling and solving large, complicated optimization problems. It can solve non-linear least squares problems with bounds constraints and general unconstrained optimization problems. It is a mature, feature rich and high-performance library that has been used in production at Google since 2010. Non-linear least squares problems with residuals written in R can be solved with ceres_nls(), with optional bounds and robust loss functions. The bundled library is built from source and can also be used from C++ through 'Rcpp', either with Rcpp::sourceCpp() or from other packages.


ceres

ceres is an R package. ceres is an interface to the Ceres Solver, an open source C++ library for modeling and solving large, non-linear, least squares optimization problems by Google. Ceres solver has been used in production at Google since 2010.

Installing ceres

ceres package is not on CRAN yet. It can be installed in R from github using the following command in the R console.

devtools::install_github('sn248/ceres')

Fitting a model from R

ceres_nls() solves non-linear least squares problems with the residuals written as an R function, with optional bounds and robust loss functions. No C++ is needed.

library(ceres)

set.seed(1)
x <- seq(0, 5, length.out = 100)
y <- exp(0.3 * x + 0.1) + rnorm(100, sd = 0.2)
y[c(20, 60)] <- y[c(20, 60)] + 10   # two outliers

resid_exp <- function(p, x, y) y - exp(p[["m"]] * x + p[["c"]])

# Ordinary least squares, with standard errors
fit <- ceres_nls(resid_exp, c(m = 0, c = 0), x = x, y = y)
summary(fit)

# A robust loss, with m constrained to be positive
robust <- ceres_nls(resid_exp, c(m = 0.2, c = 0), x = x, y = y,
                    lower = c(m = 0), loss = "cauchy", loss_scale = 0.5,
                    vcov = FALSE)
coef(robust)

See ?ceres_nls for the details. R is called for every evaluation, so for large problems write the residuals in C++ as described below.

How to use ceres from C++

Following the example provided by Ceres Solver, let's solve the simple optimization problem of finding the minima of the function $$ f(x) = 0.5 \times (10 - x)^{2}$$ The minima of this function is 0 (at $x = 10$).

See the documentation here to see the C++ implementation of this problem and its solution.

Using the example code from the link above, the same problem can be solved in R using the code below. Paste this code in a file and save with .cpp extension. Use Rcpp::sourceCpp() function (with <filename>) as the argument of the Source button in RStudio to generate a function ceres_helloworld in the R environment.

#include <ceres.h>

// [[Rcpp::depends(RcppEigen, ceres)]]

#include <ceres/ceres.h>
#include <glog/logging.h>

using namespace Rcpp;

using ceres::AutoDiffCostFunction;
using ceres::CostFunction;
using ceres::Problem;
using ceres::Solve;
using ceres::Solver;

// A templated cost functor that implements the residual r = 10 -
// x. The method operator() is templated so that we can then use an
// automatic differentiation wrapper around it to generate its
// derivatives.
struct CostFunctor {
	template <typename T>
	bool operator()(const T* const x, T* residual) const {
		residual[0] = 10.0 - x[0];
		return true;
	}
};

// [[Rcpp::export]]
int ceres_helloworld(double x){

	//google::InitGoogleLogging(argv[0]);
	
	// The variable to solve for with its initial value. It will be
	// mutated in place by the solver.
	// double x = xin;
	const double initial_x = x;
	
	// Build the problem.
	ceres::Problem problem;
	
	// Set up the only cost function (also known as residual). This uses
	// auto-differentiation to obtain the derivative (jacobian).
	CostFunction* cost_function =
		new AutoDiffCostFunction<CostFunctor, 1, 1>(new CostFunctor);
	problem.AddResidualBlock(cost_function, nullptr, &x);
	
	// Run the solver!
	Solver::Options options;
	options.minimizer_progress_to_stdout = true;
	Solver::Summary summary;
	Solve(options, &problem, &summary);
	
	Rcpp::Rcout << summary.BriefReport() << "\n";
	Rcpp::Rcout << "x : " << initial_x << " -> " << x << "\n";
	return 0;
}

NOTE - Compilation of this code will give a list of Eigen related warnings in R, which can be neglected for now.

Finally, the ceres_helloworld function can be called in R using a numeric argument, e.g.,

ceres_helloworld(0.5)

which gives the following output in the R console:

> ceres_helloworld(0.5)
iter      cost      cost_change  |gradient|   |step|    tr_ratio  tr_radius  ls_iter  iter_time  total_time
   0  4.512500e+01    0.00e+00    9.50e+00   0.00e+00   0.00e+00  1.00e+04        0    1.72e-05    3.70e-05
   1  4.511598e-07    4.51e+01    9.50e-04   9.50e+00   1.00e+00  3.00e+04        1    1.50e-05    7.49e-05
   2  5.012552e-16    4.51e-07    3.17e-08   9.50e-04   1.00e+00  9.00e+04        1    5.96e-06    8.68e-05
Ceres Solver Report: Iterations: 3, Initial cost: 4.512500e+01, Final cost: 5.012552e-16, Termination: CONVERGENCE
x : 0.5 -> 10
[1] 0

which is same answer that we get using the C++ library (see here).

Writing your own problems in C++

Any .cpp file containing // [[Rcpp::depends(ceres)]] and #include <ceres.h> can be compiled with Rcpp::sourceCpp(). The ceres plugin adds the include paths, links the bundled Ceres static library (built with its own miniglog in place of glog and gflags), and selects C++17.

Automatic differentiation

Write each residual as a functor with a templated operator() and wrap it in ceres::AutoDiffCostFunction. Ceres then computes exact derivatives, so no Jacobian has to be written by hand (see the CostFunctor above).

Multi-threading

Set options.num_threads on ceres::Solver::Options. Ceres evaluates residuals and Jacobians, and parts of the linear solver, on that many threads. Because cost functors run on worker threads, they must not touch R: no Rcpp vectors, Rcpp::stop() or Rprintf() inside operator(). Copy the data into std::vector or Eigen objects before calling ceres::Solve(). Threads only pay off when residuals are expensive or the problem is large; for cheap residuals the thread overhead can make the solve slower.

Sparse problems

Ceres is built with Eigen's sparse linear algebra, so SPARSE_NORMAL_CHOLESKY and SPARSE_SCHUR are available with options.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE. SuiteSparse, LAPACK and CUDA are not used.

Examples

Two complete examples are installed with the package:

  • curve_fitting.cpp: fits y = exp(m * x + c) to data from R using automatic differentiation and num_threads.
  • robust_smoothing.cpp: smooths a signal with outliers using a Cauchy loss, one parameter block per point and the sparse Cholesky solver.
Rcpp::sourceCpp(system.file("examples", "curve_fitting.cpp", package = "ceres"))
set.seed(1)
x <- seq(0, 5, length.out = 10000)
y <- exp(0.3 * x + 0.1) + rnorm(length(x), sd = 0.2)
fit_exponential(x, y, num_threads = 4)

Rcpp::sourceCpp(system.file("examples", "robust_smoothing.cpp", package = "ceres"))
t <- seq(0, 4 * pi, length.out = 20000)
y <- sin(t) + rnorm(length(t), sd = 0.1)
out <- sample(length(t), 500)
y[out] <- y[out] + rnorm(500, sd = 3)
fit <- robust_smooth(y, lambda = 50, num_threads = 4)
plot(t, y, pch = ".", ylim = c(-2, 2)); lines(t, fit$s, col = "red")

Using ceres from another package

Add ceres, RcppEigen and Rcpp to LinkingTo (and Rcpp to Imports) in DESCRIPTION, and put this in src/Makevars:

CXX_STD = CXX17
PKG_LIBS = $(shell "${R_HOME}/bin/Rscript" -e "ceres::LdFlags()")

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.

install.packages("ceres")

0.1.0 by Satyaprakash Nayak, 11 hours ago


Browse source code at https://github.com/cran/ceres


Authors: Satyaprakash Nayak [aut, cre] , Google Inc. [cph] (Ceres Solver , bundled in src/ceres-solver-2.2.0.tar.gz) , Sameer Agarwal [ctb] (Ceres Solver) , Keir Mierle [ctb] (Ceres Solver) , The Ceres Solver authors [ctb] (Ceres Solver; see inst/COPYRIGHTS) , The Abseil Authors [cph] (fixed_array.h and memory.h in Ceres Solver (Apache-2.0)) , Sergiu Deitsch [cph] (FindMETIS.cmake in Ceres Solver (MIT)) , Bogdan Cristea [cph] (iOS.cmake in Ceres Solver (BSD-3-Clause)) , LTE Engineering Software [cph] (iOS.cmake in Ceres Solver (BSD-3-Clause)) , Kitware , Inc. [cph] (iOS.cmake in Ceres Solver (BSD-3-Clause)) , Insight Software Consortium [cph] (iOS.cmake in Ceres Solver (BSD-3-Clause)) , Ken Martin , Will Schroeder and Bill Lorensen [cph] (FindTBB.cmake in Ceres Solver , from VTK (BSD-3-Clause))


Documentation:   PDF Manual  


GPL (>= 3) license


Imports Rcpp, stats

Suggests RcppEigen, testthat

Linking to Rcpp, RcppEigen

System requirements: cmake (>= 3.16), GNU make


See at CRAN