Real-time replanning, ROS 2 navigation and system verification
UAT 461 Autonomous Navigation and Multi-UAV Systems
Lesson
By the end of this module you will be able to
- Compute how much time a planner has to replan from sensing range, delay and braking distance, and keep a replanner from flip-flopping between routes
- Describe the Nav2 architecture (servers, behavior tree, costmaps, frames) and explain how replanning and recovery are organized in its default tree
- Design a scenario set for testing navigation with pairwise coverage and say what it does not cover
- Report a failure rate from Monte Carlo runs with a confidence interval, work out how many runs a claim needs, and monitor safety margins while running
Why this matters
The first four modules built every layer of an autonomous navigation system: localization, fusion, maps, global and local planning, trajectories and tracking. Two jobs remain. First, the layers must keep working while the world changes, which means replanning in real time without running out of time and without dithering. Second, someone must decide whether the finished system is good enough to be left alone among workers, and the decision needs evidence, not a good-looking demonstration.
This module has three parts. The first treats replanning as a budget of time and distance. The second shows how a standard robot software stack, Nav2 for ROS 2, organizes planners, controllers and recovery behaviors. The third turns “is it accurate, safe and robust?” into measurable requirements, test scenarios, statistics and runtime monitors. The ROS 2 basics are from UAT 308 and the trajectory error metrics ATE and RPE are from UAT 458; this module uses them without repeating them.
The case is the same durian orchard at the end of the season: the owner will let the ground robot work in the lanes among the crew only after an acceptance trial. All figures are assumed and the Python code can be downloaded from /downloads/uat-461/.
Replanning in real time
A replan is useful only if it finishes before the vehicle needs its result. Three things eat the distance between the first moment an obstacle is seen and the obstacle: the age of the data from module 1 (during which the vehicle keeps moving at for seconds), the time the planner takes, and the braking distance in case the plan fails. With a reliable sensing range and a safety margin , the distance left for planning is , and the time it gives is . Turned round, if the planner needs seconds the highest safe speed solves , giving with .
Example 1 How much time does each vehicle have?
Under the canopy a 0.3 m wide branch is reliably detected only from 8 m (assumed). The data are 0.5 s old (module 1 measured 0.497 s in the worst case), the safety margin is 1 m, the ground robot cruises at 1.5 m/s and brakes at 1.0 m/s², and the drone cruises at 5 m/s and brakes at 3 m/s². Compute the time each has for planning, then the highest speed for planner times of 0.1 to 4 s (the ground robot is limited to 1.5 m/s and the drone to 8 m/s).
import numpy as np
# Example 1: how much time is there to replan? (assumed sensing range, pipeline delay and braking limits)
R_SENSE, LATENCY, MARGIN = 8.0, 0.5, 1.0 # reliable detection range under the canopy (m), age of the data (s, module 1), safety margin (m)
vehicles = {"ground robot": (1.5, 1.0), "drone": (5.0, 3.0)} # cruise speed (m/s) and braking deceleration (m/s^2)
print("vehicle speed latency dist braking dist left for planning planning time")
for name, (v, a) in vehicles.items():
d_lat, d_brk = v * LATENCY, v ** 2 / (2 * a)
d_plan = R_SENSE - d_lat - d_brk - MARGIN # distance travelled while the planner works
print(f"{name:13s} {v:4.1f} {d_lat:8.2f} m {d_brk:9.2f} m {d_plan:11.2f} m {max(d_plan, 0) / v:8.2f} s")
def v_allowed(t_plan, a, v_max): # largest speed with v (t_plan + latency) + v^2 / 2a + margin = range
T = t_plan + LATENCY
return min(v_max, a * (-T + np.sqrt(T ** 2 + 2 * (R_SENSE - MARGIN) / a)))
print("planner time ground robot drone (max 8 m/s)")
for t_plan in (0.1, 0.5, 1.0, 2.0, 4.0):
print(f"{t_plan:8.1f} s {v_allowed(t_plan, 1.0, 1.5):8.2f} m/s {v_allowed(t_plan, 3.0, 8.0):8.2f} m/s")
vehicle speed latency dist braking dist left for planning planning time
ground robot 1.5 0.75 m 1.12 m 5.12 m 3.42 s
drone 5.0 2.50 m 4.17 m 0.33 m 0.07 s
planner time ground robot drone (max 8 m/s)
0.1 s 1.50 m/s 4.93 m/s
0.5 s 1.50 m/s 4.14 m/s
1.0 s 1.50 m/s 3.39 m/s
2.0 s 1.50 m/s 2.41 m/s
4.0 s 1.35 m/s 1.47 m/s
The ground robot has 5.12 m left for planning, which is 3.42 s: even a slow planner fits at 1.5 m/s, and only a 4 s planner would need it to slow to 1.35 m/s. The drone at 5 m/s has 0.33 m left, only 0.07 s: its data delay and braking distance use almost the whole 8 m. It can replan at 5 m/s only if the planner finishes in about 0.1 s (4.93 m/s allowed); a 1 s planner limits it to 3.39 m/s and a 4 s planner to 1.47 m/s. The practical consequence is that fast vehicles cannot rely on a full replan to avoid a sudden obstacle. They need a reflex layer that is always valid (a braking or hover primitive that does not wait for the planner) and a planner that improves the plan inside a fixed time budget, as an “anytime” planner such as RRT* does.
The second question is when to replan. A planner can run on a timer (the default Nav2 tree replans once per second), after a fixed distance, or when an event occurs such as a changed costmap. A timer alone wastes work when nothing has changed and reacts late when something has. The worse problem is the opposite: a replanner that always adopts the cheapest current plan will flip-flop when two routes cost almost the same, because cost estimates fluctuate from cycle to cycle (leaf flicker in the costmap, a moving worker at the edge of range). Each flip costs time because the vehicle must turn round and rejoin the other lane. The cure is hysteresis: switch only if the saving exceeds a margin tied to the noise, and not again until a minimum dwell time has passed.
Example 2 Two routes of almost equal cost
Route A takes 100 s and route B 104 s. Every second the planner re-estimates the time to go on both routes, each with noise of 3 s, and the vehicle can switch routes at a cost of 5 s lost. Compare four rules over 300 trips: switch whenever the other route looks cheaper (naive), switch if the saving exceeds 10% of the remaining cost, switch if it exceeds 6 s (twice the noise), and the 6 s margin plus a 10 s minimum dwell (assumed).
import numpy as np
# Example 2: when to switch routes? A noisy cost estimate makes a replanner flip between two nearly equal routes (assumed values)
C_A, C_B, NOISE, REALIGN, DWELL = 100.0, 104.0, 3.0, 5.0, 10 # route costs (s), cost-estimate noise (s), time lost per switch (s), minimum dwell (s)
def mission(rule, rng, t_max=600):
route, frac, t, last_switch, switches, lost = 0, 0.0, 0.0, -1e9, 0, 0.0 # route 0 = A, 1 = B; frac = fraction of the trip done
cost = (C_A, C_B)
while frac < 1.0 and t < t_max:
est = [cost[r] * (1 - frac) + rng.normal(0, NOISE) for r in (0, 1)] # each second the planner re-estimates the time to go on both routes
other = 1 - route
saving = est[route] - est[other]
if rule == "naive": go = saving > 0
elif rule == "10 % margin": go = saving > 0.10 * est[route]
elif rule == "6 s margin": go = saving > 2 * NOISE
else: go = saving > 2 * NOISE and t - last_switch > DWELL
if go:
route, last_switch, switches, lost = other, t, switches + 1, lost + REALIGN
t += REALIGN # turning back and rejoining the other lane
continue
frac += 1.0 / cost[route]; t += 1.0
return switches, t, frac >= 1.0
rng = np.random.default_rng(2)
print("rule switches per trip mean time to goal trips reaching goal in 600 s")
for rule in ("naive", "10 % margin", "6 s margin", "6 s margin + dwell"):
res = [mission(rule, rng) for _ in range(300)]
sw = np.mean([r[0] for r in res]); done = [r for r in res if r[2]]
print(f"{rule:22s} {sw:10.1f} {np.mean([r[1] for r in done]) if done else float('nan'):8.1f} s {len(done):3d} of 300")
rule switches per trip mean time to goal trips reaching goal in 600 s
naive 75.9 478.3 s 295 of 300
10 % margin 21.1 206.4 s 300 of 300
6 s margin 5.1 126.8 s 300 of 300
6 s margin + dwell 3.7 120.0 s 300 of 300
The naive rule switches 75.9 times per trip and needs 478.3 s on average; 5 trips of 300 do not arrive within 600 s. A margin of 10% of the remaining cost still switches 21.1 times (206.4 s) because the margin shrinks as the trip nears its end while the noise does not. A margin of 6 s, set from the noise, brings it down to 5.1 switches and 126.8 s, and adding the dwell time gives 3.7 switches and 120.0 s, close to the 100 s of staying on route A. The lesson is to set the switching margin from the measured noise of the cost estimate, not from a percentage chosen by taste.
Navigation in ROS 2: the Nav2 architecture
Nav2 is the navigation stack of ROS 2 (Macenski et al., 2020, 2022). It splits the work into separate servers that are managed together: a planner server computes a path to the goal, a controller server follows the path with a local planner and tracking controller, a behavior server runs recovery behaviors such as spinning, waiting and backing up, and a lifecycle manager starts and stops them in order. A behavior tree navigator decides which server to call and what to do when one fails; the tree nodes call the servers through action interfaces (Nav2 Maintainers, n.d.-a). The global and local costmaps of module 3 feed the planner and the controller, and the frames map, odom and base_link of module 1 (REP 105) tie positions together.
Figure 3 shows the structure used in this course. Nav2 was designed for ground robots on a two-dimensional map. For the drone the same structure applies at the mission level, but the lowest layer is a flight stack, and height is handled separately as in module 3. The flight stack’s offboard mode expects a continuous stream of setpoints from the companion computer at not less than 2 Hz as a proof of life, and triggers a loss-of-offboard failsafe if the stream stops (PX4 Autopilot, n.d.). So the replanner must never block the setpoint stream, which is one more reason for the reflex layer of Example 1.
The heart of replanning and recovery is the behavior tree (Colledanchise & Ögren, 2018). Each node returns success, failure or running; control nodes decide the order, and decorator nodes modify a child. In the default navigate-to-pose tree on the main branch, checked on 2 October 2026 (Nav2 Maintainers, n.d.-b), the root is a recovery node allowed 6 retries. Its main child is a pipeline sequence that, every 1.0 s through a rate controller, computes a path, and meanwhile follows the path. If either fails, a first level of recovery clears the costmap involved and retries once. If the failure persists, the root runs a round-robin of recovery actions in this order: clear the costmaps, spin 1.57 rad, wait 5 s, back up 0.30 m at 0.15 m/s; each failure moves to the next action in the cycle, and after 6 retries the whole navigation fails and the caller is told.
Example 3 How many retries? A simplified tree on 2,000 missions
A mission is a 60 m drive at 1.5 m/s. Each mission has one of four situations: nothing happens (25%); a ghost obstacle remains in the costmap although the way is clear (30%), cured by clearing the costmaps; a temporary real blocker such as a person standing in the lane for 5 to 25 s (35%), cured by waiting; a permanent blocker such as a fallen tree (10%), which no recovery can cure. The tree is the simplified version of the default one: a recovery node over a pipeline of a 1 Hz rate controller, path computation and path following, with recoveries in round-robin order (clear 1 s, spin 4 s, wait 5 s, back up 2 s; assumed). Compare 0, 1, 3 and 6 retries.
import numpy as np
# Example 3: a small behavior tree with replanning and recovery, run on 2,000 simulated missions per setting (assumed fault mix and durations)
SUCCESS, FAILURE, RUNNING = "success", "failure", "running"
class Leaf: # an action or condition: fn(ctx) returns a status
def __init__(self, fn): self.fn = fn
def tick(self, ctx): return self.fn(ctx)
class Rate: # decorator: run the child at most once per period, otherwise pass through
def __init__(self, period, child): self.period, self.child, self.last = period, child, -1e9
def tick(self, ctx):
if ctx["t"] - self.last < self.period: return SUCCESS
self.last = ctx["t"]; return self.child.tick(ctx)
class Pipeline: # tick the children in order, stop at the first one that is not SUCCESS
def __init__(self, *kids): self.kids = kids
def tick(self, ctx):
for k in self.kids:
st = k.tick(ctx)
if st != SUCCESS: return st
return SUCCESS
class RoundRobin: # run the next child on each call, cycling through them
def __init__(self, *kids): self.kids, self.i = kids, 0
def tick(self, ctx):
st = self.kids[self.i].tick(ctx); self.i = (self.i + 1) % len(self.kids); return st
class Recovery: # run the main child; on FAILURE run the recovery child and retry, at most n times
def __init__(self, main, recovery, retries): self.main, self.rec, self.n, self.used = main, recovery, retries, 0
def tick(self, ctx):
st = self.main.tick(ctx)
if st != FAILURE: return st
if self.used >= self.n or self.rec.tick(ctx) == FAILURE: return FAILURE
self.used += 1; return RUNNING
def blocked(ctx): # is the way blocked at this moment, and does the robot know it?
f = ctx["fault"]
if f == "ghost": return ctx["t"] >= ctx["t_f"] and not ctx["cleared"]
if f == "temporary": return ctx["t_f"] <= ctx["t"] < ctx["t_f"] + ctx["dur"]
if f == "permanent": return ctx["t"] >= ctx["t_f"]
return False
def compute_path(ctx): return FAILURE if blocked(ctx) else SUCCESS
def follow_path(ctx):
if blocked(ctx): return FAILURE
ctx["done"] += 1.5; ctx["t"] += 1.0 # one second of driving at 1.5 m/s
return SUCCESS if ctx["done"] >= ctx["goal"] else RUNNING
def action(seconds, effect=None):
def run(ctx):
ctx["t"] += seconds
if effect: effect(ctx)
return SUCCESS
return Leaf(run)
def clear(ctx): ctx["cleared"] = True
def mission(retries, rng):
ctx = dict(t=0.0, done=0.0, goal=60.0, cleared=False, fault=rng.choice(["none", "ghost", "temporary", "permanent"], p=[0.25, 0.30, 0.35, 0.10]),
t_f=rng.uniform(5, 30), dur=rng.uniform(5, 25))
tree = Recovery(Pipeline(Rate(1.0, Leaf(compute_path)), Leaf(follow_path)),
RoundRobin(action(1.0, clear), action(4.0), action(5.0), action(2.0)), retries) # clear costmaps, spin, wait, back up
while ctx["t"] < 400:
st = tree.tick(ctx)
if st == SUCCESS: return True, ctx["t"], ctx["fault"]
if st == FAILURE: return False, ctx["t"], ctx["fault"]
return False, ctx["t"], ctx["fault"]
FAULTS = ("none", "ghost", "temporary", "permanent")
print("retries | completed per fault type (%) | overall | mean time | mean time before")
print(" | none ghost temporary permanent | | completed | giving up")
for retries in (0, 1, 3, 6):
rng = np.random.default_rng(484)
res = [mission(retries, rng) for _ in range(2000)]
by = [100 * np.mean([r[0] for r in res if r[2] == f]) for f in FAULTS]
ok = [r[1] for r in res if r[0]]; bad = [r[1] for r in res if not r[0]]
print(f"{retries:5d} | {by[0]:6.1f} {by[1]:7.1f} {by[2]:9.1f} {by[3]:10.1f} | {100 * len(ok) / len(res):6.1f}% | {np.mean(ok):7.1f} s | {np.mean(bad):7.1f} s")
retries | completed per fault type (%) | overall | mean time | mean time before
| none ghost temporary permanent | | completed | giving up
0 | 100.0 0.0 0.0 0.0 | 24.5% | 40.0 s | 17.9 s
1 | 100.0 100.0 0.0 0.0 | 55.2% | 40.6 s | 19.0 s
3 | 100.0 100.0 28.2 0.0 | 64.8% | 41.9 s | 28.2 s
6 | 100.0 100.0 66.3 0.0 | 77.8% | 44.1 s | 35.5 s
With no retries only the 25% of untroubled missions complete (24.5% measured). One retry already cures every ghost, because clearing the costmaps is first in the cycle. Temporary blockers are cured only when the cycle reaches the 5 s wait and the retries last long enough: 28.2% of them complete with 3 retries and 66.3% with 6. The 10% permanent blockers are never cured, and more retries only delay giving up: the mean time before a mission is abandoned grows from 17.9 s to 35.5 s. So the number of retries is a trade between completing missions and giving up promptly. A failed navigation must reach the operator rather than being retried forever, which is the same attitude as the supervisor of module 2.
Evaluating a navigation system
“Is it good?” is three questions, each with its own metrics. Accuracy asks how closely the system does what was asked: goal error, cross-track error along the path (module 4), the trajectory errors ATE and RPE from UAT 458, and the consistency of the estimator through NEES and NIS (module 2). Safety asks whether it avoids harm: the smallest clearance to people and obstacles, the number of contacts with hoses or trunks, and how far inside the limits it stayed. Robustness asks what happens when conditions are worse than planned: the success rate with GNSS faults, blocked lanes and failed sensors, how long recovery takes, and whether the system degrades gracefully rather than abruptly.
A requirement is useful only if it can be tested. For the acceptance trial of the orchard system the team writes a verification matrix (all thresholds assumed).
| Question | Requirement | Metric | Method |
|---|---|---|---|
| Accuracy | End within 0.3 m of the goal; lane-centre error RMS up to 0.10 m | Goal error, cross-track RMS and largest | 20 field runs with a tape or RTK reference |
| Estimator honesty | Filter consistent for every fix type | Mean NIS inside the 95% bounds | Field logs (module 2) |
| Safety | Never touch a hose or person; at least 1.0 m clearance to people | Contacts, minimum clearance, robustness margin | Monte Carlo in simulation plus runtime monitor |
| Robustness | Complete missions with injected GNSS faults and blocked lanes | Success rate with confidence interval, time to give up | Fault-injection scenarios |
| Timing | Data at the actuators no older than 0.5 s | Measured age of data (module 1) | Timestamps in the logs |
The number of scenarios explodes if every combination is tried. With five factors of two or three levels each, the full set is 108 scenarios. Empirical studies of software faults found that most failures are triggered by one or two parameters interacting, so a pairwise (2-way) set that covers every pair of levels at least once catches most of them with far fewer runs (Kuhn et al., 2010).
Example 4 A pairwise set for the orchard scenarios
The factors are canopy (open, partial, closed), GNSS (normal, multipath bias, outage), obstacle (none, branch pile, walking worker), speed (1.0 or 1.5 m/s) and lane (2.0 m or 1.4 m wide). Build a pairwise set greedily, choosing at each step the scenario that covers the most pairs of levels not yet covered, and check that every pair is covered and how many three-way combinations the set covers by chance (assumed factors).
import itertools
# Example 4: a pairwise (2-way) test set for the orchard navigation scenarios (Kuhn et al., 2010; assumed factors and levels)
factors = {
"canopy": ["open", "partial", "closed"],
"GNSS": ["normal", "multipath bias", "outage"],
"obstacle": ["none", "branch pile", "walking worker"],
"speed": ["1.0 m/s", "1.5 m/s"],
"lane": ["2.0 m wide", "1.4 m wide"],
}
names = list(factors)
full = list(itertools.product(*factors.values()))
def pairs_of(test):
return {((i, test[i]), (j, test[j])) for i, j in itertools.combinations(range(len(names)), 2)}
need = set().union(*(pairs_of(t) for t in full)) # every pair of levels of two different factors
suite, covered = [], set()
while covered != need: # greedy: take the scenario that covers the most uncovered pairs
best = max(full, key=lambda t: (len(pairs_of(t) - covered), -full.index(t)))
suite.append(best); covered |= pairs_of(best)
print(f"full factorial: {len(full)} scenarios; pairs of levels to cover: {len(need)}")
print(f"greedy pairwise suite: {len(suite)} scenarios ({100 * len(suite) / len(full):.0f} % of the full set), pairs covered {len(covered)} of {len(need)}")
print(" " + " | ".join(f"{n:14s}" for n in names))
for k, t in enumerate(suite, 1):
print(f"{k:2d} " + " | ".join(f"{v:14s}" for v in t))
triples = {tuple((i, t[i]) for i in c) for t in full for c in itertools.combinations(range(len(names)), 3)}
got = {tuple((i, t[i]) for i in c) for t in suite for c in itertools.combinations(range(len(names)), 3)}
print(f"three-way combinations covered by the same suite: {len(got)} of {len(triples)} ({100 * len(got) / len(triples):.0f} %)")
full factorial: 108 scenarios; pairs of levels to cover: 67
greedy pairwise suite: 10 scenarios (9 % of the full set), pairs covered 67 of 67
canopy | GNSS | obstacle | speed | lane
1 open | normal | none | 1.0 m/s | 2.0 m wide
2 open | multipath bias | branch pile | 1.5 m/s | 1.4 m wide
3 partial | outage | walking worker | 1.0 m/s | 1.4 m wide
4 closed | normal | walking worker | 1.5 m/s | 2.0 m wide
5 partial | multipath bias | none | 1.5 m/s | 2.0 m wide
6 closed | outage | branch pile | 1.0 m/s | 2.0 m wide
7 closed | multipath bias | none | 1.0 m/s | 1.4 m wide
8 partial | normal | branch pile | 1.0 m/s | 1.4 m wide
9 open | outage | none | 1.5 m/s | 2.0 m wide
10 open | multipath bias | walking worker | 1.0 m/s | 2.0 m wide
three-way combinations covered by the same suite: 96 of 171 (56 %)
The full set has 108 scenarios and 67 pairs of levels to cover. The greedy method covers all 67 with 10 scenarios, 9% of the full set (the lower bound is 9, since two factors have three levels each). The same ten scenarios cover only 56% of the 171 three-way combinations, so a failure that needs three conditions together may be missed. In particular the hardest case for this robot, closed canopy with a GNSS outage, a narrow lane and a walking worker, is not in the set. A pairwise set is a base; a risk analysis adds by hand the combinations that would hurt most.
Statistical evidence and runtime monitors
Simulation lets the team run each scenario many times with different random noise, drift and fix sequences, and count failures. A count is not a rate: with 1,000 runs and 3 failures the true rate is not exactly 0.3%. The exact (Clopper-Pearson) interval (Clopper & Pearson, 1934) gives the range of rates consistent with the count. When there are no failures at all, the upper bound with 95% confidence is , and the number of runs needed to show a rate below is , about . Showing 1% needs 299 runs, 0.1% needs 2,995 and 0.01% needs 29,956. The same arithmetic is why showing that automated vehicles are safe by road testing alone would take hundreds of millions of miles (Kalra & Paddock, 2016), and why simulation and analysis must share the work with field tests.
Failure counts also hide how close the successes came. A runtime monitor evaluates a requirement continuously and reports a signed margin. For “the lateral error always stays below ” the robustness margin of a run is : positive means the requirement held with that much room, negative means it was violated (Bartocci et al., 2018). The margin turns pass or fail into a number, so a system that passes by 2 cm is told apart from one that passes by 30 cm, and the same monitor can run on the real vehicle and stop it when the margin falls.
Example 5 Lane keeping under the closed canopy: four designs, 1,000 runs each
The robot drives a 120 m lane at 1.5 m/s under a closed canopy with the fix statistics of zone Z3 (module 1). Its lateral error is reset by every usable fix with a Kalman update, and between fixes it drifts by a heading bias redrawn at each fix, with standard deviation 1.5% of the distance. A contact is a lateral error beyond 0.6 m. Compare four designs: no supervisor; the module 2 supervisor that stops the vehicle while the filter’s sigma exceeds 0.167 m; the same with an injected fault (each second a float fix carries a 1.5 m multipath bias with probability 0.02); and the same with an innovation gate that rejects a fix beyond 3 sigma (assumed model).
import numpy as np
from scipy.stats import beta
# Example 5: Monte Carlo test of lane keeping under the closed canopy, with and without a supervisor, with injected faults (assumed model)
P_FIX = [0.12, 0.38, 0.35, 0.15] # zone Z3 of module 1: fixed, float, single, none (a state persists with probability 0.80 each second)
SIG_FIX = {0: 0.02, 1: 0.30} # lateral sigma of a usable fix (fixed, float), m
EPS, SIG_MAX, LIMIT, LANE_M, SPEED = 0.015, 0.167, 0.6, 120.0, 1.5 # drift per metre, supervisor limit (module 2), hose contact at 0.6 m, lane length, speed
LIE_P, LIE_BIAS = 0.02, 1.5 # injected fault: each second a float fix may carry a 1.5 m multipath bias with probability 0.02
def run(policy, rng):
err, P0, d, drift = rng.normal(0, 0.02), 0.02 ** 2, 0.0, rng.normal(0, EPS) # start in the yard: true lateral error, variance after the last fix, metres since
state, x, t, margin = rng.choice(4, p=P_FIX), 0.0, 0, LIMIT
while x < LANE_M and t < 600:
if rng.random() > 0.80: state = rng.choice(4, p=P_FIX)
if state in (0, 1): # a usable fix arrives: scalar Kalman update of the lateral error
P, R = P0 + (EPS * d) ** 2, SIG_FIX[state] ** 2
lie = policy in ("lying fixes", "lying fixes + gate") and state == 1 and rng.random() < LIE_P
z = rng.normal(0, SIG_FIX[state]) + (LIE_BIAS * rng.choice([-1, 1]) if lie else 0.0) # measured position error
nu = z - err # innovation
if not (policy == "lying fixes + gate" and nu ** 2 / (P + R) > 9.0): # gate: reject beyond 3 sigma
K = P / (P + R)
err, P0, d, drift = err + K * nu, (1 - K) * P, 0.0, rng.normal(0, EPS)
sigma = np.sqrt(P0 + (EPS * d) ** 2) # what the filter believes
if policy == "no supervisor" or sigma <= SIG_MAX: # the supervisor stops the vehicle when sigma exceeds the limit
err += drift * SPEED; x += SPEED; d += SPEED
t += 1
margin = min(margin, LIMIT - abs(err))
return margin < 0, t, margin
def cp_interval(k, n, conf=0.95): # Clopper-Pearson (exact) two-sided interval for k contacts in n runs
a = (1 - conf) / 2
return (0.0 if k == 0 else beta.ppf(a, k, n - k + 1)), (1.0 if k == n else beta.ppf(1 - a, k + 1, n - k))
print("policy runs contacts rate 95 % interval mean time median margin")
N = 1000
for policy in ("no supervisor", "supervisor", "lying fixes", "lying fixes + gate"):
rng = np.random.default_rng(11)
res = [run(policy, rng) for _ in range(N)]
k = sum(r[0] for r in res); lo, hi = cp_interval(k, N)
print(f"{policy:20s} {N:5d} {k:8d} {100 * k / N:5.1f} % {100 * lo:5.2f} % to {100 * hi:5.2f} % {np.mean([r[1] for r in res]):6.1f} s {np.median([r[2] for r in res]):8.2f} m")
for p_target in (0.01, 0.001, 0.0001):
print(f"zero contacts needed to show a rate below {p_target * 100:g} % with 95 % confidence: {int(np.ceil(np.log(0.05) / np.log(1 - p_target)))} runs")
policy runs contacts rate 95 % interval mean time median margin
no supervisor 1000 229 22.9 % 20.33 % to 25.63 % 80.0 s 0.20 m
supervisor 1000 3 0.3 % 0.06 % to 0.87 % 108.3 s 0.34 m
lying fixes 1000 12 1.2 % 0.62 % to 2.09 % 107.9 s 0.32 m
lying fixes + gate 1000 9 0.9 % 0.41 % to 1.70 % 108.1 s 0.34 m
zero contacts needed to show a rate below 1 % with 95 % confidence: 299 runs
zero contacts needed to show a rate below 0.1 % with 95 % confidence: 2995 runs
zero contacts needed to show a rate below 0.01 % with 95 % confidence: 29956 runs
Without the supervisor 22.9% of runs touch a hose (interval 20.3% to 25.6%): the closed canopy cannot be crossed on wheels alone, as module 1 predicted. The supervisor reduces contacts to 0.3% (0.06% to 0.87%) at the price of time: 108 s against the minimum of 80 s, which is 35% longer. With lying fixes the rate is 1.2% (0.62% to 2.09%); the gate lowers it to 0.9% (0.41% to 1.70%). The intervals of the last two overlap, so 1,000 runs cannot show that the gate helps; to tell 1.2% from 0.9% takes many times more runs. The median margin of supervised runs, 0.32 m to 0.34 m, shows that the successes are not marginal. To claim a contact rate below 0.1%, even a flawless design needs 2,995 failure-free runs.
Simulation is not the field. A simulator contains only the faults its authors imagined, so the verification plan should run software in the loop (ArduPilot Dev Team, n.d.) and hardware in the loop before the field, and use the field trial to check the simulator itself: if the real fix statistics, drift and delays differ from the simulated ones, the simulated rates mean nothing. Report results with the model assumptions and the intervals, not as a single number.
Module lab
Lab: budget, tree and acceptance test
- Measure the delay of your group’s pipeline from the module 1 lab and compute and for your robot as in Example 1, using the sensing range you measure with a 0.3 m wide object in the test area.
- Record the noise of the cost estimate of two nearly equal routes in your simulator for 10 minutes, set the switching margin as twice the standard deviation of the difference, and compare it with the naive rule over 50 trips as in Example 2.
- Adapt Example 3 to the recovery order and durations of your simulator, choose the retry count for your robot and justify it with the missions completed and the time before giving up.
- List five factors with their levels for your test field, generate a pairwise set with the Example 4 code, and add by hand the two combinations you judge most dangerous.
- Run Example 5 on your lane with your own drift and fix statistics, report each design’s contact rate with its interval, and state how many failure-free runs your acceptance limit would require.
- Write a one-page verification matrix like the table in this module for your robot, with a threshold, a metric and a test method for each requirement.
Common mistakes
Watch out
- Assuming a replan always finishes in time, with no reflex layer that stays valid while the planner works
- Letting the planner block the setpoint stream to the flight stack
- Switching to the cheapest route at every cycle with noisy cost estimates, so the vehicle flip-flops
- Setting the switching margin as a percentage instead of from the measured noise
- Retrying a failed navigation without limit, or giving up so early that temporary blockers defeat the mission
- Treating every failure as curable by recovery: a permanent blocker must reach the operator
- Testing only the scenarios that come to mind instead of a systematic set plus risk-based additions
- Reporting a failure count as a rate, or claiming a rate from far too few runs
- Trusting a simulator never checked against the field
Summary
- The time to replan is ; fast vehicles need a reflex layer and an anytime planner.
- A replanner needs hysteresis set from the noise of its cost estimate, and a minimum dwell time between switches.
- Nav2 splits navigation into planner, controller and behavior servers under a behavior tree with replanning at 1 Hz and a cycle of recoveries.
- The number of retries trades missions completed against time before giving up, and permanent blockers must go to the operator.
- Accuracy, safety and robustness each need requirements with a metric, a threshold and a method; a pairwise set is a base for scenarios, not the whole set.
- A failure rate needs a Clopper-Pearson interval; with no failures, runs are required, and a margin shows how close successes came.
Self-check questions
- A robot has a sensing range of 10 m, a data delay of 0.4 s, speed 2 m/s, braking 1.0 m/s² and a 1 m margin. How much time does it have for planning?
- How many failure-free runs are needed to show, with 95% confidence, that a contact rate is below 0.5%?
- A design has 2 contacts in 400 runs. What is the observed rate and the one-sided 95% upper bound? (Use 0.0157 from a statistics package.)
- Four factors have three levels each. How many scenarios does the full set have, and what is the least number a pairwise set can have?
- A replanner re-estimates two routes each second with independent noise of 3 s on each estimate. What is the standard deviation of the difference, and what is the chance that the naive rule switches when the two routes are really equal and the margin is 6 s?
Answers
- m, so s.
- , so 598 runs.
- The rate is and the upper bound is about 1.57%, three times the observed rate.
- scenarios. Any two factors already have pairs of levels, so at least 9 scenarios are needed.
- s. With a 6 s margin the switch chance is per cycle; with the naive rule (margin 0) it is 50%.
Key formulas
| Distance left for planning and the time it gives | |
| Highest speed for a given planning time | |
| Runs needed with zero failures to show a rate below p with confidence C | |
| Robustness margin of the requirement that the error stays below a limit |
Key references
- Nav2 Maintainers. Nav2 behavior trees. Nav2 documentation (rolling). link
- Nav2 Maintainers. navigate_to_pose_w_replanning_and_recovery.xml (default behavior tree, nav2_bt_navigator, main branch). Navigation2 source repository, GitHub. link
- Colledanchise, M., & Ögren, P. (2018). Behavior trees in robotics and AI: An introduction. CRC Press. link
- Macenski, S., Martin, F., White, R., & Clavero, J. G. (2020). The Marathon 2: A navigation system. In 2020 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS) (pp. 2718–2725). IEEE. link
- Macenski, S., Foote, T., Gerkey, B., Lalancette, C., & Woodall, W. (2022). Robot Operating System 2: Design, architecture, and uses in the wild. Science Robotics, 7(66), eabm6074. link
- ROS Enhancement Proposals. REP 105: Coordinate frames for mobile platforms. link
- PX4 Autopilot. Offboard mode (multicopter). PX4 user guide (main). link
- ArduPilot Dev Team. SITL simulator (software in the loop). link
- Clopper, C. J., & Pearson, E. S. (1934). The use of confidence or fiducial limits illustrated in the case of the binomial. Biometrika, 26(4), 404–413. link
- Kuhn, D. R., Kacker, R. N., & Lei, Y. (2010). Practical combinatorial testing (NIST Special Publication 800-142). National Institute of Standards and Technology. link
- Bartocci, E., Deshmukh, J., Donzé, A., Fainekos, G., Maler, O., Ničković, D., & Sankaranarayanan, S. (2018). Specification-based monitoring of cyber-physical systems: A survey on theory, tools and applications. In Lectures on runtime verification (Lecture Notes in Computer Science, Vol. 10457, pp. 135–175). Springer. link
- Kalra, N., & Paddock, S. M. (2016). Driving to safety: How many miles of driving would it take to demonstrate autonomous vehicle reliability? (Research Report RR-1478). RAND Corporation. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
ROS 2 และการเชื่อมต่อกับ flight stack
Developing simulations and connecting SITL
UAV testing and evidence analysis
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results