Module 3/10 · Weeks 4–5 · 14 h

Maps and global path planning

UAT 461 Autonomous Navigation and Multi-UAV Systems

About 100 minDraft, awaiting reviewLast updated 1 October 2026

Lesson

By the end of this module you will be able to

  1. Build an elevation map and a layered costmap from a LiDAR point cloud, semantic layers and obstacle inflation
  2. Use Dijkstra, A* and D* Lite on a costmap and compare the number of cells expanded when a new obstacle forces replanning
  3. Explain and use RRT*, and compare how its path improves with the number of samples against RRT
  4. Plan a drone's height profile over the crowns under climb and descent rate limits

Prerequisites: Modules 1 and 2 of this course · UAT 308 Automation and Robotics Technology module 4 (RRT and path tracking) · UAT 458 Indoor Navigation Technology module 4 (grid maps and A*)

Why this matters

The first two modules answered “where am I and how far can I trust it?” This module answers the next questions: “what does the world around me look like, and which way should I go?” The planner does not see the orchard; it sees only the map that earlier layers build for it. If the map has no gully, even a brilliant planner drives the vehicle into the gully. If the map makes everything look equally dangerous, the planner cannot choose between routes.

So this module has two halves. The first builds a map the planner can really use: elevation of the ground and the crowns from a LiDAR point cloud, converted into movement costs, overlaid with semantic layers such as hoses and no-go areas, and inflated around obstacles. The second plans a global route on that map with Dijkstra, A*, D* Lite and RRT*, and then adds the drone’s height profile. Grid maps and A* were covered in UAT 458 and RRT in UAT 308; here the focus is on what is new: terrain, multi-level costs, incremental replanning, and paths that keep getting better.

The fictional case is the durian block from module 1, a 60 × 40 m section of the orchard with trees 8 m apart in 5 rows of 7. The vehicle’s service lanes run midway between the rows (y = 8, 16, 24, 32 m), each 2 m wide with a drip hose on either side. A 3 m deep gully runs along x = 30 m with two crossings, a culvert at y = 6 to 9 m and a bridge at y = 30 to 33 m, and a harvesting area that is off limits lies in the middle of the east side. All figures are assumed.

Layered maps for the orchard

The map in this module is a 2.5D grid with 0.5 m cells. Each cell stores the ground height (DTM) and the height of the crown top (DSM). Such multi-layer grids are the idea behind the grid_map library designed for rough-terrain work (Fankhauser & Hutter, 2016). They differ from an occupancy grid, which stores the probability of occupancy (Elfes, 1989), by storing several measured quantities per cell. The costs the planner uses are then computed from these layers.

A LiDAR point gives the height at which the light bounced back, but under a crown only some pulses get through the leaves to the ground. The simplest way to separate ground is to take the lowest point in each cell as ground and the highest as the crown top. A cell that saw only leaf returns then gets a ground height wrong by several metres, so a median filter must clean it before slopes are computed. The slope at a cell comes from the height differences of its neighbours, .

The vehicle’s movement cost is built in layers that are then combined.

  • Terrain layer A slope up to 5° counts as flat (cost 0); between 5° and 20° the cost grows with the square of the excess; from 20° the cell is forbidden (the vehicle’s slope limit is assumed).
  • Trunk layer Cells with a trunk are forbidden.
  • Hose layer Can be crossed but should not be (cost 60 out of a maximum of 252), because driving over a hose damages it.
  • Keep-out layer A semantic layer set by people, such as the area where workers are harvesting; forbidden.
  • Inflation layer The cost of cells near forbidden cells rises with proximity.

Inflation lets the planner treat the vehicle as a point. A cell closer to a forbidden cell than the radius the vehicle occupies, (half the width plus a margin), is forbidden. Further out, up to the inflation radius , the cost falls exponentially with distance, . The Nav2 inflation layer uses an exponential decay in the same spirit, with the parameters inflation_radius (default 0.55 m) and cost_scaling_factor (default 10.0); raising cost_scaling_factor makes the cost fall faster and lets the vehicle come closer to obstacles (Nav2 Maintainers, n.d.-a). Cells never seen must be kept as “unknown”, not “free”, as grid maps have done since Elfes (1989).

Example 1 From a LiDAR point cloud to a costmap of the durian block

Simulate a LiDAR point cloud of 96,000 points (about 40 per square metre) over terrain sloping 4% to the north with a 3 m deep gully at x = 30 m that has two crossings, and 35 durian trees whose crowns are 9 m high at the trunk and 6 m at the edge, radius 3.5 m. Under a crown only 30% of pulses reach the ground, and height noise is 5 cm. Build the DTM and DSM, compute slopes, overlay the five layers and count the cells per layer (all assumed, including m, m and ).

