Autonomy: rangefinders, maps, avoidance and precision landing · 7 MIN READ
Occupancy grids from rangefinder scans: log-odds, Bresenham rays and clamping
Build a 2D occupancy grid in local metres from rangefinder scans: add log-odds evidence along each beam traced with Bresenham's line, mark nothing for readings without a return, clamp every cell so the map can change, and compare the built map with the true obstacles after a survey flight.
A planner needs a map, and on most sites nobody hands you a current one: a crane moved, a container arrived, a tree grew. A drone can build its own with a rangefinder. Every beam says two things: the space it crossed was empty, and something stood where it ended. An occupancy grid collects that evidence cell by cell, as a probability that the cell is occupied, and keeps apart three answers that a naive map mixes up: free, occupied, and never looked at.
drones · A MAP OF THE IDEA
- Scan at each pose
- Trace beams, add log-odds
- Clamp every cell
- Threshold into a map
Useful when
- Free, occupied and unknown stay distinct.
- Each update is an addition, cheap enough for every scan.
Watch out
- Pose error smears obstacles across cells.
- A 2D slice misses anything lower than the drone.
Implementation & operation cost: A grid sized to the site, a beam tracer and a pose good to a fraction of a cell.
A grid of probabilities in local metres
Cover the area with square cells in the local ENU frame of the coordinates lesson, here 2 m cells over 60 by 40 m, and find a point's cell with floor((x - x0) / cell). Each cell holds the probability that something occupies it. It starts at 0.5, which means unknown, not half full. Bayes' rule updates a probability by multiplying odds, and the logarithm turns that product into a sum. So each cell stores its log-odds, l = log(p / (1 - p)), and every reading adds a constant: log(0.7/0.3) = 0.85 for the cell where a beam ended, log(0.4/0.6) = -0.4 for each cell it crossed. Those two numbers are the sensor model: how far one hit or one miss should move your belief. They are OctoMap's defaults, and one hit outweighs one miss on purpose: a thin obstacle in a cell is passed by far more beams than hit it. The grid is a 2D slice at the flight altitude. Range only sees obstacles taller than the drone, so the map says nothing about anything lower.
Tracing a beam with Bresenham's line
For each reading, compute the hit point from the drone's position, the beam's heading and the range, convert both ends to cells, and walk the cells between them. Bresenham's algorithm does that walk with integer additions only. It steps along one axis and keeps an error term that says when to step along the other, so it visits every cell on the line once, in order. Every cell before the end gets the miss update, and the end cell gets the hit update. A reading of drone.RangeMax means no return within 40 m, and it gets nothing at all: no free cells and no hit. No return is weak evidence, because a real lidar also gets none from glass, black paint, rain or a surface at a grazing angle. Mappers that trust their sensor clear free space along such beams up to a shorter distance. The configuration-space lesson makes that choice and explains it.
// Ray adds one reading taken at p: Bresenham's line from the drone's cell to
// the cell of the hit, free on the way and occupied at the end. A max-range
// reading has no hit and marks nothing.
func (g *Grid) Ray(p drone.Vec3, heading, r float64) bool {
if r >= drone.RangeMax {
return false
}
ax, ay := cellOf(p.X, p.Y)
bx, by := cellOf(p.X+r*math.Cos(heading), p.Y+r*math.Sin(heading))
dx, dy := abs(bx-ax), -abs(by-ay)
sx, sy := sign(bx-ax), sign(by-ay)
e := dx + dy
for ax != bx || ay != by {
g.add(ax, ay, lFree)
e2 := 2 * e
if e2 >= dy {
e += dy
ax += sx
}
if e2 <= dx {
e += dx
ay += sy
}
}
g.add(bx, by, lOcc)
return true
}dx is the run and dy the negative rise, so e = dx + dy is the error before the first step. Each pass marks the current cell free, doubles the error once and uses that one value for both tests: e2 >= dy steps in x, e2 <= dx steps in y, and both together make a diagonal step. If you recompute 2*e after the x step, an easy slip, the walk can pass the end cell and never stop. The loop ends on the hit cell, which gets lOcc, and the result lets the caller count the readings that marked nothing.
Map a site and compare it with the truth
The program places four obstacles: a 30 m tower of radius 5 m, a 25 m mast, a 14 m tree and a 6 m shed, which is lower than the 10 m survey altitude. The drone flies a 48 by 16 m loop around the tower at 4 m/s, in a 2.2 m/s wind with 1 m/s gusts. On each 5 Hz telemetry report it takes a 90-beam scan. It builds two maps from the same readings. One uses the pose a program actually has, the GPS position in telemetry. The other uses the true pose, which only a simulator knows, to show what the pose error costs. The program prints the GPS-pose map next to the true obstacles. Then, for each map, it counts what the map says about the true obstacle cells and the true free cells.
package main
import (
"fmt"
"log"
"math"
"strings"
"gopherforge.app/drone"
)
const (
cell = 2.0 // metres per cell
W, H = 30, 20 // cells: 60 m by 40 m
x0, y0 = -6.0, -20.0
alt = 10.0 // survey altitude, m
lOcc = 0.85 // log-odds added at a hit: log(0.7/0.3)
lFree = -0.4 // added to each cell the beam crossed: log(0.4/0.6)
lMin, lMax = -2.0, 3.5
)
var obstacles = []drone.Obstacle{
{Name: "tower", X: 22, Y: 8, Radius: 5, Height: 30},
{Name: "mast", X: 42, Y: -10, Radius: 1.5, Height: 25},
{Name: "tree", X: 10, Y: -10, Radius: 2.5, Height: 14},
{Name: "shed", X: 30, Y: -12, Radius: 3, Height: 6},
}
// Grid holds the log-odds of occupancy per cell (0 is unknown, p = 0.5) and
// counts the hits and pass-throughs behind each value.
type Grid struct {
L [H][W]float64
hits, passes [H][W]int
}
func cellOf(x, y float64) (int, int) {
return int(math.Floor((x - x0) / cell)), int(math.Floor((y - y0) / cell))
}
func (g *Grid) add(cx, cy int, l float64) {
if cx < 0 || cy < 0 || cx >= W || cy >= H {
return
}
g.L[cy][cx] = math.Max(lMin, math.Min(lMax, g.L[cy][cx]+l))
if l > 0 {
g.hits[cy][cx]++
} else {
g.passes[cy][cx]++
}
}
// Ray adds one reading taken at p: Bresenham's line from the drone's cell to
// the cell of the hit, free on the way and occupied at the end. A max-range
// reading has no hit and marks nothing.
func (g *Grid) Ray(p drone.Vec3, heading, r float64) bool {
if r >= drone.RangeMax {
return false
}
ax, ay := cellOf(p.X, p.Y)
bx, by := cellOf(p.X+r*math.Cos(heading), p.Y+r*math.Sin(heading))
dx, dy := abs(bx-ax), -abs(by-ay)
sx, sy := sign(bx-ax), sign(by-ay)
e := dx + dy
for ax != bx || ay != by {
g.add(ax, ay, lFree)
e2 := 2 * e
if e2 >= dy {
e += dy
ax += sx
}
if e2 <= dx {
e += dx
ay += sy
}
}
g.add(bx, by, lOcc)
return true
}
func abs(v int) int { return max(v, -v) }
func sign(v int) int { return min(max(v, -1), 1) }
func symbol(l float64) byte {
switch {
case l >= 0.5:
return '#' // p >= 0.62
case l <= -0.3:
return '.' // p <= 0.43
}
return ' ' // unknown or undecided
}
// truth draws a cell from the obstacle list: '#' where an obstacle at least
// as tall as the survey altitude overlaps it, 'o' for a lower one.
func truth(cx, cy int) byte {
t := byte('.')
lx, ly := x0+float64(cx)*cell, y0+float64(cy)*cell
for _, o := range obstacles {
nx := math.Max(lx, math.Min(o.X, lx+cell))
ny := math.Max(ly, math.Min(o.Y, ly+cell))
if math.Hypot(nx-o.X, ny-o.Y) < o.Radius {
if o.Height > alt {
return '#'
}
t = 'o'
}
}
return t
}
// score counts true obstacle cells and true free cells by what the map says.
func score(g *Grid) (occ, free [3]int) {
for cy := range H {
for cx := range W {
k := strings.IndexByte("#. ", symbol(g.L[cy][cx]))
if truth(cx, cy) == '#' {
occ[k]++
} else {
free[k]++
}
}
}
return
}
func main() {
sim := drone.New(drone.Config{Wind: drone.Vec3{X: 2, Y: 1}, Gust: 1, MaxSpeed: 4, Seed: 7, Obstacles: obstacles})
d := sim.Drone()
if err := d.Arm(); err != nil {
log.Fatal(err)
}
d.TakeOff(alt)
sim.RunUntil(30, func(float64) bool { return d.Arrived() })
// built uses the pose a program has (GPS telemetry); ideal uses the true
// pose, which only a simulator knows, to show what the pose error costs.
var built, ideal Grid
scans, readings, misses := 0, 0, 0
last := -1.0
route := []drone.Vec3{{X: 48, Z: alt}, {X: 48, Y: 16, Z: alt}, {X: 0, Y: 16, Z: alt}, {Z: alt}}
for _, wp := range route {
d.GoTo(wp)
sim.RunUntil(60, func(float64) bool {
tel := d.Telemetry()
if tel.Time != last { // a new 5 Hz report: scan with it
last = tel.Time
scans++
for i, r := range d.Scan(90) {
heading := 2 * math.Pi * float64(i) / 90
readings++
if !built.Ray(tel.GPS, heading, r) {
misses++
}
ideal.Ray(d.State().Pos, heading, r)
}
}
return d.Arrived()
})
}
d.Land()
sim.RunUntil(30, func(float64) bool { return d.State().Landed })
fmt.Printf("%d scans of 90 beams: %d readings, %d at max range (marked nothing)\n", scans, readings, misses)
fmt.Printf(" %-34s%s\n", "built map (GPS pose)", "true obstacles at 10 m (o: lower)")
for cy := H - 1; cy >= 0; cy-- { // north up
var a, b strings.Builder
for cx := range W {
a.WriteByte(symbol(built.L[cy][cx]))
b.WriteByte(truth(cx, cy))
}
fmt.Printf(" |%s| |%s|\n", a.String(), b.String())
}
fmt.Printf("%-24s%10s%10s%10s\n", "true cells", "mapped #", "mapped .", "unknown")
for _, m := range []struct {
name string
g *Grid
}{{"GPS pose", &built}, {"true pose", &ideal}} {
occ, free := score(m.g)
fmt.Printf("%-24s%10d%10d%10d\n", "obstacle, "+m.name, occ[0], occ[1], occ[2])
fmt.Printf("%-24s%10d%10d%10d\n", "free or lower, "+m.name, free[0], free[1], free[2])
}
bx, by := 0, 0
for cy := range H {
for cx := range W {
if built.hits[cy][cx] > built.hits[by][bx] {
bx, by = cx, cy
}
}
}
h, p := built.hits[by][bx], built.passes[by][bx]
raw := float64(h)*lOcc + float64(p)*lFree
fmt.Printf("busiest cell x %.0f..%.0f, y %.0f..%.0f: %d hits, %d beams through: log-odds %.1f, %.1f unclamped\n",
x0+float64(bx)*cell, x0+float64(bx+1)*cell, y0+float64(by)*cell, y0+float64(by+1)*cell, h, p, built.L[by][bx], raw)
fmt.Printf("beams through it before it reads free: %d clamped, %d unclamped\n",
int(math.Ceil((built.L[by][bx]+0.3)/-lFree)), int(math.Ceil((raw+0.3)/-lFree)))
if err := sim.Save(); err != nil {
log.Fatal(err)
}
}The 185 scans gave 16650 readings, and 14166 of them, 85 percent, ended at max range and marked nothing: on an open site most beams hit nothing. The map shows the consequence. Free space appears only where beams ended on something. The tower is a ring with an unknown inside, because no beam enters a solid. The southern rows are blank: beams that missed the tree and the mast found nothing to end on, so they marked nothing. The shed, lower than 10 m, never shows: its cells read unknown. With the true pose, 33 obstacle cells read occupied, none read free and 15 stay unknown, and no free cell reads occupied. With the GPS pose the obstacles smear: 39 obstacle cells read occupied, 2 read free, 8 free cells read occupied, and parts of the tower's ring are two and three cells thick. The busiest cell, x 8..10, y -8..-6 on the tree's north face, took 131 hits and 7 beams through it.
Clamping, thresholds and a world that changes
Without limits, that busiest cell reaches log-odds 108.5, and 273 beams would have to pass through it before it read free, long after the parked truck it saw had left. Clamping to [-2, 3.5], probabilities 0.12 and 0.97 as in OctoMap, caps both certainty and inertia: the program prints that the same cell reads free after 10 beams through it. The thresholds that turn log-odds into a symbol are a separate choice. Here 0.5 or more is occupied and -0.3 or less is free, so one hit marks a cell occupied, one miss marks it free, and anything between is undecided; higher thresholds demand more evidence. A map of a static site can live with loose clamps; a map that should forget needs tight ones. ArduPilot's object database forgets by time instead: it drops an obstacle OA_DB_EXPIRE seconds after the obstacle leaves the sensor's view. The map is also only as good as the pose. Every beam is placed at the position you believed the drone was at, and as the GPS rows of the table show, errors there smear obstacles. Survey drones keep the pose error below the cell size with RTK fixes or by fusing the lidar's own odometry.
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. The console prints both maps and the table. Output replays flight.gfflight: the four obstacles appear as grey discs labelled with their heights, along with the loop's four waypoints and the trail. Add a leg along the south side and compare the map. Climb above the tree's 14 m and the tree vanishes from the map. Set lFree to -0.85, as strong as a hit, and grazing beams erode the obstacles: with the true pose only 29 obstacle cells read occupied instead of 33.
TAKE THIS WITH YOU
An occupancy grid stores log-odds per cell. Add a constant for every beam that ends in a cell and for every beam that crosses it, trace beams with Bresenham's line, give readings without a return no hit, and clamp the values so the map can change. Keep unknown apart from free, remember the map is a slice at one altitude, and place every beam with a pose you trust, because pose error smears obstacles.
Check your understanding
Why do occupancy grids clamp each cell's log-odds, for example to [-2, 3.5]?
Go to the source
Progress stays in this browser. No account needed.