bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Building a map from range scans

Planning a path on a grid plans across a warehouse whose shelves and walls it knows exactly. A real robot does not start with that: it has to measure the world first. This example builds the map. A robot takes 360 degree range scans from points across the warehouse, folds every beam into a probabilistic occupancy grid, and then plans A* across the map it built, to see how close that comes to planning on the true map.

The true warehouse, and the 88 points the robot scans from
The map built from the scans: black occupied, light grey free, mid grey never seen

The true warehouse, with the points the robot scans from, and the map it builds. The scans recover every wall and shelf face; the insides of the shelves and everything behind the walls are never seen, and stay unknown.

What you need

Nothing beyond bitsim itself. See Installing bitsim.

Ways to represent a map

A map can be held in several ways, and bitsim has three of them:

  • Geometry (BoxWorld): the obstacles as exact shapes. It is compact and exact, and good for working out what a sensor would measure, but a robot cannot easily build it from noisy readings. Here it is the true warehouse the robot scans.
  • A binary occupancy grid (OccupancyGrid): the floor cut into cells, each free or occupied. It is what the grid planners search.
  • A probabilistic occupancy grid (ProbabilityGrid): each cell holds the probability that it is occupied. It is what a robot builds from its sensors, because it can say unknown, and can weigh readings that disagree.

Other common representations are distance fields, which hold each cell's distance to the nearest obstacle; quadtrees, which merge large uniform regions; landmark maps of features, used with SLAM; and graphs of places and the ways between them.

The scans

The robot visits a grid of points 50 cm apart across the free space, 88 of them, and at each takes a scan of 180 beams, one every 2 degrees, out to 6 m. A beam's true length is BoxWorld::ray_cast: the distance along it to the first shelf or wall. The sensor reports that with 2 cm of noise.

The probabilistic occupancy grid

Every beam says two things: the cells it passed through are probably free, and the cell it ended on, if it struck something, is probably occupied. A cell's probability \(p\) is kept as its log-odds

\[l = \log\frac{p}{1 - p} \]

which is 0 for a cell nothing has seen, \(p = 0.5\). Then folding in a beam is just an addition: each cell the beam crosses adds \(\log\frac{0.4}{0.6} \approx -0.41\), and the cell it ends on adds \(\log\frac{0.7}{0.3} \approx 0.85\). This is the inverse sensor model: how strongly one reading moves a cell. The log-odds are clamped, here to probabilities between 0.12 and 0.97, so that a cell can still change its mind when the world does.

A cell that many beams agree on ends near 0 or 1. A cell no beam has reached stays unknown: the inside of a shelf, and everything behind the walls.

From the map to a path

to_occupancy_grid thresholds the map at \(p = 0.5\) into an OccupancyGrid. Unknown cells are counted as occupied, so the robot does not plan through space it has never seen. The obstacles it sensed are then grown by a disc of the robot's radius, 25 cm, the exact clearance for a round robot, and A* searches the free cells.

To judge the map, the true warehouse is put on the same cells and grown the same way, and A* searches it too.

Running the example

./occupancy_mapping

Output

1. The map built from the scans
88 scans of 180 beams, reach 6 m
#########################################
#................##.....................#
#................##.....................#
##................##........#..#......G..#
#................##........# #.........#
#......####......##........# #.........#
#......# #......##........# ##.........#
##......# #................# #.........#
#......## #................## #.........#
#......# #................# #.........#
#......# ##......##........####.........#
#......# ##......##.....................#
#......# #......##.....................#
#......## #......##.....................#
#......# #......##.....................#
#......# #......##......########.......#
#......# ##......##......# # #.......#
#......# #......##......# # #.......#
#......# #......##......########.......#
#......# #......##.....................#
#......####......##.....................#
#................##.....................#
#................##.....................#
#.S..............##.....................#
#................##.....................#
#########################################
# ## # # # # # #
2. Planning on the built map
:::::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::
::#########################################::
::#::::::::::::::::##:::::::::::::::::::::#::
::#: :##: ::::: :#::
:##: :##: :#::#: G :#::
::#: :::: :##: :#::#: * :#::
::#: :####: :##: :#::#: * :#::
::#: :#::#: :##: :#:##: * :#::
:##: :#::#: :::: :#::#: * :#::
::#: :##:#: :##:#: ** :#::
::#: :#::#: ********* :#::#: ** :#::
::#: :#:##: *##: **:####:** :#::
::#: :#:##: *##: **::::** :#::
::#: :#::#: *##: ****** :#::
::#: :##:#: *##: :#::
::#: :#::#: *##: :::::::::: :#::
::#: :#::#: *##: :########: :#::
::#: :#:##: *##: :#:::#::#: :#::
::#: :#::#: **##: :#:#::::#: :#::
::#: :#::#: **:##: :########: :#::
::#: :#::#: ** :##: :::::::: :#::
::#: :####:** :##: :#::
::#: :::::** :##: :#::
::#: **** :##: :#::
::#:S****** :##: :#::
::#::::::::::::::::##:::::::::::::::::::::#::
::#########################################::
:::::#:##:::#:::#::#::::::#:::::#::::#:::::::
:::::::::::::::::::::::::::::::::::::::::::::
3. The built map against the true map
A* on the built map 10.33 m, 1270 cells expanded
A* on the true map 10.33 m, 1270 cells expanded
the two planning grids disagree on 11 of 5400 cells

