blob: ab9a098a69f0b98f63794d52f7b923bd34c7456e [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2015 Google Inc. All rights reserved.
3// 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: joydeepb@ri.cmu.edu (Joydeep Biswas)
30//
31// This example demonstrates how to use the DynamicAutoDiffCostFunction
32// variant of CostFunction. The DynamicAutoDiffCostFunction is meant to
33// be used in cases where the number of parameter blocks or the sizes are not
34// known at compile time.
35//
36// This example simulates a robot traversing down a 1-dimension hallway with
37// noise odometry readings and noisy range readings of the end of the hallway.
38// By fusing the noisy odometry and sensor readings this example demonstrates
39// how to compute the maximum likelihood estimate (MLE) of the robot's pose at
40// each timestep.
41//
42// The robot starts at the origin, and it is travels to the end of a corridor of
43// fixed length specified by the "--corridor_length" flag. It executes a series
44// of motion commands to move forward a fixed length, specified by the
45// "--pose_separation" flag, at which pose it receives relative odometry
46// measurements as well as a range reading of the distance to the end of the
47// hallway. The odometry readings are drawn with Gaussian noise and standard
48// deviation specified by the "--odometry_stddev" flag, and the range readings
49// similarly with standard deviation specified by the "--range-stddev" flag.
50//
51// There are two types of residuals in this problem:
52// 1) The OdometryConstraint residual, that accounts for the odometry readings
53// between successive pose estimatess of the robot.
54// 2) The RangeConstraint residual, that accounts for the errors in the observed
55// range readings from each pose.
56//
57// The OdometryConstraint residual is modeled as an AutoDiffCostFunction with
58// a fixed parameter block size of 1, which is the relative odometry being
59// solved for, between a pair of successive poses of the robot. Differences
60// between observed and computed relative odometry values are penalized weighted
61// by the known standard deviation of the odometry readings.
62//
63// The RangeConstraint residual is modeled as a DynamicAutoDiffCostFunction
64// which sums up the relative odometry estimates to compute the estimated
65// global pose of the robot, and then computes the expected range reading.
66// Differences between the observed and expected range readings are then
67// penalized weighted by the standard deviation of readings of the sensor.
68// Since the number of poses of the robot is not known at compile time, this
69// cost function is implemented as a DynamicAutoDiffCostFunction.
70//
71// The outputs of the example are the initial values of the odometry and range
72// readings, and the range and odometry errors for every pose of the robot.
73// After computing the MLE, the computed poses and corrected odometry values
74// are printed out, along with the corresponding range and odometry errors. Note
75// that as an MLE of a noisy system the errors will not be reduced to zero, but
76// the odometry estimates will be updated to maximize the joint likelihood of
77// all odometry and range readings of the robot.
78//
79// Mathematical Formulation
80// ======================================================
81//
82// Let p_0, .., p_N be (N+1) robot poses, where the robot moves down the
83// corridor starting from p_0 and ending at p_N. We assume that p_0 is the
84// origin of the coordinate system.
85// Odometry u_i is the observed relative odometry between pose p_(i-1) and p_i,
86// and range reading y_i is the range reading of the end of the corridor from
87// pose p_i. Both odometry as well as range readings are noisy, but we wish to
88// compute the maximum likelihood estimate (MLE) of corrected odometry values
89// u*_0 to u*_(N-1), such that the Belief is optimized:
90//
91// Belief(u*_(0:N-1) | u_(0:N-1), y_(0:N-1)) 1.
92// = P(u*_(0:N-1) | u_(0:N-1), y_(0:N-1)) 2.
93// \propto P(y_(0:N-1) | u*_(0:N-1), u_(0:N-1)) P(u*_(0:N-1) | u_(0:N-1)) 3.
94// = \prod_i{ P(y_i | u*_(0:i)) P(u*_i | u_i) } 4.
95//
96// Here, the subscript "(0:i)" is used as shorthand to indicate entries from all
97// timesteps 0 to i for that variable, both inclusive.
98//
99// Bayes' rule is used to derive eq. 3 from 2, and the independence of
100// odometry observations and range readings is expolited to derive 4 from 3.
101//
102// Thus, the Belief, up to scale, is factored as a product of a number of
103// terms, two for each pose, where for each pose term there is one term for the
104// range reading, P(y_i | u*_(0:i) and one term for the odometry reading,
105// P(u*_i | u_i) . Note that the term for the range reading is dependent on all
106// odometry values u*_(0:i), while the odometry term, P(u*_i | u_i) depends only
107// on a single value, u_i. Both the range reading as well as odoemtry
108// probability terms are modeled as the Normal distribution, and have the form:
109//
110// p(x) \propto \exp{-((x - x_mean) / x_stddev)^2}
111//
112// where x refers to either the MLE odometry u* or range reading y, and x_mean
113// is the corresponding mean value, u for the odometry terms, and y_expected,
114// the expected range reading based on all the previous odometry terms.
115// The MLE is thus found by finding those values x* which minimize:
116//
117// x* = \arg\min{((x - x_mean) / x_stddev)^2}
118//
119// which is in the nonlinear least-square form, suited to being solved by Ceres.
120// The non-linear component arise from the computation of x_mean. The residuals
121// ((x - x_mean) / x_stddev) for the residuals that Ceres will optimize. As
122// mentioned earlier, the odometry term for each pose depends only on one
123// variable, and will be computed by an AutoDiffCostFunction, while the term
124// for the range reading will depend on all previous odometry observations, and
125// will be computed by a DynamicAutoDiffCostFunction since the number of
126// odoemtry observations will only be known at run time.
127
Austin Schuh70cc9552019-01-21 19:46:48 -0800128#include <math.h>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800129
130#include <cstdio>
Austin Schuh70cc9552019-01-21 19:46:48 -0800131#include <vector>
132
133#include "ceres/ceres.h"
134#include "ceres/dynamic_autodiff_cost_function.h"
135#include "gflags/gflags.h"
136#include "glog/logging.h"
137#include "random.h"
138
139using ceres::AutoDiffCostFunction;
Austin Schuh70cc9552019-01-21 19:46:48 -0800140using ceres::CauchyLoss;
141using ceres::CostFunction;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800142using ceres::DynamicAutoDiffCostFunction;
Austin Schuh70cc9552019-01-21 19:46:48 -0800143using ceres::LossFunction;
144using ceres::Problem;
145using ceres::Solve;
146using ceres::Solver;
147using ceres::examples::RandNormal;
148using std::min;
149using std::vector;
150
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800151DEFINE_double(corridor_length,
152 30.0,
153 "Length of the corridor that the robot is travelling down.");
Austin Schuh70cc9552019-01-21 19:46:48 -0800154
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800155DEFINE_double(pose_separation,
156 0.5,
157 "The distance that the robot traverses between successive "
158 "odometry updates.");
Austin Schuh70cc9552019-01-21 19:46:48 -0800159
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800160DEFINE_double(odometry_stddev,
161 0.1,
162 "The standard deviation of odometry error of the robot.");
Austin Schuh70cc9552019-01-21 19:46:48 -0800163
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800164DEFINE_double(range_stddev,
165 0.01,
166 "The standard deviation of range readings of the robot.");
Austin Schuh70cc9552019-01-21 19:46:48 -0800167
168// The stride length of the dynamic_autodiff_cost_function evaluator.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800169static constexpr int kStride = 10;
Austin Schuh70cc9552019-01-21 19:46:48 -0800170
171struct OdometryConstraint {
172 typedef AutoDiffCostFunction<OdometryConstraint, 1, 1> OdometryCostFunction;
173
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800174 OdometryConstraint(double odometry_mean, double odometry_stddev)
175 : odometry_mean(odometry_mean), odometry_stddev(odometry_stddev) {}
Austin Schuh70cc9552019-01-21 19:46:48 -0800176
177 template <typename T>
178 bool operator()(const T* const odometry, T* residual) const {
179 *residual = (*odometry - odometry_mean) / odometry_stddev;
180 return true;
181 }
182
183 static OdometryCostFunction* Create(const double odometry_value) {
184 return new OdometryCostFunction(
185 new OdometryConstraint(odometry_value, FLAGS_odometry_stddev));
186 }
187
188 const double odometry_mean;
189 const double odometry_stddev;
190};
191
192struct RangeConstraint {
193 typedef DynamicAutoDiffCostFunction<RangeConstraint, kStride>
194 RangeCostFunction;
195
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800196 RangeConstraint(int pose_index,
197 double range_reading,
198 double range_stddev,
199 double corridor_length)
200 : pose_index(pose_index),
201 range_reading(range_reading),
202 range_stddev(range_stddev),
203 corridor_length(corridor_length) {}
Austin Schuh70cc9552019-01-21 19:46:48 -0800204
205 template <typename T>
206 bool operator()(T const* const* relative_poses, T* residuals) const {
207 T global_pose(0);
208 for (int i = 0; i <= pose_index; ++i) {
209 global_pose += relative_poses[i][0];
210 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800211 residuals[0] =
212 (global_pose + range_reading - corridor_length) / range_stddev;
Austin Schuh70cc9552019-01-21 19:46:48 -0800213 return true;
214 }
215
216 // Factory method to create a CostFunction from a RangeConstraint to
217 // conveniently add to a ceres problem.
218 static RangeCostFunction* Create(const int pose_index,
219 const double range_reading,
220 vector<double>* odometry_values,
221 vector<double*>* parameter_blocks) {
222 RangeConstraint* constraint = new RangeConstraint(
223 pose_index, range_reading, FLAGS_range_stddev, FLAGS_corridor_length);
224 RangeCostFunction* cost_function = new RangeCostFunction(constraint);
225 // Add all the parameter blocks that affect this constraint.
226 parameter_blocks->clear();
227 for (int i = 0; i <= pose_index; ++i) {
228 parameter_blocks->push_back(&((*odometry_values)[i]));
229 cost_function->AddParameterBlock(1);
230 }
231 cost_function->SetNumResiduals(1);
232 return (cost_function);
233 }
234
235 const int pose_index;
236 const double range_reading;
237 const double range_stddev;
238 const double corridor_length;
239};
240
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800241namespace {
242
Austin Schuh70cc9552019-01-21 19:46:48 -0800243void SimulateRobot(vector<double>* odometry_values,
244 vector<double>* range_readings) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800245 const int num_steps =
246 static_cast<int>(ceil(FLAGS_corridor_length / FLAGS_pose_separation));
Austin Schuh70cc9552019-01-21 19:46:48 -0800247
248 // The robot starts out at the origin.
249 double robot_location = 0.0;
250 for (int i = 0; i < num_steps; ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800251 const double actual_odometry_value =
252 min(FLAGS_pose_separation, FLAGS_corridor_length - robot_location);
Austin Schuh70cc9552019-01-21 19:46:48 -0800253 robot_location += actual_odometry_value;
254 const double actual_range = FLAGS_corridor_length - robot_location;
255 const double observed_odometry =
256 RandNormal() * FLAGS_odometry_stddev + actual_odometry_value;
257 const double observed_range =
258 RandNormal() * FLAGS_range_stddev + actual_range;
259 odometry_values->push_back(observed_odometry);
260 range_readings->push_back(observed_range);
261 }
262}
263
264void PrintState(const vector<double>& odometry_readings,
265 const vector<double>& range_readings) {
266 CHECK_EQ(odometry_readings.size(), range_readings.size());
267 double robot_location = 0.0;
268 printf("pose: location odom range r.error o.error\n");
269 for (int i = 0; i < odometry_readings.size(); ++i) {
270 robot_location += odometry_readings[i];
271 const double range_error =
272 robot_location + range_readings[i] - FLAGS_corridor_length;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800273 const double odometry_error = FLAGS_pose_separation - odometry_readings[i];
Austin Schuh70cc9552019-01-21 19:46:48 -0800274 printf("%4d: %8.3f %8.3f %8.3f %8.3f %8.3f\n",
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800275 static_cast<int>(i),
276 robot_location,
277 odometry_readings[i],
278 range_readings[i],
279 range_error,
280 odometry_error);
Austin Schuh70cc9552019-01-21 19:46:48 -0800281 }
282}
283
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800284} // namespace
285
Austin Schuh70cc9552019-01-21 19:46:48 -0800286int main(int argc, char** argv) {
287 google::InitGoogleLogging(argv[0]);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800288 GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
Austin Schuh70cc9552019-01-21 19:46:48 -0800289 // Make sure that the arguments parsed are all positive.
290 CHECK_GT(FLAGS_corridor_length, 0.0);
291 CHECK_GT(FLAGS_pose_separation, 0.0);
292 CHECK_GT(FLAGS_odometry_stddev, 0.0);
293 CHECK_GT(FLAGS_range_stddev, 0.0);
294
295 vector<double> odometry_values;
296 vector<double> range_readings;
297 SimulateRobot(&odometry_values, &range_readings);
298
299 printf("Initial values:\n");
300 PrintState(odometry_values, range_readings);
301 ceres::Problem problem;
302
303 for (int i = 0; i < odometry_values.size(); ++i) {
304 // Create and add a DynamicAutoDiffCostFunction for the RangeConstraint from
305 // pose i.
306 vector<double*> parameter_blocks;
307 RangeConstraint::RangeCostFunction* range_cost_function =
308 RangeConstraint::Create(
309 i, range_readings[i], &odometry_values, &parameter_blocks);
310 problem.AddResidualBlock(range_cost_function, NULL, parameter_blocks);
311
312 // Create and add an AutoDiffCostFunction for the OdometryConstraint for
313 // pose i.
314 problem.AddResidualBlock(OdometryConstraint::Create(odometry_values[i]),
315 NULL,
316 &(odometry_values[i]));
317 }
318
319 ceres::Solver::Options solver_options;
320 solver_options.minimizer_progress_to_stdout = true;
321
322 Solver::Summary summary;
323 printf("Solving...\n");
324 Solve(solver_options, &problem, &summary);
325 printf("Done.\n");
326 std::cout << summary.FullReport() << "\n";
327 printf("Final values:\n");
328 PrintState(odometry_values, range_readings);
329 return 0;
330}