Local planning, obstacle avoidance, trajectories and tracking
UAT 461 Autonomous Navigation and Multi-UAV Systems
Lesson
By the end of this module you will be able to
- Explain why potential fields get stuck in local minima, and use a dynamic window planner with a global path to pass a branch pile and a worker
- Choose a steering direction from a polar histogram (VFH) and test candidate velocities against a velocity obstacle for a moving person
- Generate a minimum-snap trajectory through waypoints and stretch its timing to respect speed and acceleration limits
- Compare pure pursuit, Stanley and LQR with feed-forward tracking a path that includes a U-turn, and say what each one is good at
Why this matters
The global planner of module 3 runs once a second at most and sees only the map it was given. Between two plans the world changes: a pile of pruned branches is left in the lane, a worker steps onto the route. The layer that reacts to what the map does not contain is the local planner. It runs at about 10 Hz, looks a few seconds ahead, and answers “which velocity should I command in the next fraction of a second?” Below it, the trajectory and the tracking controller turn that decision into smooth commands the vehicle can really follow.
This module covers that chain in order: local planners and the local-minimum trap, direction-based avoidance, moving obstacles, smooth trajectories, and tracking controllers. Pure pursuit and the ROS 2 navigation stack were introduced in UAT 308; here the controllers are compared and tested on the same path, and feed-forward is added. Indoor flight systems belong to UAT 458; this module treats a vehicle on open orchard ground and, where the maths is the same, a drone flying at a fixed height.
The case is still the durian orchard. The ground robot (0.5 m radius for planning, speed limit 1.5 m/s) follows a global path along a lane. After pruning, a crew has left a U-shaped pile of branches 12 m ahead, opening towards the robot, and a worker will step into the lane when the robot is already moving. All figures are assumed and the Python code can be downloaded from /downloads/uat-461/.
Local planners and the local-minimum trap
The oldest local planner is the potential field (Khatib, 1986). The goal pulls the vehicle with a force proportional to the distance, and every obstacle closer than a radius pushes it away with a force that grows quickly near the obstacle, , where points away from the obstacle. The vehicle moves along the sum. It is cheap and easy to write, but Koren and Borenstein (1991) showed its inherent limits: the vehicle can be trapped where the forces cancel (a local minimum, typically in front of a U-shaped obstacle), it can oscillate in narrow passages, and it cannot take the vehicle’s acceleration limits into account.
The dynamic window approach (DWA) (Fox et al., 1997) searches velocities rather than following forces. Each control period it considers only the speeds the vehicle can reach in one period, the window . For each pair it simulates a circular arc a few seconds ahead and discards pairs that are not admissible, meaning the vehicle could not stop before the nearest obstacle on that arc, . The survivors are scored, , and the best pair is sent to the controller. Because acceleration limits are built into the window, the commands are always ones the vehicle can follow.
DWA still looks only a few seconds ahead, so it can also get stuck in front of a U-shaped pile if it is asked to drive straight to a faraway goal. The usual cure is not a cleverer local planner but a better division of labour: the global planner supplies waypoints around large obstacles and the local planner follows them while dodging what the map missed.
Example 1 A potential field and DWA meet a U-shaped branch pile
The pile is made of 0.3 m radius branch stacks forming a U with its back wall at x = 12 m, 6 m wide and opening towards the robot. The robot starts at the origin, the goal is at (20, 0) m, the speed limit is 1.5 m/s, the acceleration limits are 1.0 m/s² and 2.0 rad/s², and the control period is 0.1 s. Three runs are compared: the potential field driving straight to the goal, DWA driving straight to the goal, and DWA following the three waypoints the global planner gave around the pile ((6, 5.5), (15, 5.5), (20, 0) m). In the third run a worker comes into sensor range at 7 s and stands on the route at (12.5, 5.6) m (all values assumed). Report the outcome, the smallest clearance between the robot edge and an obstacle edge, and the largest change of velocity command per second.
import numpy as np
# Example 1: a potential field and a dynamic window planner meet a U-shaped branch pile (assumed geometry and limits)
R_ROBOT, R_OBS = 0.5, 0.3 # robot radius and trunk/branch radius (m)
def u_pile(): # branches piled in a U that opens towards the robot
back = [(12.0, y) for y in np.arange(-3.0, 3.01, 0.6)]
sides = [(x, s * 3.0) for x in np.arange(8.4, 11.9, 0.6) for s in (-1, 1)]
return np.array(back + sides)
PILE = u_pile()
START, GOAL = np.array([0.0, 0.0]), np.array([20.0, 0.0])
V_MAX, A_V, A_W, DT = 1.5, 1.0, 2.0, 0.1 # speed limit, accelerations, control period
def clearance(p, obs): # distance between robot edge and the nearest obstacle edge
return np.min(np.hypot(*(obs - p).T)) - R_ROBOT - R_OBS
def run_field(obs, goal, steps=1200):
p, v_prev, max_acc, cmin = START.copy(), np.zeros(2), 0.0, 9.0
for k in range(steps):
v = 1.0 * (goal - p) # attraction towards the goal
for o in obs:
d = np.hypot(*(p - o))
if d < 3.0: v += 2.0 * (1 / d - 1 / 3.0) / d ** 2 * (p - o) / d # repulsion inside 3 m
if np.hypot(*v) > V_MAX: v = v / np.hypot(*v) * V_MAX
max_acc = max(max_acc, np.hypot(*(v - v_prev)) / DT); v_prev = v
p = p + v * DT; cmin = min(cmin, clearance(p, obs))
if np.hypot(*(goal - p)) < 0.5: return k * DT, np.hypot(*(goal - p)), cmin, max_acc
return None, np.hypot(*(goal - p)), cmin, max_acc
def run_dwa(obs, waypoints, extra=None, steps=1500):
x = np.array([START[0], START[1], 0.0]); v, w, wp, cmin, max_acc = 0.0, 0.0, 0, 9.0, 0.0
t = np.arange(1, 21) * DT # 2 s look-ahead
for k in range(steps):
all_obs = obs if extra is None or k * DT < extra[0] else np.vstack([obs, extra[1]])
goal = waypoints[wp]
if np.hypot(*(goal - x[:2])) < 1.0 and wp < len(waypoints) - 1: wp += 1; goal = waypoints[wp]
if wp == len(waypoints) - 1 and np.hypot(*(goal - x[:2])) < 0.5: return k * DT, np.hypot(*(goal - x[:2])), cmin, max_acc
vs = np.linspace(max(0.0, v - A_V * DT), min(V_MAX, v + A_V * DT), 7) # the dynamic window: speeds reachable in one period
ws = np.linspace(w - A_W * DT, w + A_W * DT, 15)
best, best_cmd = -1e9, (vs[0], 0.0) # fallback: brake as hard as the window allows
for vc in vs:
for wc in ws:
th = x[2] + wc * t
px = x[0] + np.cumsum(vc * np.cos(th) * DT); py = x[1] + np.cumsum(vc * np.sin(th) * DT)
near = np.min(np.hypot(px[:, None] - all_obs[:, 0], py[:, None] - all_obs[:, 1]), axis=1)
dist = lambda r: (np.argmax(near <= r) + 1) * vc * DT if (near <= r).any() else 3.0 # arc length before reaching distance r
if vc > 0 and (near[0] <= R_ROBOT + R_OBS + 0.2 or vc > np.sqrt(2 * A_V * dist(R_ROBOT + R_OBS + 0.2))): continue # cannot stop in time: not admissible
free = dist(R_ROBOT + R_OBS + 0.4) # arc length before entering the 0.4 m comfort margin
ang = np.arctan2(goal[1] - py[-1], goal[0] - px[-1]) - th[-1]
heading = 1 - abs((ang + np.pi) % (2 * np.pi) - np.pi) / np.pi
score = 1.0 * heading + 1.0 * free / 3.0 + 0.3 * vc / V_MAX
if score > best: best, best_cmd = score, (vc, wc)
max_acc = max(max_acc, abs(best_cmd[0] - v) / DT)
v, w = best_cmd
x = x + np.array([v * np.cos(x[2]) * DT, v * np.sin(x[2]) * DT, w * DT])
cmin = min(cmin, clearance(x[:2], all_obs))
return None, np.hypot(*(waypoints[-1] - x[:2])), cmin, max_acc
WAYPOINTS = [np.array(p) for p in ((6.0, 5.5), (15.0, 5.5), (20.0, 0.0))] # global path around the pile (from the planner of module 3)
WORKER = (7.0, np.array([[12.5, 5.6]])) # at 7 s a worker comes into sensor range, standing on that path
runs = (("potential field to the goal", run_field(PILE, GOAL)),
("DWA to the goal", run_dwa(PILE, [GOAL])),
("DWA on the global path + worker", run_dwa(PILE, WAYPOINTS, WORKER)))
print("method result distance left min clearance peak acceleration")
for name, (t, dist, cmin, acc) in runs:
print(f"{name:33s} {'reached in %3.0f s' % t if t else 'stuck':16s} {dist:8.1f} m {cmin:11.2f} m {acc:14.2f} m/s^2")
method result distance left min clearance peak acceleration
potential field to the goal stuck 8.6 m -0.20 m 30.00 m/s^2
DWA to the goal stuck 8.9 m 0.05 m 1.00 m/s^2
DWA on the global path + worker reached in 24 s 0.5 m 0.40 m 1.00 m/s^2
Both planners that drive straight at the goal fail. The potential field never gets round the pile: it presses into the back wall (clearance −0.20 m means the robot overlaps the branches) and chatters back and forth, with command changes of up to 30 m/s², thirty times the 1.0 m/s² this vehicle can accelerate. DWA stops 0.05 m from the pile and stays there, because every arc towards the goal is inadmissible and none leads round. The same DWA given the global path reaches the goal in 24 s, passes the worker with 0.40 m clearance (the comfort margin in its score), and never asks for more than 1.00 m/s², which is its own acceleration limit.
The lesson is that a local minimum is a property of the problem, not a bug to tune away. A planner that sees only the next few metres cannot know the pile is a dead end. Planners with a longer view, such as a global planner re-run on the local costmap, are what get the vehicle out.
Choosing a direction: the vector field histogram
Sometimes there is no good global path at all, for example on first entering an unmapped corner, and the vehicle must pick a direction from a single range scan. The vector field histogram (VFH) (Borenstein & Koren, 1991) does this in three steps. First, it divides the directions around the vehicle into bins (here 5° each) and adds to every bin an obstacle weight; an obstacle at distance with radius blocks the bins within the half-angle of its bearing, so the vehicle can be treated as a point, and nearer obstacles weigh more (here ). Second, it smooths the histogram and declares bins below a threshold free; runs of free bins are valleys. Third, it ignores valleys that are too narrow to steer through, and steers towards the valley closest to the target direction, staying a margin away from the valley edges.
Example 2 Choosing a steering direction from one scan
The robot heads along +x with the target straight ahead (0°). A scan shows three obstacles of radius 0.3 m at (3.5, 0.0), (2.6, 3.6) and (3.0, −3.4) m in the robot frame. The robot radius is 0.5 m, the margin 0.2 m, the sensing range 6 m, and the free-bin threshold 0.10. Valleys narrower than 15° are ignored, and in a valley 60° wide or more the vehicle stays 20° from the edges (all assumed).
import numpy as np
# Example 2: vector field histogram (Borenstein & Koren, 1991): pick a free direction from one scan (assumed obstacles)
R_ROBOT, MARGIN, RANGE = 0.5, 0.2, 6.0
obstacles = [(3.5, 0.0, 0.3), (2.6, 3.6, 0.3), (3.0, -3.4, 0.3)] # x, y, radius (m) in the robot frame, heading = +x
N_BINS = 72 # 5 degrees per bin
centres = np.arange(N_BINS) * 5.0 - 180.0 + 2.5
H = np.zeros(N_BINS)
for x, y, r in obstacles:
d = np.hypot(x, y)
if d > RANGE: continue
bearing = np.degrees(np.arctan2(y, x))
half = np.degrees(np.arcsin(min(1.0, (r + R_ROBOT + MARGIN) / d))) # enlarge the obstacle by the robot size
diff = np.abs((centres - bearing + 180) % 360 - 180)
H[diff <= half] += 1.0 - d / RANGE # nearer obstacles weigh more
H = np.convolve(np.r_[H[-1:], H, H[:1]], np.ones(3) / 3, mode="valid") # smooth over three bins
free = H < 0.10 # threshold: below it the direction is open
valleys, k = [], 0 # runs of free bins (the direction directly behind the robot is the cut)
while k < N_BINS:
if free[k]:
j = k
while j + 1 < N_BINS and free[j + 1]: j += 1
valleys.append((k, j)); k = j + 1
else:
k += 1
TARGET = 0.0
print(f"blocked bins: {int((~free).sum())} of {N_BINS}; the target direction {TARGET:.0f} deg is {'blocked' if not free[int((TARGET + 180) // 5)] else 'free'}")
best = None
for a, b in valleys:
lo, hi = centres[a] - 2.5, centres[b] + 2.5 # edges of the valley (deg)
width = hi - lo
if width < 15: continue # too narrow to steer through with a heading error
margin = 20.0 if width >= 60 else width / 2 # in a wide valley keep 20 degrees from the edges
steer = float(np.clip(TARGET, lo + margin, hi - margin))
print(f"valley {lo:7.1f} to {hi:6.1f} deg, width {width:5.1f} deg, closest usable direction {steer:6.1f} deg")
if best is None or abs(steer - TARGET) < abs(best - TARGET): best = steer
print(f"steer to {best:.1f} deg, {abs(best - TARGET):.1f} deg away from the target direction")
blocked bins: 18 of 72; the target direction 0 deg is blocked
valley -180.0 to -60.0 deg, width 120.0 deg, closest usable direction -80.0 deg
valley -35.0 to -20.0 deg, width 15.0 deg, closest usable direction -27.5 deg
valley 20.0 to 40.0 deg, width 20.0 deg, closest usable direction 30.0 deg
valley 65.0 to 180.0 deg, width 115.0 deg, closest usable direction 85.0 deg
steer to -27.5 deg, 27.5 deg away from the target direction
The target direction is blocked by the first obstacle, 18 of the 72 bins are blocked, and four valleys remain. The widest valleys, below −60° and above 65°, are far from the target and the vehicle would steer −80° or 85°, almost sideways. The narrow valley from −35° to −20° is only 15° wide, but it is the closest to the target, so the vehicle steers −27.5°, 27.5° away from where it wanted to go. The choice depends on the rule: a score that also rewards valley width would pick a wider one. At about 3 m a 15° valley is only about 0.8 m wide for the vehicle’s centre (the obstacles are already enlarged by the robot radius and margin), which leaves little room for heading error, so a real system should lower speed when it chooses a narrow valley.
Moving obstacles: the velocity obstacle
A histogram treats obstacles as fixed. A worker walking across the lane is not. The velocity obstacle (Fiorini & Shiller, 1998) reasons in velocity space. Let be the sum of the two radii plus a comfort margin, the distance to the other party, and the worker’s velocity as seen from the robot. If the robot commands velocity , the pair will come closer than within the horizon if for some , which is a quadratic in . The set of such is the velocity obstacle. When the worker is stationary it is exactly the cone of directions that points at the obstacle, with half-angle ; when the worker moves, the cone is shifted by the worker’s velocity.
The planner then picks, from candidate velocities outside the velocity obstacle, the one closest to the velocity it would like to use. This avoids the common failure of “turn away from the obstacle’s current position” when the obstacle is moving towards where the robot is turning.
Example 3 A worker walks across the lane
The robot is at the origin, wants 1.5 m/s along +x, and the horizon is 6 s. A worker 0.3 m in radius is at (6.0, −2.5) m walking at 0.7 m/s along +y. The robot radius is 0.5 m and the comfort margin 0.3 m, so = 1.1 m. Candidate velocities have speeds 0 to 1.5 m/s in steps of 0.1 and headings −60° to 60° in steps of 5° (assumed).
import numpy as np
# Example 3: velocity obstacle for a worker walking across the lane (Fiorini & Shiller, 1998; assumed positions and speeds)
R = 0.5 + 0.3 + 0.3 # robot radius + worker radius + comfort margin (m)
p_w, v_w = np.array([6.0, -2.5]), np.array([0.0, 0.7]) # worker position (m) and velocity (m/s), robot at the origin
v_pref = np.array([1.5, 0.0]) # the velocity the planner wants
T_HORIZON = 6.0
def time_to_conflict(v_robot):
"""First time within the horizon at which robot and worker come closer than R, or None."""
u = v_w - v_robot # relative velocity of the worker as seen from the robot
a, b, c = u @ u, 2 * p_w @ u, p_w @ p_w - R ** 2
if c <= 0: return 0.0
if a < 1e-12: return None
disc = b * b - 4 * a * c
if disc < 0: return None
t = (-b - np.sqrt(disc)) / (2 * a)
return t if 0 <= t <= T_HORIZON else None
d = np.hypot(*p_w)
print(f"worker is {d:.1f} m away; the collision cone has a half-angle of {np.degrees(np.arcsin(R / d)):.1f} degrees")
t0 = time_to_conflict(v_pref)
print(f"preferred velocity 1.50 m/s straight ahead: conflict in {t0:.1f} s" if t0 is not None else "preferred velocity is safe")
cands = [(s, h, np.array([s * np.cos(np.radians(h)), s * np.sin(np.radians(h))])) for s in np.arange(0.0, 1.51, 0.1) for h in range(-60, 61, 5)]
safe = [(s, h, v) for s, h, v in cands if time_to_conflict(v) is None]
print(f"{len(cands) - len(safe)} of {len(cands)} candidate velocities are inside the velocity obstacle ({100 * (len(cands) - len(safe)) / len(cands):.0f} %)")
s, h, v = min(safe, key=lambda c: np.hypot(*(c[2] - v_pref)))
print(f"closest safe velocity: {s:.1f} m/s at {h} degrees, a change of {np.hypot(*(v - v_pref)):.2f} m/s from the preferred one")
slow = min((c for c in safe if c[1] == 0), key=lambda c: abs(c[0] - 1.5), default=None)
print(f"closest safe velocity without turning: {slow[0]:.1f} m/s (slow down)" if slow else "no safe speed without turning")
worker is 6.5 m away; the collision cone has a half-angle of 9.7 degrees
preferred velocity 1.50 m/s straight ahead: conflict in 3.3 s
32 of 400 candidate velocities are inside the velocity obstacle (8 %)
closest safe velocity: 1.5 m/s at -10 degrees, a change of 0.26 m/s from the preferred one
closest safe velocity without turning: 1.1 m/s (slow down)
At 6.5 m the cone has a half-angle of 9.7°, but the worker is moving, so the preferred velocity runs into a conflict in 3.3 s. Of the 400 candidates, 32 (8%) are inside the velocity obstacle. The closest safe velocity keeps the full 1.5 m/s and turns 10° to the right (behind the worker, who is crossing from right to left), changing the velocity by only 0.26 m/s. If the lane is too narrow to turn, the closest safe velocity without turning is 1.1 m/s, which lets the worker cross first. Both are smaller reactions than stopping, and they use the worker’s motion rather than ignoring it.
Two cautions. People do not hold their velocity, so the margin should be generous and the plan must be recomputed every cycle. And the velocity obstacle assumes only one side avoids; with two robots that both avoid, reciprocal versions are needed, which this course does not cover.
Smooth trajectories: minimum snap
A path is only a line. Before a vehicle can follow it, time must be added: when does it pass each point, and how fast? A trajectory is a path with timing. For a multicopter the choice matters because its inputs (thrust and moments) are functions of the position and its first four derivatives, so the trajectory must be at least four times differentiable. The minimum-snap method (Mellinger & Kumar, 2011) minimizes , the integral of the squared fourth derivative (snap), over a chain of polynomial segments joined smoothly at the waypoints. With 7th-order polynomials per segment this is a quadratic problem with equality constraints (pass through the waypoints, continuous derivatives at the joints, rest at the ends) and has a closed-form solution (Richter et al., 2016). The method suits ground vehicles too, because smooth acceleration saves the steering and drive motors.
The method gives no guarantee of clearance from obstacles: between waypoints the curve can bulge. Richter et al. (2016) add corridor constraints for that. Here the waypoints are placed to keep the curve clear and timing is chosen separately. If times are set from the distances at an average speed, the peaks of speed and acceleration come out above the limits. Stretching all segment times by a factor keeps the path unchanged and scales speed by , acceleration by and jerk by , so the smallest that respects both limits is .
Example 4 Passing a branch with minimum snap
The robot drives along the lane centre and must swing 1.5 m to one side round a branch lying at x = 14 m. The waypoints are (0, 0), (8, 0), (14, 1.5), (20, 0) and (28, 0) m. Segment times come from the straight-line distances at 2.5 m/s average. The limits are 3.0 m/s speed and 2.0 m/s² acceleration. Start and end at rest (assumed).
import numpy as np
from math import factorial
from scipy.linalg import block_diag
# Example 4: minimum-snap trajectory through waypoints (Mellinger & Kumar, 2011; Richter et al., 2016), assumed limits
N = 8 # 7th-order polynomial per segment: 8 coefficients
def snap_cost(T): # Q such that c^T Q c = integral of (4th derivative)^2 over [0, T]
Q = np.zeros((N, N))
for i in range(4, N):
for j in range(4, N):
Q[i, j] = factorial(i) / factorial(i - 4) * factorial(j) / factorial(j - 4) * T ** (i + j - 7) / (i + j - 7)
return Q
def deriv(t, k): # row r with r @ c = k-th derivative of the polynomial at time t
r = np.zeros(N)
for i in range(k, N): r[i] = factorial(i) / factorial(i - k) * t ** (i - k)
return r
def min_snap(wp, T):
M = len(T)
A, b = [], []
def add(row_parts, rhs):
row = np.zeros(N * M)
for seg, r, sign in row_parts: row[seg * N:(seg + 1) * N] += sign * r
A.append(row); b.append(rhs)
for i in range(M): # each segment starts and ends on its waypoints
add([(i, deriv(0, 0), 1)], wp[i]); add([(i, deriv(T[i], 0), 1)], wp[i + 1])
for k in (1, 2, 3):
add([(0, deriv(0, k), 1)], 0.0); add([(M - 1, deriv(T[-1], k), 1)], 0.0) # start and end at rest
for i in range(M - 1): add([(i, deriv(T[i], k), 1), (i + 1, deriv(0, k), -1)], 0.0) # smooth joints up to jerk
A, b = np.array(A), np.array(b)
Q = block_diag(*[snap_cost(t) for t in T])
K = np.block([[2 * Q, A.T], [A, np.zeros((len(b), len(b)))]])
sol = np.linalg.solve(K, np.r_[np.zeros(N * M), b])
return sol[:N * M].reshape(M, N)
def sample(coefs, T, k, step=0.01): # k-th derivative sampled over the whole trajectory
out = []
for c, t_end in zip(coefs, T):
t = np.arange(0, t_end, step)
out.append(sum(factorial(i) / factorial(i - k) * c[i] * t ** (i - k) for i in range(k, N)) if k else sum(c[i] * t ** i for i in range(N)))
return np.concatenate(out)
way = np.array([(0, 0), (8, 0), (14, 1.5), (20, 0), (28, 0)], float) # lane centre, swing 1.5 m round a branch, back to the centre (m)
V_CRUISE, V_LIM, A_LIM = 2.5, 3.0, 2.0
T = np.hypot(*np.diff(way, axis=0).T) / V_CRUISE
def metrics(T):
cx, cy = min_snap(way[:, 0], T), min_snap(way[:, 1], T)
v = np.hypot(sample(cx, T, 1), sample(cy, T, 1)); a = np.hypot(sample(cx, T, 2), sample(cy, T, 2)); j = np.hypot(sample(cx, T, 3), sample(cy, T, 3))
return v.max(), a.max(), j.max()
print("segment times at 2.5 m/s average: " + " ".join(f"{t:.2f}" for t in T) + f" s, total {T.sum():.1f} s")
v, a, j = metrics(T)
print(f"peak speed {v:.2f} m/s, peak acceleration {a:.2f} m/s^2, peak jerk {j:.2f} m/s^3")
s = max(1.0, v / V_LIM, np.sqrt(a / A_LIM)) # stretching all times by s divides speed by s, acceleration by s^2
print(f"stretch time by {s:.2f} to respect {V_LIM} m/s and {A_LIM} m/s^2")
v2, a2, j2 = metrics(T * s)
print(f"after stretching: total {T.sum() * s:.1f} s, peak speed {v2:.2f} m/s, peak acceleration {a2:.2f} m/s^2, peak jerk {j2:.2f} m/s^3")
dirs = np.diff(way, axis=0); ang = np.degrees(np.abs(np.diff(np.arctan2(dirs[:, 1], dirs[:, 0]))))
print("heading changes at the waypoint corners of the straight-line path: " + ", ".join(f"{x:.1f} deg" for x in ang))
segment times at 2.5 m/s average: 3.20 2.47 2.47 3.20 s, total 11.3 s
peak speed 4.87 m/s, peak acceleration 2.89 m/s^2, peak jerk 3.18 m/s^3
stretch time by 1.62 to respect 3.0 m/s and 2.0 m/s^2
after stretching: total 18.4 s, peak speed 3.00 m/s, peak acceleration 1.09 m/s^2, peak jerk 0.74 m/s^3
heading changes at the waypoint corners of the straight-line path: 14.0 deg, 28.1 deg, 14.0 deg
With timing from the average speed, the minimum-snap curve takes 11.3 s but peaks at 4.87 m/s and 2.89 m/s², above both limits. The binding limit is speed: . After stretching, the trajectory takes 18.4 s and peaks at 3.00 m/s, 1.09 m/s² and 0.74 m/s³. The speed limit is met exactly while the acceleration has plenty of margin, which shows that stretching by a single factor is conservative: a better method would give each segment its own factor. The straight-line path has heading changes of 14.0°, 28.1° and 14.0° at its corners, which a vehicle with a finite steering rate cannot follow exactly; the smooth curve removes them.
On the drone, the same trajectory is sampled at a fixed rate and the companion computer streams position, velocity and acceleration setpoints to the flight stack, which does the actual tracking with its own controllers (PX4 Autopilot, n.d.). Sampling the acceleration as well as the position is what makes the vehicle follow a curve without lagging behind it.
Tracking the path: pure pursuit, Stanley and LQR
The tracking controller turns the trajectory into steering and speed commands. For a vehicle with a wheelbase the three common choices differ in what they look at (Snider, 2009).
- Pure pursuit aims at a point on the path a look-ahead distance ahead of the rear axle. If the angle between the vehicle heading and the line to that point is , the steering angle is . It is simple and forgiving of noise; the look-ahead trades smoothness against corner cutting.
- Stanley measures the cross-track error at the front axle: , where is the heading error. It corrects the offset quickly at any speed but has no knowledge of the path’s curvature, so on a bend it needs a standing offset to produce the steering the bend demands.
- LQR with feed-forward adds the steering the path’s curvature requires, , and a state feedback on the errors, with from a linear-quadratic regulator for the error dynamics. It needs the curvature of the trajectory ahead and a model, but tracks bends with almost no error.
Example 5 Three trackers on a path with a headland U-turn
The path is 30 m straight, a half circle of radius 4 m, and 30 m straight back. The vehicle (wheelbase 1.0 m, 1.5 m/s) starts 0.5 m beside the path. The steering lags the command with a time constant of 0.2 s and is limited to 30° (assumed). Pure pursuit uses a 2 m look-ahead, Stanley uses and LQR weights the offset 1.0, the heading error 0.3 and the steering 2.0 (assumed). Compare the time to settle within 5 cm, and the RMS and largest cross-track error on the straights and in the U-turn.
import numpy as np
from scipy.linalg import solve_discrete_are
# Example 5: pure pursuit, Stanley and LQR on a bicycle model through a headland U-turn (Snider, 2009; assumed vehicle)
L_WB, V, DT, TAU, D_MAX = 1.0, 1.5, 0.02, 0.2, np.radians(30) # wheelbase, speed, step, steering lag, steering limit
R_TURN = 4.0
s = np.arange(0, 30, 0.05) # path: 30 m straight, half circle of radius 4 m, 30 m straight back
arc = np.arange(0, np.pi * R_TURN, 0.05)
px = np.r_[s, 30 + R_TURN * np.sin(arc / R_TURN), 30 - s]
py = np.r_[np.zeros_like(s), R_TURN - R_TURN * np.cos(arc / R_TURN), np.full_like(s, 2 * R_TURN)]
pth = np.r_[np.zeros_like(s), arc / R_TURN, np.full_like(s, np.pi)]
kap = np.r_[np.zeros_like(s), np.full_like(arc, 1 / R_TURN), np.zeros_like(s)]
def nearest(x, y, i0): # nearest path index, searched forward from the last one
j = np.arange(i0, min(i0 + 200, len(px)))
return j[np.argmin((px[j] - x) ** 2 + (py[j] - y) ** 2)]
wrap = lambda a: (a + np.pi) % (2 * np.pi) - np.pi
A = np.array([[1, V * DT], [0, 1]]); B = np.array([[V ** 2 * DT ** 2 / (2 * L_WB)], [V * DT / L_WB]]) # lateral error dynamics (offset, heading error)
P = solve_discrete_are(A, B, np.diag([1.0, 0.3]), np.array([[2.0]]))
K_LQR = np.linalg.solve(2.0 + B.T @ P @ B, B.T @ P @ A)[0]
def pure_pursuit(x, y, th, i):
j = i
while j < len(px) - 1 and np.hypot(px[j] - x, py[j] - y) < 2.0: j += 1 # look-ahead point 2 m away
return np.arctan(2 * L_WB * np.sin(wrap(np.arctan2(py[j] - y, px[j] - x) - th)) / 2.0)
def stanley(x, y, th, i):
fx, fy = x + L_WB * np.cos(th), y + L_WB * np.sin(th) # cross-track error is measured at the front axle
j = nearest(fx, fy, i)
e = (px[j] - fx) * -np.sin(pth[j]) + (py[j] - fy) * np.cos(pth[j]) # path is to the left of the front axle when positive
return wrap(pth[j] - th) + np.arctan(2.0 * e / V)
def lqr(x, y, th, i):
e = (x - px[i]) * -np.sin(pth[i]) + (y - py[i]) * np.cos(pth[i]) # vehicle offset to the left of the path
return np.arctan(L_WB * kap[i]) - K_LQR @ np.array([e, wrap(th - pth[i])])
def drive(ctrl):
x, y, th, d, i = 0.0, 0.5, 0.0, 0.0, 0 # starts 0.5 m beside the path
err, idx = [], []
while i < len(px) - 20 and len(err) < 4000:
i = nearest(x, y, i)
cmd = np.clip(ctrl(x, y, th, i), -D_MAX, D_MAX)
d += (cmd - d) * DT / TAU # the steering actuator lags the command
x += V * np.cos(th) * DT; y += V * np.sin(th) * DT; th += V * np.tan(d) / L_WB * DT
err.append((x - px[i]) * -np.sin(pth[i]) + (y - py[i]) * np.cos(pth[i])); idx.append(i)
return np.array(err), np.array(idx)
print("controller settles within 5 cm | straights (after 8 m) | U-turn: RMS and largest error (m)")
for name, ctrl in (("pure pursuit", pure_pursuit), ("Stanley", stanley), ("LQR + feed-forward", lqr)):
e, idx = drive(ctrl)
straight = (idx >= 160) & (kap[idx] == 0)
turn = kap[idx] > 0
settle = (np.flatnonzero(np.abs(e[:1000]) > 0.05)[-1] + 1) * DT # last time inside the first 20 s that the error exceeds 5 cm
print(f"{name:18s} {settle:6.1f} s | RMS {np.sqrt(np.mean(e[straight] ** 2)):.3f} m, largest {np.abs(e[straight]).max():.3f} m | {np.sqrt(np.mean(e[turn] ** 2)):.3f}, {np.abs(e[turn]).max():.3f}")
controller settles within 5 cm | straights (after 8 m) | U-turn: RMS and largest error (m)
pure pursuit 2.3 s | RMS 0.015 m, largest 0.077 m | 0.030, 0.076
Stanley 2.2 s | RMS 0.012 m, largest 0.097 m | 0.111, 0.121
LQR + feed-forward 2.0 s | RMS 0.008 m, largest 0.043 m | 0.017, 0.044
All three settle within about 2 s, and on the straights their RMS error is about a centimetre. The U-turn separates them. Stanley holds a standing offset of about 0.12 m throughout the turn (RMS 0.111 m) because it does not know the path is curved. Pure pursuit has smaller error in the turn (RMS 0.030 m) but overshoots by 0.076 m as it enters and leaves, because its look-ahead point sees the bend early and the exit late; the largest error on the straights, 0.077 m, is that exit transient. LQR with feed-forward is best throughout (RMS 0.017 m in the turn, largest 0.044 m) because the curvature term gives most of the steering before any error appears. The price is the model and the curvature, which a global path from a grid planner may not provide cleanly.
Choose by the path and the vehicle: pure pursuit when the path is noisy or roughly planned, Stanley when speed varies and corrections must be quick, LQR with feed-forward when the trajectory is smooth and its curvature known, as after the minimum-snap step above. Whatever the choice, test it on the sharpest bend of the real route, and in the presence of steering lag, as here.
Module lab
Lab: dodge, smooth and track in simulation
- Build a 2D simulated lane for your group with a pile of obstacles (U shape or a wall), a global path with at least two waypoints around it, and a walking person who appears after a few seconds.
- Adapt Example 1: run DWA straight to the goal and along the global path. Change the three score weights and report how clearance and travel time change.
- Feed one range scan of your scene to the Example 2 code. Mark the valleys, then change the threshold and the minimum width and report how the chosen direction changes.
- Apply Example 3 to your person’s position and speed. Draw the velocity obstacle and state the closest safe velocity with and without turning.
- Run Example 4 on your waypoints with your own speed and acceleration limits and report the stretch factor and the final time. Explain which limit is binding.
- Run Example 5 with your own wheelbase, speed and steering lag. Report RMS and largest error on the straights and bends for each controller and recommend one for your robot.
Common mistakes
Watch out
- Sending a local planner straight at a faraway goal and then blaming the planner when it stops in front of a U-shaped obstacle
- Letting the planner use velocities the vehicle cannot reach: ignoring acceleration limits gives commands that jump
- Treating a moving person as a fixed obstacle, or avoiding where the person is now instead of where the person will be
- Choosing a narrow gap without lowering speed, so a small heading error brings the vehicle into the obstacle
- Setting the time of a trajectory from the average speed and not checking peaks of speed, acceleration and jerk
- Assuming a smooth trajectory is also clear of obstacles: minimum snap alone gives no clearance guarantee
- Using a controller without curvature information on tight bends and accepting the standing offset
- Testing a tracker only on straight lines or without actuator lag
Summary
- A local planner reacts at about 10 Hz to what the map misses, and a local minimum is a property of the problem; a global path gives it a way out.
- DWA searches the velocities reachable within one period that still allow stopping, so its commands respect acceleration limits.
- VFH picks a free direction from a polar histogram; narrow valleys call for lower speed.
- A velocity obstacle uses a moving person’s velocity, and the closest safe velocity is often a small turn or a slight slowing.
- Minimum snap produces a smooth, multiple-times-differentiable trajectory; stretching time by divides speed by and acceleration by .
- Pure pursuit is forgiving, Stanley corrects offset quickly but lags on bends, and LQR with feed-forward tracks bends best when curvature is known.
Self-check questions
- A robot moves at 0.8 m/s and 0.1 rad/s. With = 1.0 m/s², = 2.0 rad/s² and a period of 0.1 s, what is its dynamic window?
- On one arc the nearest obstacle is 0.9 m away and = 1.0 m/s². What is the largest admissible speed? Is 1.5 m/s admissible?
- A person is 5 m away and the sum of radii and margin is = 1.0 m. What is the half-angle of the collision cone?
- A minimum-snap trajectory peaks at 4.0 m/s and 3.5 m/s², with limits of 3.0 m/s and 2.0 m/s², and takes 10 s. By what factor must its timing be stretched, and how long does it take then?
- A vehicle with = 1.0 m has a heading error of 20° to a look-ahead point 2 m away (pure pursuit). Another vehicle has a heading error of 5°, a cross-track error of 0.3 m, a speed of 1.5 m/s and = 2 (Stanley). What steering angles do they command?
Answers
- Speed to m/s (0.8 ± 1.0 × 0.1) and turn rate to rad/s (0.1 ± 2.0 × 0.1).
- m/s, so 1.5 m/s is not admissible.
- .
- , so the time becomes s.
- Pure pursuit: . Stanley: .
Key formulas
| Dynamic window of speeds reachable in one control period | |
| Admissible speed (the vehicle must be able to stop before the obstacle) | |
| Half-angle of the collision cone | |
| Minimum-snap cost and time scaling | |
| Pure pursuit and Stanley steering |
Key references
- Khatib, O. (1986). Real-time obstacle avoidance for manipulators and mobile robots. The International Journal of Robotics Research, 5(1), 90–98. link
- Koren, Y., & Borenstein, J. (1991). Potential field methods and their inherent limitations for mobile robot navigation. In Proceedings of the 1991 IEEE International Conference on Robotics and Automation (pp. 1398–1404). IEEE. link
- Fox, D., Burgard, W., & Thrun, S. (1997). The dynamic window approach to collision avoidance. IEEE Robotics & Automation Magazine, 4(1), 23–33. link
- Borenstein, J., & Koren, Y. (1991). The vector field histogram—Fast obstacle avoidance for mobile robots. IEEE Transactions on Robotics and Automation, 7(3), 278–288. link
- Fiorini, P., & Shiller, Z. (1998). Motion planning in dynamic environments using velocity obstacles. The International Journal of Robotics Research, 17(7), 760–772. link
- Mellinger, D., & Kumar, V. (2011). Minimum snap trajectory generation and control for quadrotors. In 2011 IEEE International Conference on Robotics and Automation (pp. 2520–2525). IEEE. link
- Richter, C., Bry, A., & Roy, N. (2016). Polynomial trajectory planning for aggressive quadrotor flight in dense indoor environments. In Robotics Research (Springer Tracts in Advanced Robotics, Vol. 114, pp. 649–666). Springer. link
- Snider, J. M. (2009). Automatic steering methods for autonomous automobile path tracking (Tech. Rep. CMU-RI-TR-09-08). Robotics Institute, Carnegie Mellon University. link
- PX4 Autopilot. Offboard mode (multicopter). PX4 user guide (main). link
- Siegwart, R., Nourbakhsh, I. R., & Scaramuzza, D. (2011). Introduction to autonomous mobile robots (2nd ed.). MIT Press. link
- Thrun, S., Burgard, W., & Fox, D. (2005). Probabilistic robotics. 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