In the map, # is likely occupied, . likely free, : seen but unsure, and a blank never seen; each character is 2 x 2 cells, showing the most occupied of them. The scans recover every wall and shelf, one cell thick where the beams struck them. The shelves are hollow: their insides were never seen, so they are unknown, and stay blocked when planning.

The path on the built map is the same as on the true map, 10.33 m, and the two planning grids differ in 11 cells of 5400. It is shorter than the 10.76 m of Planning a path on a grid because the obstacles here are grown by a disc, which rounds their corners, where grid_planning grows them as rectangles.

A few # lie just outside the walls. Those are beams whose noise carried them more than half a cell past a wall. A cell behind a wall is never crossed by a beam, so nothing corrects it; it lies outside the free space, so the plan is not affected.

Where the cells sit

The map's cells start half a cell off the warehouse's 10 cm layout, so the faces of the shelves fall in the middle of cells. If the cells lined up with the layout, every face would sit on a cell boundary, and the noise would split its hits between the cell of the shelf and the free cell in front of it. That free cell would then be hit as often as it is crossed, and since a hit counts for more than a miss, it would end up occupied: every obstacle would grow by a cell. Try MAP_OFFSET = 0.0: the door narrows, the path grows to 10.21 m against 9.58 m on the true map, and the grids differ in 348 cells. A robot's map has no reason to line up with the walls, but it pays to know what a grid does to a reading that falls on its boundary.

Things to try

  1. Raise the noise to 10 cm. How thick do the walls get, and does the robot still fit through the door?
  2. Scan from fewer points, 1 m apart. Which parts of the warehouse stay unknown, and what does the planner do about them?
  3. Count unknown cells as free, to_occupancy_grid(0.5, false). Where does the path go?
  4. Make a hit count for no more than a miss, p_hit = 0.6. What happens to the walls?

The code

