Path planning and testing of indoor autonomous flight
UAT 458 Indoor Autonomous UAS and Navigation Technology
Lesson
By the end of this module you will be able to
- Plan a route on a building grid with A*, inflating obstacles by the aircraft size and a margin
- Turn a route in the local frame into an autopilot mission and check that the mission fits the battery
- Plan indoor autonomous flight testing in stages with acceptance criteria for each stage
- Assess how low a failure rate a number of passed test flights can demonstrate, and configure safety settings for indoor missions
- Explain what SITL, Gazebo and HITL simulation can and cannot prove, and fit and check a simulator against logged flights before trusting it
Why this matters
Once the drone knows its position, hovers steadily and stops before obstacles, what remains is taking it to work along a safe route and proving it can do so before anyone else is asked to trust it. The manager of the water treatment plant will not ask which algorithm you used. They will ask “how safe is flying in our building, and how do you know?” A good answer is a route designed from the map, a mission that fits the battery, staged testing with evidence, and numbers that say honestly how much a given amount of testing proves.
This module brings the whole course together into an inspection mission in the pump hall and lays the foundation for the end-of-term mini-project.
Three layers of path planning
Mobile-robot path planning is usually split into three layers running at different rates (LaValle, 2006).
- The global planner finds the whole route on a known map, before flight or when the map changes. In this course it runs on a ground computer using the SLAM map tied to the plan in module 3.
- The local avoidance layer reacts to what the sensors see right now; this is the system of module 4.
- The path follower turns the route into velocity commands for the controller; this is the autopilot’s Auto mode.
The planning map is an occupancy grid (Elfes, 1989), but the planner treats the drone as a point, so obstacles must first be inflated by the aircraft radius plus a margin. If the drone’s centre stays outside the inflated region, the propeller tips stay clear of the real object. Indoors, routes are usually planned in height layers, because the obstacles at 3 m (pumps, pipe racks) differ from those at 8 m (crane rails, roof trusses).
Grid search uses A* by Hart et al. (1968), which expands the node with the lowest , where is the cost from the start and an estimate of the remaining cost to the goal. If never overestimates, A* always returns the shortest path. On a grid that allows diagonal moves, the octile distance serves as .
A* on the pump-hall grid
Example 1 Route from the door to the crane-rail inspection point
The 3 m layer of the pump hall (48 × 20 m) is divided into 0.5 m cells. It contains six 3 × 3 m pumps and a long pipe rack with a 1.5 m gap. The drone starts at the door (2, 2) and goes to the point where it climbs to inspect the crane rail, (23, 18). The aircraft radius including guards is 0.45 m plus a 0.55 m margin, so obstacles are inflated by 1.0 m (layout assumed).
import heapq, math
import numpy as np
# A* on the 3 m flight layer of the pump hall: 48 m x 20 m, 0.5 m cells (layout assumed)
CELL = 0.5
NX, NY = int(48 / CELL), int(20 / CELL)
occ = np.zeros((NX, NY), bool)
def block(x0, x1, y0, y1): # mark a rectangle given in metres as occupied
occ[int(x0 / CELL):int(x1 / CELL), int(y0 / CELL):int(y1 / CELL)] = True
for xc in (6, 13, 20, 27, 34, 41): # six pumps, 3 m x 3 m
block(xc - 1.5, xc + 1.5, 7, 10)
block(4, 22.5, 13, 14); block(24, 44, 13, 14) # pipe rack with a 1.5 m gap at x = 22.5-24 m
occ[0, :] = occ[-1, :] = occ[:, 0] = occ[:, -1] = True # walls
def inflate(grid, radius_m):
k = math.ceil(radius_m / CELL)
out = grid.copy()
for i, j in zip(*np.nonzero(grid)):
for di in range(-k, k + 1):
for dj in range(-k, k + 1):
if di * di + dj * dj <= k * k and 0 <= i + di < NX and 0 <= j + dj < NY:
out[i + di, j + dj] = True
return out
def astar(grid, start, goal):
s, g = (int(start[0] / CELL), int(start[1] / CELL)), (int(goal[0] / CELL), int(goal[1] / CELL))
h = lambda a: CELL * (max(abs(a[0] - g[0]), abs(a[1] - g[1])) + (math.sqrt(2) - 1) * min(abs(a[0] - g[0]), abs(a[1] - g[1])))
openq, cost, parent, expanded = [(h(s), 0.0, s)], {s: 0.0}, {s: None}, 0
while openq:
f, c, n = heapq.heappop(openq)
if c > cost[n]:
continue
expanded += 1
if n == g:
path = []
while n:
path.append(n); n = parent[n]
return c, path[::-1], expanded
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
m = (n[0] + dx, n[1] + dy)
if (dx or dy) and 0 <= m[0] < NX and 0 <= m[1] < NY and not grid[m]:
nc = c + CELL * math.hypot(dx, dy)
if nc < cost.get(m, math.inf):
cost[m], parent[m] = nc, n
heapq.heappush(openq, (nc + h(m), nc, m))
return math.inf, [], expanded
START, GOAL = (2.0, 2.0), (23.0, 18.0)
for label, radius in (("no inflation", 0.0), ("inflated 1.0 m", 1.0)):
length, path, n_exp = astar(inflate(occ, radius) if radius else occ, START, GOAL)
print(f"{label:15s}: path {length:5.1f} m, {len(path)} cells, {n_exp} nodes expanded")
no inflation : path 30.3 m, 52 cells, 564 nodes expanded
inflated 1.0 m : path 34.1 m, 65 cells, 723 nodes expanded
Without inflation, A* returns the shortest path, 30.3 m, through the 1.5 m gap in the pipe rack. But the drone is 0.9 m wide including guards, so the propeller tips would clear the pipes by only 0.3 m on each side before any wander. Inflated by 1.0 m the gap closes (it would need to be at least 2.0 m wide), so the route goes round the western end of the rack. It grows to 34.1 m, only 3.8 m longer, in exchange for at least 1.0 m from every object. The inflation must also agree with module 4’s stopping distance (1.2 m); otherwise the avoidance system brakes all the way because the route brings the drone closer than its setting.
From route to autopilot mission
ArduPilot and PX4 missions store waypoints as latitude, longitude and altitude, even indoors without GNSS. The system therefore needs an EKF origin (module 1), and waypoints planned in the local frame must be converted to latitude and longitude relative to that origin. Over a few tens of metres a flat-earth approximation is fine: and , where is the Earth radius, 6,378,137 m.
Example 2 Converting waypoints and checking battery time
The pump-hall inspection mission has five waypoints in the local frame (north, east, height). The last climbs to inspect the crane rail at 8 m, then the drone returns to the start. There are 10 photo stops of 20 seconds each, cruise speed is 1.0 m/s, and the battery hovers indoors for 14 minutes with a 30% reserve (EKF origin and all values assumed).
# waypoints in the local frame (north, east, up from the EKF origin) to latitude/longitude (origin assumed)
LAT0, LON0, R_E = 14.000000, 100.600000, 6378137.0
wps = [(0.0, 0.0, 3.0), (2.0, 14.0, 3.0), (2.0, 44.0, 3.0), (16.0, 46.0, 3.0), (18.0, 23.0, 8.0)]
for n_m, e_m, up in wps:
lat = LAT0 + math.degrees(n_m / R_E)
lon = LON0 + math.degrees(e_m / (R_E * math.cos(math.radians(LAT0))))
print(f"N {n_m:4.1f} E {e_m:4.1f} -> {lat:.7f}, {lon:.7f}, {up:.0f} m")
# does the inspection mission fit the battery? (assumed values)
legs = wps + [wps[0]] # fly the waypoints, then back to the start
route_m = sum(math.dist(a, b) for a, b in zip(legs, legs[1:]))
speed, stops, hover_s = 1.0, 10, 20 # cruise speed (m/s), inspection stops, seconds per stop
endurance_min, reserve = 14.0, 0.30
t_min = (route_m / speed + stops * hover_s) / 60
print(f"route {route_m:.1f} m, mission {t_min:.1f} min, allowed {endurance_min * (1 - reserve):.1f} min -> "
f"{'go' if t_min <= endurance_min * (1 - reserve) else 'split the mission'}")
N 0.0 E 0.0 -> 14.0000000, 100.6000000, 3 m
N 2.0 E 14.0 -> 14.0000180, 100.6001296, 3 m
N 2.0 E 44.0 -> 14.0000180, 100.6004074, 3 m
N 16.0 E 46.0 -> 14.0001437, 100.6004259, 3 m
N 18.0 E 23.0 -> 14.0001617, 100.6002129, 8 m
route 111.5 m, mission 5.2 min, allowed 9.8 min -> go
Every 2 m north adds 0.000018° of latitude, so at least seven decimal places must be kept, or waypoints shift by metres. The 111.5 m mission takes 5.2 minutes, under the allowed 9.8, so one flight is enough. Recompute whenever inspection points are added, because hovering for photos often takes longer than travelling: here 200 of 311.5 seconds.
Indoor mission safety settings must suit the ceiling and walls (ArduPilot Dev Team, n.d.).
- Failsafe actions: Land, or Brake then Land, instead of RTL.
FENCE_ACTION, for example, offers 2 (Always Land) and 4 (Brake or Land). - EKF failsafe:
FS_EKF_ACTION= 1 lands if the current mode needs position, or 3 lands from all modes;FS_EKF_THRESHdefaults to 0.8 and can be set to 0.6 for a stricter check. - Virtual fences: use a polygon inclusion fence to stay inside the building and exclusion zones around machinery. Note that
FENCE_ALT_MAXhas a documented range of 10 to 1000 m, so it cannot act as a roof guard in the pump hall, whose ceiling is only 10 m high; the route and an upward rangefinder must do that job. - Emergency switches: set
RCx_OPTION= 31 (Motor Emergency Stop) and the avoidance switch (40) within the pilot’s immediate reach.
Testing in stages
An indoor autonomous system should never be tested for the first time on a real mission. Good testing raises the risk one step at a time, and each step has measurable acceptance criteria: pass, then move up; fail, then go back and fix.
| Stage | What is tested | Acceptance criteria (examples for this case) |
|---|---|---|
| 1 Bench and walk test | Frames, source switching | Closure within 1% of distance; EKF healthy for 10 s after switching (module 2) |
| 2 SITL | Mission, failsafes, fences | Every failsafe case lands as configured; no climb in any case |
| 3 Netted cage, manual modes | Indoor stability | As PX4 card MC_05: no oscillation, no bounce on landing |
| 4 Hold and box crossing | Altitude and position hold | R95 ≤ 0.5 m; no rising and falling over boxes (module 4) |
| 5 Soft obstacles | Stopping | Stops before the set distance every time, at every speed tested |
| 6 Slow mission | Route, return | Reaches every waypoint; no unnecessary avoidance braking |
| 7 Full mission | Whole system with crew | Follows the operating procedure; no safety occurrence |
The SITL stage runs the real autopilot software on a computer with a simulated vehicle (ArduPilot Dev Team, n.d.; PX4 Autopilot, n.d.), which suits events too dangerous to try for real, such as losing the position source mid-mission. Stages 3 and 4 can use PX4’s test cards as templates. Cards MC_06 (optical flow) and MC_09 (VIO) disable all other position sources, test Altitude and Position modes and landing, and expect position to be held within 1 m without oscillation. Every stage needs a recorded test card: objective, firmware version and parameter file, map version, preconditions, steps, expected result, actual result, pass or fail, and the log number.
How many test flights are enough?
If 20 test flights all pass, does that mean the system never fails? No. Statistics can only say the true failure rate is “unlikely to be higher than” some value. Hanley and Lippman-Hand (1983) give the rule of three: with no events in trials, the upper limit of the 95% confidence interval for the rate is about . The exact value comes from the method of Clopper and Pearson (1934), which for zero failures reduces to .
Example 3 Twenty passes: what do they prove?
from scipy.stats import beta
# how much do n successful test flights prove? one-sided 95% upper bound on the failure rate
for n, k in ((10, 0), (20, 0), (30, 0), (30, 1), (59, 0)):
upper = beta.ppf(0.95, k + 1, n - k) # Clopper-Pearson
rule3 = f", rule of three {3 / n:.3f}" if k == 0 else ""
print(f"{k} failure(s) in {n:2d} flights: upper bound {upper:.3f}{rule3}")
n = math.ceil(math.log(0.05) / math.log(0.95))
print(f"flights needed with no failure to show a rate below 5%: {n}")
0 failure(s) in 10 flights: upper bound 0.259, rule of three 0.300
0 failure(s) in 20 flights: upper bound 0.139, rule of three 0.150
0 failure(s) in 30 flights: upper bound 0.095, rule of three 0.100
1 failure(s) in 30 flights: upper bound 0.149
0 failure(s) in 59 flights: upper bound 0.050, rule of three 0.051
flights needed with no failure to show a rate below 5%: 59
Twenty passes only show that the failure rate per flight is unlikely to exceed 13.9%, which is still very high for work in a building with people in it. To claim a rate below 5% takes at least 59 consecutive passes, and one failure in 30 flights raises the bound to 14.9%. The practical conclusion is not to rely on passed test flights alone as evidence of safety; other layers are needed too: keeping people out from under the flight path, tested failsafes and a pilot ready to take over.
Simulation: what it can and cannot prove
Real flights are few and costly, and Example 3 showed how little a handful of passes proves. A simulator can run a case thousands of times, including the cases too dangerous to fly, such as losing the position source or a stalled estimator. There are three common set-ups. In software in the loop (SITL) the autopilot code is built to run on an ordinary computer and takes its sensor data from a simulated vehicle; ArduPilot’s SITL has a built-in physics model for each vehicle and can swap it for an external simulator such as Gazebo, Webots or a script (ArduPilot Dev Team, n.d.). PX4 with Gazebo adds simulated sensors, among them a 2D LiDAR, a depth camera and vision odometry (PX4 Autopilot, n.d.). In hardware in the loop (HITL) the normal PX4 firmware runs on the real flight controller while a simulator supplies the sensors; it exercises the real hardware, but SITL runs more of the standard system code (PX4 Autopilot, n.d.).
A simulator holds only what someone modelled. The difference between the simulated and the real world, the sim-to-real gap, degrades whatever was tuned or tested in simulation once it meets a real vehicle (Zhao et al., 2020). Glass, haze, a shiny floor, recirculating air and magnetic interference (modules 1, 4 and 8) are absent unless someone adds them. A simulator is therefore trusted for a class of test only after it reproduces real logs: fit its unknowns on one flight, then check it on a different one, in the range where it will be used.
Example 4 Fitting a simulator and checking it on another flight
Two hold-test flights are logged at 10 Hz, a 2 m step and a 4 m step. Here they are generated stand-ins with values the team does not know (delay 0.15 s, attitude lag 0.12 s, a 3 m/s² acceleration limit) plus 1 cm of noise. The simulator is the loop of module 4 Example 5 with the PX4 default gains. The team fits the delay and lag on the 2 m step and accepts the simulator only if its error on the 4 m step stays under 5 cm (assumed criterion). Then it injects a late estimate into the accepted model.
import numpy as np
# fit a simulator to a logged step, then check it on a different step (the logged flights here are generated stand-ins)
def sim(delay, tau_a, target, acc_max=1e9, kp=0.95, kv=1.8, dt=0.01, t_end=12.0):
n, lag = int(t_end / dt), int(round(delay / dt))
x, v, a = np.zeros(n + 1), np.zeros(n + 1), 0.0
for i in range(n):
j = max(i - lag, 0) # the controller sees the state from `delay` seconds ago
v_sp = max(-12.0, min(12.0, kp * (target - x[j]))) # PX4 default position gain
a_cmd = max(-acc_max, min(acc_max, kv * (v_sp - v[j]))) # velocity loop with an acceleration limit
a += (a_cmd - a) / tau_a * dt # attitude and thrust lag
v[i + 1] = v[i] + a * dt
x[i + 1] = x[i] + v[i + 1] * dt
return x[::10] # 10 Hz, like the log
def flown(target, seed): # true values are unknown to the team
return sim(0.15, 0.12, target, acc_max=3.0) + np.random.default_rng(seed).normal(0, 0.01, 121)
rmse = lambda a, b: float(np.sqrt(np.mean((a - b) ** 2)))
log2, log4 = flown(2.0, 1), flown(4.0, 2)
def fit(acc_max): # search the delay and lag that best match the 2 m step
return min((rmse(sim(d, t, 2.0, acc_max), log2), d, t) for d in np.arange(0.0, 0.31, 0.01) for t in np.arange(0.05, 0.26, 0.01))
print(f"nominal model: RMSE {rmse(sim(0.0, 0.10, 2.0), log2) * 100:.1f} cm on the 2 m step")
for label, acc in (("no acceleration limit", 1e9), ("limit 3 m/s2", 3.0)):
err, d, t = fit(acc)
check = rmse(sim(d, t, 4.0, acc), log4)
print(f"fitted, {label}: delay {d:.2f} s, lag {t:.2f} s, RMSE {err * 100:.1f} cm on 2 m")
print(f" held-out 4 m step: RMSE {check * 100:.1f} cm -> {'accept' if check <= 0.05 else 'reject'} (limit 5 cm)")
for fault in (0.3, 0.6): # injected estimator delay, calibrated model
x = sim(fault, t, 2.0, 3.0)
print(f"fault, estimator delay {fault:.1f} s: peak {x.max():.2f} m, swing in the last 3 s {x[-30:].max() - x[-30:].min():.2f} m")
nominal model: RMSE 7.6 cm on the 2 m step
fitted, no acceleration limit: delay 0.12 s, lag 0.14 s, RMSE 0.9 cm on 2 m
held-out 4 m step: RMSE 25.1 cm -> reject (limit 5 cm)
fitted, limit 3 m/s2: delay 0.15 s, lag 0.12 s, RMSE 0.9 cm on 2 m
held-out 4 m step: RMSE 1.0 cm -> accept (limit 5 cm)
fault, estimator delay 0.3 s: peak 2.43 m, swing in the last 3 s 0.01 m
fault, estimator delay 0.6 s: peak 4.38 m, swing in the last 3 s 4.14 m
The model without an acceleration limit matches the 2 m step to 0.9 cm, yet misses the 4 m step by 25.1 cm, because the large step saturates the acceleration, which this model cannot do; a good fit on one flight proves nothing about another. Adding the autopilot’s known acceleration limit repairs the structure, and the same fit then passes the 4 m check at 1.0 cm. Only now is the model used for the fault: a 0.3 s delay is harmless, but a 0.6 s stall of the estimate starts a swing of 4.1 m that does not die away. That is the case to run in SITL with the failsafes configured, and never to try in the hall. The simulation shows where a failsafe must act; how likely such a stall is in the real building still needs the stage-by-stage real tests.
Safety in indoor mission operations
A safety management system under ICAO Doc 9859 centres on identifying hazards, assessing risk and learning continuously from occurrences (International Civil Aviation Organization, 2018). For indoor missions the team should have at least:
- Clear roles: a pilot in command ready to take over in a mode that does not need position, an observer who keeps the drone in sight throughout, and an area controller who liaises with the plant and keeps people clear
- A pre-flight checklist: firmware and parameter file match what was tested, map version, floor reference mark within tolerance, source set in use, emergency switches working, large doors and fans in the agreed state, permit to work signed
- Batteries: charged and stored where the plant allows, in fire-resistant containers, never charging unattended
- A review after every flight: download the log, check R95, source switches and avoidance events, record near misses and feed them back into the procedure
Module lab
Lab: plan and test an indoor inspection mission
- From the map tied to the plan in module 3, build a grid for the flight layer, inflate obstacles by the aircraft size and the stopping distance from module 4, and plan the route with the code in Example 1.
- Define at least 8 inspection points, convert them to waypoints with the code in Example 2 and check the battery time.
- Configure failsafes, fences and emergency switches as described in the route-to-mission section, then test in SITL, including loss of the position source mid-mission.
- Write test cards for stages 1 to 6 with acceptance criteria and test in order as far as space and time allow, under the instructor’s supervision.
- Count the passed flights in stage 6, compute the upper bound on the failure rate with the code in Example 3, and state the limits of this evidence.
- Prepare the mini-project report: zone table, source configuration, map and plan tie, hover results, route, test cards and operating procedure.
Common mistakes
Watch out
- Planning without inflating obstacles, so the shortest route grazes everything.
- Inflating less than the avoidance stopping distance, so the drone brakes all the way.
- Keeping too few decimal places of latitude and longitude, so waypoints shift by metres.
- Assuming a maximum-altitude fence protects every roof, although its minimum is 10 m.
- Skipping test stages, such as going straight from SITL to a real mission.
- Claiming safety because 20 test flights passed, when the upper bound is still about 14%.
- Trusting a simulator fitted to one flight, without checking it on a different flight in the range where it will be used
Summary
- Path planning has three layers: global planner, local avoidance and path follower. Plan in height layers on the map tied to the building plan.
- A* expands the node with the lowest ; obstacles must be inflated by the aircraft radius plus a margin, which may close narrow gaps and lengthen the route a little.
- Convert local waypoints to latitude and longitude relative to the EKF origin, and check mission time against the battery after the reserve.
- Indoors, set failsafes to Land or Brake then Land, and test in stages with acceptance criteria and test cards.
- Passing tests shows only that the failure rate is unlikely to exceed ; other layers of protection are always needed.
- A simulator is trusted for a class of test only after it reproduces real logs on a flight it was not fitted to; use it for cases too dangerous to fly, not as a replacement for staged real tests
Check your understanding
- Forty test flights with no failure: what is the 95% upper bound on the failure rate, and how does it compare with the rule of three?
- Aircraft radius 0.45 m, margin 0.55 m, grid 0.5 m: by how many cells must obstacles be inflated, and is a 1.5 m gap still passable?
- A 120 m route at 1.0 m/s with 12 photo stops of 20 seconds each, a 14-minute battery and a 30% reserve: can it be done in one flight?
- Why should
FENCE_ACTIONnot use an option containing RTL indoors, and which option should be used? - A waypoint is 10 m north of the EKF origin. How much does its latitude differ from the origin’s?
Answers
- (7.2%); the rule of three gives , very close
- cells. The gap would need to be at least 2.0 m for the centre to pass, so the 1.5 m gap is closed
- minutes against allowed, so yes
- RTL climbs to
RTL_ALT_Mbefore returning, which indoors risks hitting the roof, and there may be no safe way back; use 2 (Always Land) or 4 (Brake or Land) - rad
Key formulas
| A* cost | |
| Local coordinates to latitude and longitude (short range) | |
| 95% upper bound when all n tests pass |
Key references
- Elfes, A. (1989). Using occupancy grids for mobile robot perception and navigation. Computer, 22(6), 46–57. link
- 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
- LaValle, S. M. (2006). Planning algorithms. Cambridge University Press. link
- ArduPilot Dev Team. Non-GPS navigation. ArduPilot Copter documentation. link
- ArduPilot Dev Team. Parameter list (Copter stable V4.7.1). ArduPilot Copter documentation. link
- ArduPilot Dev Team. SITL simulator (software in the loop). link
- PX4 Autopilot. Gazebo simulation. PX4 user guide (main). link
- PX4 Autopilot. Test MC_06: Optical flow (inside). PX4 guide (main). link
- PX4 Autopilot. Test MC_09: VIO (visual-inertial odometry). PX4 guide (main). link
- Hanley, J. A., & Lippman-Hand, A. (1983). If nothing goes wrong, is everything all right? Interpreting zero numerators. JAMA, 249(13), 1743–1745. 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
- International Civil Aviation Organization. (2018). Safety management manual (Doc 9859, 4th ed.). link
- PX4 Autopilot. Hardware in the loop simulation (HITL). PX4 user guide (main). link
- Zhao, W., Queralta, J. P., & Westerlund, T. (2020). Sim-to-real transfer in deep reinforcement learning for robotics: A survey. In 2020 IEEE Symposium Series on Computational Intelligence (SSCI) (pp. 737-744). IEEE. link
Further reading
Study the assigned knowledge units in advance, review media and take the module quiz
การวางแผนเส้นทางและหลบหลีกสิ่งกีดขวางอัตโนมัติ
Developing simulations and connecting SITL
ระบบบริหารความปลอดภัย (SMS)
In class / field
Lab or field practice from worksheets with a safety checklist
Learning evidence: Checked worksheets and quiz results