import numpy as np
from scipy import ndimage
# Example 1: from a LiDAR point cloud to a layered costmap of a 60 x 40 m orchard block (synthetic terrain, assumed values)
rng = np.random.default_rng(31)
RES, NX, NY = 0.5, 120, 80                                       # cell size (m) and grid size
def ground(x, y):                                                # 4 % slope to the north and a 3 m deep gully at x = 30
    away = np.minimum(np.maximum(np.maximum(6 - y, y - 9), 0), np.maximum(np.maximum(30 - y, y - 33), 0))   # metres from the nearest crossing
    trench = 3.0 * np.clip(away / 3.0, 0, 1)                      # culvert at y 6-9 and bridge at y 30-33: no trench, ramps either side
    return 0.04 * y - trench * np.exp(-((x - 30.0) / 3.0) ** 2)
trees = np.array([(4 + 8 * i, 4 + 8 * j) for i in range(7) for j in range(5)], float)   # trunk centres (m)

n = 96000                                                        # about 40 returns per square metre
px, py = rng.uniform(0, 60, n), rng.uniform(0, 40, n)
d = np.min(np.hypot(px[:, None] - trees[:, 0], py[:, None] - trees[:, 1]), axis=1)   # distance to the nearest trunk
canopy = np.where(d < 3.5, 6.0 + 3.0 * (1 - d / 3.5), 0.0)       # cone-shaped crown, 9 m at the trunk, 6 m at the edge
hit_ground = (canopy == 0) | (rng.random(n) < 0.30)             # under a crown only 30 % of the pulses reach the ground
pz = ground(px, py) + np.where(hit_ground, 0.0, canopy) + rng.normal(0, 0.05, n)

ix, iy = np.minimum((px / RES).astype(int), NX - 1), np.minimum((py / RES).astype(int), NY - 1)
dtm = np.full((NX, NY), np.inf); dsm = np.full((NX, NY), -np.inf)
np.minimum.at(dtm, (ix, iy), pz); np.maximum.at(dsm, (ix, iy), pz)       # lowest return = ground, highest = crown top
empty = np.isinf(dtm)                                                       # cells where no pulse reached the ground
dtm = dtm[tuple(ndimage.distance_transform_edt(empty, return_distances=False, return_indices=True))]   # copy the nearest ground cell
dtm = ndimage.median_filter(dtm, size=3, mode="nearest")                 # drop cells that only saw the crown, smooth the noise
gx = (np.arange(NX) + 0.5) * RES; gy = (np.arange(NY) + 0.5) * RES
X, Y = np.meshgrid(gx, gy, indexing="ij")
print(f"cells without a ground return: {int(empty.sum())} of {NX * NY}")
print(f"DTM error RMS {np.sqrt(np.mean((dtm - ground(X, Y)) ** 2)):.2f} m, tallest crown top {dsm.max() - ground(X, Y)[np.unravel_index(dsm.argmax(), dsm.shape)]:.1f} m above ground")

dzx, dzy = np.gradient(dtm, RES)
slope = np.degrees(np.arctan(np.hypot(dzx, dzy)))
LETHAL = 254
terrain = np.where(slope >= 20, LETHAL, np.where(slope > 5, 200 * ((slope - 5) / 15) ** 2, 0)).astype(float)   # slope layer
trunk = np.zeros((NX, NY)); trunk[(np.abs(X[..., None] - trees[:, 0]) <= 0.3).any(-1) & (np.abs(Y[..., None] - trees[:, 1]) <= 0.3).any(-1)] = LETHAL
hose = np.zeros((NX, NY))                                         # hoses 1 m either side of each service lane (y = 8, 16, 24, 32)
for lane in (8, 16, 24, 32):
    hose[np.abs(np.abs(Y - lane) - 1.0) <= 0.25] = 60
keepout = np.zeros((NX, NY)); keepout[(X >= 44) & (X <= 52) & (Y >= 10) & (Y <= 18)] = LETHAL      # picking area, no-go zone
base = np.maximum.reduce([terrain, trunk, hose, keepout])         # layers combined by the maximum
dist = ndimage.distance_transform_edt(base < LETHAL, sampling=RES)   # metres to the nearest lethal cell
R_INS, R_INFL, K = 0.5, 1.5, 3.0                                  # robot half-width + margin, inflation radius, decay factor
inflated = np.where(dist <= R_INS, LETHAL, np.where(dist <= R_INFL, 252 * np.exp(-K * (dist - R_INS)), 0))
cost = np.maximum(base, inflated)
print(f"cells above 20 degrees: {100 * np.mean(slope >= 20):.1f} % of the block, steepest {slope.max():.0f} degrees")
for name, layer in (("terrain", terrain), ("trunks", trunk), ("hoses", hose), ("keep-out", keepout)):
    print(f"{name:9s} lethal {int((layer == LETHAL).sum()):5d}  graded {int(((layer > 0) & (layer < LETHAL)).sum()):5d}")
