Autonomy: rangefinders, maps, avoidance and precision landing · 6 MIN READ
Configuration space: inflating your own map, deciding about unknown cells and flying the plan
Turn a self-built occupancy grid into a configuration space by growing occupied cells by the airframe radius, a margin and half a cell, decide whether unknown cells count as free or blocked, plan on the result with A*, fly the plan and check the clearance with the rangefinder.
The path-planning lesson searched a grid that someone else had drawn and inflated. Here the drone builds the map itself, so two decisions come before the search: how much room to leave around what it saw, and what to assume about what it never saw. Both decide whether the planned path is safe. A wrong answer to the second does not show on the map: the path looks clear because nobody looked.
drones · A MAP OF THE IDEA
- Survey into a grid
- Inflate; decide unknown
- A* and prune
- Fly and log clearance
Useful when
- A point planner gets an airframe-safe path.
- Range readings turn the margin into a test.
Watch out
- Unknown as free is safe only with replanning.
- Coarse cells and big margins close narrow gaps.
Implementation & operation cost: An inflation pass per map update, a written decision about unknown space, and clearance logged on every flight.
From the map to configuration space
A planner that treats the drone as a point needs a map in which a point is safe exactly where the real airframe would be. That map is the configuration space: grow every obstacle by the vehicle's radius, and a point outside the grown obstacles stands for an airframe clear of the real ones. On a grid, grow by more. The simulator counts contact when the drone's centre comes within 0.3 m of a surface, so the airframe radius is 0.3 m. Add a margin for what the plan cannot know: the tracking error in gusts, the map's own error and, on a real vehicle, the position estimate's error. Then add half a cell's diagonal, 0.7 m for 1 m cells, because a free cell only says the drone is somewhere inside it. The program measures from each cell centre to the edge of an occupied cell, because the obstacle can be anywhere inside it, and blocks every cell within 2.5 m. ArduPilot's object avoidance has the same knob, OA_MARGIN_MAX, and its documentation calls 2 m typical.
Unknown space: free or blocked
The occupancy-grid lesson ended with a map that was mostly unknown, because beams without a return marked nothing. A planner must treat each unknown cell as one or the other. Treat it as free and the plan is short and optimistic, but it crosses space no sensor has seen. That is acceptable only if the vehicle keeps scanning and replans the moment a beam ends somewhere new, as exploration planners do. Treat it as blocked and the plan uses only space seen to be empty, which may make it longer or impossible. Here unknown cells are inflated too, because an obstacle in unseen space can stand right at its edge. This program also makes a choice the previous lesson did not: a beam without a return clears 25 m of free space. That is safe in this simulator, where Range sees every obstacle taller than the drone. It is not safe for a lidar that loses returns on glass or wet surfaces, and there open ground stays unknown.
// CSpace blocks every cell whose centre lies within inflate of an occupied
// cell, or of an unknown one unless unknownFree.
func (m *Map) CSpace(unknownFree bool) *CSpace {
var c CSpace
k := int(math.Ceil(inflate / cell))
for y := range H {
for x := range W {
if l := m[y][x]; l <= -0.3 || unknownFree && l < 0.5 {
continue
}
for v := y - k; v <= y+k; v++ {
for u := x - k; u <= x+k; u++ {
dx := math.Max(0, math.Abs(float64(u-x))-0.5) * cell // to the cell's edge
dy := math.Max(0, math.Abs(float64(v-y))-0.5) * cell
if (P{u, v}).In() && math.Hypot(dx, dy) < inflate {
c[v][u] = true
}
}
}
}
}
return &c
}Free cells, with log-odds of -0.3 or less, block nothing, and with unknownFree neither do undecided cells below 0.5. Every other cell blocks the cells around it whose centres lie closer than inflate to its square. dx and dy run from the neighbour's centre to the cell's nearest edge, so the cell itself and its eight neighbours are always blocked, and the corners of the 7 by 7 window are cut round. k = ceil(2.5 / 1) = 3 bounds the window.
Plan both ways, fly both
A hall of radius 5 m stands between home and a goal 40 m east, with a tank south-east of it and a tree south-west. A 20 m mast stands behind the hall. The drone surveys with an RTK-grade fix (GPSNoise 0.05 m) from two hover points, home and a point 24 m east and 14 m south, with three 360-beam sweeps at each, then comes back home. The mast hides behind the hall from home and behind the tank from the second point, so no beam reaches it. The program builds the configuration space twice and plans each with A*: the path-planning lesson's search, with a plain slice as the open list. It prunes each path by line of sight and flies it in its own simulation with the same seed, scanning 72 beams on every step. In the map, # is an occupied cell, + a cell blocked by inflation, a blank an unknown cell, o and * the two plans, and M the mast.
package main
import (
"cmp"
"fmt"
"log"
"math"
"slices"
"gopherforge.app/drone"
)
const (
cell = 1.0 // metres per cell
W, H = 48, 26 // cells
x0, y0 = -4.0, -16.0
alt = 8.0
vehicle = 0.3 // airframe radius: the simulator's contact distance
margin = 1.5 // tracking error in gusts plus what the map gets wrong
clearTo = 25.0 // a beam without a return clears this far
)
// inflate is the configuration-space radius: the airframe, the margin and
// half a cell's diagonal, because the obstacle may be anywhere in an
// occupied cell and the drone anywhere in a free one.
var inflate = vehicle + margin + cell*math.Sqrt2/2
var obstacles = []drone.Obstacle{
{Name: "hall", X: 16, Y: 0, Radius: 5, Height: 20},
{Name: "tank", X: 27, Y: -4, Radius: 2.5, Height: 15},
{Name: "mast", X: 28, Y: 5, Radius: 1, Height: 20},
{Name: "tree", X: 6, Y: -9, Radius: 2, Height: 12},
}
type P struct{ X, Y int }
var home, goal = P{4, 16}, P{44, 18}
type Map [H][W]float64 // log-odds, as in the occupancy-grid lesson
type CSpace [H][W]bool // true: the drone's centre must not be in this cell
func cellOf(x, y float64) P {
return P{int(math.Floor((x - x0) / cell)), int(math.Floor((y - y0) / cell))}
}
func (p P) In() bool { return p.X >= 0 && p.Y >= 0 && p.X < W && p.Y < H }
func (p P) Centre() drone.Vec3 {
return drone.Vec3{X: x0 + (float64(p.X)+0.5)*cell, Y: y0 + (float64(p.Y)+0.5)*cell, Z: alt}
}
func unknown(l float64) bool { return l > -0.3 && l < 0.5 } // never seen, or undecided
func (c *CSpace) Blocked(p P) bool { return !p.In() || c[p.Y][p.X] }
func (m *Map) add(p P, l float64) {
if p.In() {
m[p.Y][p.X] = math.Max(-2, math.Min(3.5, m[p.Y][p.X]+l))
}
}
// Ray traces one reading with Bresenham's line: free cells on the way and
// an occupied cell at a hit; a beam without a return clears clearTo metres.
func (m *Map) Ray(from drone.Vec3, heading, r float64) {
hit := r < drone.RangeMax
if !hit {
r = clearTo
}
a, b := cellOf(from.X, from.Y), cellOf(from.X+r*math.Cos(heading), from.Y+r*math.Sin(heading))
dx, dy := max(b.X-a.X, a.X-b.X), -max(b.Y-a.Y, a.Y-b.Y)
sx, sy := min(max(b.X-a.X, -1), 1), min(max(b.Y-a.Y, -1), 1)
for e := dx + dy; a != b; {
m.add(a, -0.4)
e2 := 2 * e
if e2 >= dy {
e, a.X = e+dy, a.X+sx
}
if e2 <= dx {
e, a.Y = e+dx, a.Y+sy
}
}
m.add(b, map[bool]float64{true: 0.85, false: -0.4}[hit])
}
// CSpace blocks every cell whose centre lies within inflate of an occupied
// cell, or of an unknown one unless unknownFree.
func (m *Map) CSpace(unknownFree bool) *CSpace {
var c CSpace
k := int(math.Ceil(inflate / cell))
for y := range H {
for x := range W {
if l := m[y][x]; l <= -0.3 || unknownFree && l < 0.5 {
continue
}
for v := y - k; v <= y+k; v++ {
for u := x - k; u <= x+k; u++ {
dx := math.Max(0, math.Abs(float64(u-x))-0.5) * cell // to the cell's edge
dy := math.Max(0, math.Abs(float64(v-y))-0.5) * cell
if (P{u, v}).In() && math.Hypot(dx, dy) < inflate {
c[v][u] = true
}
}
}
}
}
return &c
}
// AStar is the path-planning lesson's search: 8-connected, octile heuristic,
// no corner cutting; a plain slice serves as the open list.
func AStar(c *CSpace, start, goal P) []P {
cost, from, open := map[P]float64{start: 0}, map[P]P{}, []P{start}
f := func(p P) float64 {
dx, dy := math.Abs(float64(p.X-goal.X)), math.Abs(float64(p.Y-goal.Y))
return cost[p] + max(dx, dy) + (math.Sqrt2-1)*min(dx, dy)
}
for len(open) > 0 {
cur := slices.MinFunc(open, func(a, b P) int { return cmp.Compare(f(a), f(b)) })
open = slices.DeleteFunc(open, func(p P) bool { return p == cur })
if cur == goal {
path := []P{goal}
for p := goal; p != start; path = append([]P{p}, path...) {
p = from[p]
}
return path
}
for _, d := range []P{{1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1}} {
n := P{cur.X + d.X, cur.Y + d.Y}
g := cost[cur] + math.Hypot(float64(d.X), float64(d.Y))
if old, seen := cost[n]; !c.Blocked(n) && !c.Blocked(P{n.X, cur.Y}) && !c.Blocked(P{cur.X, n.Y}) && (!seen || g < old) {
cost[n], from[n] = g, cur
open = append(open, n)
}
}
}
return nil
}
// Prune keeps only the cells that line of sight cannot skip, and returns
// the length of the result.
func Prune(c *CSpace, path []P) ([]P, float64) {
clear := func(a, b P) bool {
n := 4 * max(b.X-a.X, a.X-b.X, b.Y-a.Y, a.Y-b.Y, 1)
for i := 0; i <= n; i++ {
t := float64(i) / float64(n)
if c.Blocked(P{a.X + int(math.Round(t*float64(b.X-a.X))), a.Y + int(math.Round(t*float64(b.Y-a.Y)))}) {
return false
}
}
return true
}
out, length := []P{path[0]}, 0.0
for i := 1; i < len(path); i++ {
if last := out[len(out)-1]; i == len(path)-1 || !clear(last, path[i+1]) {
out, length = append(out, path[i]), length+path[i].Centre().Sub(last.Centre()).Len()
}
}
return out, length
}
// survey maps from two hover points with three 360-beam sweeps each, then
// comes back over home.
func survey(sim *drone.Sim) *Map {
d, m := sim.Drone(), &Map{}
if err := d.Arm(); err != nil {
log.Fatal(err)
}
d.TakeOff(alt)
for i, p := range []drone.Vec3{home.Centre(), {X: 24.5, Y: -13.5, Z: alt}, home.Centre()} {
d.GoTo(p)
sim.RunUntil(40, func(float64) bool { return d.Arrived() })
for sweep := 0; sweep < 3 && i < 2; sweep++ {
pose := d.Telemetry().GPS
for i, r := range d.Scan(360) {
m.Ray(pose, 2*math.Pi*float64(i)/360, r)
}
sim.Run(0.5, nil)
}
}
return m
}
// fly follows the waypoints and lands, scanning 72 beams on every step; it
// returns the smallest reading.
func fly(sim *drone.Sim, wps []P) float64 {
d, closest := sim.Drone(), drone.RangeMax
for i, p := range wps[1:] {
d.GoTo(p.Centre())
sim.RunUntil(60, func(float64) bool {
closest = min(closest, slices.Min(d.Scan(72)))
if i == len(wps)-2 {
return d.Arrived() || d.State().Mode == drone.Crashed
}
return d.State().Pos.Sub(p.Centre()).Len() < 1 || d.State().Mode == drone.Crashed
})
}
d.Land()
sim.RunUntil(30, func(float64) bool { return d.State().Pos.Z == 0 })
return closest
}
func main() {
cfg := drone.Config{Wind: drone.Vec3{X: 1, Y: -2}, Gust: 1.5, MaxSpeed: 5, Seed: 11, GPSNoise: 0.05, Obstacles: obstacles}
sims := []*drone.Sim{drone.New(cfg), drone.New(cfg)}
m := survey(sims[0])
survey(sims[1]) // the same seed flies the same survey and builds the same map
fmt.Printf("occupied cells grown by %.1f m: %.1f airframe + %.1f margin + %.1f half-diagonal\n",
inflate, vehicle, margin, cell*math.Sqrt2/2)
spaces := []*CSpace{m.CSpace(true), m.CSpace(false)}
var plans, wps [2][]P
for i, name := range []string{"unknown as free:", "unknown as blocked:"} {
if plans[i] = AStar(spaces[i], home, goal); plans[i] == nil {
log.Fatalf("%s no path", name)
}
var length float64
wps[i], length = Prune(spaces[i], plans[i])
n := len(slices.DeleteFunc(slices.Clone(plans[i]), func(p P) bool { return !unknown(m[p.Y][p.X]) }))
fmt.Printf("%-20s%d cells, %d unknown, %d waypoints, %.1f m\n", name, len(plans[i]), n, len(wps[i]), length)
}
// The careful planner's map with both plans and the mast no beam reached.
var rows [H][W]byte
for y := range H {
for x := range W {
rows[y][x] = '.'
if l := m[y][x]; l >= 0.5 {
rows[y][x] = '#'
} else if unknown(l) {
rows[y][x] = ' '
} else if spaces[1][y][x] {
rows[y][x] = '+'
}
}
}
for i, c := range []byte("o*") {
for _, p := range plans[i] {
rows[p.Y][p.X] = c
}
}
for i, p := range []P{home, goal, cellOf(obstacles[2].X, obstacles[2].Y)} {
rows[p.Y][p.X] = "HGM"[i]
}
for y := H - 1; y >= 0; y-- { // north up
fmt.Printf(" |%s|\n", rows[y][:])
}
for i, name := range []string{"optimistic", "flight"} {
closest := fly(sims[i], wps[i])
events := sims[i].Events()
last := events[len(events)-1]
fmt.Printf("%s: %s at %.1f s; closest reading %.2f m, margin left %+.2f m\n",
name, last.Text, last.T, closest, closest-vehicle-margin)
if err := sims[i].SaveAs(name); err != nil {
log.Fatal(err)
}
}
}With unknown as free, A* finds 41 cells, 8 of them unknown, pruned to 3 waypoints and 42.3 m. The path goes north round the hall and straight through the unseen space behind it, past M. With unknown as blocked, the path needs 56 cells, 7 waypoints and 59.6 m, and it runs south of the tree, the hall and the tank through space the survey saw. Flown, the optimistic plan ends with 'hit mast at 27.1 s', a closest reading of 0.24 m and margin left -1.56 m. The careful plan lands at the goal at 44.8 s. Its closest reading on the whole flight was 2.93 m, which leaves 1.13 m beyond the 0.3 m airframe and the 1.5 m margin.
Checking the margin, and replanning
The rangefinder makes the margin testable in flight. The closest return on any beam, minus the airframe radius, is the clearance. A program can log it, raise an alarm on it, or fail a simulation test on it, like the invariants in the simulation-testing lesson. A 72-beam scan leaves 5 degree gaps, 0.9 m wide at 10 m, so a thin pole can slip between beams at a distance, and real proximity sensors have similar blind wedges. The optimistic flight also shows the cure for its own failure. Seconds before the impact, as it rounded the hall, its beams were already ending on the mast, in cells the map had as unknown. A careful program treats such a return as a new map: it stops, adds the scan, rebuilds the configuration space and plans again, as the path-planning lesson did for a new restriction. Unknown as free with replanning is how exploration works. Unknown as free without replanning is a bet.
Fly it in GopherForge
In GopherForge choose New project > Robotics and simulation > Drone flight, replace main.go with this program (mission.go can stay; its Square helper does not clash) and tap Run. Output lists two recordings, with the hall, tank, tree and mast drawn as grey discs: optimistic.gfflight ends at the mast, and flight.gfflight goes the long way round and lands at the goal. Set margin to 0.5 and the careful plan shortens from 59.6 m to 47.2 m. Set clearTo to 0, so that a beam without a return marks nothing, as in the previous lesson, and the program stops with 'unknown as blocked: no path'.
TAKE THIS WITH YOU
Plan in configuration space: grow occupied cells by the airframe radius, a margin for tracking and map error, and half a cell's diagonal. Decide what unknown means before you plan. Blocked is safe but may find no path; free is short, and safe only while the vehicle keeps scanning and replans when a beam ends somewhere new. Measure the clearance in flight to prove the margin held.
Check your understanding
A grid planner treats the drone as a point. By how much should occupied cells be grown so that a path through free cells keeps the airframe clear?
Go to the source
Progress stays in this browser. No account needed.