Teaching a machine to fly¶
A machine that knows nothing about aeroplanes learns to fly one: take off, fly a circuit round the airfield, and land, in random winds, on a flight simulator it has never seen inside.
This notebook is the short version of the whole project, in three parts. Each part is an engineering lesson, not a stage of the flight:
- The learner needs a world to practise in. Measure what you have before building around it.
- The score is the specification. The learner does what you reward, not what you meant.
- Learned parts have to be put together, and tested honestly.
Each part also mentions a few blind alleys: things that seemed reasonable and weren't. The full story, with every step,
is in seven longer notebooks, learning_to_fly_1.ipynb to learning_to_fly_7.ipynb, kept alongside this one.
The whole notebook runs in a few minutes, on the simulator's physics running locally. The long training runs are loaded from their saved results; one short one runs live.
Setup¶
%matplotlib inline
import inspect, json, time
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import Code, HTML, display, clear_output
import circuit as C, compare_landing as cl, compare_takeoff, landing_pilot as lp, pilot, takeoff_pilot as tp, viz
from localsim import COL, FIELDS, LocalSim, Pool
from recorder import TICK
def show(obj):
# print a function from the project's own code
display(Code(inspect.getsource(obj), language="python"))
pool = Pool() # many copies of the simulator, one per CPU thread
Part 1: the learner needs a world to practise in¶
The simulator, and what a pilot is told¶
The simulator is BigSkySim, a browser-based simulator of a small airfield with a Cessna-like plane. It has an HTTP API for flying the plane from a program, and the API tells a pilot what a pilot would know: the instruments, rounded like real gauges, and word-pictures of what you'd see out of the window. Here is one reading, on the runway before take-off:
sim = LocalSim(seed=1)
cs = sim.spawn()
reading = sim.read(cs)
sim.close()
print(json.dumps(reading["instruments"], indent=1)[:900])
print("out of the window:", json.dumps(reading["visual"])[:300])
print("position report: ", reading["position"]["report"])
{
"airspeed_kt": 0,
"altitude_ft": 0,
"vertical_speed_fpm": 0,
"heading_deg": 270,
"bank_deg": 0,
"pitch_deg": 0,
"turn_rate": 0,
"slip_ball": 0,
"rpm": 650,
"flaps_deg": 0,
"stall_warning": false
}
out of the window: {"papi": "not visible", "centreline": {"position": "on", "offset_m": 0}, "drift": "none", "runway_ahead_m": 1000, "threshold_off_nose_deg": null, "wheel_height_ft": 0, "surface": "runway", "taxi_speed": "stopped", "runway": "clear", "windsock": {"from_deg": 240, "strength": "moderate", "about_kt": 1
position report: runway, at the runway 27 threshold
A program can ask for those, set the controls (elevator, aileron, rudder, throttle, brakes, flaps, trim), and step the clock a quarter of a second at a time. That's all a pilot gets. Nothing says where the plane is to the metre, or how the aircraft's physics works.
The learner¶
The learner is the same one that learned to drive a race car in the first project: neuroevolution. Each pilot is a tiny neural network, a few hundred numbers (weights) that turn what it senses into control positions:
show(tp.think)
print("weights in a take-off pilot:", tp.N_WEIGHTS)
def think(genomes, inputs):
"""genomes (planes, N_WEIGHTS), inputs (planes, 8) -> controls (planes, 4): elevator,
aileron, rudder, throttle (always 100)."""
w1, b1, w2, b2 = _unpack(genomes)
hidden = np.tanh(np.einsum("pi,pih->ph", inputs, w1) + b1)
out = np.tanh(np.einsum("ph,pho->po", hidden, w2) + b2)
return np.column_stack([50 * out[:, 0], 40 * out[:, 1], 80 * out[:, 2], np.full(len(out), 100.0)])
weights in a take-off pilot: 99
A thousand pilots with random weights each fly the same few situations, and get a score. The best are kept, and mutated copies of good ones (their weights plus a little random noise) fill the rest of the next generation. Nothing in this knows anything about flying. Everything about what flying well means is in the score.
show(pilot.next_generation)
def next_generation(genomes, fitness, rng, keep=0.05, parents=0.20, mutation=0.1):
"""The same breeding as the car: keep the top 5%, children of the top 20% with noise."""
n = len(genomes)
ranked = np.argsort(-fitness)
n_keep, n_parents = max(1, int(n * keep)), max(1, int(n * parents))
survivors = genomes[ranked[:n_keep]]
chosen = ranked[rng.integers(0, n_parents, size=n - n_keep)]
children = genomes[chosen] + rng.normal(0.0, mutation, size=(n - n_keep, genomes.shape[1]))
return np.vstack([survivors, children])
Blind alley: a stand-in for the simulator¶
Evolution needs a lot of practice: a thousand pilots, a dozen situations each, a minute or two of flying each, a hundred generations. That's thousands of hours of flying. The simulator runs in a browser, answering over HTTP, and the first measurement was 65 ms per request: about real time.
So the first plan was a stand-in: record 15 minutes of deliberately wobbly flying, fit a simple model that predicts the next quarter of a second from the last second (a linear model, fitted in milliseconds), and evolve pilots on the model instead. It worked, within limits. The stand-in stayed within a few knots and degrees for tens of seconds, and pilots evolved on it flew the real plane well at the first attempt.
But it had a cost, which only showed up later. A pilot trained on the real physics, with the same brain, the same score and the same number of generations, flew about 5 points better, and was never worse in any of 191 test situations. Part of the stand-in pilot's skill had gone into flying the stand-in's mistakes. (Parts 2 and 3 of the full story.)
Measure before deciding¶
What changed was a closer measurement. Of those 65 ms, almost all was the network and the browser relaying the request. The physics itself took microseconds. BigSkySim's simulation core is plain JavaScript, so it can run outside the browser in Node, as many separate worlds at once, one process per CPU thread. Here is one generation of take-off practice:
rng = np.random.default_rng(1)
genomes = tp.random_genomes(1000, rng)
starts = tp.make_starts(12, rng)
t0 = time.time()
fitness = tp.trial(genomes, pool, starts)
took = time.time() - t0
hours = len(genomes) * len(starts) * tp.TRIAL_SECONDS / 3600
print(f"{len(genomes) * len(starts):,} take-offs, {hours:.0f} hours of flying, in {took:.1f} s "
f"({hours * 3600 / took:,.0f}x real time)")
12,000 take-offs, 300 hours of flying, in 4.5 s (240,843x real time)
The stand-in was a sensible answer to the question as first measured, and the wrong answer to the real one.
Determinism¶
One more property of the local simulator turns out to be worth a lot: it's deterministic. The same seed and the same controls give exactly the same flight, every time. So a training run can be repeated exactly. The champion take-off pilot was trained for 100 generations; running the first 25 again, live, here, gives the same scores, generation by generation (about 2 minutes):
saved = np.load("data/takeoff_history.npy") # best and median score of each generation, from the real run
best, med = [], []
def watch(gen, fitness, genomes):
best.append(fitness.max()); med.append(np.median(fitness))
if gen % 5 == 4:
clear_output(wait=True)
fig, ax = plt.subplots(figsize=(8, 3.2))
ax.plot(saved[:, 0], color="0.8", lw=4, label="saved run: best"); ax.plot(saved[:, 1], color="0.8", lw=4, ls=":")
ax.plot(best, color="C0", label="live: best"); ax.plot(med, color="C0", ls=":", label="live: median")
ax.set_xlabel("generation"); ax.set_ylabel("take-off score"); ax.set_ylim(-5, 70); ax.grid(alpha=0.3); ax.legend()
plt.show()
held_out = tp.make_starts(100, np.random.default_rng(99))
t0 = time.time()
tp.evolve(pool, held_out, 25, np.random.default_rng(1), on_generation=watch)
print(f"{time.time() - t0:.0f} s; same scores as the saved run, every generation: {np.allclose(best, saved[:25, 0]) and np.allclose(med, saved[:25, 1])}")
123 s; same scores as the saved run, every generation: True
In about 20 generations, a thousand random brains turn into pilots that take off: brakes off, keep straight with the rudder while the wind pushes the nose round, lift off at the right speed, and climb without stalling.
Determinism also means any moment of any flight can be replayed exactly, from a seed and a short list of control changes. That gets used in Part 3.
Part 2: the score is the specification¶
Every pilot in this project was told only one thing: its score. Here is the take-off pilot's, for each quarter-second:
show(tp.points)
print("rules (break one and the trial ends):", tp.LIMITS, "on the ground:", tp.GROUND_LIMITS)
def points(r, centreline=True, ball=True):
"""Score for one tick, 0..1. Mostly for height (full marks from 500 ft), a little for
speed on the way (so a pilot that keeps it on the runway and accelerates is already
better than one that runs onto the grass), all of it only while pointing along the
runway: falling to nothing 30 degrees off. With centreline=True, on the ground it also
falls off with distance from the centreline: nothing at the runway edge, 15 m out. With
ball=True, in the air it falls off as the slip ball leaves the middle (half at 1.5 ball
widths): fly straight through the air, not sideways."""
c = lambda name: r[:, COL[name]]
speed = np.clip(np.nan_to_num(c("airspeed_kt")) / 55, 0, 1)
height = np.clip(np.nan_to_num(c("altitude_ft")) / TARGET_FT, 0, 1)
hdg_ok = np.clip(1 - np.abs(wrap(RUNWAY_HDG - np.nan_to_num(c("heading_deg")))) / 30, 0, 1)
p = hdg_ok * (0.3 * speed + 0.7 * height)
if centreline:
on_ground = c("on_ground") == 1
line_ok = np.clip(1 - np.abs(np.nan_to_num(c("xtrack_m"))) / 15, 0, 1)
p = np.where(on_ground, p * line_ok, p)
if ball:
in_air = c("on_ground") == 0
ball_ok = np.clip(1 - np.abs(np.nan_to_num(c("slip_ball"))) / 3, 0, 1)
p = np.where(in_air, p * ball_ok, p)
return p
rules (break one and the trial ends): {'bank_deg': (-30, 30), 'pitch_deg': (-5, 15), 'stall_warning': (0, 0)} on the ground: {'xtrack_m': (-10, 10)}
It didn't start like that. Each line is there because a champion found a way to score well that wasn't what we meant. The same thing happened at every stage:
| the champion... | because the score... | fixed with |
|---|---|---|
| held height and heading by banging the controls end to end | only said where to be | points for smoothness |
| flew right along the edge of the region the stand-in was trusted in | ended the trial there | (went with the stand-in) |
| banked 55° to turn faster, on the real physics | didn't forbid it | a rule: "normal flying", bank within 45° |
| took off rolling 8 m off the centreline | didn't mention the centreline | a rule (10 m) and points for staying central |
| climbed with the rudder held hard over, the slip ball out | didn't mention the ball | points for a centred ball |
| landed hands-off at 350 ft/min and survived | only asked for a landing | points for a soft touchdown |
| stood on the brakes with full power after landing | paid for a short roll, not how | a rule: no power on the runway |
Two of them, side by side. First the take-off: where the first champion and the final one were at lift-off, in 200 winds none of them trained on:
exam = tp.make_starts(200, np.random.default_rng(2024))
brains = np.array([np.load("brains/takeoff_first.npy"), np.load("brains/takeoff.npy")])
_, ex = tp.trial(brains, pool, exam, trace=True, per_start=True, ground_limits=None)
S = len(exam)
def liftoff_offset(k):
r, alive = ex["readings"][:, k * S:(k + 1) * S], ex["alive"][:, k * S:(k + 1) * S]
ground = (r[:, :, COL["on_ground"]] == 1) & alive
return np.array([r[np.flatnonzero(ground[:, j])[-1], j, COL["xtrack_m"]] for j in range(S)])
fig, ax = plt.subplots(figsize=(8, 3))
for k, (name, col) in enumerate((("first champion", "C3"), ("final champion", "C2"))):
ax.hist(liftoff_offset(k), bins=np.arange(-15, 15.5, 1), alpha=0.6, color=col, label=name)
ax.axvline(0, color="k", lw=1); ax.set_xlabel("metres right of the centreline at lift-off"); ax.set_ylabel("take-offs")
ax.legend(); ax.grid(alpha=0.3); plt.show()
Nothing said "stay on the centreline", so it didn't, not exactly. It had found the side of the runway where the wind's push on the nose was easiest to hold.
And after landing, the first landing champion against the final one, in the same wind: speed, throttle and brake from the moment the wheels touch:
lexam = cl.EXAM() # 200 approaches and winds no landing pilot trained on
def fly_landings(genomes, starts, **rules):
_, tr = lp.trial(np.atleast_2d(genomes), pool, starts, trace=True, per_start=True, **rules)
return tr
first_tr = fly_landings(np.load("brains/landing_first.npy"), lexam, rollout=False)
final_tr = fly_landings(np.load("brains/landing_level.npy"), lexam)
xw = np.array([tp.crosswind(s["env"]) for s in lexam])
k = int(np.argmin(np.abs(xw))) # the calmest crosswind in the exam
def after_touchdown(tr, j, seconds=20):
r, c = tr["readings"], tr["controls"]
t0 = int(np.flatnonzero(r[:, j, COL["on_ground"]] == 1)[0])
i = np.arange(t0, min(t0 + int(seconds / TICK), len(c)))
speed = np.diff(r[:, j, COL["along_m"]])[i - 1] / TICK / 0.5144 # over the ground, kt
return (i - t0) * TICK, speed, c[i, j, 3], c[i, j, 4]
fig, axs = plt.subplots(1, 2, figsize=(12, 3.2), sharey=True)
for ax, tr, name in zip(axs, (first_tr, final_tr), ("first champion", "final champion")):
t, speed, thr, brk = after_touchdown(tr, k)
ax.plot(t, speed, label="speed (kt)"); ax.plot(t, thr, label="throttle (%)"); ax.plot(t, brk, label="brake (%)")
ax.set_title(name); ax.set_xlabel("seconds since touchdown"); ax.grid(alpha=0.3)
axs[0].legend(fontsize=8); plt.tight_layout(); plt.show()
The first champion was paid for stopping, so it stopped: brakes full on and throttle wide open at the same time, which the simulator's physics doesn't punish. "Stop" was what we said; "stop the way a pilot would" was what we meant.
Rules and points do different jobs¶
Two kinds of fix appear in that table, and they behave differently:
- Points say what's better. They change outcomes: the short-roll points halved the landing roll.
- Rules say what's unacceptable, and end the trial. They change habits: only a rule got rid of "slow down → full power".
But a rule needs a slope, not a cliff. The first version of the no-power rule was all-or-nothing: break it once and score nothing. Evolution, starting from random brains, never found a pilot that could stop without breaking it, so every pilot scored about the same, there was no direction to improve in, and it gave up on stopping altogether. Partial credit for slowing down, and starting from a pilot that could already land, fixed it:
h_cliff, h_slope = np.load("data/landing_cliff_history.npy"), np.load("data/landing_throttle_history.npy")
fig, ax = plt.subplots(figsize=(8, 3))
ax.plot(h_cliff[:, 0], color="C7", label="rule as a cliff, from nothing: best")
ax.plot(h_slope[:, 0], color="C4", label="rule as a slope, fine-tuning: best")
ax.set_xlabel("generation"); ax.set_ylabel("training score"); ax.grid(alpha=0.3); ax.legend(fontsize=8); plt.show()
What it worked out for itself¶
The score's loopholes are one side of this. The other side is what the learner finds that nobody told it. The landing pilot's score says soft touchdowns score more; it doesn't say how. Here is the sink rate at each height above the runway, for a plane left hands-off on the approach settings and for the final landing pilot:
real_think = lp.think
lp.think = cl.hands_off # the approach settings, and nothing else
try:
hands = fly_landings(np.zeros(lp.N_WEIGHTS), lexam)
finally:
lp.think = real_think
def sink_by_height(tr):
r, alive = tr["readings"], tr["alive"]
wh, vs = r[:, :, COL["wheel_height_ft"]], r[:, :, COL["vertical_speed_fpm"]]
air = (r[:, :, COL["on_ground"]] == 0) & alive & ~np.isnan(wh)
hs = np.array(sorted(set(wh[air].tolist())))
return hs, np.array([np.median(vs[air & (wh == h)]) for h in hs])
fig, ax = plt.subplots(figsize=(8, 3.2))
for tr, name, col in ((hands, "hands-off", "C0"), (final_tr, "final landing pilot", "C2")):
hs, v = sink_by_height(tr)
ax.plot(hs, v, "o-", color=col, label=name)
ax.set_xlabel("height of the wheels above the runway, as the pilot sees it (ft)"); ax.set_ylabel("median vertical speed (ft/min)")
ax.set_xlim(0, 60); ax.grid(alpha=0.3); ax.legend(); plt.show()
It flares: in the last few feet it eases the sink rate off to almost nothing, the way a pilot is taught. Nobody wrote that down. In the same way, the take-off pilot was never told about crosswinds; it just met a lot of them in practice. In crosswinds of 10–15 kt the hand-written take-off script reached 500 ft 6% of the time, and the evolved pilot 100%.
Watch one landing: the side view above, the view from above below.
j = int(np.argmax(np.abs(xw))) # the strongest crosswind in the exam
r = final_tr["readings"][:, j]
e = lexam[j]["env"]
HTML(viz.approach_player([dict(name="final landing pilot", color="#2ca02c", along=r[:, COL["along_m"]], xtrack=r[:, COL["xtrack_m"]],
height=r[:, COL["altitude_ft"]], speed=r[:, COL["airspeed_kt"]], vs=r[:, COL["vertical_speed_fpm"]])],
TICK, title=f"wind {e['wind_from_deg']:.0f}° at {e['wind_kt']:.0f} kt, gusting {e['gust_kt']:.0f} kt more "
f"(crosswind {xw[j]:+.0f} kt)"))
Part 3: putting learned parts together, and testing honestly¶
Three pilots and a navigator¶
There are three evolved pilots, each good at one job: take off to 500 ft; hold a height and a heading it's given; land from a mile out. A whole flight needs all three, and something to tell them what to do: a navigator, a few hand-written lines that know the shape of a circuit (the rectangle round the airfield every training flight flies), give the cruise pilot a heading and height for each leg, and decide when one pilot hands over to the next. This is how most real autopilots are built too: separate modes, and logic that switches between them.
200 whole flights, in 200 random winds:
takeoff, cruise, landing = (np.load(f"brains/{b}.npy") for b in ("takeoff", "onsim_normal", "landing_level"))
flights = tp.make_starts(200, np.random.default_rng(2024))
t0 = time.time()
f = C.fly(takeoff, cruise, landing, pool, flights, reckon=True, cues=True)
print(f"{time.time() - t0:.0f} s")
C.describe(f)
3 s stopped on the runway: 199/200 flights that ended early, by leg: landing 1 crashes: hit the ground at 3160 fpm x1 at handover (200): 97 kt (91..100), +9 ft above the slope (-19..+40), 20 m off the line touchdown (199): 140 m in, 0.8 m off the line, 50 fpm landing roll median 162 m; whole flight median 8.4 min
def circuit_tracks(f, ks, colors):
r = f["readings"]
return [dict(name=f"flight {k}", color=c, why=str(f["why"][k]), leg=f["leg"][:, k],
along=np.where(f["alive"][:, k], r[:, k, COL["along_m"]], np.nan), xtrack=r[:, k, COL["xtrack_m"]],
speed=r[:, k, COL["airspeed_kt"]], height=r[:, k, COL["altitude_ft"]]) for k, c in zip(ks, colors)]
xw_c = np.array([tp.crosswind(s["env"]) for s in flights])
pick = [int(np.argmin(np.abs(xw_c))), int(np.argmax(xw_c)), int(np.argmin(xw_c))]
HTML(viz.circuit_player(circuit_tracks(f, pick, ["#2ca02c", "#d62728", "#1f77b4"]), TICK, C.LEGS,
title="three whole flights: the calmest, the strongest crosswinds from the right and from the left"))
Getting here took two blind alleys, and both are about the same thing: a learned skill only works on the kind of situation it learned on.
Asking for a 90° turn all at once. The first navigator set the new heading in one go at each corner. The cruise pilot had learned to turn onto headings up to about 120° away, but from level flight in wobbly air; a sudden demand at a corner lost 16 flights in 200. Turning the requested heading gradually, 3° a second, the way an autopilot's heading bug moves, lost none.
Distribution shift at the handover. The landing pilot passed its own exam (197 of 200), and then failed one landing in six after a real circuit. The circuit hands it a different plane from the one it practised on:
h = f["handover"][~np.isnan(f["handover"][:, 0])]
practised = [s["air"]["speed_kt"] for s in lp.make_starts(1000, np.random.default_rng(1))]
fig, ax = plt.subplots(figsize=(8, 3))
ax.hist(practised, bins=np.arange(55, 105, 1), alpha=0.6, density=True, label="what the landing pilot first practised on")
ax.hist(h[:, COL["airspeed_kt"]], bins=np.arange(55, 105, 1), alpha=0.6, density=True, label="what the circuit hands it")
ax.set_xlabel("airspeed when the landing pilot takes over (kt)"); ax.set_yticks([]); ax.legend(fontsize=8); plt.show()
Faster, and coming down more steeply, than anything in its practice. The fix used determinism from Part 1: every handover in a few hundred circuits can be replayed exactly, as a seed and a short script of control changes, so the landing pilot was fine-tuned on half real handovers and half its usual approaches. Then 194 of 200 whole flights stopped on the runway, and it was better on its old exam too.
Only use what you'll really have¶
The navigator above doesn't know where the plane is. An earlier version did: it turned at exact positions, and the local simulator could tell it the plane's position to the metre. The real simulator's API never does. It gives the instruments, what you see, and a rough position report, like a pilot's radio call ("late downwind, 2.5 NM SE of the runway 27 threshold"). So the navigator now turns on cues a pilot is taught, all in that report:
show(C.report_turns)
def report_turns(leg, r):
"""The turns as a pilot makes them, from the position report and the view out of the window
(GET /position and /visual), with no position estimate at all:
crosswind the far end of the runway is 1 NM behind
downwind the report puts the plane south-west of the threshold (it's 45 degrees off the runway line)
base the threshold is at 7 o'clock or further behind (45 degrees behind the left wing) and at
least BASE_NM away: a tight downwind would otherwise leave too short a final
final the centreline, seen from base, is no longer "well" to the right but "moderately"."""
leg = leg.copy()
leg[(leg == UPWIND) & (r[:, COL["far_nm"]] >= 1.0)] = CROSSWIND
leg[(leg == CROSSWIND) & (r[:, COL["thr_is_deg"]] == 225)] = DOWNWIND
behind = np.isin(r[:, COL["thr_clock"]], (5, 6, 7))
leg[(leg == DOWNWIND) & behind & (r[:, COL["thr_nm"]] >= BASE_NM)] = BASE
leg[(leg == BASE) & (np.abs(r[:, COL["line_amount"]]) <= 2)] = FINAL # NaN (not in view) compares False
return leg
In between, it estimates where it is by dead reckoning (airspeed, heading, and the wind the windsock shows), pulled back inside whatever the position report, the centreline and the approach lights say. Its estimate against the truth, for one flight:
k = pick[0]
true_e, true_n = -f["readings"][:, k, COL["along_m"]], f["readings"][:, k, COL["xtrack_m"]]
bel_e, bel_n = -f["believed"][:, k, 0], f["believed"][:, k, 1]
alive = f["alive"][:, k] & (f["leg"][:, k] != C.STOPPED)
fig, ax = plt.subplots(figsize=(11, 4.2))
ax.plot([0, -1000], [0, 0], color="0.3", lw=6, solid_capstyle="butt", label="runway")
ax.plot(true_e[alive], true_n[alive], color="#2980b9", label="where it really was")
ax.plot(bel_e[alive], bel_n[alive], color="#e67e22", ls="--", label="where the navigator thought it was")
ax.set_aspect("equal"); ax.set_xlabel("m east of the threshold"); ax.set_ylabel("m north"); ax.legend(loc="lower left", fontsize=8)
plt.show()
print(f"furthest apart: {np.hypot(true_e - bel_e, true_n - bel_n)[alive].max():.0f} m")
furthest apart: 118 m
Flying by the report was as good as knowing the truth: on 500 new circuits, 489 stopped on the runway against 488.
The blind alley here was a real rule taken too literally. "Turn onto base when the runway threshold is 45° behind your left wing" is what pilots are taught. On its own it lost a third of the flights, because these circuits come out wider or narrower with the wind, and a narrow circuit turned base early and left a final too short to settle on. It needed a second condition: not before 2.5 NM out. A rule written for people quietly relies on the rest of what they know.
Testing honestly¶
The last improvement was to the landing: in gusts the wings rocked near the ground, and about one landing in a hundred ended with a wingtip on the runway. Two ideas, each a fine-tune of the landing pilot:
- a new sense, the roll rate (until then it saw the bank angle only as a snapshot rounded to 5°);
- new points, for keeping the wings level below 60 ft.
The first round of results, on 2,000 whole flights each, was confusing: the roll sense made things much worse, and switching the new sense off again didn't undo the damage. The cause was the test inside training. Each run picks its champion from its best 50 brains on 100 practice approaches. How often does a pilot that crashes 3% of the time look better than one that crashes 0.5% of the time, on 100 tries?
rng = np.random.default_rng(0)
bad, good = rng.binomial(100, 0.03, 100_000), rng.binomial(100, 0.005, 100_000)
print(f"on 100 tries: the 3% pilot crashes {np.median(bad):.0f} times, the 0.5% pilot {np.median(good):.0f} (medians)")
print(f"the 3% pilot looks as good or better {np.mean(bad <= good):.0%} of the time")
for n in (100, 1000):
b, g = rng.binomial(n, 0.03, 100_000), rng.binomial(n, 0.005, 100_000)
print(f" on {n:4d} tries: {np.mean(b <= g):.1%}")
on 100 tries: the 3% pilot crashes 3 times, the 0.5% pilot 0 (medians) the 3% pilot looks as good or better 13% of the time on 100 tries: 13.0% on 1000 tries: 0.0%
With 50 candidates, some bad ones are bound to look good on 100 tries, and the pick is partly luck. The fix was to judge on 1,000 approaches, and to keep the starting pilot as a candidate, so a fine-tune can't come back worse than it started.
And one more trap: having compared six brains on the same 2,000 circuits, picking the best of them on those circuits flatters the winner a little too. So the final comparison was made on 2,000 circuits none of them had been chosen on:
ev = json.load(open("data/landing_level_eval.json"))
print(f"{'':28s}{'lost in the landing':>20}{'rocky landings':>16} (rocky: banked 15° or more below 60 ft)")
for split, title in (("test", "the circuits used to choose"), ("fresh", "fresh circuits, used once")):
print(title)
for name, v in ev[split].items():
print(f" {name:26s}{v['landing_lost']:>14} / 2000{v['bank15']:>13.0f}%")
lost in the landing rocky landings (rocky: banked 15° or more below 60 ft) the circuits used to choose landing_circuit (before) 12 / 2000 47% roll sense, round 1 64 / 2000 62% level points, round 1 5 / 2000 34% both, round 1 93 / 2000 46% level points, round 2 10 / 2000 24% both, round 2 5 / 2000 53% fresh circuits, used once landing_circuit (before) 14 / 2000 49% level points, round 1 11 / 2000 32% level points, round 2 5 / 2000 24% both, round 2 8 / 2000 52%
The points for level wings worked: rocky landings halved, on both sets of circuits. The new sense didn't help, with or without the points; with this much evolution, it found no use for it. Ideas that sound obviously right still need the test.
The final exam: the real simulator¶
Everything so far ran on the simulator's physics locally. The exam is the real BigSkySim, running in a browser on a server, through its ordinary HTTP API: one plane at a time, the clock paused and stepped a quarter of a second at a time, and nothing in the code able to see where the plane really is. Ten whole flights with the final pilots:
summary = json.load(open("data/exams/circuit_summary.json"))
real = {k: v for k, v in summary.items() if 17 <= int(k.split("_")[1]) <= 26}
print(f"{'':11s}{'outcome':22s}{'touchdown':>12}{'off the centreline':>20}{'sink':>10}")
for k, v in sorted(real.items(), key=lambda kv: int(kv[0].split("_")[1])):
td = v["touchdown"]
print(f"{k:11s}{v['outcome']:22s}{td['along_m']:>7.0f} m in{abs(td['offset_m']):>17.0f} m{abs(td['sink_fpm']):>6.0f} fpm")
outcome touchdown off the centreline sink circuit_17 stopped on the runway 100 m in 0 m 150 fpm circuit_18 stopped on the runway 200 m in 2 m 100 fpm circuit_19 stopped on the runway 100 m in 2 m 200 fpm circuit_20 stopped on the runway 200 m in 0 m 150 fpm circuit_21 stopped on the runway 100 m in 2 m 0 fpm circuit_22 stopped on the runway 200 m in 1 m 50 fpm circuit_23 stopped on the runway 100 m in 1 m 100 fpm circuit_24 stopped on the runway 100 m in 0 m 50 fpm circuit_25 stopped on the runway 200 m in 1 m 50 fpm circuit_26 stopped on the runway 200 m in 0 m 0 fpm
fig, ax = plt.subplots(figsize=(11, 4.2))
ax.plot([0, -1000], [0, 0], color="0.3", lw=6, solid_capstyle="butt")
colour = {C.TAKEOFF: "#e67e22", C.LANDING: "#8e44ad", C.STOPPED: "#8e44ad"}
for k in real:
tr = np.load(f"data/exams/{k}.npz")
e, n, legs = -tr["believed"][:, 0], tr["believed"][:, 1], tr["leg"]
for leg in np.unique(legs):
m = np.where(legs == leg, 1.0, np.nan)
ax.plot(e * m, n * m, color=colour.get(leg, "#2980b9"), lw=1)
ax.set_aspect("equal"); ax.set_xlabel("m east of the threshold"); ax.set_ylabel("m north")
ax.set_title("the ten real flights, as the navigator believed them (orange take-off, blue circuit, purple landing)")
plt.show()
Ten out of ten stopped on the runway, touching down 100–200 m in, within 2 m of the centreline, at 0–200 ft/min. (There's no truth to draw this time: the real API never says where the plane is. The little steps are the position report pulling the estimate back into line.)
What carried through all three parts¶
- The score is where the intent goes in. Every champion did exactly what it was paid for, and found every gap between that and what was meant: seven times in this project. Rules change habits and points change outcomes, and a rule needs a slope evolution can climb, not a cliff.
- Measure before deciding. The stand-in model answered the wrong question, "the simulator is slow". Measuring where the time went said "the browser is slow", and running the physics locally, in parallel, made practice hundreds of thousands of times faster than real time.
- Determinism is a tool. Repeatable training runs; and any moment of any flight can be replayed exactly, which is what turned the handover problem into training data.
- A learned skill only works on what it learned on. A sudden 90° turn, a faster handover: the parts were fine alone and failed together until they practised on what the other parts really hand them.
- Use only the information you'll really have, and test on what you didn't choose on. The navigator works from a pilot's radio-call position report, and the final comparisons are made on flights no choice was made on.
Still open: gusts. Every pilot's rare failures are a wingtip strike in strong gusts with little steady wind.
pool.close()