print(f"lethal cells before inflation {int((base == LETHAL).sum())}, after inflation {int((cost == LETHAL).sum())}")
print(f"master costmap: free {100 * np.mean(cost == 0):.1f} %, graded {100 * np.mean((cost > 0) & (cost < LETHAL)):.1f} %, lethal {100 * np.mean(cost == LETHAL):.1f} %")
cells without a ground return: 1 of 9600
DTM error RMS 0.07 m, tallest crown top 9.0 m above ground
cells above 20 degrees: 10.4 % of the block, steepest 55 degrees
terrain   lethal   995  graded  1000
trunks    lethal   140  graded     0
hoses     lethal     0  graded  1920
keep-out  lethal   256  graded     0
lethal cells before inflation 1367, after inflation 1931
master costmap: free 47.3 %, graded 32.6 %, lethal 20.1 %

The DTM is off the true ground by 0.07 m (RMS), even under crowns where only three in ten pulses reach the ground, and it sees the tallest crown top at 9.0 m. Cells with a slope of 20° or more make up 10.4% of the block, mostly gully walls, which the terrain layer forbids in 995 cells. Trunks forbid 140 cells and the keep-out area another 256. After inflation, the forbidden cells grow from 1,367 to 1,931, leaving 47.3% of the whole block as plain free space, 32.6% at intermediate cost (hoses and the surroundings of trunks) and 20.1% forbidden.

Graph search: Dijkstra, A* and D* Lite

With a costmap, treat each cell as a node and its eight neighbours as edges. The cost of moving from cell to cell is the distance times the average weight of the two cells, where a cell’s weight is (open flat ground weighs 1, a cell next to a tree up to 26). Dijkstra expands nodes in order of cumulative cost from the start and always finds the cheapest path, but expands in every direction. A* (Hart et al., 1968) picks the node with the lowest , where estimates the remaining cost. If never exceeds the true cost (admissible), A* still finds the cheapest path, the same as Dijkstra, while expanding fewer nodes. Here is the distance over open ground at weight 1, which never exceeds the true cost because every cell weighs at least 1.

The trouble starts when the world changes on the way. The vehicle sees a fallen branch ahead and the old plan is unusable. A* must start over from the current position, even though most of the map is unchanged. D* Lite (Koenig & Likhachev, 2002) fixes this by searching backwards from the goal and keeping the costs it has already computed. When the cost of some cell changes, only the cells whose values are no longer consistent are updated. Each cell has two values: , the estimated cost, and , the cost it should have looking one step ahead. Cells where go into a queue to be fixed. A constant , which grows with the distance the robot has moved, saves recomputing every priority in the queue.

Example 2 Plan from S to G, then find a branch in the way

Use the costmap of Example 1, with start S = (3, 18) m and goal G = (57, 26) m, which requires crossing the gully at the culvert or the bridge. First run Dijkstra and A* and compare the cells expanded, then plan with D* Lite. When the vehicle has gone a third of the way it finds a 2 × 2 m branch lying about 7 m ahead. Replan with A* from scratch and with D* Lite updating its earlier plan.

