bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
Planning a path on a grid

A robot has to cross a warehouse, past shelves and through the door of a wall, without touching anything. This example cuts the floor into cells, marks the ones the robot cannot be in, and searches the free ones for a path. It runs several grid planners on the same warehouse, from breadth-first search to any-angle Theta*, and compares the paths they find and the work they do.

What you need

Nothing beyond bitsim itself. See Installing bitsim.

The warehouse

BoxWorld holds the warehouse: its size, 8 x 5 m, the shelves and the wall as boxes, the robot's radius, 25 cm, and the start and goal. BoxWorld::warehouse is the layout this example and Planning a path with a random tree both plan across, so the two share one map. It builds an OccupancyGrid for a grid planner, or tests a single point for a sampling planner such as RRT.

The occupancy grid

OccupancyGrid cuts the floor into cells of 10 cm, each free or occupied. A robot is not a point: its centre has to stay its radius away from every shelf and wall. So the obstacles are grown by that radius before they go on the grid, and then the robot can be planned as a point: any free cell is a place where its centre can be.

From a cell the robot can move to its eight neighbours, the four that share a side and the four that share a corner, but not diagonally past the corner of an occupied cell.

The searches

All of these search the same grid; they differ in the order they expand cells and in the paths they allow.

  • Breadth-first (bfs_grid) expands cells in rings of equal move count from the start. It finds a path with the fewest moves, but every move counts the same, so the path is not the shortest in metres, and it fans out in every direction.
  • Dijkstra is a_star with a heuristic weight of zero: it expands cells in order of their distance from the start and finds a shortest path, after a lot of work.
  • A* (a_star_grid) orders its open cells by \(f(n) = g(n) + w\,h(n)\), the cost \(g\) of the best path to \(n\) so far plus the weighted heuristic \(h\), here the straight-line distance to the goal, which never guesses too high. With \(w = 1\) it finds a shortest path and expands far fewer cells than Dijkstra; with \(w > 1\) it heads for the goal and expands fewer still, but the path may be longer.
  • Theta* (theta_star_grid) is A* that, each time it reaches a cell, checks whether the cell has a clear line of sight to the parent of the cell it came from. If it does, it links the cell straight to that grandparent. The path then takes straight shortcuts at any angle instead of following the grid and its 45° diagonals, so it is shorter.

Watching them search

Each search coloured in blue as it expands cells, with the path it finds in red; the robot goes from the green start to the orange goal.

Breadth-first search

Breadth-first fans out in rings in every direction and finds a path with the fewest moves, 11.17 m.

Dijkstra's algorithm

Dijkstra expands cells in order of distance from the start, again in every direction, and finds a shortest path, 10.76 m.

A*

A* follows its heuristic towards the goal, so it expands a narrow band of cells and finds the same 10.76 m path for much less work.

Theta*

Theta* searches like A* but lets the path leave the grid, so it cuts straight across at any angle for the shortest path of all, 10.26 m.

Running the example

./grid_planning

Output

1. The warehouse and the shortest path
80 x 50 cells of 0.1 m, 1927 of them too close to an obstacle
::::::::::::::::::#:::::::::::::::::::::
:: ::#: :::::: :
:: ::#: ::##:: G :
:: :::::: ::#: ::##:: * :
:: :::::: ::#: ::##:: * :
:: ::##:: ::#: ::##:: * :
:: ::##:: :::: ::##:: * :
:: ::##:: ::##:: * :
:: ::##:: ******** ::##:: ** :
:: ::##:: *:::: * ::##:: ** :
:: ::##:: *::#: * ::::::** :
:: ::##:: *::#: ******** :
:: ::##:: *::#: :
:: ::##:: *::#: :::::::::: :
:: ::##:: *::#: :::::::::: :
:: ::##:: *::#: :########: :
:: ::##:: *::#: :########: :
:: ::##:: *::#: :::::::::: :
:: ::##:: **::#: :::::::::: :
:: ::##:: ** ::#: :
:: ::::::** ::#: :
:: ***** ::#: :
::S****** ::#: :
::::::::::::::::::#:::::::::::::::::::::
::::::::::::::::::#:::::::::::::::::::::
2. How the searches compare
search length expanded
breadth-first 11.17 m 1998 cells expanded
Dijkstra (weight 0) 10.76 m 2031 cells expanded
A* 10.76 m 1297 cells expanded
weighted A* (weight 3) 12.67 m 807 cells expanded
A*, moves along the axes 12.40 m 1520 cells expanded
Theta* (any angle) 10.26 m 1106 cells expanded
3. Theta*: a path at any angle
::::::::::::::::::#:::::::::::::::::::::
:: ::#: :::::: :
:: ::#: ::##:: G :
:: :::::: ::#: ::##:: ** :
:: :::::: ::#: ::##:: * :
:: ::##:: ::#: ::##:: ** :
:: ::##:: :::: ::##:: ** :
:: ::##:: ::##:: * :
:: ::##:: ******* ::##:: ** :
:: ::##:: *:::: *** ::##::** :
:: ::##:: **::#: ** ::::::* :
:: ::##:: * ::#: ********* :
:: ::##:: * ::#: :
:: ::##:: * ::#: :::::::::: :
:: ::##:: ** ::#: :::::::::: :
:: ::##:: * ::#: :########: :
:: ::##:: * ::#: :########: :
:: ::##::** ::#: :::::::::: :
:: ::##::* ::#: :::::::::: :
:: ::##::* ::#: :
:: :::::** ::#: :
:: ***** ::#: :
::S***** ::#: :
::::::::::::::::::#:::::::::::::::::::::
::::::::::::::::::#:::::::::::::::::::::
A* along the grid 10.76 m, 97 cells
Theta* any angle 10.26 m, 7 corners
4. A robot that is too wide for the door
A*, robot radius 0.45 m no path

