blob: fd848d91ecfea4c0c3ee46fa44ca3377b6eda0e8 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
Austin Schuh3de38b02024-06-25 18:25:10 -07002// Copyright 2023 Google Inc. All rights reserved.
Austin Schuh70cc9552019-01-21 19:46:48 -08003// http://ceres-solver.org/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10// * Redistributions in binary form must reproduce the above copyright notice,
11// this list of conditions and the following disclaimer in the documentation
12// and/or other materials provided with the distribution.
13// * Neither the name of Google Inc. nor the names of its contributors may be
14// used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28//
29// Author: keir@google.com (Keir Mierle)
30//
31// This fits circles to a collection of points, where the error is related to
32// the distance of a point from the circle. This uses auto-differentiation to
33// take the derivatives.
34//
35// The input format is simple text. Feed on standard in:
36//
37// x_initial y_initial r_initial
38// x1 y1
39// x2 y2
40// y3 y3
41// ...
42//
43// And the result after solving will be printed to stdout:
44//
45// x y r
46//
47// There are closed form solutions [1] to this problem which you may want to
48// consider instead of using this one. If you already have a decent guess, Ceres
49// can squeeze down the last bit of error.
50//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080051// [1] http://www.mathworks.com/matlabcentral/fileexchange/5557-circle-fit/content/circfit.m // NOLINT
Austin Schuh70cc9552019-01-21 19:46:48 -080052
53#include <cstdio>
54#include <vector>
55
56#include "ceres/ceres.h"
57#include "gflags/gflags.h"
58#include "glog/logging.h"
59
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080060DEFINE_double(robust_threshold,
61 0.0,
62 "Robust loss parameter. Set to 0 for normal squared error (no "
63 "robustification).");
Austin Schuh70cc9552019-01-21 19:46:48 -080064
65// The cost for a single sample. The returned residual is related to the
66// distance of the point from the circle (passed in as x, y, m parameters).
67//
68// Note that the radius is parameterized as r = m^2 to constrain the radius to
69// positive values.
70class DistanceFromCircleCost {
71 public:
72 DistanceFromCircleCost(double xx, double yy) : xx_(xx), yy_(yy) {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080073 template <typename T>
74 bool operator()(const T* const x,
75 const T* const y,
76 const T* const m, // r = m^2
77 T* residual) const {
Austin Schuh70cc9552019-01-21 19:46:48 -080078 // Since the radius is parameterized as m^2, unpack m to get r.
79 T r = *m * *m;
80
81 // Get the position of the sample in the circle's coordinate system.
82 T xp = xx_ - *x;
83 T yp = yy_ - *y;
84
85 // It is tempting to use the following cost:
86 //
87 // residual[0] = r - sqrt(xp*xp + yp*yp);
88 //
89 // which is the distance of the sample from the circle. This works
90 // reasonably well, but the sqrt() adds strong nonlinearities to the cost
91 // function. Instead, a different cost is used, which while not strictly a
92 // distance in the metric sense (it has units distance^2) it produces more
93 // robust fits when there are outliers. This is because the cost surface is
94 // more convex.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080095 residual[0] = r * r - xp * xp - yp * yp;
Austin Schuh70cc9552019-01-21 19:46:48 -080096 return true;
97 }
98
99 private:
100 // The measured x,y coordinate that should be on the circle.
101 double xx_, yy_;
102};
103
104int main(int argc, char** argv) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800105 GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
Austin Schuh70cc9552019-01-21 19:46:48 -0800106 google::InitGoogleLogging(argv[0]);
107
108 double x, y, r;
109 if (scanf("%lg %lg %lg", &x, &y, &r) != 3) {
110 fprintf(stderr, "Couldn't read first line.\n");
111 return 1;
112 }
113 fprintf(stderr, "Got x, y, r %lg, %lg, %lg\n", x, y, r);
114
115 // Save initial values for comparison.
116 double initial_x = x;
117 double initial_y = y;
118 double initial_r = r;
119
120 // Parameterize r as m^2 so that it can't be negative.
121 double m = sqrt(r);
122
Austin Schuh3de38b02024-06-25 18:25:10 -0700123 ceres::Problem problem;
Austin Schuh70cc9552019-01-21 19:46:48 -0800124
125 // Configure the loss function.
Austin Schuh3de38b02024-06-25 18:25:10 -0700126 ceres::LossFunction* loss = nullptr;
127 if (CERES_GET_FLAG(FLAGS_robust_threshold)) {
128 loss = new ceres::CauchyLoss(CERES_GET_FLAG(FLAGS_robust_threshold));
Austin Schuh70cc9552019-01-21 19:46:48 -0800129 }
130
131 // Add the residuals.
132 double xx, yy;
133 int num_points = 0;
134 while (scanf("%lf %lf\n", &xx, &yy) == 2) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700135 ceres::CostFunction* cost =
136 new ceres::AutoDiffCostFunction<DistanceFromCircleCost, 1, 1, 1, 1>(xx,
137 yy);
Austin Schuh70cc9552019-01-21 19:46:48 -0800138 problem.AddResidualBlock(cost, loss, &x, &y, &m);
139 num_points++;
140 }
141
142 std::cout << "Got " << num_points << " points.\n";
143
144 // Build and solve the problem.
Austin Schuh3de38b02024-06-25 18:25:10 -0700145 ceres::Solver::Options options;
Austin Schuh70cc9552019-01-21 19:46:48 -0800146 options.max_num_iterations = 500;
147 options.linear_solver_type = ceres::DENSE_QR;
Austin Schuh3de38b02024-06-25 18:25:10 -0700148 ceres::Solver::Summary summary;
149 ceres::Solve(options, &problem, &summary);
Austin Schuh70cc9552019-01-21 19:46:48 -0800150
151 // Recover r from m.
152 r = m * m;
153
154 std::cout << summary.BriefReport() << "\n";
155 std::cout << "x : " << initial_x << " -> " << x << "\n";
156 std::cout << "y : " << initial_y << " -> " << y << "\n";
157 std::cout << "r : " << initial_r << " -> " << r << "\n";
158 return 0;
159}