Blame examples/robot_pose_mle.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: joydeepb@ri.cmu.edu (Joydeep Biswas)
Packit ea1746
//
Packit ea1746
// This example demonstrates how to use the DynamicAutoDiffCostFunction
Packit ea1746
// variant of CostFunction. The DynamicAutoDiffCostFunction is meant to
Packit ea1746
// be used in cases where the number of parameter blocks or the sizes are not
Packit ea1746
// known at compile time.
Packit ea1746
//
Packit ea1746
// This example simulates a robot traversing down a 1-dimension hallway with
Packit ea1746
// noise odometry readings and noisy range readings of the end of the hallway.
Packit ea1746
// By fusing the noisy odometry and sensor readings this example demonstrates
Packit ea1746
// how to compute the maximum likelihood estimate (MLE) of the robot's pose at
Packit ea1746
// each timestep.
Packit ea1746
//
Packit ea1746
// The robot starts at the origin, and it is travels to the end of a corridor of
Packit ea1746
// fixed length specified by the "--corridor_length" flag. It executes a series
Packit ea1746
// of motion commands to move forward a fixed length, specified by the
Packit ea1746
// "--pose_separation" flag, at which pose it receives relative odometry
Packit ea1746
// measurements as well as a range reading of the distance to the end of the
Packit ea1746
// hallway. The odometry readings are drawn with Gaussian noise and standard
Packit ea1746
// deviation specified by the "--odometry_stddev" flag, and the range readings
Packit ea1746
// similarly with standard deviation specified by the "--range-stddev" flag.
Packit ea1746
//
Packit ea1746
// There are two types of residuals in this problem:
Packit ea1746
// 1) The OdometryConstraint residual, that accounts for the odometry readings
Packit ea1746
//    between successive pose estimatess of the robot.
Packit ea1746
// 2) The RangeConstraint residual, that accounts for the errors in the observed
Packit ea1746
//    range readings from each pose.
Packit ea1746
//
Packit ea1746
// The OdometryConstraint residual is modeled as an AutoDiffCostFunction with
Packit ea1746
// a fixed parameter block size of 1, which is the relative odometry being
Packit ea1746
// solved for, between a pair of successive poses of the robot. Differences
Packit ea1746
// between observed and computed relative odometry values are penalized weighted
Packit ea1746
// by the known standard deviation of the odometry readings.
Packit ea1746
//
Packit ea1746
// The RangeConstraint residual is modeled as a DynamicAutoDiffCostFunction
Packit ea1746
// which sums up the relative odometry estimates to compute the estimated
Packit ea1746
// global pose of the robot, and then computes the expected range reading.
Packit ea1746
// Differences between the observed and expected range readings are then
Packit ea1746
// penalized weighted by the standard deviation of readings of the sensor.
Packit ea1746
// Since the number of poses of the robot is not known at compile time, this
Packit ea1746
// cost function is implemented as a DynamicAutoDiffCostFunction.
Packit ea1746
//
Packit ea1746
// The outputs of the example are the initial values of the odometry and range
Packit ea1746
// readings, and the range and odometry errors for every pose of the robot.
Packit ea1746
// After computing the MLE, the computed poses and corrected odometry values
Packit ea1746
// are printed out, along with the corresponding range and odometry errors. Note
Packit ea1746
// that as an MLE of a noisy system the errors will not be reduced to zero, but
Packit ea1746
// the odometry estimates will be updated to maximize the joint likelihood of
Packit ea1746
// all odometry and range readings of the robot.
Packit ea1746
//
Packit ea1746
// Mathematical Formulation
Packit ea1746
// ======================================================
Packit ea1746
//
Packit ea1746
// Let p_0, .., p_N be (N+1) robot poses, where the robot moves down the
Packit ea1746
// corridor starting from p_0 and ending at p_N. We assume that p_0 is the
Packit ea1746
// origin of the coordinate system.
Packit ea1746
// Odometry u_i is the observed relative odometry between pose p_(i-1) and p_i,
Packit ea1746
// and range reading y_i is the range reading of the end of the corridor from
Packit ea1746
// pose p_i. Both odometry as well as range readings are noisy, but we wish to
Packit ea1746
// compute the maximum likelihood estimate (MLE) of corrected odometry values
Packit ea1746
// u*_0 to u*_(N-1), such that the Belief is optimized:
Packit ea1746
//
Packit ea1746
// Belief(u*_(0:N-1) | u_(0:N-1), y_(0:N-1))                                  1.
Packit ea1746
//   =        P(u*_(0:N-1) | u_(0:N-1), y_(0:N-1))                            2.
Packit ea1746
//   \propto  P(y_(0:N-1) | u*_(0:N-1), u_(0:N-1)) P(u*_(0:N-1) | u_(0:N-1))  3.
Packit ea1746
//   =       \prod_i{ P(y_i | u*_(0:i)) P(u*_i | u_i) }                       4.
Packit ea1746
//
Packit ea1746
// Here, the subscript "(0:i)" is used as shorthand to indicate entries from all
Packit ea1746
// timesteps 0 to i for that variable, both inclusive.
Packit ea1746
//
Packit ea1746
// Bayes' rule is used to derive eq. 3 from 2, and the independence of
Packit ea1746
// odometry observations and range readings is expolited to derive 4 from 3.
Packit ea1746
//
Packit ea1746
// Thus, the Belief, up to scale, is factored as a product of a number of
Packit ea1746
// terms, two for each pose, where for each pose term there is one term for the
Packit ea1746
// range reading, P(y_i | u*_(0:i) and one term for the odometry reading,
Packit ea1746
// P(u*_i | u_i) . Note that the term for the range reading is dependent on all
Packit ea1746
// odometry values u*_(0:i), while the odometry term, P(u*_i | u_i) depends only
Packit ea1746
// on a single value, u_i. Both the range reading as well as odoemtry
Packit ea1746
// probability terms are modeled as the Normal distribution, and have the form:
Packit ea1746
//
Packit ea1746
// p(x) \propto \exp{-((x - x_mean) / x_stddev)^2}
Packit ea1746
//
Packit ea1746
// where x refers to either the MLE odometry u* or range reading y, and x_mean
Packit ea1746
// is the corresponding mean value, u for the odometry terms, and y_expected,
Packit ea1746
// the expected range reading based on all the previous odometry terms.
Packit ea1746
// The MLE is thus found by finding those values x* which minimize:
Packit ea1746
//
Packit ea1746
// x* = \arg\min{((x - x_mean) / x_stddev)^2}
Packit ea1746
//
Packit ea1746
// which is in the nonlinear least-square form, suited to being solved by Ceres.
Packit ea1746
// The non-linear component arise from the computation of x_mean. The residuals
Packit ea1746
// ((x - x_mean) / x_stddev) for the residuals that Ceres will optimize. As
Packit ea1746
// mentioned earlier, the odometry term for each pose depends only on one
Packit ea1746
// variable, and will be computed by an AutoDiffCostFunction, while the term
Packit ea1746
// for the range reading will depend on all previous odometry observations, and
Packit ea1746
// will be computed by a DynamicAutoDiffCostFunction since the number of
Packit ea1746
// odoemtry observations will only be known at run time.
Packit ea1746
Packit ea1746
#include <cstdio>
Packit ea1746
#include <math.h>
Packit ea1746
#include <vector>
Packit ea1746
Packit ea1746
#include "ceres/ceres.h"
Packit ea1746
#include "ceres/dynamic_autodiff_cost_function.h"
Packit ea1746
#include "gflags/gflags.h"
Packit ea1746
#include "glog/logging.h"
Packit ea1746
#include "random.h"
Packit ea1746
Packit ea1746
using ceres::AutoDiffCostFunction;
Packit ea1746
using ceres::DynamicAutoDiffCostFunction;
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
using ceres::examples::RandNormal;
Packit ea1746
using std::min;
Packit ea1746
using std::vector;
Packit ea1746
Packit ea1746
DEFINE_double(corridor_length, 30.0, "Length of the corridor that the robot is "
Packit ea1746
              "travelling down.");
