Blame examples/circle_fit.cc

Packit ea1746
// Ceres Solver - A fast non-linear least squares minimizer
Packit ea1746
// Copyright 2015 Google Inc. All rights reserved.
Packit ea1746
// http://ceres-solver.org/
Packit ea1746
//
Packit ea1746
// Redistribution and use in source and binary forms, with or without
Packit ea1746
// modification, are permitted provided that the following conditions are met:
Packit ea1746
//
Packit ea1746
// * Redistributions of source code must retain the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer.
Packit ea1746
// * Redistributions in binary form must reproduce the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer in the documentation
Packit ea1746
//   and/or other materials provided with the distribution.
Packit ea1746
// * Neither the name of Google Inc. nor the names of its contributors may be
Packit ea1746
//   used to endorse or promote products derived from this software without
Packit ea1746
//   specific prior written permission.
Packit ea1746
//
Packit ea1746
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
Packit ea1746
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Packit ea1746
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
Packit ea1746
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
Packit ea1746
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Packit ea1746
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
Packit ea1746
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
Packit ea1746
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
Packit ea1746
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
Packit ea1746
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
Packit ea1746
// POSSIBILITY OF SUCH DAMAGE.
Packit ea1746
//
Packit ea1746
// Author: keir@google.com (Keir Mierle)
Packit ea1746
//
Packit ea1746
// This fits circles to a collection of points, where the error is related to
Packit ea1746
// the distance of a point from the circle. This uses auto-differentiation to
Packit ea1746
// take the derivatives.
Packit ea1746
//
Packit ea1746
// The input format is simple text. Feed on standard in:
Packit ea1746
//
Packit ea1746
//   x_initial y_initial r_initial
Packit ea1746
//   x1 y1
Packit ea1746
//   x2 y2
Packit ea1746
//   y3 y3
Packit ea1746
//   ...
Packit ea1746
//
Packit ea1746
// And the result after solving will be printed to stdout:
Packit ea1746
//
Packit ea1746
//   x y r
Packit ea1746
//
Packit ea1746
// There are closed form solutions [1] to this problem which you may want to
Packit ea1746
// consider instead of using this one. If you already have a decent guess, Ceres
Packit ea1746
// can squeeze down the last bit of error.
Packit ea1746
//
Packit ea1746
//   [1] http://www.mathworks.com/matlabcentral/fileexchange/5557-circle-fit/content/circfit.m
Packit ea1746
Packit ea1746
#include <cstdio>
Packit ea1746
#include <vector>
Packit ea1746
Packit ea1746
#include "ceres/ceres.h"
Packit ea1746
#include "gflags/gflags.h"
Packit ea1746
#include "glog/logging.h"
Packit ea1746
Packit ea1746
using ceres::AutoDiffCostFunction;
Packit ea1746
using ceres::CauchyLoss;
Packit ea1746
using ceres::CostFunction;
Packit ea1746
using ceres::LossFunction;
Packit ea1746
using ceres::Problem;
Packit ea1746
using ceres::Solve;
Packit ea1746
using ceres::Solver;
Packit ea1746
Packit ea1746
DEFINE_double(robust_threshold, 0.0, "Robust loss parameter. Set to 0 for "
Packit ea1746
              "normal squared error (no robustification).");