// Building a map before planning a path. A robot does not start with the warehouse; it has to
// measure it. This example drives a robot to a set of vantage points, takes a 360 degree range
// scan at each by ray-casting the true BoxWorld::warehouse() geometry with a little noise, and
// folds the beams into a probabilistic occupancy grid (log-odds). It then thresholds and grows
// the built map into an OccupancyGrid and plans A* across it, exactly as the grid_planning
// example does on the known map.
//
// Usage: occupancy_mapping
#include <cmath>
#include <iomanip>
#include <iostream>
#include <random>
#include <set>
#include <string>
#include <vector>
{
using namespace bitsim::planning;
const real_t CELL = 0.1; // [m]
const real_t MARGIN = 0.5; // [m] the map reaches this far past the walls, to capture them
// The map's cells start half a cell off the warehouse's 10 cm layout, so the faces of the
// shelves fall mid-cell. Aligned, every face would sit on a cell boundary and the range noise
// would split its hits between two cells, fattening each obstacle by a cell. Try 0.0
const real_t MAP_OFFSET = CELL / 2.0;
const real_t ORIGIN = -MARGIN + MAP_OFFSET; // [m] the lower left corner of the map
const real_t MAX_RANGE = 6.0; // [m] the sensor's reach
const uint_t N_BEAMS = 180; // beams in one 360 degree scan
const real_t NOISE_STD = 0.02; // [m] range noise
const real_t SCAN_STEP = 0.5; // [m] the grid of vantage points
const real_t SCAN_CLEAR = 0.3; // [m] keep the sensor this clear of obstacles
// The poses the robot scans from: a grid of points in the free space
std::vector<std::array<real_t, 3>> scan_poses(const BoxWorld &world)
{
std::vector<std::array<real_t, 3>> poses;
for (real_t y = SCAN_STEP; y < world.height(); y += SCAN_STEP)
{
for (real_t x = SCAN_STEP; x < world.width(); x += SCAN_STEP)
{
if (world.is_free({x, y}, SCAN_CLEAR))
{
poses.push_back({x, y, 0.0});
}
}
}
return poses;
}
// Build the map: at every pose, cast N_BEAMS rays against the true geometry, add noise, and fold
// the scan into the probabilistic grid
void map_the_warehouse(const BoxWorld &world, ProbabilityGrid &grid)
{
std::mt19937 rng(1);
std::normal_distribution<real_t> noise(0.0, NOISE_STD);
std::vector<real_t> bearings(N_BEAMS);
for (uint_t i = 0; i < N_BEAMS; ++i)
{
bearings[i] = 2.0 * M_PI * i / N_BEAMS;
}
for (const auto &pose : scan_poses(world))
{
std::vector<real_t> ranges(N_BEAMS);
for (uint_t i = 0; i < N_BEAMS; ++i)
{
const auto beam = world.ray_cast({pose[0], pose[1]}, pose[2] + bearings[i], MAX_RANGE);
ranges[i] = beam.hit ? std::max(0.0, beam.distance + noise(rng)) : MAX_RANGE;
}
grid.integrate_scan(pose, bearings, ranges, MAX_RANGE);
}
}
// The built map from above, two cells a character, each showing the most occupied of its four
// cells: '#' likely occupied, '.' likely free, ':' seen but unsure, ' ' never seen, S and G the
// start and the goal
void draw_map(const ProbabilityGrid &grid, const GridCell &start, const GridCell &goal)
{
const int cols = static_cast<int>(grid.n_cols() / 2);
const int rows = static_cast<int>(grid.n_rows() / 2);
for (int r = rows - 1; r >= 0; --r)
{
std::cout << " ";
for (int c = 0; c < cols; ++c)
{
bool known = false;
real_t p_max = 0.0;
for (int k = 0; k < 4; ++k)
{
const GridCell cell{2 * c + k % 2, 2 * r + k / 2};
if (grid.is_known(cell))
{
known = true;
p_max = std::max(p_max, grid.probability(cell));
}
}
char ch = ' ';
if (known)
{
ch = p_max >= 0.65 ? '#' : (p_max <= 0.35 ? '.' : ':');
}
if (c == start.col / 2 && r == start.row / 2)
{
ch = 'S';
}
if (c == goal.col / 2 && r == goal.row / 2)
{
ch = 'G';
}
std::cout << ch;
}
std::cout << "\n";
}
}
// A map and its path, two cells a character: '#' an obstacle, ':' grown or never seen, '*' the
// path, S and G
void draw_path(const OccupancyGrid &obstacles, const OccupancyGrid &planning,
const std::vector<GridCell> &path, const GridCell &start, const GridCell &goal)
{
std::set<std::pair<int, int>> on_path;
for (const auto &c : path)
{
on_path.insert({static_cast<int>(c.col / 2), static_cast<int>(c.row / 2)});
}
const int cols = static_cast<int>(planning.n_cols() / 2);
const int rows = static_cast<int>(planning.n_rows() / 2);
for (int r = rows - 1; r >= 0; --r)
{
std::cout << " ";
for (int c = 0; c < cols; ++c)
{
bool obstacle = false;
bool blocked = false;
for (int k = 0; k < 4; ++k)
{
const GridCell cell{2 * c + k % 2, 2 * r + k / 2};
obstacle = obstacle || !obstacles.is_free(cell);
blocked = blocked || !planning.is_free(cell);
}
char ch = obstacle ? '#' : (blocked ? ':' : ' ');
if (on_path.count({c, r}))
{
ch = '*';
}
if (c == start.col / 2 && r == start.row / 2)
{
ch = 'S';
}
if (c == goal.col / 2 && r == goal.row / 2)
{
ch = 'G';
}
std::cout << ch;
}
std::cout << "\n";
}
}
// The grid a robot of the given radius is planned on as a point: the cells of blocked, with
// every cell of obstacles grown by a disc of that radius, the exact clearance of a round robot
OccupancyGrid inflate(OccupancyGrid blocked, const OccupancyGrid &obstacles, real_t radius)
{
for (uint_t row = 0; row < obstacles.n_rows(); ++row)
{
for (uint_t col = 0; col < obstacles.n_cols(); ++col)
{
const GridCell c{static_cast<int_t>(col), static_cast<int_t>(row)};
if (!obstacles.is_free(c))
{
const auto p = obstacles.to_world(c);
blocked.add_circle(p[0], p[1], radius);
}
}
}
return blocked;
}
// The true warehouse on the same cells as the built map: the boxes, and everything outside the
// walls, which the robot can no more enter than a shelf. A cell whose centre lies on a face is
// counted in, as the built map counts the cell a beam ends on
OccupancyGrid true_obstacles(const BoxWorld &world, uint_t n_cols, uint_t n_rows)
{
const real_t eps = 1.0e-6;
const real_t far = 1.0e3;
OccupancyGrid grid(n_cols, n_rows, CELL, ORIGIN, ORIGIN);
for (const auto &b : world.obstacles())
{
grid.add_rectangle(b.x0 - eps, b.y0 - eps, b.x1 + eps, b.y1 + eps);
}
const real_t w = world.width();
const real_t h = world.height();
grid.add_rectangle(-far, -far, eps, far); // left of the warehouse
grid.add_rectangle(w - eps, -far, far, far); // right
grid.add_rectangle(-far, -far, far, eps); // below
grid.add_rectangle(-far, h - eps, far, far); // above
return grid;
}
void run()
{
const BoxWorld world = BoxWorld::warehouse();
// the map covers the warehouse and a margin around it, so the outer walls land inside it
const uint_t n_cols = static_cast<uint_t>(std::lround((world.width() + 2 * MARGIN) / CELL));
const uint_t n_rows = static_cast<uint_t>(std::lround((world.height() + 2 * MARGIN) / CELL));
ProbabilityGrid grid(n_cols, n_rows, CELL, ORIGIN, ORIGIN);
map_the_warehouse(world, grid);
const GridCell start = grid.to_cell(world.start()[0], world.start()[1]);
const GridCell goal = grid.to_cell(world.goal()[0], world.goal()[1]);
bitsim::utils::io::print_title("1. The map built from the scans");
std::cout << " " << scan_poses(world).size() << " scans of " << N_BEAMS << " beams, reach "
<< MAX_RANGE << " m\n\n";
draw_map(grid, start, goal);
bitsim::utils::io::print_title("2. Planning on the built map");
// the sensed obstacles, grown by the robot's radius; unknown cells stay blocked, ungrown
const OccupancyGrid sensed = grid.to_occupancy_grid(0.5, false);
const OccupancyGrid built =
inflate(grid.to_occupancy_grid(0.5, true), sensed, world.robot_radius());
const auto built_path = a_star_grid(built, start, goal);
draw_path(sensed, built, built_path.path, start, goal);
bitsim::utils::io::print_title("3. The built map against the true map");
// the true warehouse on the same cells, grown the same way, so only the mapping differs
const OccupancyGrid truth_obstacles = true_obstacles(world, n_cols, n_rows);
const OccupancyGrid truth = inflate(truth_obstacles, truth_obstacles, world.robot_radius());
const auto true_path = a_star_grid(truth, start, goal);
uint_t disagree = 0;
for (uint_t row = 0; row < n_rows; ++row)
{
for (uint_t col = 0; col < n_cols; ++col)
{
const GridCell c{static_cast<int_t>(col), static_cast<int_t>(row)};
if (built.is_free(c) != truth.is_free(c))
{
++disagree;
}
}
}
std::cout << std::fixed << std::setprecision(2);
std::cout << " A* on the built map " << built_path.cost << " m, " << built_path.n_expanded
<< " cells expanded\n";
std::cout << " A* on the true map " << true_path.cost << " m, " << true_path.n_expanded
<< " cells expanded\n";
std::cout << " the two planning grids disagree on " << disagree << " of " << n_cols * n_rows
<< " cells\n";
}
} // namespace occupancy_mapping
int main()
{
return 0;
}
The basic types of bitsim. Code outside this file names Eigen's matrix and vector types only through ...
A rectangular slice of the plane with axis-aligned box obstacles, a start and a goal.
Definition box_world.h:29
bool is_free(const Point &p) const
True if a disc of the given radius centred at p touches no obstacle and no outer wall....
Definition box_world.h:68
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
real_t robot_radius() const noexcept
Definition box_world.h:59
const Point & goal() const noexcept
Definition box_world.h:62
RayHit ray_cast(const Point &origin, real_t angle, real_t max_range) const
Cast a ray from origin in the direction angle (radians, measured from the x axis) and return the dist...
Definition box_world.cpp:112
const std::vector< Box > & obstacles() const noexcept
Definition box_world.h:60
real_t width() const noexcept
Definition box_world.h:57
real_t height() const noexcept
Definition box_world.h:58
const Point & start() const noexcept
Definition box_world.h:61
A rectangle of the plane cut into square cells, each free or occupied.
Definition occupancy_grid.h:43
void add_circle(real_t x, real_t y, real_t radius)
Occupy the cells whose centres are within radius of (x, y).
Definition occupancy_grid.cpp:58
std::array< real_t, 2 > to_world(const GridCell &c) const noexcept
The centre of a cell [m].
Definition occupancy_grid.cpp:80
bool is_free(const GridCell &c) const noexcept
True if the cell is in the grid and not occupied.
Definition occupancy_grid.cpp:28
uint_t n_cols() const noexcept
Definition occupancy_grid.h:54
uint_t n_rows() const noexcept
Definition occupancy_grid.h:55
An occupancy map built from range sensors, each cell holding the probability that it is occupied.
Definition probability_grid.h:33
int main()
Definition discounted_returns.cpp:19
SearchResult< GridCell > a_star_grid(const OccupancyGrid &grid, const GridCell &start, const GridCell &goal, bool diagonal, real_t weight)
A* on an occupancy grid, moving to the neighbours of a cell (see OccupancyGrid::neighbours) with the ...
Definition a_star_search.cpp:10
Definition a_star_search.cpp:8
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
int int_t
integer type
Definition bitsim_types.h:30
CartPoleState start()
Definition cart_pole_lqr_mpc.cpp:73
real_t h(real_t x)
Definition importance_sampling.cpp:39
grid(layout_path, episode_path, out, title)
Definition multi_agent_gif.py:36
Definition occupancy_mapping.cpp:26
const real_t MAP_OFFSET
Definition occupancy_mapping.cpp:38
OccupancyGrid true_obstacles(const BoxWorld &world, uint_t n_cols, uint_t n_rows)
Definition occupancy_mapping.cpp:196
const real_t CELL
Definition occupancy_mapping.cpp:33
const real_t SCAN_CLEAR
Definition occupancy_mapping.cpp:44
OccupancyGrid inflate(OccupancyGrid blocked, const OccupancyGrid &obstacles, real_t radius)
Definition occupancy_mapping.cpp:176
const real_t MAX_RANGE
Definition occupancy_mapping.cpp:40
const real_t SCAN_STEP
Definition occupancy_mapping.cpp:43
const real_t ORIGIN
Definition occupancy_mapping.cpp:39
const real_t NOISE_STD
Definition occupancy_mapping.cpp:42
void draw_path(const OccupancyGrid &obstacles, const OccupancyGrid &planning, const std::vector< GridCell > &path, const GridCell &start, const GridCell &goal)
Definition occupancy_mapping.cpp:132
const real_t MARGIN
Definition occupancy_mapping.cpp:34
void map_the_warehouse(const BoxWorld &world, ProbabilityGrid &grid)
Definition occupancy_mapping.cpp:65
void run()
Definition occupancy_mapping.cpp:214
void draw_map(const ProbabilityGrid &grid, const GridCell &start, const GridCell &goal)
Definition occupancy_mapping.cpp:91
const uint_t N_BEAMS
Definition occupancy_mapping.cpp:41
std::vector< std::array< real_t, 3 > > scan_poses(const BoxWorld &world)
Definition occupancy_mapping.cpp:47
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
bool hit
false if the beam reached max_range without striking anything
Definition box_world.h:42
A cell of an OccupancyGrid: its column, along x, and row, along y.
Definition occupancy_grid.h:21
int_t row
Definition occupancy_grid.h:23
int_t col
Definition occupancy_grid.h:22