Packit ea1746
Packit ea1746
DEFINE_double(pose_separation, 0.5, "The distance that the robot traverses "
Packit ea1746
              "between successive odometry updates.");
Packit ea1746
Packit ea1746
DEFINE_double(odometry_stddev, 0.1, "The standard deviation of "
Packit ea1746
              "odometry error of the robot.");
Packit ea1746
Packit ea1746
DEFINE_double(range_stddev, 0.01, "The standard deviation of range readings of "
Packit ea1746
              "the robot.");
Packit ea1746
Packit ea1746
// The stride length of the dynamic_autodiff_cost_function evaluator.
Packit ea1746
static const int kStride = 10;
Packit ea1746
Packit ea1746
struct OdometryConstraint {
Packit ea1746
  typedef AutoDiffCostFunction<OdometryConstraint, 1, 1> OdometryCostFunction;
Packit ea1746
Packit ea1746
  OdometryConstraint(double odometry_mean, double odometry_stddev) :
Packit ea1746
      odometry_mean(odometry_mean), odometry_stddev(odometry_stddev) {}
Packit ea1746
Packit ea1746
  template <typename T>
Packit ea1746
  bool operator()(const T* const odometry, T* residual) const {
Packit ea1746
    *residual = (*odometry - odometry_mean) / odometry_stddev;
Packit ea1746
    return true;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  static OdometryCostFunction* Create(const double odometry_value) {
Packit ea1746
    return new OdometryCostFunction(
Packit ea1746
        new OdometryConstraint(odometry_value, FLAGS_odometry_stddev));
Packit ea1746
  }
Packit ea1746
Packit ea1746
  const double odometry_mean;
Packit ea1746
  const double odometry_stddev;
Packit ea1746
};
Packit ea1746
Packit ea1746
struct RangeConstraint {
Packit ea1746
  typedef DynamicAutoDiffCostFunction<RangeConstraint, kStride>
Packit ea1746
      RangeCostFunction;
Packit ea1746
Packit ea1746
  RangeConstraint(
Packit ea1746
      int pose_index,
Packit ea1746
      double range_reading,
Packit ea1746
      double range_stddev,
Packit ea1746
      double corridor_length) :
Packit ea1746
      pose_index(pose_index), range_reading(range_reading),
Packit ea1746
      range_stddev(range_stddev), corridor_length(corridor_length) {}
Packit ea1746
Packit ea1746
  template <typename T>
Packit ea1746
  bool operator()(T const* const* relative_poses, T* residuals) const {
Packit ea1746
    T global_pose(0);
Packit ea1746
    for (int i = 0; i <= pose_index; ++i) {
Packit ea1746
      global_pose += relative_poses[i][0];
Packit ea1746
    }
Packit ea1746
    residuals[0] = (global_pose + range_reading - corridor_length) /
Packit ea1746
        range_stddev;
Packit ea1746
    return true;
Packit ea1746
  }
Packit ea1746
Packit ea1746
  // Factory method to create a CostFunction from a RangeConstraint to
Packit ea1746
  // conveniently add to a ceres problem.
Packit ea1746
  static RangeCostFunction* Create(const int pose_index,
Packit ea1746
                                   const double range_reading,
Packit ea1746
                                   vector<double>* odometry_values,
Packit ea1746
                                   vector<double*>* parameter_blocks) {
Packit ea1746
    RangeConstraint* constraint = new RangeConstraint(
Packit ea1746
        pose_index, range_reading, FLAGS_range_stddev, FLAGS_corridor_length);
Packit ea1746
    RangeCostFunction* cost_function = new RangeCostFunction(constraint);
Packit ea1746
    // Add all the parameter blocks that affect this constraint.
Packit ea1746
    parameter_blocks->clear();
Packit ea1746
    for (int i = 0; i <= pose_index; ++i) {
Packit ea1746
      parameter_blocks->push_back(&((*odometry_values)[i]));
Packit ea1746
      cost_function->AddParameterBlock(1);
Packit ea1746
    }
Packit ea1746
    cost_function->SetNumResiduals(1);
Packit ea1746
    return (cost_function);
Packit ea1746
  }
Packit ea1746
Packit ea1746
  const int pose_index;
Packit ea1746
  const double range_reading;
Packit ea1746
  const double range_stddev;
Packit ea1746
  const double corridor_length;
Packit ea1746
};
Packit ea1746
Packit ea1746
void SimulateRobot(vector<double>* odometry_values,
Packit ea1746
                   vector<double>* range_readings) {
Packit ea1746
  const int num_steps = static_cast<int>(
Packit ea1746
      ceil(FLAGS_corridor_length / FLAGS_pose_separation));
Packit ea1746
Packit ea1746
  // The robot starts out at the origin.
Packit ea1746
  double robot_location = 0.0;
Packit ea1746
  for (int i = 0; i < num_steps; ++i) {
Packit ea1746
    const double actual_odometry_value = min(
Packit ea1746
        FLAGS_pose_separation, FLAGS_corridor_length - robot_location);
Packit ea1746
    robot_location += actual_odometry_value;
Packit ea1746
    const double actual_range = FLAGS_corridor_length - robot_location;
Packit ea1746
    const double observed_odometry =
Packit ea1746
        RandNormal() * FLAGS_odometry_stddev + actual_odometry_value;
Packit ea1746
    const double observed_range =
Packit ea1746
        RandNormal() * FLAGS_range_stddev + actual_range;
Packit ea1746
    odometry_values->push_back(observed_odometry);
Packit ea1746
    range_readings->push_back(observed_range);
Packit ea1746
  }
Packit ea1746
}
Packit ea1746
Packit ea1746
void PrintState(const vector<double>& odometry_readings,
Packit ea1746
                const vector<double>& range_readings) {
Packit ea1746
  CHECK_EQ(odometry_readings.size(), range_readings.size());
Packit ea1746
  double robot_location = 0.0;
Packit ea1746
  printf("pose: location     odom    range  r.error  o.error\n");
Packit ea1746
  for (int i = 0; i < odometry_readings.size(); ++i) {
Packit ea1746
    robot_location += odometry_readings[i];
Packit ea1746
    const double range_error =
Packit ea1746
        robot_location + range_readings[i] - FLAGS_corridor_length;
Packit ea1746
    const double odometry_error =
Packit ea1746
        FLAGS_pose_separation - odometry_readings[i];
Packit ea1746
    printf("%4d: %8.3f %8.3f %8.3f %8.3f %8.3f\n",
Packit ea1746
           static_cast<int>(i), robot_location, odometry_readings[i],
Packit ea1746
           range_readings[i], range_error, odometry_error);
Packit ea1746
  }
Packit ea1746
}
Packit ea1746
Packit ea1746
int main(int argc, char** argv) {
Packit ea1746
  google::InitGoogleLogging(argv[0]);
Packit ea1746
  CERES_GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);
Packit ea1746
  // Make sure that the arguments parsed are all positive.
Packit ea1746
  CHECK_GT(FLAGS_corridor_length, 0.0);
Packit ea1746
  CHECK_GT(FLAGS_pose_separation, 0.0);
Packit ea1746
  CHECK_GT(FLAGS_odometry_stddev, 0.0);
Packit ea1746
  CHECK_GT(FLAGS_range_stddev, 0.0);
Packit ea1746
Packit ea1746
  vector<double> odometry_values;
Packit ea1746
  vector<double> range_readings;
Packit ea1746
  SimulateRobot(&odometry_values, &range_readings);
Packit ea1746
Packit ea1746
  printf("Initial values:\n");
Packit ea1746
  PrintState(odometry_values, range_readings);
Packit ea1746
  ceres::Problem problem;
Packit ea1746
Packit ea1746
  for (int i = 0; i < odometry_values.size(); ++i) {
Packit ea1746
    // Create and add a DynamicAutoDiffCostFunction for the RangeConstraint from
Packit ea1746
    // pose i.
Packit ea1746
    vector<double*> parameter_blocks;
Packit ea1746
    RangeConstraint::RangeCostFunction* range_cost_function =
Packit ea1746
        RangeConstraint::Create(
Packit ea1746
            i, range_readings[i], &odometry_values, &parameter_blocks);
Packit ea1746
    problem.AddResidualBlock(range_cost_function, NULL, parameter_blocks);
Packit ea1746
Packit ea1746
    // Create and add an AutoDiffCostFunction for the OdometryConstraint for
Packit ea1746
    // pose i.
Packit ea1746
    problem.AddResidualBlock(OdometryConstraint::Create(odometry_values[i]),
Packit ea1746
                             NULL,
Packit ea1746
                             &(odometry_values[i]));
Packit ea1746
  }
Packit ea1746
Packit ea1746
  ceres::Solver::Options solver_options;
Packit ea1746
  solver_options.minimizer_progress_to_stdout = true;
Packit ea1746
Packit ea1746
  Solver::Summary summary;
Packit ea1746
  printf("Solving...\n");
Packit ea1746
  Solve(solver_options, &problem, &summary);
Packit ea1746
  printf("Done.\n");
Packit ea1746
  std::cout << summary.FullReport() << "\n";
Packit ea1746
  printf("Final values:\n");
Packit ea1746
  PrintState(odometry_values, range_readings);
Packit ea1746
  return 0;
Packit ea1746
}