Packit ea1746
Packit ea1746
// The cost for a single sample. The returned residual is related to the
Packit ea1746
// distance of the point from the circle (passed in as x, y, m parameters).
Packit ea1746
//
Packit ea1746
// Note that the radius is parameterized as r = m^2 to constrain the radius to
Packit ea1746
// positive values.
Packit ea1746
class DistanceFromCircleCost {
Packit ea1746
 public:
Packit ea1746
  DistanceFromCircleCost(double xx, double yy) : xx_(xx), yy_(yy) {}
Packit ea1746
  template <typename T> bool operator()(const T* const x,
Packit ea1746
                                        const T* const y,
Packit ea1746
                                        const T* const m,  // r = m^2
Packit ea1746
                                        T* residual) const {
Packit ea1746
    // Since the radius is parameterized as m^2, unpack m to get r.
Packit ea1746
    T r = *m * *m;
Packit ea1746
Packit ea1746
    // Get the position of the sample in the circle's coordinate system.
Packit ea1746
    T xp = xx_ - *x;
Packit ea1746
    T yp = yy_ - *y;
Packit ea1746
Packit ea1746
    // It is tempting to use the following cost:
Packit ea1746
    //
Packit ea1746
    //   residual[0] = r - sqrt(xp*xp + yp*yp);
Packit ea1746
    //
Packit ea1746
    // which is the distance of the sample from the circle. This works
Packit ea1746
    // reasonably well, but the sqrt() adds strong nonlinearities to the cost
Packit ea1746
    // function. Instead, a different cost is used, which while not strictly a
Packit ea1746
    // distance in the metric sense (it has units distance^2) it produces more
Packit ea1746
    // robust fits when there are outliers. This is because the cost surface is
Packit ea1746
    // more convex.
Packit ea1746
    residual[0] = r*r - xp*xp - yp*yp;
Packit ea1746
    return true;
Packit ea1746
  }
Packit ea1746
Packit ea1746
 private:
Packit ea1746
  // The measured x,y coordinate that should be on the circle.
Packit ea1746
  double xx_, yy_;
Packit ea1746
};
Packit ea1746
Packit ea1746
int main(int argc, char** argv) {
Packit ea1746
  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
Packit ea1746
  google::InitGoogleLogging(argv[0]);
Packit ea1746
Packit ea1746
  double x, y, r;
Packit ea1746
  if (scanf("%lg %lg %lg", &x, &y, &r) != 3) {
Packit ea1746
    fprintf(stderr, "Couldn't read first line.\n");
Packit ea1746
    return 1;
Packit ea1746
  }
Packit ea1746
  fprintf(stderr, "Got x, y, r %lg, %lg, %lg\n", x, y, r);
Packit ea1746
Packit ea1746
  // Save initial values for comparison.
Packit ea1746
  double initial_x = x;
Packit ea1746
  double initial_y = y;
Packit ea1746
  double initial_r = r;
Packit ea1746
Packit ea1746
  // Parameterize r as m^2 so that it can't be negative.
Packit ea1746
  double m = sqrt(r);
Packit ea1746
Packit ea1746
  Problem problem;
Packit ea1746
Packit ea1746
  // Configure the loss function.
Packit ea1746
  LossFunction* loss = NULL;
Packit ea1746
  if (FLAGS_robust_threshold) {
Packit ea1746
    loss = new CauchyLoss(FLAGS_robust_threshold);
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Add the residuals.
Packit ea1746
  double xx, yy;
Packit ea1746
  int num_points = 0;
Packit ea1746
  while (scanf("%lf %lf\n", &xx, &yy) == 2) {
Packit ea1746
    CostFunction *cost =
Packit ea1746
        new AutoDiffCostFunction<DistanceFromCircleCost, 1, 1, 1, 1>(
Packit ea1746
            new DistanceFromCircleCost(xx, yy));
Packit ea1746
    problem.AddResidualBlock(cost, loss, &x, &y, &m);
Packit ea1746
    num_points++;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  std::cout << "Got " << num_points << " points.\n";
Packit ea1746
Packit ea1746
  // Build and solve the problem.
Packit ea1746
  Solver::Options options;
Packit ea1746
  options.max_num_iterations = 500;
Packit ea1746
  options.linear_solver_type = ceres::DENSE_QR;
Packit ea1746
  Solver::Summary summary;
Packit ea1746
  Solve(options, &problem, &summary);
Packit ea1746
Packit ea1746
  // Recover r from m.
Packit ea1746
  r = m * m;
Packit ea1746
Packit ea1746
  std::cout << summary.BriefReport() << "\n";
Packit ea1746
  std::cout << "x : " << initial_x << " -> " << x << "\n";
Packit ea1746
  std::cout << "y : " << initial_y << " -> " << y << "\n";
Packit ea1746
  std::cout << "r : " << initial_r << " -> " << r << "\n";
Packit ea1746
  return 0;
Packit ea1746
}