bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Mapping with EKF-SLAM

Building a map from range scans built a map from range scans, but it was told exactly where the robot was for every scan. A real robot does not know that either: its odometry drifts, and a map built from drifting poses drifts with them. To map, it has to localise; to localise, it needs a map. Simultaneous localisation and mapping, SLAM, does both at once. This example does it with an extended Kalman filter: a robot drives a loop through the warehouse knowing nothing but its odometry, maps the posts it sees, and keeps track of itself against them.

The posts, where SLAM put them, and the three paths

The true path in green, dead reckoning in red, EKF-SLAM in blue. Dead reckoning, the odometry alone, ends 1.7 m off and drives through the wall; SLAM stays on the true path. Every post is where SLAM put it, inside its 3-sigma ellipse.

What you need

Nothing beyond bitsim itself. See Installing bitsim. It builds on Extended Kalman filtering.

A landmark map

The map here is not a grid but a list of landmarks: 17 posts along the walls and shelves, each with a marker, so that the sensor can tell them apart. Twice a second the sensor reports the range and the bearing of every post within 2.5 m that no shelf or wall hides, with noise of 5 cm and about 1 degree, and the post's id. A landmark map is small, a few numbers a landmark, and it is what a robot needs to find itself; it says nothing about the free space in between.

One state for the robot and the map

EKFSlam keeps the robot's pose and every landmark in one state

\[x = (x_r, y_r, \psi, m_{1x}, m_{1y}, m_{2x}, m_{2y}, \dots) \]

with one covariance \(P\) over all of it. It is an ExtendedKalmanFilter whose state grows by two values each time a post is seen for the first time.

  • Predict. The odometry says the robot drove \(d\) and turned \(\Delta\psi\). Only the pose moves; the landmarks stay put. The odometry's noise grows with the square root of the distance and the turn, so the pose's uncertainty grows as the robot drives.
  • A new landmark is put where its first sighting says, \(m = (x_r + r\cos(\psi + b),\ y_r + r\sin(\psi + b))\) for range \(r\) and bearing \(b\). Its covariance has two parts: the sighting's noise, and the robot's own uncertainty, carried over through the Jacobian of \(m\) with respect to the pose. The second part also correlates the landmark with the robot, and with everything the robot is correlated with.
  • A landmark seen again corrects the state: the predicted range and bearing are \(r = \sqrt{\delta_x^2 + \delta_y^2}\) and \(b = \operatorname{atan2}(\delta_y, \delta_x) - \psi\), for \(\delta\) the landmark less the robot, and the bearing's innovation is wrapped to \((-\pi, \pi]\). A sighting that the estimate cannot explain is turned away by the filter's gate.

Why it works: the loop closing

The correlations in \(P\) are what make SLAM more than dead reckoning with landmarks on the side. Posts mapped near the start are known well, because the robot was. Posts mapped far away are known only as well as the robot was when it saw them, and their errors are tied to its error then. When the robot comes back and sees the first posts again, the correction does not stop at its pose: it runs through the correlations to every landmark mapped on the way, and all of them sharpen. This is loop closure.

Position error and uncertainty along the loop

SLAM's 1-sigma grows from the start to the far corner, 0.16 m, and shrinks on the way back, as the robot sees again the posts it mapped on the way out and, at the end, the posts by the start.

Running the example

./ekf_slam

Output