import heapq, math
# Example 2a: Dijkstra and A* on the costmap of Example 1 (uses cost, RES, NX, NY, LETHAL from that block)
W = np.where(cost >= LETHAL, np.inf, 1.0 + cost / 10.0)           # traversal weight of a cell: 1 on flat open ground, up to 26 near trunks
MOVES = [(dx, dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if dx or dy]
def edge(a, b):                                                    # cost of moving between neighbouring cells a and b
    return RES * math.hypot(a[0] - b[0], a[1] - b[1]) * (W[a] + W[b]) / 2
def octile(a, b):                                                  # straight-line cost on open ground, never above the true cost
    dx, dy = abs(a[0] - b[0]), abs(a[1] - b[1])
    return RES * (max(dx, dy) + (math.sqrt(2) - 1) * min(dx, dy))
def search(start, goal, use_h):
    g, parent, closed, expanded = {start: 0.0}, {start: None}, set(), 0
    q = [((octile(start, goal) if use_h else 0.0), start)]
    while q:
        _, u = heapq.heappop(q)
        if u in closed: continue
        closed.add(u); expanded += 1
        if u == goal: break
        for dx, dy in MOVES:
            v = (u[0] + dx, u[1] + dy)
            if 0 <= v[0] < NX and 0 <= v[1] < NY and W[v] < np.inf:
                nc = g[u] + edge(u, v)
                if nc < g.get(v, np.inf):
                    g[v], parent[v] = nc, u
                    heapq.heappush(q, (nc + (octile(v, goal) if use_h else 0.0), v))
    path, u = [], goal
    while u is not None: path.append(u); u = parent[u]
    return g[goal], path[::-1], expanded
S, G = (6, 36), (114, 52)                                          # start (3, 18) m and goal (57, 26) m
for name, use_h in (("Dijkstra", False), ("A*", True)):
    c, path, n = search(S, G, use_h)
    crossing = [p for p in path if p[0] == 60][0][1] * RES         # y at which the path crosses the gully (x = 30 m)
    print(f"{name:9s} cost {c:6.1f}  length {sum(math.hypot(a[0] - b[0], a[1] - b[1]) for a, b in zip(path, path[1:])) * RES:5.1f} m  expanded {n:5d} of {int((W < np.inf).sum())} free cells  crosses the gully at y = {crossing:.1f} m")
Dijkstra  cost  102.9  length  65.8 m  expanded  7088 of 7669 free cells  crosses the gully at y = 31.5 m
A*        cost  102.9  length  65.8 m  expanded  4629 of 7669 free cells  crosses the gully at y = 31.5 m
# Example 2b: a fallen branch appears; replan with A* from scratch and with D* Lite (Koenig & Likhachev, 2002); uses W, edge, octile, search, S, G
INF = math.inf
def nbrs(u):
    return [(u[0] + dx, u[1] + dy) for dx, dy in MOVES if 0 <= u[0] + dx < NX and 0 <= u[1] + dy < NY]
class DStarLite:
    def __init__(self, start, goal):
        self.start, self.last, self.goal, self.km = start, start, goal, 0.0
        self.g, self.rhs, self.queue, self.key_of, self.expanded = {}, {goal: 0.0}, [], {}, 0
        self.push(goal)
    def key(self, s):
        m = min(self.g.get(s, INF), self.rhs.get(s, INF))
        return (m + octile(self.start, s) + self.km, m)
    def push(self, s):
        self.key_of[s] = self.key(s); heapq.heappush(self.queue, (self.key_of[s], s))
    def update(self, u):
        if u != self.goal:
            self.rhs[u] = min((edge(u, v) + self.g.get(v, INF) for v in nbrs(u)), default=INF)
        self.key_of.pop(u, None)
        if self.g.get(u, INF) != self.rhs.get(u, INF): self.push(u)
    def compute(self):
        self.expanded = 0
        while self.queue:
            k, u = self.queue[0]
            if self.key_of.get(u) != k: heapq.heappop(self.queue); continue          # stale entry
            if not (k < self.key(self.start) or self.rhs.get(self.start, INF) != self.g.get(self.start, INF)): break
            heapq.heappop(self.queue); del self.key_of[u]
            if k < self.key(u): self.push(u); continue                               # priority grew: reinsert
            self.expanded += 1
            if self.g.get(u, INF) > self.rhs.get(u, INF):
                self.g[u] = self.rhs[u]
                for v in nbrs(u): self.update(v)
            else:
                self.g[u] = INF
                for v in nbrs(u) + [u]: self.update(v)
    def path(self):
        p, u = [self.start], self.start
        while u != self.goal:
            u = min(nbrs(u), key=lambda v: edge(u, v) + self.g.get(v, INF)); p.append(u)
        return p

planner = DStarLite(S, G); planner.compute()
first = planner.path()
print(f"initial plan: D* Lite expanded {planner.expanded} cells, cost {planner.g[S]:.1f}")
here = first[len(first) // 3]                                       # the robot has driven a third of the way
ahead = first[len(first) // 3 + 14]                                 # a branch lies across the path 7 m further on
blocked = [(ahead[0] + i, ahead[1] + j) for i in range(-2, 2) for j in range(-2, 2)]
for c in blocked: W[c] = np.inf                                     # the new obstacle appears in the map
cost_new, _, n_astar = search(here, G, True)
planner.km += octile(planner.last, here); planner.last = planner.start = here
for c in blocked:
    for u in nbrs(c) + [c]: planner.update(u)
planner.compute()
print(f"robot at ({here[0] * RES:.1f}, {here[1] * RES:.1f}) m finds {len(blocked)} blocked cells at ({ahead[0] * RES:.1f}, {ahead[1] * RES:.1f}) m")
print(f"replan with A* from scratch: expanded {n_astar:5d} cells, cost {cost_new:.1f}")
print(f"replan with D* Lite:         expanded {planner.expanded:5d} cells, cost {planner.g[here]:.1f}")
initial plan: D* Lite expanded 4516 cells, cost 102.9
robot at (19.5, 30.5) m finds 16 blocked cells at (25.5, 31.5) m
replan with A* from scratch: expanded  1847 cells, cost 72.1
replan with D* Lite:         expanded   348 cells, cost 72.1

Dijkstra and A* find the same path of cost 102.9 and length 65.8 m, crossing the gully at the bridge (y = 31.5 m), but A* expands 4,629 cells against Dijkstra’s 7,088 of 7,669 reachable cells. The heuristic saves about a third of the work, less than on open ground, because the true cost of cells near trunks and hoses is higher than the heuristic assumes. D* Lite computes the first plan with work close to A* (4,516 cells, the same cost of 102.9). But when the branch is found at (25.5, 31.5) m with the vehicle at (19.5, 30.5) m, A* from scratch expands 1,847 cells and gets cost 72.1, while D* Lite expands only 348 cells (5.3 times fewer) and gets the same cost of 72.1. The equal cost confirms that D* Lite gives the same cheapest path as A*; the difference is in the work done.

Costmap of the 60 by 40 metre block. Dark grey cells are forbidden: trunks as round dots in a grid, the gully as a vertical band down the middle with two openings, the culvert at the bottom and the bridge near the top, and the keep-out area as a rectangle on the right. Orange horizontal bands are hoses, which can be crossed at high cost. The pink dashed line is the initial plan from S on the left, going up to cross the bridge at the top. The dark square is the fallen branch. The blue line is the new plan that avoids the branch toward G on the right
Figure 1 Layered costmap of the block with the initial path and the replanned path
Horizontal bar chart of cells expanded. Initial plan group: Dijkstra 7,088, A* 4,629, D* Lite 4,516. Replan after the branch group: A* from scratch 1,847 and D* Lite 348
Figure 2 Number of cells each planner expanded

D* Lite is not always better. Its advantage appears when the goal is fixed and costs change locally. If the goal moves or the map changes over a wide area, recomputing with A* is not much slower and the code is simpler.

RRT*: sampling that converges to the shortest path

In continuous space, or when several dimensions must be considered, a fine grid has too many cells. RRT (LaValle, 1998) builds a tree by sampling, as covered in UAT 308. The path it finds is feasible but not short, and sampling longer does not improve a path already found, because a new node is always attached to the nearest node. RRT* (Karaman & Frazzoli, 2011) adds two steps for every new node. First, it chooses as parent the node within a radius that gives the lowest cost to the new node, instead of the nearest one. Second, it rewires neighbouring nodes through the new node if that lowers the neighbour’s cost. The result is a path that keeps improving as more samples are drawn and converges to the minimum-cost path in probability (asymptotically optimal), with computation cost within a constant factor of the original RRT as the paper proves. In practice it is “anytime”: stop whenever you like and you have the best path found so far.

Example 3 RRT versus RRT* across the gully

Use the same block but in continuous space. Trunks are circles of radius 0.3 m inflated by 0.5 m for half the vehicle width plus margin; the gully walls and the keep-out area are rectangles already inflated, with openings at the culvert and the bridge. Step length is 3 m, the rewiring radius is 6 m, and 5% of samples are the goal itself. Run 6 random seeds per method and record the best path length found after 500, 1,000, 2,000 and 3,000 samples, against the shortest route through the bridge gap computed directly from the obstacle corners (assumed).

import math
import numpy as np
# Example 3: RRT versus RRT* (Karaman & Frazzoli, 2011) between trunks, across the gully; 6 seeds each (assumed geometry)
TRUNKS = np.array([(4 + 8 * i, 4 + 8 * j) for i in range(7) for j in range(5)], float)
R_TRUNK = 0.3 + 0.5                                                  # trunk radius plus robot half-width
BOXES = [(26.5, -1, 33.5, 5.5), (26.5, 9.5, 33.5, 29.5), (26.5, 33.5, 33.5, 41), (43.5, 9.5, 52.5, 18.5)]   # gully walls and keep-out area, already inflated by 0.5 m
START, GOAL = np.array([3.0, 18.0]), np.array([57.0, 26.0])
ETA, RADIUS = 3.0, 6.0                                               # step length and rewiring radius (m)
def free(p):
    p = np.atleast_2d(p)
    if np.any(np.hypot(p[:, None, 0] - TRUNKS[:, 0], p[:, None, 1] - TRUNKS[:, 1]) < R_TRUNK): return False
    if np.any((p[:, 0] < 0) | (p[:, 0] > 60) | (p[:, 1] < 0) | (p[:, 1] > 40)): return False
    return not any(np.any((p[:, 0] > x0) & (p[:, 0] < x1) & (p[:, 1] > y0) & (p[:, 1] < y1)) for x0, y0, x1, y1 in BOXES)
def seg_free(a, b):
    m = max(2, int(np.linalg.norm(b - a) / 0.25) + 1)
    return free(a + (b - a) * np.linspace(0, 1, m)[:, None])
def plan(seed, iterations, star, checkpoints):
    rng = np.random.default_rng(seed)
    pts, parent, cost, kids, goals, out = [START], [-1], [0.0], [[]], [], {}
    for it in range(1, iterations + 1):
        s = GOAL if rng.random() < 0.05 else rng.uniform([0, 0], [60, 40])
        P = np.array(pts)
        i = int(np.argmin(np.hypot(*(P - s).T)))
        v = s - P[i]; new = P[i] + v / max(np.linalg.norm(v), 1e-9) * min(ETA, np.linalg.norm(v))
        if free(new) and seg_free(P[i], new):
            best_p, best_c = i, cost[i] + np.linalg.norm(new - P[i])
            near = np.flatnonzero(np.hypot(*(P - new).T) < RADIUS) if star else []
            for j in near:                                           # RRT* chooses the cheapest parent among the neighbours
                c = cost[j] + np.linalg.norm(new - P[j])
                if c < best_c and seg_free(P[j], new): best_p, best_c = int(j), c
            k = len(pts); pts.append(new); parent.append(best_p); cost.append(best_c); kids.append([]); kids[best_p].append(k)
            at_goal = np.linalg.norm(new - GOAL) < 1e-9
            if at_goal: goals.append(k)
            for j in ([] if at_goal else near):                      # ... and rewires neighbours through the new node when cheaper
                c = best_c + np.linalg.norm(P[j] - new)
                if j != best_p and c < cost[j] - 1e-9 and seg_free(new, P[j]):
                    delta = c - cost[j]; kids[parent[j]].remove(int(j)); parent[j] = k; kids[k].append(int(j)); cost[j] = c
                    stack = [int(j)]                                 # pass the saving on to every descendant
                    while stack:
                        for w in kids[stack.pop()]:
                            cost[w] += delta; stack.append(w)
        if it in checkpoints: out[it] = min((cost[w] for w in goals), default=math.inf)
    return out
SEEDS, CHECK = 6, (500, 1000, 2000, 3000)
res = {star: [plan(seed, max(CHECK), star, CHECK) for seed in range(SEEDS)] for star in (False, True)}
print("iterations | RRT solved, mean cost (m) | RRT* solved, mean cost (m)")
for n in CHECK:
    row = []
    for star in (False, True):
        c = [r[n] for r in res[star] if r[n] < math.inf]
        row.append(f"{len(c)} of {SEEDS}, {np.mean(c):6.1f}" if c else f"0 of {SEEDS},      -")
    print(f"{n:10d} | {row[0]:25s} | {row[1]}")
corner = lambda a, b: float(np.linalg.norm(np.array(a) - np.array(b)))
ref = corner(START, (26.5, 29.5)) + corner((26.5, 29.5), (33.5, 29.5)) + corner((33.5, 29.5), GOAL)   # shortest route through the bridge gap
print(f"reference: shortest route through the bridge gap is {ref:.1f} m")
iterations | RRT solved, mean cost (m) | RRT* solved, mean cost (m)
       500 | 6 of 6,   72.1            | 6 of 6,   60.1
      1000 | 6 of 6,   72.1            | 6 of 6,   58.1
      2000 | 6 of 6,   72.1            | 6 of 6,   57.3
      3000 | 6 of 6,   72.1            | 6 of 6,   57.2
reference: shortest route through the bridge gap is 56.9 m

Both methods found a path within 500 samples in all 6 runs. RRT gives 72.1 m and never improves however long it samples. RRT* gives 60.1 m at 500 samples and falls to 58.1, 57.3 and 57.2 m at 1,000, 2,000 and 3,000, coming within 0.3 m of the shortest route of 56.9 m. The gap between RRT and RRT* comes from RRT choosing a poorer crossing or detour the first time and never changing, while RRT* can move the tree onto a better route. The price is computation per sample, because RRT* must search for neighbouring nodes and check more edges for collision at every sample.

Line graph of mean path length against samples drawn, 500 to 3,000. The orange RRT line is constant at 72.1 metres. The green RRT* line falls from 60.1 to 58.1, 57.3 and 57.2 metres. A dashed pink line marks the shortest route through the bridge gap, 56.9 metres
Figure 3 Mean path length of RRT and RRT* against the number of samples drawn

Choose the planner to suit the problem.

PlannerSuitsLimits
DijkstraCheapest paths to many goals from one pointExpands in all directions, slower than A* with a single goal
A*A one- or two-dimensional grid map with one goalEvery map change means starting over; cell count grows fast in 3D
D* LiteA map discovered gradually, a fixed goal, locally changing costsMust keep the state of every cell; more complex code
RRT*Continuous space, many dimensions or motion constraints, and a path that improves with timeResults depend on sampling, so run it several times; more time per sample than RRT

Real systems combine them, for example A* on a coarse grid for a rough route across the whole block, then D* Lite or RRT* to refine the nearby stretch.

Height planning for the drone

A drone flies in three dimensions, but orchard missions are still “2.5D”: choose a route on the plane, then set the height from the elevation map. Nav2, which was designed for ground robots on a two-dimensional map (Nav2 Maintainers, n.d.-b), does not plan height, so the drone’s side must do it. The commanded height must never fall below the lowest required height , which equals the ground height plus the lane height (3 m) or the crown top plus a safety clearance (6 m), depending on position. But a drone climbs slowly. If the permitted climb rate, relative to ground speed, is a slope , the commanded height must start rising well before the crowns. A backward sweep gives , followed by a forward sweep with the descent slope. The result is the lowest profile that can actually be flown.

Public terrain databases cannot replace our own DTM. ArduPilot Copter uses SRTM data supplied by the ground station, with a default spacing of 100 m, and its documentation gives a typical accuracy of about 10 m (ArduPilot Dev Team, n.d.), far too coarse for flying 3 m above ground in an orchard that slopes by only a few metres. Flying near the ground needs our own elevation map or a downward rangefinder.

Example 4 The drone’s height along the tree row at y = 20 m

The drone flies along the tree row at y = 20 m, starting in the west lane at 3 m above ground, passing over seven crowns and the gully, then descending into the east lane. Ground speed is 3 m/s, climb is limited to 2.0 m/s and descent to 1.5 m/s, and the clearance above the crown tops is 6 m. The 1 m gap between two crowns is too small for the drone to fly through, so the whole row of crowns counts as one continuous obstacle (all assumed).

# Example 4: altitude profile for a survey line along the tree row y = 20 m (uses ground, trees from Example 1; assumed limits)
DS, V = 0.5, 3.0                                          # step along the line (m) and ground speed (m/s)
UP, DOWN = 2.0 / V, 1.5 / V                               # climb slope 2.0 m/s and descent slope 1.5 m/s at 3 m/s
LANE_AGL, CLEAR = 3.0, 6.0                                # height kept in the lanes, clearance above the crown tops (m)
sx = np.arange(-30, 90 + DS, DS); sy = np.full_like(sx, 20.0)
dd = np.min(np.hypot(sx[:, None] - trees[:, 0], sy[:, None] - trees[:, 1]), axis=1)
crown = np.where((dd < 3.5) & (sx >= 0) & (sx <= 60), 6.0 + 3.0 * (1 - dd / 3.5), 0.0)      # no trees outside the block
z_req = ground(sx, sy) + np.where(crown > 0, crown + CLEAR, LANE_AGL)                      # lowest altitude (above sea level of the model)
z = z_req.copy()
for i in range(len(z) - 2, -1, -1): z[i] = max(z[i], z[i + 1] - UP * DS)                   # backward: start climbing early enough
for i in range(1, len(z)): z[i] = max(z[i], z[i - 1] - DOWN * DS)                          # forward: allow only the permitted descent
agl = z - ground(sx, sy)
x_first, x_last = sx[np.argmax(crown > 0)], sx[len(sx) - 1 - np.argmax(crown[::-1] > 0)]
climb_from = sx[np.argmax(agl > LANE_AGL + 0.01)]
gap = int(np.argmin(np.abs(sx - 8.0)))                                                    # the 1 m gap between two crowns
print(f"height needed above the first crown: {agl[np.argmax(crown > 0)]:.1f} m, highest point of the profile {agl.max():.1f} m above ground")
print(f"climb must start at x = {climb_from:.1f} m, {x_first - climb_from:.1f} m before the first crown; descent ends {sx[np.flatnonzero(agl > LANE_AGL + 0.01)[-1]] - x_last:.1f} m after the last")
print(f"steepest climb {np.max(np.diff(z)) / DS * V:.2f} m/s, steepest descent {np.max(-np.diff(z)) / DS * V:.2f} m/s")
print(f"over the gap between crowns at x = 8 m the profile stays {agl[gap]:.1f} m above ground, not {LANE_AGL:.1f} m")
height needed above the first crown: 13.0 m, highest point of the profile 15.3 m above ground
climb must start at x = -13.5 m, 14.5 m before the first crown; descent ends 20.5 m after the last
steepest climb 2.00 m/s, steepest descent 1.50 m/s
over the gap between crowns at x = 8 m the profile stays 13.0 m above ground, not 3.0 m

The first crown top needs a height of 13.0 m above ground, but climbing 10 m at 2.0 m/s takes 15 m of horizontal distance, so the climb must start at x = −13.5 m, 14.5 m before the first crown. The mission’s launch point must therefore be at least about 14 m outside the west edge of the block, and descending at 1.5 m/s needs a continuous 20.5 m after the last crown. Over the gap between crowns at x = 8 m the commanded height stays at 13.0 m and does not drop to 3 m, because it could not climb back in time. The conclusion is that height planning is not separate from planning on the plane: horizontal room for climbing and descending must be reserved too.

Graph of height above ground against position x from minus 30 to 90 metres. Green shapes are seven crowns up to 9 metres between x about 0 and 56. The pink dashed line is the lowest required height, jumping to about 13 to 15 metres over each crown and dropping to 3 metres between trees. The blue line is the commanded height: it starts climbing at x about minus 13.5 to about 15 metres, stays above the crowns without dropping between trees, then descends to 3 metres at x about 76
Figure 4 Drone height profile along a tree row with climb and descent rate limits

Module lab

Lab: build a costmap, plan a route and replan

  1. Use terrain data prepared by the lecturer (a point cloud or a DTM), or build a simulated area for your group of 60 × 40 m with at least three kinds of obstacle, and adapt the code of Example 1 to build a costmap of at least four layers.
  2. Adjust , and and watch how the A* path changes. State the values that keep a 0.8 m wide vehicle from passing within half a metre of a trunk.
  3. Run Example 2 with the group’s start and goal and compare the cells expanded by Dijkstra and A*.
  4. Place a simulated branch at three different positions along the route, compare the cells expanded by A* from scratch and by D* Lite for each, and explain how the ratio changes with position.
  5. Run Example 3 with 6 new random seeds and report the mean and the minimum and maximum of the path length for RRT and RRT*.
  6. Compute the height profile as in Example 4 for the group’s flight line and state how much horizontal room must be left before and after the row of trees.

Common mistakes

Watch out

  • Taking the lowest point in each cell as ground without filtering: cells that saw only crowns create false hills and wrong slopes
  • Forgetting to inflate obstacles by the vehicle’s size, or inflating without letting the cost fall with distance, so the vehicle grazes obstacles every time
  • Treating the semantic layer as just a colour the planner does not read; always convert it into a cost or a forbidden cell
  • Using a heuristic that overestimates the true cost, after which A* no longer finds the cheapest path
  • Restarting A every time a small part of the map changes in a large block*, when D* Lite is cheaper
  • Trusting one RRT result*: results depend on sampling, and you must check whether the number of samples is enough
  • Using a public terrain database to plan heights near the ground, whose resolution and accuracy are not enough
  • Planning height without reserving horizontal room for climbing and descending, then needing a climb steeper than the drone can fly

Summary

  • A planner’s map is a layered grid: ground and crown height, slope, trunks, hoses, semantic keep-out areas and inflation, combined into a costmap.
  • Slope comes from height differences between neighbouring cells, and cells that saw only crowns must be filtered out first.
  • A* finds the same cheapest path as Dijkstra while expanding fewer cells, when the heuristic never exceeds the true cost.
  • D* Lite reuses earlier results when a new obstacle appears and finds the same cheapest path with far less work when the goal is fixed.
  • RRT* keeps improving the path by choosing parents and rewiring, unlike RRT, which never improves a path once found.
  • A drone’s height must stay above the lowest required height and be climbable and descendable within the rate limits, so horizontal room must be reserved before and after obstacles.

Self-check questions

  1. A cell has slopes of 0.2 along x and 0.1 along y (metres per metre). What is the slope angle, and what cost does the terrain layer of Example 1 give?
  2. A cell is 0.9 m from a forbidden cell, m and . What cost does the inflation layer give?
  3. Why does D* Lite expand fewer cells than A* from scratch when replanning after the branch in Example 2?
  4. Why does RRT in Example 3 stay at 72.1 m through 3,000 samples while RRT* improves?
  5. A drone must climb from 3 m to 14 m at 4 m/s ground speed with a climb rate of at most 2 m/s. What is the minimum horizontal distance?
Answers
  1. ; cost .
  2. .
  3. A* from scratch throws away earlier results and searches again from the current position. D* Lite keeps and for every cell and updates only the cells affected by the branch, so it expanded 348 cells instead of 1,847.
  4. RRT always attaches a new node to the nearest node, so a node already connected to the goal is never improved. RRT* chooses the lowest-cost parent and rewires its neighbours, so the path shortens as more samples are drawn.
  5. The slope is , so the horizontal distance is m.

Key formulas

Slope angle from an elevation map
Exponential inflation cost
A* evaluation function
D* Lite rhs value
Lowest height that can still be climbed to within the rate limit

Key references

  1. Elfes, A. (1989). Using occupancy grids for mobile robot perception and navigation. Computer, 22(6), 46–57. link
  2. Fankhauser, P., & Hutter, M. (2016). A universal grid map library: Implementation and use case for rough terrain navigation. In Robot Operating System (ROS): The complete reference (Vol. 1, pp. 99–120). Springer. link
  3. Hart, P. E., Nilsson, N. J., & Raphael, B. (1968). A formal basis for the heuristic determination of minimum cost paths. IEEE Transactions on Systems Science and Cybernetics, 4(2), 100–107. link
  4. Koenig, S., & Likhachev, M. (2002). D* Lite. In Proceedings of the Eighteenth National Conference on Artificial Intelligence (AAAI-02). AAAI Press. link
  5. Karaman, S., & Frazzoli, E. (2011). Sampling-based algorithms for optimal motion planning. The International Journal of Robotics Research, 30(7), 846–894. link
  6. LaValle, S. M. (1998). Rapidly-exploring random trees: A new tool for path planning (TR 98-11). Iowa State University. link
  7. LaValle, S. M. (2006). Planning algorithms. Cambridge University Press. link
  8. Nav2 Maintainers. Inflation layer parameters. Nav2 documentation (rolling). link
  9. Nav2 Maintainers. Navigating using GPS localization. Nav2 documentation (Jazzy). link
  10. ArduPilot Dev Team. Terrain following (in Auto, Guided, etc). ArduPilot Copter documentation. link
  11. Thrun, S., Burgard, W., & Fox, D. (2005). Probabilistic robotics. MIT Press. link
  12. Siegwart, R., Nourbakhsh, I. R., & Scaramuzza, D. (2011). Introduction to autonomous mobile robots (2nd ed.). MIT Press. link

Further reading

Study the assigned knowledge units in advance, review media and take the module quiz

In class / field

Lab or field practice from worksheets with a safety checklist

Learning evidence: Checked worksheets and quiz results

Module quiz

This is a formative self-check, not a graded exam

Knowledge domain: Control, autopilot and navigation · Automation, robotics and swarms · Surveying, mapping and geoinformatics