Each character is 2 x 2 cells: # a shelf or the wall, : where the robot's centre cannot be, * the path. The path hugs the grown shelf and goes through the door, 80 cm wide.

The table tells the story. Breadth-first and Dijkstra expand almost the whole free space; breadth-first's path is the longest because it counts moves, not metres. A* finds the same shortest path as Dijkstra for a third fewer cells. Weighted A* expands fewer still but its path is 2 m longer; with moves along the axes only, the robot has to zigzag, and the path is 15 % longer. Theta* is the shortest of all, 10.26 m: its path leaves the grid and cuts across at any angle, through just 7 corners rather than 97 cells. A robot with a radius of 45 cm does not fit through the door, and A* says there is no path.

Things to try

  1. Move the door down to the floor. Does the path change, and does Dijkstra still expand more cells?
  2. Try weights between 1 and 3. When does the A* path start to get longer?
  3. Compare the Theta* path with the shortened RRT path in Planning a path with a random tree. Which is shorter?
  4. Make the cells 5 cm. How do the number of cells expanded and the time grow?

The code

// Planning a path for a robot across a warehouse on a grid. The floor is cut into cells of 10 cm,
// the shelves and walls are grown by the robot's radius so that the robot can be planned as a
// point, and the free cells are searched. The example runs several grid planners on the same
// warehouse and compares them: breadth-first search, Dijkstra, A* (plain, weighted, and axes
// only), and Theta*, which plans at any angle rather than along the grid.
//
// The warehouse is bitsim::planning::BoxWorld::warehouse(), shared with the rrt example.
//
// Usage: grid_planning
#include <iomanip>
#include <iostream>
#include <set>
#include <string>
#include <vector>
namespace grid_planning
{
using namespace bitsim::planning;
const real_t CELL = 0.1; // [m]
// The cells a path passes through, with the straight segments of an any-angle path filled in so
// that the corner cells of a Theta* path are joined up
std::vector<GridCell> densify(const std::vector<GridCell> &path)
{
std::vector<GridCell> cells;
for (std::size_t i = 0; i < path.size(); ++i)
{
if (i == 0)
{
cells.push_back(path[i]);
continue;
}
// step from path[i - 1] to path[i] one cell at a time
GridCell c = path[i - 1];
const int_t dx = std::abs(path[i].col - c.col);
const int_t dy = std::abs(path[i].row - c.row);
const int_t x_inc = path[i].col > c.col ? 1 : -1;
const int_t y_inc = path[i].row > c.row ? 1 : -1;
int_t error = dx - dy;
while (c != path[i])
{
if (error > 0)
{
c.col += x_inc;
error -= 2 * dy;
}
else if (error < 0)
{
c.row += y_inc;
error += 2 * dx;
}
else
{
c.col += x_inc;
c.row += y_inc;
error += 2 * dx - 2 * dy;
}
cells.push_back(c);
}
}
return cells;
}
// The warehouse from above, two cells a character: # an obstacle, : where the robot's centre
// cannot go, * the path, S and G the start and the goal
void draw(const BoxWorld &world, const OccupancyGrid &obstacles, const OccupancyGrid &grown,
const std::vector<GridCell> &path)
{
std::set<std::pair<int, int>> on_path;
for (const auto &c : densify(path))
{
on_path.insert({static_cast<int>(c.col / 2), static_cast<int>(c.row / 2)});
}
const GridCell s = grown.to_cell(world.start()[0], world.start()[1]);
const GridCell g = grown.to_cell(world.goal()[0], world.goal()[1]);
const int cols = static_cast<int>(grown.n_cols() / 2);
const int rows = static_cast<int>(grown.n_rows() / 2);
for (int r = rows - 1; r >= 0; --r)
{
std::cout << " ";
for (int c = 0; c < cols; ++c)
{
const GridCell cell{2 * c, 2 * r};
char ch = ' ';
if (!obstacles.is_free(cell))
{
ch = '#';
}
else if (!grown.is_free(cell))
{
ch = ':';
}
if (on_path.count({c, r}))
{
ch = '*';
}
if (c == s.col / 2 && r == s.row / 2)
{
ch = 'S';
}
if (c == g.col / 2 && r == g.row / 2)
{
ch = 'G';
}
std::cout << ch;
}
std::cout << "\n";
}
}
void report(const std::string &name, const SearchResult<GridCell> &result)
{
std::cout << " " << std::left << std::setw(26) << name << std::right;
if (!result.found)
{
std::cout << "no path\n";
return;
}
std::cout << std::fixed << std::setprecision(2) << std::setw(8) << result.cost << " m"
<< std::setw(10) << result.n_expanded << " cells expanded\n";
}
void run()
{
const BoxWorld world = BoxWorld::warehouse();
const OccupancyGrid obstacles = world.occupancy_grid(CELL, 0.0);
const OccupancyGrid grid = world.occupancy_grid(CELL); // grown by the robot's radius
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 warehouse and the shortest path");
std::cout << " " << grid.n_cols() << " x " << grid.n_rows() << " cells of " << CELL << " m, "
<< grid.n_occupied() << " of them too close to an obstacle\n\n";
const auto best = a_star_grid(grid, start, goal);
draw(world, obstacles, grid, best.path);
bitsim::utils::io::print_title("2. How the searches compare");
std::cout << " search length expanded\n";
report("breadth-first", bfs_grid(grid, start, goal));
report("Dijkstra (weight 0)", a_star_grid(grid, start, goal, true, 0.0));
report("A*", best);
report("weighted A* (weight 3)", a_star_grid(grid, start, goal, true, 3.0));
report("A*, moves along the axes", a_star_grid(grid, start, goal, false));
report("Theta* (any angle)", theta_star_grid(grid, start, goal));
bitsim::utils::io::print_title("3. Theta*: a path at any angle");
const auto any_angle = theta_star_grid(grid, start, goal);
draw(world, obstacles, grid, any_angle.path);
std::cout << std::fixed << std::setprecision(2) << "\n A* along the grid " << best.cost
<< " m, " << best.path.size() << " cells\n Theta* any angle " << any_angle.cost
<< " m, " << any_angle.path.size() << " corners\n";
bitsim::utils::io::print_title("4. A robot that is too wide for the door");
const OccupancyGrid wide = world.occupancy_grid(CELL, 0.45);
report("A*, robot radius 0.45 m", a_star_grid(wide, start, goal));
}
} // namespace grid_planning
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
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
OccupancyGrid occupancy_grid(real_t cell_size) const
The world as an OccupancyGrid of square cells, with the obstacles and the outer walls grown by margin...
Definition box_world.h:76
const Point & goal() const noexcept
Definition box_world.h:62
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
bool is_free(const GridCell &c) const noexcept
True if the cell is in the grid and not occupied.
Definition occupancy_grid.cpp:28
GridCell to_cell(real_t x, real_t y) const noexcept
The cell that the point (x, y) is in. It may be out of bounds.
Definition occupancy_grid.cpp:74
uint_t n_cols() const noexcept
Definition occupancy_grid.h:54
uint_t n_rows() const noexcept
Definition occupancy_grid.h:55
int main()
Definition discounted_returns.cpp:19
SearchResult< GridCell > theta_star_grid(const OccupancyGrid &grid, const GridCell &start, const GridCell &goal)
Theta*: any-angle search on an occupancy grid.
Definition grid_search.cpp:136
SearchResult< GridCell > bfs_grid(const OccupancyGrid &grid, const GridCell &start, const GridCell &goal, bool diagonal)
Breadth-first search on an occupancy grid.
Definition grid_search.cpp:88
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
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 error(const Pose &a, const Pose &b)
Definition ekf_slam.cpp:176
Definition grid_planning.cpp:25
const real_t CELL
Definition grid_planning.cpp:31
void report(const std::string &name, const SearchResult< GridCell > &result)
Definition grid_planning.cpp:123
void run()
Definition grid_planning.cpp:135
std::vector< GridCell > densify(const std::vector< GridCell > &path)
Definition grid_planning.cpp:35
void draw(const BoxWorld &world, const OccupancyGrid &obstacles, const OccupancyGrid &grown, const std::vector< GridCell > &path)
Definition grid_planning.cpp:78
grid(layout_path, episode_path, out, title)
Definition multi_agent_gif.py:36
Print labelled values, one per line, as the examples do: two spaces, the label padded to a width,...
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
What a search found.
Definition a_star_search.h:23
uint_t n_expanded
how many nodes the search took off its open list
Definition a_star_search.h:27
bool found
whether the goal was reached
Definition a_star_search.h:24
real_t cost
the cost of the path
Definition a_star_search.h:26