1. The loop
17 posts, seen within 2.5 m unless a shelf or wall is in the way; 28.8 m driven in 1004 steps of 0.1 s
2. Dead reckoning against SLAM, waypoint by waypoint
waypoint driven [m] odometry error [m] SLAM error [m] SLAM 1-sigma [m] posts mapped
1 2.3 0.012 0.035 0.043 6
2 5.1 0.077 0.035 0.069 10
3 6.8 0.130 0.026 0.089 12
4 9.4 0.199 0.034 0.079 13
5 12.2 0.361 0.071 0.131 16
6 16.1 0.307 0.094 0.159 17
7 18.9 0.117 0.031 0.099 17
8 20.2 0.011 0.033 0.085 17
9 21.9 0.306 0.007 0.067 17
10 23.1 0.457 0.010 0.077 17
11 24.7 0.843 0.017 0.066 17
12 28.4 1.528 0.035 0.032 17
13 28.8 1.676 0.019 0.032 17
3. The map: where SLAM put the posts
post true x, y [m] SLAM x, y [m] error [m] 1-sigma [m]
0 1.00, 0.25 0.99, 0.25 0.007 0.023
1 2.75, 0.25 2.74, 0.24 0.021 0.038
2 0.25, 2.50 0.26, 2.50 0.013 0.038
3 1.25, 2.50 1.27, 2.50 0.020 0.038
4 2.25, 1.00 2.24, 1.00 0.011 0.033
8 3.25, 1.50 3.25, 1.50 0.003 0.046
5 2.25, 4.00 2.27, 4.00 0.016 0.060
7 3.25, 4.50 3.27, 4.49 0.022 0.073
16 4.25, 4.50 4.27, 4.47 0.036 0.082
12 5.25, 3.50 5.27, 3.48 0.027 0.084
6 1.00, 4.75 1.02, 4.75 0.018 0.066
9 3.95, 1.50 3.97, 1.47 0.034 0.060
10 4.75, 0.25 4.77, 0.21 0.050 0.073
15 7.25, 0.40 7.29, 0.37 0.045 0.108
11 6.75, 1.75 6.76, 1.72 0.033 0.099
13 7.75, 2.50 7.76, 2.49 0.018 0.116
14 6.25, 4.75 6.25, 4.74 0.014 0.107
mean error 0.023 m; 0 sightings turned away by the gate
4. The warehouse, the posts and the two paths
| .. . ## ***** |
| . x .. ## *********x * |
| **********. x## x* .........* |
| .* *. ## * ### * |
| .* o*. ## * ### * |
| .* ### x** ## * ### * |
| . * ### *... * ### * |
| . * ### ********** x### * |
| . * ### *********. ### * |
|. * ### * *. ### * |
|. * ### * ## *. * |
|. * ### * ## * * |
| x * x### * ## * * x |
| * ### * ## * * |
| * ### * ## * * |
| * ### * ## * ######## * |
| * ### * ## * ########x * |
| ** ### * x##x .* ######## * |
| * ### * ## .* * |
| ** ### o * ## .* .** |
| * x * ## .* ****** |
| * .* ## .************ . |
| S************ ## ......o |
| xo x ## x x |
| ## |

In the table, dead reckoning's error does not grow steadily: its errors are a random walk, and they can cancel for a while, as between waypoints 6 and 8, before they pile up to 1.68 m. SLAM's error peaks at 13 cm in the far room, stays below its 1-sigma 98 % of the way, and ends at 2 cm. At the first waypoint SLAM is a little behind the odometry: its first posts were each placed from a single noisy sighting.

In the map, every error is below its 1-sigma: the filter is not only accurate, it is consistent, it knows how much it knows. The posts far from the start have the largest sigmas, up to 12 cm, the posts by the start the smallest. In the drawing, x marks where SLAM put a post, usually on top of the true o; * is SLAM's path and . dead reckoning's.

Things to try

  1. Stop the loop at the far corner, after waypoint 6. How uncertain are the posts there, and the robot?
  2. Double the odometry's noise. How far does dead reckoning drift, and does SLAM still close the loop?
  3. Give the sensor a reach of 1.5 m. Which posts are never mapped, and what happens on the long straights?
  4. Here every post has an id. Without ids the filter has to work out which post a sighting is of, data association: try the nearest post by Mahalanobis distance, and see what one wrong match does to the map.

The code

// Mapping with SLAM: a robot drives through the warehouse knowing nothing of it but its own
// odometry. Posts with markers stand along the walls and shelves, and a sensor gives the range and
// bearing of every post it can see within 2.5 m, with its id. EKF-SLAM works out where the robot
// is and where the posts are, at once. The robot drives a loop, through the door and back, and the
// example compares SLAM with dead reckoning, the odometry alone, and shows the loop closing: when
// the robot sees the first posts again, its uncertainty collapses.
//
// The warehouse is bitsim::planning::BoxWorld::warehouse(); its shelves and walls hide posts from
// the sensor, but the robot does not know where they are.
//
// Usage: ekf_slam
#include <algorithm>
#include <array>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>
#include <vector>
namespace ekf_slam
{
const real_t DT = 0.1; // [s]
const real_t SPEED = 0.3; // [m/s]
const real_t MAX_TURN = 1.5; // [rad/s]
const real_t SENSOR_RANGE = 2.5; // [m] the posts the sensor sees
const uint_t SIGHT_EVERY = 5; // steps between sightings: twice a second
using Point = std::array<real_t, 2>;
// The posts, with markers, along the walls and the shelves; their ids are their indices
const std::vector<Point> POSTS{{1.0, 0.25}, {2.75, 0.25}, {0.25, 2.5}, {1.25, 2.5}, {2.25, 1.0},
{2.25, 4.0}, {1.0, 4.75}, {3.25, 4.5}, {3.25, 1.5}, {3.95, 1.5},
{4.75, 0.25}, {6.75, 1.75}, {5.25, 3.5}, {7.75, 2.5}, {6.25, 4.75},
{7.25, 0.4}, {4.25, 4.5}};
// The loop the robot drives: around the first shelf, through the door, around the second room
// and back the same way to where it started
const std::vector<Point> ROUTE{{2.8, 0.6}, {2.8, 3.4}, {4.5, 3.4}, {4.5, 0.8}, {7.3, 0.8},
{7.3, 4.7}, {4.5, 4.7}, {4.5, 3.4}, {2.8, 3.4}, {2.4, 4.5},
{0.8, 4.5}, {0.8, 0.8}, {0.5, 0.5}};
// What a run gives: the poses at every step, true, by dead reckoning and by SLAM, and the map
struct Run
{
std::vector<Pose> truth;
std::vector<Pose> odometry;
std::vector<Pose> slam;
std::vector<real_t> slam_sigma; // the 1-sigma radius of SLAM's position [m]
std::vector<uint_t> n_mapped; // landmarks in the map
std::vector<std::size_t> waypoints; // the step at which each waypoint was reached
std::vector<uint_t> ids; // the landmarks mapped, in order
std::vector<Point> estimates; // where SLAM put them
std::vector<std::array<real_t, 3>> covariances; // their (xx, xy, yy)
real_t length{0.0}; // [m] driven
};
// The sightings from the true pose: the posts within reach that no shelf or wall hides, with
// noise on their ranges and bearings
std::vector<EKFSlam::Observation> sight(const BoxWorld &world, const Pose &pose,
const EKFSlam::Parameters &p, std::mt19937 &rng)
{
std::normal_distribution<real_t> range_noise(0.0, p.range_noise);
std::normal_distribution<real_t> bearing_noise(0.0, p.bearing_noise);
std::vector<EKFSlam::Observation> sightings;
for (uint_t id = 0; id < POSTS.size(); ++id)
{
const real_t dx = POSTS[id][0] - pose.x;
const real_t dy = POSTS[id][1] - pose.y;
const real_t range = std::hypot(dx, dy);
if (range > SENSOR_RANGE)
{
continue;
}
const real_t angle = std::atan2(dy, dx);
if (world.ray_cast({pose.x, pose.y}, angle, range).hit)
{
continue; // a shelf or a wall is in the way
}
sightings.push_back(
{id, range + range_noise(rng), wrap_angle(angle - pose.yaw + bearing_noise(rng))});
}
return sightings;
}
{
const BoxWorld world = BoxWorld::warehouse();
std::mt19937 rng(7);
std::normal_distribution<real_t> unit(0.0, 1.0);
Pose truth{world.start()[0], world.start()[1], 0.0};
Pose odometry = truth;
EKFSlam slam(truth, p);
const auto record = [&]()
{
run.truth.push_back(truth);
run.odometry.push_back(odometry);
run.slam.push_back(slam.pose());
const auto P = slam.pose_covariance();
run.slam_sigma.push_back(std::sqrt(P(0, 0) + P(1, 1)));
run.n_mapped.push_back(slam.n_landmarks());
};
record();
std::size_t step = 0;
for (const auto &target : ROUTE)
{
while (std::hypot(target[0] - truth.x, target[1] - truth.y) > 0.05)
{
// steer the true robot towards the waypoint, slowing down when it faces away
const real_t error =
wrap_angle(std::atan2(target[1] - truth.y, target[0] - truth.x) - truth.yaw);
const real_t turn = std::clamp(error, -MAX_TURN * DT, MAX_TURN * DT);
const real_t distance = SPEED * DT * std::max(0.0, std::cos(error));
const real_t mid = truth.yaw + 0.5 * turn;
truth.x += distance * std::cos(mid);
truth.y += distance * std::sin(mid);
truth.yaw = wrap_angle(truth.yaw + turn);
run.length += distance;
// what the odometry says: the true step with noise of the size SLAM expects
const real_t sd = p.distance_noise * std::sqrt(distance);
const real_t st = std::sqrt(p.turn_noise * p.turn_noise * std::abs(turn) +
p.turn_drift * p.turn_drift * distance);
const real_t measured_distance = distance + sd * unit(rng);
const real_t measured_turn = turn + st * unit(rng);
const real_t omid = odometry.yaw + 0.5 * measured_turn;
odometry.x += measured_distance * std::cos(omid);
odometry.y += measured_distance * std::sin(omid);
odometry.yaw = wrap_angle(odometry.yaw + measured_turn);
slam.predict(measured_distance, measured_turn);
if (++step % SIGHT_EVERY == 0)
{
slam.update(sight(world, truth, p, rng));
}
record();
}
run.waypoints.push_back(run.truth.size() - 1);
}
for (const auto id : slam.landmark_ids())
{
run.ids.push_back(id);
run.estimates.push_back(slam.landmark(id));
const auto C = slam.landmark_covariance(id);
run.covariances.push_back({C(0, 0), C(0, 1), C(1, 1)});
}
run.n_rejected = slam.n_rejected();
return run;
}
real_t error(const Pose &a, const Pose &b) { return std::hypot(a.x - b.x, a.y - b.y); }
// The warehouse from above, 0.2 m a character: # a shelf or wall, o a post, x where SLAM put it,
// * the path by SLAM, . the path by dead reckoning, S the start
void draw(const BoxWorld &world, const Run &run)
{
const real_t cell = 0.2;
const int cols = static_cast<int>(std::lround(world.width() / cell));
const int rows = static_cast<int>(std::lround(world.height() / cell));
std::vector<std::string> canvas(rows, std::string(cols, ' '));
const auto put = [&](real_t x, real_t y, char ch)
{
const int c = static_cast<int>(std::floor(x / cell));
const int r = static_cast<int>(std::floor(y / cell));
if (c >= 0 && c < cols && r >= 0 && r < rows)
{
canvas[r][c] = ch;
}
};
for (int r = 0; r < rows; ++r)
{
for (int c = 0; c < cols; ++c)
{
for (const auto &b : world.obstacles())
{
const real_t x = (c + 0.5) * cell;
const real_t y = (r + 0.5) * cell;
if (x >= b.x0 && x <= b.x1 && y >= b.y0 && y <= b.y1)
{
canvas[r][c] = '#';
}
}
}
}
for (const auto &pose : run.odometry)
{
put(pose.x, pose.y, '.');
}
for (const auto &pose : run.slam)
{
put(pose.x, pose.y, '*');
}
for (const auto &post : POSTS)
{
put(post[0], post[1], 'o');
}
for (const auto &e : run.estimates)
{
put(e[0], e[1], 'x');
}
put(run.truth.front().x, run.truth.front().y, 'S');
for (int r = rows - 1; r >= 0; --r)
{
std::cout << " |" << canvas[r] << "|\n";
}
}
void run()
{
const BoxWorld world = BoxWorld::warehouse();
const Run run = simulate();
std::cout << " " << POSTS.size() << " posts, seen within " << SENSOR_RANGE
<< " m unless a shelf or wall is in the way; " << std::fixed << std::setprecision(1)
<< run.length << " m driven in " << run.truth.size() - 1 << " steps of " << DT
<< " s\n";
bitsim::utils::io::print_title("2. Dead reckoning against SLAM, waypoint by waypoint");
std::cout << " waypoint driven [m] odometry error [m] SLAM error [m] SLAM 1-sigma [m]"
" posts mapped\n";
real_t driven = 0.0;
std::size_t last = 0;
for (std::size_t w = 0; w < run.waypoints.size(); ++w)
{
const std::size_t k = run.waypoints[w];
for (std::size_t i = last + 1; i <= k; ++i)
{
driven += error(run.truth[i], run.truth[i - 1]);
}
last = k;
std::cout << std::setw(10) << w + 1 << std::setprecision(1) << std::setw(12) << driven
<< std::setprecision(3) << std::setw(20) << error(run.truth[k], run.odometry[k])
<< std::setw(16) << error(run.truth[k], run.slam[k]) << std::setw(18)
<< run.slam_sigma[k] << std::setw(14) << run.n_mapped[k] << "\n";
}
bitsim::utils::io::print_title("3. The map: where SLAM put the posts");
std::cout << " post true x, y [m] SLAM x, y [m] error [m] 1-sigma [m]\n";
real_t sum = 0.0;
for (std::size_t i = 0; i < run.ids.size(); ++i)
{
const auto &t = POSTS[run.ids[i]];
const auto &e = run.estimates[i];
const real_t err = std::hypot(t[0] - e[0], t[1] - e[1]);
const real_t sigma = std::sqrt(run.covariances[i][0] + run.covariances[i][2]);
sum += err;
std::cout << std::setw(6) << run.ids[i] << std::setprecision(2) << std::setw(9) << t[0]
<< "," << std::setw(5) << t[1] << std::setw(10) << e[0] << "," << std::setw(5)
<< e[1] << std::setprecision(3) << std::setw(12) << err << std::setw(14) << sigma
<< "\n";
}
std::cout << " mean error " << sum / run.ids.size() << " m; " << run.n_rejected
<< " sightings turned away by the gate\n";
bitsim::utils::io::print_title("4. The warehouse, the posts and the two paths");
draw(world, run);
}
} // namespace ekf_slam
int main()
{
return 0;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
Simultaneous localisation and mapping with an extended Kalman filter: a robot works out where it is a...
Definition ekf_slam.h:145
A rectangular slice of the plane with axis-aligned box obstacles, a start and a goal.
Definition box_world.h:29
static BoxWorld warehouse()
The warehouse of the grid_planning and rrt examples: 8 x 5 m, a 0.25 m robot, five shelves and a wall...
Definition box_world.cpp:152
int main()
Definition discounted_returns.cpp:19
std::iterator_traits< IteratorType >::value_type sum(IteratorType begin, IteratorType end, bool parallel=true)
Definition vector_math.h:89
@ P
Definition fixed_wing_dynamics.h:37
real_t wrap_angle(real_t angle)
The angle [rad] wrapped to , so that angles that differ by whole turns compare equal.
Definition math_utils.h:66
void print_title(const std::string &title, std::ostream &out)
An empty line and then the title.
Definition print_utils.cpp:17
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
void record(const std::vector< Run > &runs, const std::string &directory)
Definition cart_pole_lqr_mpc.cpp:194
Definition ekf_slam.cpp:29
const real_t SENSOR_RANGE
Definition ekf_slam.cpp:40
const std::vector< Point > ROUTE
Definition ekf_slam.cpp:53
const real_t MAX_TURN
Definition ekf_slam.cpp:39
Run simulate()
Definition ekf_slam.cpp:103
void run()
Definition ekf_slam.cpp:233
void draw(const BoxWorld &world, const Run &run)
Definition ekf_slam.cpp:180
const uint_t SIGHT_EVERY
Definition ekf_slam.cpp:41
real_t wrap_angle(real_t angle)
The angle [rad] wrapped to , so that angles that differ by whole turns compare equal.
Definition math_utils.h:66
std::vector< EKFSlam::Observation > sight(const BoxWorld &world, const Pose &pose, const EKFSlam::Parameters &p, std::mt19937 &rng)
Definition ekf_slam.cpp:77
const real_t SPEED
Definition ekf_slam.cpp:38
EKFSlam::Pose Pose
Definition ekf_slam.cpp:57
const std::vector< Point > POSTS
Definition ekf_slam.cpp:46
std::array< real_t, 2 > Point
Definition ekf_slam.cpp:43
real_t error(const Pose &a, const Pose &b)
Definition ekf_slam.cpp:176
const real_t DT
Definition ekf_slam.cpp:37
Vector step(const QuadrotorDynamicsConfig &config, const Vector &x, const Vector &u, real_t max_rotor_speed)
Definition quadrotor_lqr.cpp:114
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
Definition ekf_slam.h:148
Definition ekf_slam.h:158
Definition ekf_slam.cpp:61
std::vector< real_t > slam_sigma
Definition ekf_slam.cpp:65
std::vector< uint_t > ids
Definition ekf_slam.cpp:68
uint_t n_rejected
Definition ekf_slam.cpp:71
std::vector< Pose > truth
Definition ekf_slam.cpp:62
real_t length
Definition ekf_slam.cpp:72
std::vector< Pose > odometry
Definition ekf_slam.cpp:63
std::vector< std::size_t > waypoints
Definition ekf_slam.cpp:67
std::vector< Pose > slam
Definition ekf_slam.cpp:64
std::vector< uint_t > n_mapped
Definition ekf_slam.cpp:66
std::vector< std::array< real_t, 3 > > covariances
Definition ekf_slam.cpp:70
std::vector< Point > estimates
Definition ekf_slam.cpp:69