"""The moving map: what is drawn, and whether the file is really a GIF. A picture is checked here the way a picture has to be -- by reading the pixels back -- and the file by taking it apart with a reader written from the GIF specification rather than from the encoder in the program. An encoder checked against itself is not checked. """ import struct import subprocess from pathlib import Path import numpy as np import pytest from bandsaunter import flightmap as fm from bandsaunter.flightlog import Fix, Track # --------------------------------------------------------------------------- # A GIF reader, built from the specification # --------------------------------------------------------------------------- def lzw_decode(data: bytes, code_bits: int) -> bytes: """GIF's LZW, the reading side, written from the standard.""" clear, end = 1 << code_bits, (1 << code_bits) + 1 table = {i: bytes([i]) for i in range(clear)} width = code_bits + 1 counter = end + 1 # counts codes read, not entries added out = bytearray() previous = None value = held = at = 0 while True: while held < width and at < len(data): value |= data[at] << held held += 8 at += 1 if held < width: break code = value & ((1 << width) - 1) value >>= width held -= width if code == clear: table = {i: bytes([i]) for i in range(clear)} width, counter, previous = code_bits + 1, end + 1, None continue if code == end: break # The width goes up as codes are read rather than as the table is # filled: the decoder builds its table one code behind the encoder, # and counting entries instead would widen the codes one too late. read_at = counter if counter < 4096: counter += 1 if counter > (1 << width) and width < 12: width += 1 if code in table: entry = table[code] elif previous is not None: entry = previous + previous[:1] else: raise ValueError(f"code {code} before anything defined it") out += entry if previous is not None and read_at - 1 < 4096: table[read_at - 1] = previous + entry[:1] previous = entry return bytes(out) def read_gif(path: Path) -> dict: """Take a GIF apart: the screen, the palette and every frame in it.""" raw = Path(path).read_bytes() assert raw[:6] == b"GIF89a", "not a GIF89a" width, height, packed, _bg, _aspect = struct.unpack("> 2) & 0x07, "transparent": body[3] if body[0] & 1 else None, "delay": struct.unpack(" list[np.ndarray]: """Every frame as it appears on the screen, patches laid over each other.""" canvas = np.zeros((gif["height"], gif["width"]), dtype=np.uint8) out = [] for frame in gif["frames"]: patch = frame["pixels"] top, left = frame["top"], frame["left"] area = canvas[top:top + frame["height"], left:left + frame["width"]] if frame.get("transparent") is None: area[:, :] = patch else: keep = patch != frame["transparent"] area[keep] = patch[keep] out.append(canvas.copy()) return out # --------------------------------------------------------------------------- # Tracks to draw # --------------------------------------------------------------------------- def straight(icao="4CA1FA", callsign="RYR1234", lat=51.0, lon=-1.0, heading=90.0, speed=480.0, altitude=35_000, seconds=600.0, every=20.0, start=1_000_000.0) -> Track: """One aircraft flying a straight line at a steady speed.""" from bandsaunter.flightlog import move fixes = [] when = 0.0 while when <= seconds: step = speed * when / 3600.0 here = move(lat, lon, heading, step) fixes.append(Fix(at=start + when, latitude=here[0], longitude=here[1], altitude_ft=altitude, ground_speed_kt=speed, track_deg=heading)) when += every return Track(icao=icao, callsign=callsign, fixes=fixes, frames=len(fixes) * 3, first_seen=start, last_seen=start + seconds) def two_aircraft() -> list[Track]: return [straight(), straight(icao="A835AF", callsign="UAL1902", lat=51.4, lon=-0.6, heading=250.0, speed=300.0, altitude=9_000)] # --------------------------------------------------------------------------- # Colours and geometry # --------------------------------------------------------------------------- def test_the_palette_is_a_full_table_with_room_for_transparency(): assert fm.PALETTE.shape == (256, 3) assert fm.TRANSPARENT == 255 def test_altitude_becomes_a_colour_that_climbs_with_it(): steps = [fm.altitude_step(ft) for ft in (0, 5_000, 20_000, 35_000, 45_000)] assert steps == sorted(steps) assert steps[0] == 0 and steps[-1] == fm.RAMP_STEPS - 1 assert fm.altitude_step(90_000) == fm.RAMP_STEPS - 1 # clamped def test_the_map_holds_every_position_that_was_reported(): tracks = two_aircraft() view = fm.fit(tracks, width=800) for track in tracks: for fix in track.fixes: assert view.inside(fix.latitude, fix.longitude) x, y = view.xy(fix.latitude, fix.longitude) assert view.left <= x < view.left + view.width assert view.top <= y < view.top + view.height def test_a_mile_across_is_a_mile_up_the_picture(): """Longitude is squeezed by the cosine, or everything at fifty degrees north comes out stretched half as wide again.""" view = fm.fit(two_aircraft(), width=800) per_nm_x = view.width / view.width_nm tall_nm = (view.north - view.south) * 60.0 per_nm_y = view.height / tall_nm assert per_nm_x == pytest.approx(per_nm_y, rel=0.02) def test_one_aircraft_heard_once_still_gets_a_map(): track = Track(icao="4CA1FA", fixes=[Fix(at=1.0, latitude=51.0, longitude=-1.0)]) view = fm.fit([track], width=400) assert view is not None and view.north > view.south def test_nothing_to_draw_draws_nothing(tmp_path): assert fm.fit([Track(icao="4CA1FA")]) is None assert fm.animate([Track(icao="4CA1FA")], tmp_path / "x.gif") is None # --------------------------------------------------------------------------- # What ends up on the picture # --------------------------------------------------------------------------- def test_the_background_has_a_grid_a_scale_and_a_title(): view = fm.fit(two_aircraft(), width=800) base = fm.background(view, title="6 AIRCRAFT 2026-09-03") assert (base == fm.GRID).sum() > 200 # the graticule and the border assert (base == fm.INK).sum() > 40 # the title assert (base == fm.DIM).sum() > 40 # scale bar and axis labels assert (base == fm.RAMP + fm.RAMP_STEPS - 1).any() # the key def test_an_aircraft_is_drawn_where_it_was_at_that_moment(): tracks = [straight()] view = fm.fit(tracks, width=800) base = fm.background(view) when = tracks[0].first_seen + 300.0 frame = fm.render_frame(base, view, tracks, when) fix = tracks[0].at(when) x, y = view.xy(fix.latitude, fix.longitude) patch = frame[y - 6:y + 7, x - 6:x + 7] assert (patch >= fm.RAMP).any() and (patch < fm.TRAIL).any() def test_the_aircraft_moves_between_frames_and_leaves_a_trail(): tracks = [straight()] view = fm.fit(tracks, width=800) base = fm.background(view) early = fm.render_frame(base, view, tracks, tracks[0].first_seen + 60) late = fm.render_frame(base, view, tracks, tracks[0].first_seen + 540) assert not np.array_equal(early, late) trail_early = (early >= fm.TRAIL) & (early < fm.TRANSPARENT) trail_late = (late >= fm.TRAIL) & (late < fm.TRANSPARENT) assert trail_late.sum() > trail_early.sum() def test_an_aircraft_is_not_drawn_before_it_was_ever_heard(): tracks = [straight()] view = fm.fit(tracks, width=800) base = fm.background(view) frame = fm.render_frame(base, view, tracks, tracks[0].first_seen - 10) assert np.array_equal(frame, base) def test_an_aircraft_long_gone_is_not_drawn_at_a_guessed_position(): tracks = [straight()] view = fm.fit(tracks, width=800) base = fm.background(view) frame = fm.render_frame(base, view, tracks, tracks[0].last_seen + 900, stale=300) assert np.array_equal(frame, base) def test_the_clock_and_the_count_are_drawn_over_the_map(): tracks = two_aircraft() view = fm.fit(tracks, width=800) base = fm.background(view) frame = fm.render_frame(base, view, tracks, tracks[0].first_seen + 60, clock="19:45:02") assert (frame == fm.PANEL).any() assert (frame == fm.INK).sum() > (base == fm.INK).sum() # --------------------------------------------------------------------------- # The file # --------------------------------------------------------------------------- def test_the_lzw_stream_reads_back_as_what_went_in(): for body in (b"\x00" * 300, bytes(range(256)) * 3, bytes([7, 7, 7, 8, 9, 7, 7, 8]) * 40): assert lzw_decode(fm._lzw(body, 8), 8) == body def test_a_long_stream_survives_the_table_filling_up(): rng = np.random.default_rng(4) body = rng.integers(0, 60, size=200_000, dtype=np.uint8).tobytes() assert lzw_decode(fm._lzw(body, 8), 8) == body def test_the_animation_is_a_gif_that_loops(tmp_path): out = fm.animate(two_aircraft(), tmp_path / "flights.gif", fps=10, seconds=4, width=480) assert out is not None and out.path.exists() gif = read_gif(out.path) assert gif["loops"], "a map that plays once and stops" assert len(gif["frames"]) == out.frames assert (gif["width"], gif["height"]) == (out.width, out.height) assert gif["frames"][0]["delay"] == 10 # hundredths, so 10 a second def test_only_what_changed_is_written_after_the_first_frame(tmp_path): out = fm.animate(two_aircraft(), tmp_path / "flights.gif", fps=8, seconds=4, width=480) gif = read_gif(out.path) first = gif["frames"][0] assert (first["width"], first["height"]) == (out.width, out.height) later = gif["frames"][1:] assert later, "one frame is not an animation" assert all(f["width"] * f["height"] < out.width * out.height for f in later) assert all(f["transparent"] is not None for f in later) def test_the_frames_played_back_show_the_aircraft_moving(tmp_path): tracks = [straight()] out = fm.animate(tracks, tmp_path / "one.gif", fps=8, seconds=4, width=480) screens = played(read_gif(out.path)) assert len(screens) == out.frames def where(frame): lit = np.argwhere((frame >= fm.RAMP) & (frame < fm.TRAIL)) return lit.mean(axis=0) start, end = where(screens[1]), where(screens[-1]) assert abs(end[1] - start[1]) > 20 # it went east across the picture for frame in screens: assert frame.shape == (out.height, out.width) def test_the_animation_says_how_much_flying_it_covers(tmp_path): tracks = two_aircraft() out = fm.animate(tracks, tmp_path / "flights.gif", fps=10, seconds=5, width=400) assert out.covers == pytest.approx(600.0, abs=1.0) played_for = out.frames / out.fps assert played_for == pytest.approx(5.0, rel=0.3) assert out.speed == pytest.approx(out.covers / played_for, rel=0.05) assert "aircraft" in out.summary() def test_asking_for_a_speed_gives_that_speed(tmp_path): out = fm.animate(two_aircraft(), tmp_path / "flights.gif", fps=10, speed=60.0, width=400) assert out.speed == pytest.approx(60.0, rel=0.1) assert out.frames == pytest.approx(600 / 60 * 10, abs=2) def test_a_still_picture_is_a_png_of_the_whole_evening(tmp_path): from bandsaunter.images import PNG_SIGNATURE out = fm.animate(two_aircraft(), tmp_path / "flights.png", width=400) assert out.kind == "png" assert out.path.read_bytes()[:8] == PNG_SIGNATURE def test_pillow_agrees_that_it_is_an_animation(tmp_path): """Not a dependency; when it happens to be installed it is a second opinion from a decoder nobody here wrote.""" Image = pytest.importorskip("PIL.Image") out = fm.animate(two_aircraft(), tmp_path / "flights.gif", fps=10, seconds=3, width=400) with Image.open(out.path) as picture: assert picture.n_frames == out.frames assert picture.size == (out.width, out.height) picture.seek(0) first = np.array(picture.convert("RGB")) picture.seek(picture.n_frames - 1) last = np.array(picture.convert("RGB")) assert not np.array_equal(first, last) @pytest.mark.skipif(not fm.ffmpeg_available(), reason="ffmpeg is not installed") def test_a_video_can_be_written_where_ffmpeg_exists(tmp_path): out = fm.animate(two_aircraft(), tmp_path / "flights.mp4", fps=10, seconds=3, width=400) assert out.kind == "mp4" and out.path.stat().st_size > 1000 probe = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", str(out.path)], capture_output=True, text=True) if probe.returncode == 0: assert probe.stdout.strip() == f"{out.width},{out.height}" def test_the_picture_is_an_even_number_of_pixels_across(tmp_path): """Video encoders refuse an odd width, and it costs nothing to be even.""" for width in (401, 402, 555): view = fm.fit(two_aircraft(), width=width) w, h = fm.canvas_size(view) assert w % 2 == 0 and h % 2 == 0 # --------------------------------------------------------------------------- # Speeds in whatever the user reads # --------------------------------------------------------------------------- def _label_text(unit: str, width: int = 700) -> np.ndarray: """Draw one aircraft and hand back the pixels its label was written in.""" tracks = [straight(speed=480.0)] view = fm.fit(tracks, width=width) base = fm.background(view, unit=unit) return fm.render_frame(base, view, tracks, tracks[0].first_seen + 120, unit=unit) def _has_text(frame: np.ndarray, text: str) -> bool: """Whether a string was stamped anywhere in the frame, found by drawing it again and looking for the same pattern.""" from bandsaunter.images import GLYPH_H, draw_text, text_width stamp = np.zeros((GLYPH_H, max(1, text_width(text))), dtype=np.uint8) draw_text(stamp, 0, 0, text, 1) rows, cols = stamp.shape wanted = stamp.astype(bool) if not wanted.any(): return False for y in range(frame.shape[0] - rows): for x in range(frame.shape[1] - cols): patch = frame[y:y + rows, x:x + cols] if np.all(patch[wanted] != fm.BG) and \ np.all(patch[~wanted] == patch[~wanted][0]): return True return False @pytest.mark.parametrize("unit,label", [("knots", "KT"), ("mph", "MPH"), ("kph", "KM/H")]) def test_the_speed_on_the_map_carries_its_unit(unit, label): """A bare 480 beside an aircraft is three different speeds depending on who is reading it.""" assert _has_text(_label_text(unit), label) def test_the_number_beside_it_is_converted(): assert _has_text(_label_text("knots"), "480KT") assert _has_text(_label_text("mph"), "552MPH") assert _has_text(_label_text("kph"), "889KM/H") @pytest.mark.parametrize("unit,label", [("knots", "NM"), ("mph", "MI"), ("kph", "KM")]) def test_the_scale_bar_uses_the_same_kind_of_mile(unit, label): """Miles an hour beside a scale in nautical miles is two different miles on one picture.""" view = fm.fit(two_aircraft(), width=700) assert _has_text(fm.background(view, unit=unit), label) def test_the_animation_takes_the_unit_through_to_the_file(tmp_path): out = fm.animate(two_aircraft(), tmp_path / "mph.png", width=500, unit="mph") assert out is not None and out.path.is_file() # --------------------------------------------------------------------------- # Framing the picture on the receiver # --------------------------------------------------------------------------- def far_away(icao="BAD001", lat=-9.5, lon=-112.5) -> Track: """One aircraft in the wrong hemisphere: a decode that went wrong.""" return Track(icao=icao, callsign="GHOST", fixes=[Fix(at=1_000_000.0, latitude=lat, longitude=lon, altitude_ft=35_000, ground_speed_kt=400.0)], first_seen=1_000_000.0, last_seen=1_000_000.0) def test_the_middle_of_what_was_heard_is_where_the_receiver_is(): """A median, so a handful of wrong positions cannot drag it anywhere.""" from bandsaunter.flightlog import centre_of tracks = two_aircraft() + [far_away(), far_away("BAD002", 60.0, 120.0)] lat, lon = centre_of(tracks) assert lat == pytest.approx(51.0, abs=1.0) assert lon == pytest.approx(-1.0, abs=1.5) def test_a_radius_leaves_the_far_ones_off_the_map(): tracks = two_aircraft() + [far_away()] view_all = fm.fit([t for t in tracks if t.located]) assert view_all.north - view_all.south > 50 # dragged across a globe from bandsaunter.flightlog import centre_of, within lat, lon = centre_of(two_aircraft()) near = [t for t in within(tracks, lat, lon, 100.0) if t.located] assert {t.icao for t in near} == {t.icao for t in two_aircraft()} def test_the_frame_is_the_radius_rather_than_whatever_turned_up(): """The scale should not change with the traffic.""" from bandsaunter.flightlog import box_around, centre_of, distance_nm lat, lon = centre_of(two_aircraft()) box = box_around(lat, lon, 100.0) view = fm.fit(two_aircraft(), width=600, box=box) assert view.south == pytest.approx(box[0]) and view.north == pytest.approx(box[2]) across = distance_nm(lat, box[1], lat, box[3]) assert across == pytest.approx(200.0, rel=0.02) # a hundred each way def test_the_radius_is_kept_by_the_animation(tmp_path): """Without one the frame stretches to reach a bad position on the other side of the equator, and the real aircraft come out a pixel wide.""" from bandsaunter.flightlog import box_around, centre_of tracks = two_aircraft() + [far_away()] wide = fm.animate(tracks, tmp_path / "wide.png", width=400, radius_nm=0) tight = fm.animate(tracks, tmp_path / "tight.png", width=400, radius_nm=100) assert wide.aircraft == 3 and tight.aircraft == 2 everything = fm.fit([t for t in tracks if t.located], width=400) lat, lon = centre_of(two_aircraft()) framed = fm.fit(two_aircraft(), width=400, box=box_around(lat, lon, 100.0)) assert everything.north - everything.south > 50 # most of a hemisphere assert framed.north - framed.south < 4 # a hundred miles def test_an_explicit_receiver_position_is_used_as_given(tmp_path): """Somewhere with no aircraft near it: everything falls outside.""" out = fm.animate(two_aircraft(), tmp_path / "elsewhere.png", width=400, radius_nm=50, centre=(0.0, 0.0)) assert out is None def test_a_track_with_one_bad_fix_keeps_the_rest_of_its_flight(): """Per fix rather than per aircraft: one wrong position in the middle of a real flight must not take the flight off the map with it.""" from bandsaunter.flightlog import within track = straight() good = len(track.fixes) track.fixes.insert(len(track.fixes) // 2, Fix(at=track.fixes[0].at + 1, latitude=-9.5, longitude=-112.5, altitude_ft=35_000)) kept = within([track], 51.0, -1.0, 100.0)[0] assert len(kept.fixes) == good # --------------------------------------------------------------------------- # Drawing off the edge # --------------------------------------------------------------------------- @pytest.mark.parametrize("x,y", [(-28, -89), (-4000, 400), (450, -9000), (2000, 400), (450, 4000)]) def test_an_aircraft_off_the_picture_paints_nothing(x, y): """Clamping the near edge of the centre dot and leaving the far one alone reads as a negative slice, which numpy counts back from the far side -- and fills most of the frame with one colour.""" img = np.zeros((300, 500), dtype=np.uint8) fm._marker(img, x, y, 90.0, 20) assert int((img != 0).sum()) == 0 @pytest.mark.parametrize("x,y", [(0, 0), (499, 299), (250, 150)]) def test_an_aircraft_on_the_picture_is_still_drawn(x, y): img = np.zeros((300, 500), dtype=np.uint8) fm._marker(img, x, y, 90.0, 20) assert 0 < int((img != 0).sum()) < 60 def test_a_still_draws_where_they_were_not_where_they_might_have_got_to(): """A still of a whole evening is drawn hours after most of the aircraft stopped transmitting; flying them on for those hours would scatter them across three states.""" tracks = [straight(seconds=600.0)] view = fm.fit(tracks, width=500) base = fm.background(view) hours_later = tracks[0].last_seen + 6 * 3600 projected = fm.render_frame(base, view, tracks, hours_later, stale=7 * 3600, project=True, labels=False) still = fm.render_frame(base, view, tracks, hours_later, stale=7 * 3600, project=False, labels=False) def markers(frame): """Just the aircraft: what changed, in the aircraft colours, inside the map itself. The altitude key along the bottom is drawn in those same colours and belongs to the background.""" body = slice(view.top, view.top + view.height), \ slice(view.left, view.left + view.width) drawn = (frame[body] != base[body]) & (frame[body] >= fm.RAMP) & \ (frame[body] < fm.TRAIL) return int(drawn.sum()) assert markers(projected) == 0 # flown clean off the picture assert markers(still) > 0 # drawn where it last was last = tracks[0].fixes[-1] x, y = view.xy(last.latitude, last.longitude) assert (still[y - 6:y + 7, x - 6:x + 7] >= fm.RAMP).any() def test_a_whole_evening_as_one_picture_keeps_every_aircraft_on_it(tmp_path): tracks = two_aircraft() for t in tracks: # heard hours ago for f in t.fixes: f.at -= 6 * 3600 t.first_seen -= 6 * 3600 t.last_seen -= 6 * 3600 tracks.append(straight(icao="C0FFEE", callsign="LATE", lat=51.2, lon=-0.9)) out = fm.animate(tracks, tmp_path / "evening.png", width=500) assert out is not None and out.aircraft == 3 # --------------------------------------------------------------------------- # Throwing out what could not have happened # --------------------------------------------------------------------------- def _with_bad_fix(track: Track, at_index: int, lat=-9.5, lon=-112.5) -> Track: """Drop one impossible position into the middle of a real flight.""" when = track.fixes[at_index].at + 0.001 track.fixes.insert(at_index + 1, Fix(at=when, latitude=lat, longitude=lon, altitude_ft=35_000, ground_speed_kt=400.0)) return track def test_a_position_no_aircraft_could_reach_is_thrown_out(): from bandsaunter.flightlog import recheck track = _with_bad_fix(straight(), 10) good = len(track.fixes) - 1 clean, dropped = recheck([track]) assert dropped == 1 assert len(clean[0].fixes) == good assert all(-90 <= f.latitude <= 90 for f in clean[0].fixes) def test_a_flight_that_is_entirely_real_loses_nothing(): from bandsaunter.flightlog import recheck clean, dropped = recheck(two_aircraft()) assert dropped == 0 assert [len(t.fixes) for t in clean] == [len(t.fixes) for t in two_aircraft()] def test_a_bad_position_early_on_does_not_take_the_flight_with_it(): """Keeping whatever is reachable from the last position kept lets one bad fix become the reference, and then the truth is what gets thrown away. On a real recording that discarded a fifth of everything.""" from bandsaunter.flightlog import recheck track = _with_bad_fix(straight(), 0) clean, dropped = recheck([track]) assert dropped == 1 assert len(clean[0].fixes) == len(straight().fixes) def test_a_run_of_bad_positions_that_agree_with_each_other_still_goes(): """Three bad decodes can land in the same wrong place and agree perfectly; they are still wrong.""" from bandsaunter.flightlog import recheck track = straight() where = 10 for i in range(3): track.fixes.insert(where + 1 + i, Fix(at=track.fixes[where].at + 0.001 * (i + 1), latitude=-9.5 + i * 0.001, longitude=-112.5, altitude_ft=35_000)) clean, dropped = recheck([track]) assert dropped == 3 assert all(f.latitude > 0 for f in clean[0].fixes) def test_a_position_that_is_not_on_earth_never_survives(): from bandsaunter.flightlog import recheck track = _with_bad_fix(straight(), 5, lat=239.6, lon=-111.0) clean, _ = recheck([track]) assert all(-90 <= f.latitude <= 90 for f in clean[0].fixes) def test_an_aircraft_that_went_quiet_and_came_back_is_not_an_error(): """Out of range for ten minutes, then heard again a long way off: that is an aeroplane, not a bad decode, and there is no way to say otherwise.""" from bandsaunter.flightlog import recheck track = straight(seconds=200.0) last = track.fixes[-1] track.fixes.append(Fix(at=last.at + 900, latitude=last.latitude + 1.5, longitude=last.longitude + 2.0, altitude_ft=35_000, ground_speed_kt=480.0)) clean, dropped = recheck([track]) assert dropped == 0 def test_two_positions_that_contradict_each_other_do_not_both_stand(): """One of them is wrong and nothing says which; what comes out has at least to be a story.""" from bandsaunter.flightlog import recheck track = Track(icao="4CA1FA", fixes=[ Fix(at=0.0, latitude=51.5, longitude=-0.12), Fix(at=0.5, latitude=-9.5, longitude=-112.5)]) clean, dropped = recheck([track]) assert dropped == 1 assert len(clean[0].fixes) == 1 def test_a_jitter_of_a_few_yards_is_never_called_an_error(): """Positions arrive twice a second and are stamped to the millisecond, so two of them a thousandth of a second apart imply thousands of knots across a few yards.""" from bandsaunter.flightlog import recheck track = Track(icao="4CA1FA", fixes=[ Fix(at=0.0, latitude=51.5000, longitude=-0.1200), Fix(at=0.001, latitude=51.5001, longitude=-0.1201), Fix(at=0.002, latitude=51.5002, longitude=-0.1202)]) clean, dropped = recheck([track]) assert dropped == 0 def test_nothing_survives_that_needed_an_impossible_speed(): """The promise of the whole thing, said as one assertion.""" from bandsaunter.flightlog import (MAX_GROUND_SPEED_KT, distance_nm, implied_speed_kt, recheck) tracks = [_with_bad_fix(straight(), i) for i in (3, 12, 20)] clean, dropped = recheck(tracks) assert dropped == 3 for track in clean: for a, b in zip(track.fixes, track.fixes[1:]): if 0 < b.at - a.at <= 300 and distance_nm( a.latitude, a.longitude, b.latitude, b.longitude) > 2: assert implied_speed_kt(a, b) <= MAX_GROUND_SPEED_KT # --------------------------------------------------------------------------- # What is written beside each aircraft # --------------------------------------------------------------------------- class _Entry: """A register's answer, in the shape flightmap reads it.""" def __init__(self, **over): self.type_code = over.get("type_code", "B739") self.model = over.get("model", "737-932ER") self.registration = over.get("registration", "N904DN") self.origin_code = over.get("origin_code", "KATL") self.origin = over.get("origin", "Atlanta") self.origin_country = over.get("origin_country", "US") self.destination_code = over.get("destination_code", "EGLL") self.destination = over.get("destination", "London Heathrow") self.destination_country = over.get("destination_country", "GB") # The map draws an airport where a lookup gave it a position. self.origin_lat = over.get("origin_lat", 33.6367) self.origin_lon = over.get("origin_lon", -84.4281) self.destination_lat = over.get("destination_lat", 51.4706) self.destination_lon = over.get("destination_lon", -0.4619) def test_the_label_says_height_speed_type_and_both_ends_of_the_route(): track = straight() rows = fm.label_lines(track, track.fixes[0], "knots", _Entry()) text = [line for line, _flag in rows] # The height in feet with its unit on it: "350" is only a height to # somebody who already knows it is one. assert text[0].startswith("35,000 ft") assert "480KT" in text[0] assert "B739 N904DN" in text assert "KATL" in text and "EGLL" in text def test_each_end_of_the_route_carries_its_own_country(): track = straight() rows = dict((line, flag) for line, flag in fm.label_lines(track, track.fixes[0], "knots", _Entry())) assert rows["KATL"] == "US" assert rows["EGLL"] == "GB" def test_with_no_register_the_label_is_what_the_aircraft_itself_said(): """The height and the speed, which came off the air, and the flag of the country that issued the address, which needs no register either.""" track = straight() rows = fm.label_lines(track, track.fixes[0], "knots", None) assert rows[0][0].startswith("35,000 ft") and rows[0][1] == "" assert [flag for _text, flag in rows if flag] == ["IE"] assert not any("N904DN" in text for text, _flag in rows) def test_the_flag_is_there_for_an_aircraft_no_register_has_heard_of(): """Taking the country from the register's answer left the flag off exactly the aircraft that had nothing else beside them either. The address block says it without asking anybody.""" for icao, expected in (("4CA1FA", "IE"), ("A12345", "US"), ("0D0468", "MX"), ("406B12", "GB")): track = straight(icao=icao) rows = fm.label_lines(track, track.fixes[0], "knots", None) assert [flag for _text, flag in rows if flag] == [expected], icao def test_an_airport_with_no_code_is_named_short_rather_than_in_full(): track = straight() entry = _Entry(origin_code="", origin="Hartsfield Jackson Atlanta " "International Airport") said = [line for line, _ in fm.label_lines(track, track.fixes[0], "knots", entry)] assert "Hartsfield Jackson" in said assert not any(len(line) > 20 for line in said), said def test_the_flag_is_drawn_in_the_flag_colours(): from bandsaunter.flags import COLOUR_ORDER, FLAG_H, FLAG_W img = np.full((40, 60), fm.BG, dtype=np.uint8) fm.draw_flag(img, 5, 5, "JP") patch = img[5:5 + FLAG_H, 5:5 + FLAG_W] assert (patch >= fm.FLAG).all() assert (patch < fm.FLAG + len(COLOUR_ORDER)).all() # White at the corner and red in the middle: the flag of Japan. assert patch[0, 0] == fm.flag_index("w") assert patch[4, 6] == fm.flag_index("r") def test_a_country_with_no_flag_is_named_in_letters_instead(): img = np.full((40, 60), fm.BG, dtype=np.uint8) fm.draw_flag(img, 5, 5, "ZZ") assert (img == fm.GRID).any() # the letters, in grey assert not (img >= fm.FLAG).any() # and no flag pretending to be one def test_a_flag_off_the_edge_of_the_picture_paints_nothing(): for x, y in ((-40, 5), (5, -40), (200, 5), (5, 200)): img = np.full((40, 60), fm.BG, dtype=np.uint8) fm.draw_flag(img, x, y, "US") assert (img == fm.BG).all(), (x, y) def test_the_flag_colours_fit_in_the_palette_beside_everything_else(): from bandsaunter.flags import COLOUR_ORDER assert fm.FLAG + len(COLOUR_ORDER) < fm.TRANSPARENT assert fm.PALETTE.shape == (256, 3) # And each index really is the colour it claims. from bandsaunter.flags import COLOURS for letter in COLOUR_ORDER: assert tuple(int(v) for v in fm.PALETTE[fm.flag_index(letter)]) == \ COLOURS[letter] def test_the_register_is_asked_once_per_aircraft_not_once_per_frame(tmp_path): """A five-hundred-frame animation asking the same question five hundred times would be five hundred times as rude.""" asked = [] class _Book: def get(self, icao, callsign=""): asked.append(icao) return _Entry() fm.animate(two_aircraft(), tmp_path / "counted.gif", fps=8, seconds=3, width=400, book=_Book()) assert asked, "the register was never asked at all" assert len(asked) == len(set(asked)), f"asked twice about the same: {asked}" def test_the_route_reaches_the_drawn_picture(tmp_path): """End to end: a register with a route, and the flags on the frame.""" class _Book: def get(self, icao, callsign=""): return _Entry() tracks = two_aircraft() view = fm.fit(tracks, width=700) base = fm.background(view) known = {t.icao: _Entry() for t in tracks} frame = fm.render_frame(base, view, tracks, tracks[0].first_seen + 60, known=known) assert _has_flag(frame), "no flag was drawn" assert _has_text(frame, "KATL") assert _has_text(frame, "B739") def _has_flag(frame) -> bool: """Whether any flag was drawn: its own colours, at any fade step. Checked by the exact palette ranges rather than "any index above the flags", because everything a fading label is drawn in lives above them too. """ import numpy as np from bandsaunter.flags import COLOUR_ORDER wide = len(COLOUR_ORDER) return bool(((frame >= fm.FLAG) & (frame < fm.FLAG + wide)).any() or ((frame >= fm.FLAG_FADED) & (frame < fm.FLAG_FADED + 3 * wide)).any()) def test_a_crowded_frame_goes_back_to_the_short_label(): """Five lines beside each of three hundred aircraft is not more information, it is a page of overlapping text with a map behind it.""" many = [straight(icao=f"{i:06X}", callsign=f"FLT{i}", lat=51.0 + i * 0.02, lon=-1.0 + i * 0.02) for i in range(fm.CROWDED + 4)] view = fm.fit(many, width=900) base = fm.background(view) known = {t.icao: _Entry() for t in many} frame = fm.render_frame(base, view, many, many[0].first_seen + 60, known=known) assert not _has_flag(frame), "still drawing flags when crowded" assert not _has_text(frame, "B739") def test_a_quiet_frame_keeps_every_detail(): tracks = two_aircraft() view = fm.fit(tracks, width=700) base = fm.background(view) known = {t.icao: _Entry() for t in tracks} frame = fm.render_frame(base, view, tracks, tracks[0].first_seen + 60, known=known) assert (frame >= fm.FLAG).any() assert _has_text(frame, "B739") def test_the_callsign_and_height_survive_a_crowd(): """Whatever else goes, what the aircraft itself said stays.""" many = [straight(icao=f"{i:06X}", callsign=f"FLT{i}", lat=51.0 + i * 0.02, lon=-1.0 + i * 0.02) for i in range(fm.CROWDED + 4)] view = fm.fit(many, width=900) frame = fm.render_frame(fm.background(view), view, many, many[0].first_seen + 60, known={t.icao: _Entry() for t in many}) assert _has_text(frame, "FLT0") def test_labels_step_aside_rather_than_landing_on_each_other(): """Two aircraft passing close together is exactly the moment somebody is looking at that part of the picture.""" close = [straight(icao=f"{i:06X}", callsign=f"FLT{i}", lat=51.0 + i * 0.004, lon=-1.0 + i * 0.004, seconds=60) for i in range(6)] view = fm.fit(close, width=800, box=(50.8, -1.4, 51.3, -0.6)) taken = [] base = fm.background(view) fm.render_frame(base, view, close, close[0].first_seen, labels=True) # Place them by hand so the boxes can be compared. for track in close: now = track.at(track.first_seen) x, y = view.xy(now.latitude, now.longitude) fm._label(base, x, y, track, now, fm.RAMP, taken) for i, one in enumerate(taken): for two in taken[i + 1:]: assert not fm._overlaps(one, two), f"{one} overlaps {two}" # --------------------------------------------------------------------------- # The country an aircraft is registered in # --------------------------------------------------------------------------- def test_the_registration_carries_the_country_it_is_registered_in(): track = straight() entry = _Entry() entry.owner_country = "United Kingdom" rows = dict((text, flag) for text, flag in fm.label_lines(track, track.fixes[0], "knots", entry)) assert rows["B739 N904DN"] == "GB" def test_the_address_block_stands_in_when_a_register_says_nothing(): """The 24-bit address says which country issued it, by treaty, with no website involved at all.""" track = straight() entry = _Entry() entry.owner_country = "" entry.country = "United States" rows = dict(fm.label_lines(track, track.fixes[0], "knots", entry)) assert rows["B739 N904DN"] == "US" def test_a_country_nobody_named_gets_no_flag(): """An address outside every block anybody has published, and a register that did not say either: no flag rather than a guessed one.""" from bandsaunter.flights import describe_address assert describe_address("0F0000") == "", "pick an unallocated address" track = straight(icao="0F0000") entry = _Entry() entry.owner_country = "" entry.country = "" rows = fm.label_lines(track, track.fixes[0], "knots", entry) assert not any(flag for _text, flag in rows if _text == "B739 N904DN") assert dict(rows)["B739 N904DN"] == "" # --------------------------------------------------------------------------- # Airports on the map # --------------------------------------------------------------------------- def test_an_airport_a_route_gave_a_position_for_is_marked(): known = {"A": _Entry()} found = fm._airports_from(known) assert {code for code, _, _ in found} == {"KATL", "EGLL"} def test_an_airport_with_only_a_code_is_looked_up_so_it_can_be_marked(): """A route names two airports and often gives a position for neither; an airport that cannot be placed cannot be drawn.""" asked = [] class _Book: def airports(self, codes): asked.extend(codes) return [{"code": code, "latitude": 32.1, "longitude": -110.9} for code in codes] entry = _Entry(origin_lat=0.0, origin_lon=0.0, destination_lat=0.0, destination_lon=0.0) found = fm._airports_from({"A": entry}, _Book()) assert sorted(asked) == ["EGLL", "KATL"] assert len(found) == 2 def test_an_airport_that_cannot_be_looked_up_is_simply_not_drawn(): class _Book: def airports(self, codes): raise OSError("no network") entry = _Entry(origin_lat=0.0, origin_lon=0.0, destination_lat=0.0, destination_lon=0.0) assert fm._airports_from({"A": entry}, _Book()) == [] def test_an_airport_already_placed_is_not_looked_up_again(): asked = [] class _Book: def airports(self, codes): asked.extend(codes) return [] fm._airports_from({"A": _Entry()}, _Book()) assert asked == [], "asked about airports it already had" def test_an_airport_is_drawn_where_it_is_and_named(): view = fm.fit(two_aircraft(), width=600) middle = ((view.south + view.north) / 2, (view.west + view.east) / 2) base = fm.background(view, airports=[("EGLL", middle[0], middle[1])]) x, y = view.xy(*middle) marker = (base[y - 4:y + 5, x - 4:x + 5] == fm.AIRPORT) assert marker.any(), "no marker where the airport is" # And its name beside it, in the same colour, to the right of the marker. beside = (base[y - 6:y + 8, x + 5:x + 60] == fm.AIRPORT) assert beside.sum() > 10, "the airport was marked but not named" def test_an_airport_off_the_edge_is_not_drawn(): view = fm.fit(two_aircraft(), width=600) plain = fm.background(view) away = fm.background(view, airports=[("KSEA", 47.4, -122.3)]) assert np.array_equal(plain, away) # --------------------------------------------------------------------------- # How dark the ground is # --------------------------------------------------------------------------- def _brightest_drawn(brightness): """The lightest the map actually gets at one brightness setting.""" top = int(fm.dim_ground(np.array([[fm.GROUND_SHADES - 1]]), brightness)[0, 0]) return fm.PALETTE[fm.GROUND + top].astype(float).mean() def test_the_map_is_light_enough_to_read(): """It was too dark to make out a coastline at all.""" assert _brightest_drawn(fm.GROUND_BRIGHTNESS) > 110 def test_the_aircraft_stay_brighter_than_the_ground_they_are_over(): """Whatever else, the picture has to stay about the aeroplanes.""" ground = _brightest_drawn(fm.GROUND_BRIGHTNESS) for feet in (0, 10_000, 25_000, 40_000): marker = fm.PALETTE[fm.RAMP + fm.altitude_step(feet)] assert marker.astype(float).mean() > ground, feet def test_there_is_room_to_turn_it_up_and_down(): assert _brightest_drawn(1.0) > _brightest_drawn(fm.GROUND_BRIGHTNESS) assert _brightest_drawn(0.3) < _brightest_drawn(fm.GROUND_BRIGHTNESS) @pytest.mark.parametrize("brightness", [0.0, -1.0, 5.0, 1.0, 0.1]) def test_a_brightness_outside_the_range_is_brought_back_into_it(brightness): shades = fm.dim_ground(np.arange(fm.GROUND_SHADES, dtype=np.uint8), brightness) assert shades.min() >= 0 and shades.max() <= fm.GROUND_SHADES - 1 def test_turning_it_down_really_does_darken_the_picture(): levels = np.full((20, 20), fm.GROUND_SHADES - 1, dtype=np.uint8) assert fm.dim_ground(levels, 0.3).max() < fm.dim_ground(levels, 0.9).max() def test_the_darkest_ground_is_no_darker_than_the_background(): darkest = fm.PALETTE[fm.GROUND].astype(float).mean() background = fm.PALETTE[fm.BG].astype(float).mean() assert darkest >= background # --------------------------------------------------------------------------- # Fading out rather than blinking out # --------------------------------------------------------------------------- def test_an_aircraft_still_being_heard_is_at_full_strength(): track = straight(seconds=120) seen = fm.showing(track, track.fixes[-1].at, stale=300.0, fade=20.0) assert seen is not None and seen[1] == 1.0 def test_one_that_has_gone_quiet_fades_instead_of_disappearing(): track = straight(seconds=120) last = track.fixes[-1].at strengths = [] for gone in (301, 305, 310, 315, 319): seen = fm.showing(track, last + gone, stale=300.0, fade=20.0) assert seen is not None, gone strengths.append(seen[1]) assert strengths == sorted(strengths, reverse=True) assert strengths[0] > 0.9 and strengths[-1] < 0.1 def test_it_is_gone_once_the_fade_is_over(): track = straight(seconds=120) last = track.fixes[-1].at assert fm.showing(track, last + 321, stale=300.0, fade=20.0) is None def test_no_fade_takes_it_away_the_moment_it_is_given_up_on(): track = straight(seconds=120) last = track.fixes[-1].at assert fm.showing(track, last + 301, stale=300.0, fade=0.0) is None def test_it_fades_where_it_was_last_seen_and_not_where_it_might_be(): """The whole reason for giving up on an aircraft is that where it would be by now is a guess; fading it along that guess would be inventing an aeroplane slowly instead of quickly.""" track = straight(seconds=120) last = track.fixes[-1] seen = fm.showing(track, last.at + 310, stale=300.0, fade=20.0) assert (seen[0].latitude, seen[0].longitude) == (last.latitude, last.longitude) def test_before_it_was_ever_heard_it_is_still_not_drawn(): track = straight(seconds=120) assert fm.showing(track, track.fixes[0].at - 60, fade=20.0) is None def test_the_fading_aircraft_is_drawn_in_fainter_colours(): track = straight(seconds=120) view = fm.fit([track], width=500) base = fm.background(view) last = track.fixes[-1].at def drawn(when): """The aircraft's own pixels: what changed, not what was already there. The altitude key along the bottom is painted in the same colours and belongs to the background.""" frame = fm.render_frame(base, view, [track], when, stale=300.0, fade=20.0, labels=False) return frame[frame != base] fresh = drawn(last) faint = drawn(last + 318) assert fresh.size and faint.size # A live aircraft has its marker in the full colours; its trail behind it # is dimmer on purpose, so only the brightest pixels are the test. assert (fresh < fm.TRAIL).any(), "a live aircraft was drawn faintly" # A nearly gone one has nothing in them at all. assert not (faint < fm.FAINT).any(), "a fading aircraft was drawn brightly" def test_a_faded_aircraft_keeps_its_symbol_and_loses_its_label(): track = straight(seconds=120) view = fm.fit([track], width=500) base = fm.background(view) last = track.fixes[-1].at known = {track.icao: _Entry()} faint = fm.render_frame(base, view, [track], last + 318, stale=300.0, fade=20.0, known=known) assert (faint != base).any(), "nothing was drawn at all" assert not _has_text(faint, "B739"), "the label survived the fade" def test_the_trail_fades_with_the_aircraft_it_belongs_to(): """The two are one thing on the picture, and half of it lingering would be worse than either.""" track = straight(seconds=120) view = fm.fit([track], width=500) base = fm.background(view) last = track.fixes[-1].at faint = fm.render_frame(base, view, [track], last + 318, stale=300.0, fade=20.0, labels=False) drawn = faint[faint != base] assert drawn.size assert drawn.min() >= fm.FAINT, "the trail stayed behind when it faded" def test_the_faint_colours_are_the_same_hues_only_dimmer(): for step in (0, 15, 31): bright = fm.PALETTE[fm.RAMP + step].astype(float) faint = fm.PALETTE[fm.FAINT + step].astype(float) assert faint.sum() < bright.sum() # The same colour, turned down: the ratios between the channels hold. assert np.allclose(faint / max(1e-9, faint.sum()), bright / bright.sum(), atol=0.03) def test_the_palette_still_has_room_after_the_fade_colours(): assert fm.FAINT + fm.RAMP_STEPS < fm.TRANSPARENT assert fm.PALETTE.shape == (256, 3) def test_a_route_the_aircraft_cannot_be_flying_is_not_drawn_beside_it(): """A route beside an aircraft reads as a statement about that aircraft, and a callsign is a flight number rather than a leg.""" track = straight(lat=32.7, lon=-110.4) entry = _Entry(origin_code="KHOU", origin_lat=29.65, origin_lon=-95.28, destination_code="KSAT", destination_lat=29.53, destination_lon=-98.47) said = [text for text, _flag in fm.label_lines(track, track.fixes[0], "knots", entry)] assert "KHOU" not in said and "KSAT" not in said assert any("B739" in line for line in said), "the rest of it went too" def test_a_route_it_could_be_flying_is_drawn(): track = straight(lat=32.7, lon=-110.4) entry = _Entry(origin_code="KLAX", origin_lat=33.94, origin_lon=-118.41, destination_code="KDFW", destination_lat=32.90, destination_lon=-97.04) said = [text for text, _flag in fm.label_lines(track, track.fixes[0], "knots", entry)] assert "KLAX" in said and "KDFW" in said # --------------------------------------------------------------------------- # What sort of aircraft it is # --------------------------------------------------------------------------- def test_the_label_says_what_sort_of_aircraft_it_is(): """It comes off the air: the three bits under an identification message's type code, which every aircraft sends with its callsign.""" track = straight() track.category = "heavy" said = [text for text, _flag in fm.label_lines(track, track.fixes[0], "knots", None)] assert "heavy" in said def test_a_military_address_says_so_beside_the_aircraft(): """No aircraft broadcasts that it is military -- a tanker calls itself "heavy" exactly as an airliner does -- so it is read off the address.""" track = straight(icao="AE07D3") # a United States military block track.category = "heavy" said = [text for text, _flag in fm.label_lines(track, track.fixes[0], "knots", None)] assert "military heavy" in said plain = straight(icao="A12345") # the civil part of the same range plain.category = "heavy" assert "heavy" in [t for t, _f in fm.label_lines(plain, plain.fixes[0], "knots", None)] assert "military heavy" not in [t for t, _f in fm.label_lines(plain, plain.fixes[0], "knots", None)] def test_an_aircraft_that_says_nothing_about_itself_is_not_given_a_class(): track = straight() assert not any(t in ("heavy", "large", "light") for t, _f in fm.label_lines(track, track.fixes[0], "knots", None)) def test_the_class_carries_the_flag_so_the_type_line_need_not(): """One flag per aircraft, on the first row that says what it is.""" track = straight() track.category = "large" rows = fm.label_lines(track, track.fixes[0], "knots", _Entry()) flags = [(text, flag) for text, flag in rows if flag] assert ("large", "IE") in flags assert dict(rows)["B739 N904DN"] == "" # --------------------------------------------------------------------------- # A label that has to move swings there # --------------------------------------------------------------------------- def test_the_label_glide_moves_towards_the_target_and_arrives(): here = (0.0, 0.0) for _ in range(40): here = fm._glide(here, (120.0, -80.0), 0.05, fm.LABEL_GLIDE) assert 0.0 <= here[0] <= 120.0 and -80.0 <= here[1] <= 0.0 assert here == (120.0, -80.0) def test_the_label_glide_is_the_same_swing_at_any_frame_rate(): fast = slow = (0.0, 0.0) for _ in range(8): fast = fm._glide(fast, (200.0, 0.0), 0.025, fm.LABEL_GLIDE) for _ in range(2): slow = fm._glide(slow, (200.0, 0.0), 0.1, fm.LABEL_GLIDE) assert abs(fast[0] - slow[0]) < 1.0 def test_a_label_keeps_the_place_it_has(): """The reason labels stay still: one is only moved when its own place has actually been taken, never because the placer would now prefer a different one.""" places = fm.LabelPlaces() places.settle("ABC123", 100, 100, (160, 90)) kept = places.kept("ABC123", 104, 100, lambda bx, by: (int(bx), int(by))) assert kept == (164, 90), "it did not travel with its aircraft" def test_a_label_whose_place_is_taken_is_sent_looking(): places = fm.LabelPlaces() places.settle("ABC123", 100, 100, (160, 90)) assert places.kept("ABC123", 100, 100, lambda bx, by: None) is None def test_a_label_that_has_to_move_swings_rather_than_jumps(): places = fm.LabelPlaces() places.settle("ABC123", 0, 0, (100, 100)) assert places.drawn("ABC123", 0, 0, (100, 100), 0.08) == (100, 100) part = places.drawn("ABC123", 0, 0, (300, 240), 0.08) assert part != (300, 240), "it jumped the whole way in one frame" assert 100 < part[0] < 300 for _ in range(40): part = places.drawn("ABC123", 0, 0, (300, 240), 0.08) assert part == (300, 240) def test_a_label_is_forgotten_when_its_aircraft_goes(): """Otherwise one that comes back glides in from wherever it stood half an hour ago, across the whole picture.""" places = fm.LabelPlaces() places.begin() places.settle("ABC123", 0, 0, (100, 100)) places.drawn("ABC123", 0, 0, (100, 100), 0.08) places.end() assert "ABC123" in places.at places.begin() places.end() assert places.at == {} and places.want == {} def test_a_label_swings_across_a_real_frame_rather_than_jumping(): """The same easing the window does, wired through a drawn frame: the label is somewhere between where it was and where it now belongs, and what is spoken for is where it is going.""" track = straight() # A canvas with room around the aircraft, so that a displaced label is # displaced rather than pushed off the edge and refused. view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0)) base = fm.background(view, unit="knots") places = fm.LabelPlaces() when = track.fixes[0].at fm.render_frame(base, view, [track], when, labels=True, unit="knots", places=places, step=1.0 / 12.0) settled = places.want[track.icao] assert places.at[track.icao] == (float(settled[0]), float(settled[1])) # Push its place a long way, as a crowd of aircraft arriving would. places.want[track.icao] = (settled[0] - 120, settled[1] + 90) after = fm.render_frame(base, view, [track], when, labels=True, unit="knots", places=places, step=1.0 / 12.0) target = places.want[track.icao] now_at = places.at[track.icao] assert target != settled, "the test did not displace it" assert now_at != (float(settled[0]), float(settled[1])), "it did not move" assert now_at != (float(target[0]), float(target[1])), \ "it jumped the whole way in one frame" part = (now_at[0] - settled[0]) / (target[0] - settled[0]) assert 0.05 < part < 0.60, f"one frame carried it {part:.0%} of the way" # And it gets there, given the frames. for _ in range(30): fm.render_frame(base, view, [track], when, labels=True, unit="knots", places=places, step=1.0 / 12.0) assert places.at[track.icao] == (float(places.want[track.icao][0]), float(places.want[track.icao][1])) assert after.shape == base.shape def test_a_still_picture_places_its_labels_exactly_as_it_always_did(): """There is no frame before a still, so there is nothing to keep and nothing to swing: the placing has to be untouched.""" track = straight() view = fm.fit([track], width=800) base = fm.background(view, unit="knots") when = track.fixes[0].at plain = fm.render_frame(base, view, [track], when, labels=True, unit="knots", project=False) again = fm.render_frame(base, view, [track], when, labels=True, unit="knots", project=False) assert np.array_equal(plain, again) def test_the_height_does_not_claim_to_know_a_foot_it_was_not_told(): """Most moments in an animation are between two reports and the height at them is interpolated. Mode S reports altitude in twenty-five foot steps, so a real reading survives untouched and an invented one stops pretending to be exact.""" track = straight(altitude=37_675) fix = track.fixes[0] assert fm.label_lines(track, fix, "knots", None)[0][0] \ .startswith("37,675 ft") from dataclasses import replace between = replace(fix, altitude_ft=37_699) assert fm.label_lines(track, between, "knots", None)[0][0] \ .startswith("37,700 ft") # --------------------------------------------------------------------------- # The box fades with the aircraft # --------------------------------------------------------------------------- def test_the_fade_level_follows_the_strength(): assert fm.fade_level(1.0) == 0 assert fm.fade_level(0.5) == 1 assert fm.fade_level(0.3) == 2 assert fm.fade_level(0.05) == 3 def test_each_fade_step_of_the_row_grey_is_darker_than_the_last(): greys = [fm.PALETTE[fm.LABEL_INK + i].astype(int).sum() for i in range(4)] assert greys == sorted(greys, reverse=True) assert greys[0] > greys[-1] * 3, "the last step is barely dimmer" def test_each_fade_step_of_a_flag_colour_is_darker_than_the_last(): for letter in ("r", "w", "b"): shades = [fm.PALETTE[fm.flag_index(letter, level)].astype(int).sum() for level in range(4)] assert shades == sorted(shades, reverse=True), letter def test_a_fading_label_is_drawn_fainter_than_a_full_one(): """The name already faded, because it is drawn in the aircraft's own colour. The rows and the flag were fixed colours, so the brightest thing left on that part of the picture was the one aeroplane nothing had been heard from.""" track = straight() view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0)) base = fm.background(view, unit="knots") entry = _Entry() def rows_of(strength): img = base.copy() fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots", entry=entry, strength=strength) drawn = img != base return fm.PALETTE[img[drawn]].astype(int).sum() full = rows_of(1.0) half = rows_of(0.5) nearly_gone = rows_of(0.05) assert half < full, "a fading label was as bright as a full one" assert nearly_gone < half def _label_pixels(strength, entry=None): """One label drawn at a strength, as the palette indices it used.""" track = straight() track.category = "large" view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0)) base = fm.background(view, unit="knots") img = base.copy() fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots", entry=entry if entry is not None else _Entry(), strength=strength) return set(np.unique(img[img != base]).tolist()) def test_the_rows_are_drawn_in_the_grey_for_the_strength_they_are_at(): """Not merely dimmer on average -- the label has a name in it that fades on its own -- but each row written in the grey that belongs to how far the aircraft has faded.""" full = _label_pixels(1.0) assert fm.LABEL_INK + 0 in full for strength, level in ((0.5, 1), (0.3, 2), (0.05, 3)): used = _label_pixels(strength) assert fm.LABEL_INK + level in used, strength assert not any(fm.LABEL_INK + other in used for other in range(4) if other != level), strength def test_the_flag_on_a_label_is_drawn_at_the_labels_own_fade_step(): from bandsaunter.flags import COLOUR_ORDER wide = len(COLOUR_ORDER) full = _label_pixels(1.0) assert any(fm.FLAG <= i < fm.FLAG + wide for i in full), "no flag drawn" for strength, level in ((0.5, 1), (0.3, 2), (0.05, 3)): used = _label_pixels(strength) assert not any(fm.FLAG <= i < fm.FLAG + wide for i in used), \ f"a full-strength flag on a label faded to {strength}" want = fm.FLAG_FADED + (level - 1) * wide assert any(want <= i < want + wide for i in used), strength def test_a_flag_on_a_fading_label_fades_with_it(): from bandsaunter.flags import FLAG_H, FLAG_W bright = np.full((40, 60), fm.BG, dtype=np.uint8) faint = np.full((40, 60), fm.BG, dtype=np.uint8) fm.draw_flag(bright, 5, 5, "US", 0) fm.draw_flag(faint, 5, 5, "US", 3) patch = (slice(5, 5 + FLAG_H), slice(5, 5 + FLAG_W)) assert fm.PALETTE[faint[patch]].astype(int).sum() < \ fm.PALETTE[bright[patch]].astype(int).sum() def test_a_named_country_with_no_flag_fades_too(): faint = np.full((40, 60), fm.BG, dtype=np.uint8) bright = np.full((40, 60), fm.BG, dtype=np.uint8) fm.draw_flag(bright, 5, 5, "ZZ", 0) fm.draw_flag(faint, 5, 5, "ZZ", 3) assert fm.PALETTE[faint].astype(int).sum() < \ fm.PALETTE[bright].astype(int).sum() def test_an_airport_cannot_be_mistaken_for_an_aircraft(): """The old amber sat sixteen units of CIELAB from the ramp's yellow, which is to say it was the same colour: an aeroplane low over a field was drawn in the field's own colour and neither could be picked out. Stated as the property rather than as the colour, so that changing the altitude ramp cannot quietly walk an aircraft back into the airports. """ def lab(rgb): c = np.asarray(rgb, float) / 255.0 c = np.where(c > 0.04045, ((c + 0.055) / 1.055) ** 2.4, c / 12.92) m = np.array([[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722], [0.0193, 0.1192, 0.9505]]) xyz = (c @ m.T) / np.array([0.9505, 1.0, 1.089]) f = np.where(xyz > 0.008856, np.cbrt(xyz), 7.787 * xyz + 16 / 116) return np.array([116 * f[1] - 16, 500 * (f[0] - f[1]), 200 * (f[1] - f[2])]) airport = lab(fm.PALETTE[fm.AIRPORT]) apart = min(float(np.linalg.norm(airport - lab(fm.PALETTE[fm.RAMP + i]))) for i in range(fm.RAMP_STEPS)) assert apart > 40, (f"the airport colour is {apart:.0f} units from the " f"nearest altitude colour; under about 25 they read " f"as the same colour") # --------------------------------------------------------------------------- # The flag on the receiver # --------------------------------------------------------------------------- def test_the_frame_flies_a_flag_where_the_receiver_was_told_it_is(): track = straight() view = fm.fit([track], width=600) middle = ((view.south + view.north) / 2, (view.west + view.east) / 2) base = fm.background(view, unit="knots") assert not (base == fm.HOME).any(), "the ground still flies the flag" flagged = fm.render_frame(base, view, [track], track.fixes[0].at, unit="knots", home=middle) assert (flagged == fm.HOME).any(), "no flag was drawn" # The foot of the pole is the position it is pointing at. x, y = view.xy(*middle) assert flagged[y, x] == fm.HOME def test_no_flag_where_nobody_said_the_receiver_is(): """The middle is otherwise worked out from whatever flew past, which is not a place anybody is standing, and a flag on it would say one is.""" track = straight() view = fm.fit([track], width=600) base = fm.background(view, unit="knots") assert not (fm.render_frame(base, view, [track], track.fixes[0].at, unit="knots") == fm.HOME).any() def test_a_receiver_outside_the_picture_is_not_flagged_at_its_edge(): track = straight() view = fm.fit([track], width=600) base = fm.background(view, unit="knots") away = (view.north + 20.0, view.east + 20.0) assert not (fm.render_frame(base, view, [track], track.fixes[0].at, unit="knots", home=away) == fm.HOME).any() def test_nothing_is_drawn_over_the_flag(): """It says where the receiver is standing, which is the one thing on the picture that must never be hidden behind an aeroplane that happened to fly over it.""" track = straight() view = fm.fit([track], width=600) base = fm.background(view, unit="knots") # An aircraft exactly on top of the receiver, with a label and a trail. here = (track.fixes[0].latitude, track.fixes[0].longitude) img = fm.render_frame(base, view, [track], track.fixes[0].at, unit="knots", labels=True, home=here, trail_seconds=600.0) x, y = view.xy(*here) assert img[y, x] == fm.HOME, "the aircraft was drawn over the flag" # The whole pole, not just its foot. pole = img[y - fm.HOME_POLE:y + 1, x] assert (pole == fm.HOME).all(), "part of the pole was painted over" def test_the_animation_flies_the_flag_only_where_it_was_given_a_centre(tmp_path): track = straight() middle = (track.fixes[0].latitude, track.fixes[0].longitude) told = fm.animate([track], tmp_path / "told.png", ground=False, airports=False, centre=middle, radius_nm=200.0) guessed = fm.animate([track], tmp_path / "guessed.png", ground=False, airports=False) assert told is not None and guessed is not None import numpy as np from PIL import Image def has_red(path): picture = np.array(Image.open(path).convert("RGB")) return bool(((picture[:, :, 0] == fm.HOME_RED[0]) & (picture[:, :, 1] == fm.HOME_RED[1]) & (picture[:, :, 2] == fm.HOME_RED[2])).any()) assert has_red(told.path) assert not has_red(guessed.path) # --------------------------------------------------------------------------- # The line from a label to its aircraft # --------------------------------------------------------------------------- def test_a_dashed_line_has_gaps_in_it(): img = np.full((40, 80), fm.BG, dtype=np.uint8) fm._dashed(img, 5, 20, 74, 20, fm.LEADER) row = img[20, 5:75] assert (row == fm.LEADER).any(), "nothing was drawn" assert (row == fm.BG).any(), "no gaps: that is a solid line" # On and off in the lengths asked for, near enough to the pixel. runs, last, count = [], row[0], 0 for value in row: if value == last: count += 1 else: runs.append((last, count)) last, count = value, 1 runs.append((last, count)) on = [n for value, n in runs[1:-1] if value == fm.LEADER] assert on and all(4 <= n <= 6 for n in on), on def test_a_dash_is_the_same_length_whichever_way_the_line_runs(): """Stepped along the line rather than along whichever axis is longer, so a nearly-horizontal leader and a nearly-vertical one come out the same instead of one of them turning into a dotted line.""" import math drawn = [] for x1, y1 in ((79, 21), (21, 39), (79, 39)): img = np.full((40, 80), fm.BG, dtype=np.uint8) fm._dashed(img, 1, 1, x1, y1, fm.LEADER) length = math.hypot(x1 - 1, y1 - 1) drawn.append((img == fm.LEADER).sum() / length) assert max(drawn) - min(drawn) < 0.25, drawn def test_a_leader_stops_at_the_aircraft_rather_than_running_past_it(): """Walked along the line's own length, so the last step lands on the far end. Walked along whichever axis is longer instead, a diagonal overshoots by half as much again and the leader carries on past the aeroplane it was drawn to point at.""" img = np.full((80, 80), fm.BG, dtype=np.uint8) fm._dashed(img, 10, 10, 50, 50, fm.LEADER) ys, xs = np.where(img == fm.LEADER) assert len(xs), "nothing was drawn" assert xs.max() <= 50 and ys.max() <= 50, \ f"ran past the end to ({xs.max()}, {ys.max()})" assert xs.min() >= 10 and ys.min() >= 10 # And it does reach it, near enough to the pixel. assert xs.max() >= 46 and ys.max() >= 46 def test_a_leader_that_goes_nowhere_draws_nothing(): img = np.full((40, 80), fm.BG, dtype=np.uint8) fm._dashed(img, 20, 20, 20, 20, fm.LEADER) assert not (img == fm.LEADER).any() def test_the_animation_ties_a_label_to_its_aircraft(): """The window has always had a leader; here there was nothing at all, and a label pushed out into one of the rings by a crowd had nothing tying it to the aeroplane it was about.""" track = straight() view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0)) base = fm.background(view, unit="knots") img = base.copy() fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots", entry=_Entry()) assert (img == fm.LEADER).any(), "no leader was drawn" def test_the_animation_leader_is_not_the_aircrafts_own_colour(): """A solid line running out of an aeroplane in the colour of the path behind it reads as more path; so does a line of any pattern in that colour, and this one is neither.""" from bandsaunter.flightmap import LEADER, PALETTE, RAMP, RAMP_STEPS leader = tuple(int(v) for v in PALETTE[LEADER]) ramp = {tuple(int(v) for v in PALETTE[RAMP + i]) for i in range(RAMP_STEPS)} assert leader not in ramp def test_the_leader_fades_with_the_label_it_belongs_to(): track = straight() view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0)) base = fm.background(view, unit="knots") def leader_shade(strength): img = base.copy() fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots", entry=_Entry(), strength=strength) drawn = {int(v) for v in np.unique(img[img != base])} return {v for v in drawn if fm.LEADER <= v <= fm.LEADER + 2} assert leader_shade(1.0) == {fm.LEADER} faded = leader_shade(0.45) assert faded and fm.LEADER not in faded, faded # --------------------------------------------------------------------------- # Range rings # --------------------------------------------------------------------------- def _ring_view(width=400): track = straight() return fm.fit([track], width=width, box=(50.0, -3.0, 52.0, 3.0)) def test_the_rings_lift_the_ground_more_the_nearer_the_middle_they_are(): """Concentric and translucent, so they stack: three lifts inside the innermost, two in the next, one in the outer, none beyond.""" view = _ring_view() home = ((view.south + view.north) / 2, (view.west + view.east) / 2) ground = np.zeros((view.height, view.width), dtype=np.uint8) img = fm.background(view, unit="knots", ground=ground, home=home, rings=60.0) lift = fm.RING_LIFT counts = [int((img == fm.GROUND + lift * n).sum()) for n in range(4)] assert all(counts), f"not every ring was drawn: {counts}" # Each ring is an annulus further out than the last, so it covers more # of the picture than the one inside it. assert counts[3] < counts[2] < counts[1], counts def test_the_rings_stack_on_a_picture_with_no_map_under_it(): """With no map there is nothing but background to lift, and a pixel the outer disc has lifted has to count as ground for the next one -- otherwise every ring lands on bare background and they all come out the same shade.""" view = _ring_view() home = ((view.south + view.north) / 2, (view.west + view.east) / 2) img = fm.background(view, unit="knots", home=home, rings=60.0) lift = fm.RING_LIFT shades = [int((img == fm.GROUND + lift * n).sum()) for n in (1, 2, 3)] assert all(shades), f"the rings did not stack: {shades}" assert shades[0] > shades[1] > shades[2], shades def test_the_rings_stop_at_the_radius_they_were_given(): view = _ring_view() home = ((view.south + view.north) / 2, (view.west + view.east) / 2) ground = np.zeros((view.height, view.width), dtype=np.uint8) img = fm.background(view, unit="knots", ground=ground, home=home, rings=60.0) away = fm._distance_field( home, view.north - (view.north - view.south) * (np.arange(view.height) + 0.5) / view.height, view.west + (view.east - view.west) * (np.arange(view.width) + 0.5) / view.width) # The view sits inside the canvas, below the title and inside the # margins, so the distance field lines up with that part of it. patch = img[view.top:view.top + view.height, view.left:view.left + view.width] # Ground only: the flag is drawn over the middle of the innermost ring # and is not ground that was lifted. ground = (patch >= fm.GROUND) & (patch < fm.GROUND + fm.GROUND_SHADES) lifted = ground & (patch > fm.GROUND) beyond = away > 60.0 * 0.75 + 1.0 assert not (lifted & beyond).any(), \ "the ground beyond the outer ring was lifted" assert (lifted & (away < 60.0 * 0.25)).any(), "the innermost ring is missing" def test_no_rings_without_a_radius_or_without_a_position(): view = _ring_view() home = ((view.south + view.north) / 2, (view.west + view.east) / 2) ground = np.zeros((view.height, view.width), dtype=np.uint8) plain = fm.background(view, unit="knots", ground=ground) assert np.array_equal( fm.background(view, unit="knots", ground=ground, home=None, rings=60.0), plain) # A position on its own is not a reason to draw rings: it is the radius # that says how far out they go. placed = fm.background(view, unit="knots", ground=ground, home=home) assert not (placed == fm.GROUND + fm.RING_LIFT).any() def _labels_drawn(**over): """Every string the drawing was asked to stamp, in order. Read by watching the drawing rather than by looking for the letters in the picture afterwards: a picture with a ring on it has large areas of one flat colour, and searching those for a pattern of pixels finds whatever it is asked for. """ view = _ring_view(width=700) home = ((view.south + view.north) / 2, (view.west + view.east) / 2) said = [] real = fm.draw_text def watch(img, x, y, text, colour): said.append(text) return real(img, x, y, text, colour) fm.draw_text = watch try: fm.background(view, home=home, rings=60.0, **over) finally: fm.draw_text = real return said def test_each_ring_is_labelled_with_how_far_out_it_is(): said = _labels_drawn(unit="knots") for nm in (15, 30, 45): assert f"{nm} NM" in said, (nm, said) def test_the_ring_labels_are_in_the_unit_the_rest_of_the_picture_uses(): """Miles an hour beside a ring measured in nautical miles would be two different miles on one picture.""" said = _labels_drawn(unit="mph") assert "17 MI" in said, said # 15 nm, written as statute assert not any(word.endswith(" NM") for word in said), said def test_the_rings_leave_the_aerodromes_and_the_grid_alone(): """They only lift pixels that are still map or still empty.""" view = _ring_view() home = ((view.south + view.north) / 2, (view.west + view.east) / 2) airports = [("EGLL", home[0], home[1] + 0.2)] img = fm.background(view, unit="knots", airports=airports, home=home, rings=300.0) assert (img == fm.AIRPORT).any(), "the aerodrome was washed out" assert (img == fm.GRID).any(), "the grid was washed out" def test_a_distance_field_measures_from_the_place_it_was_given(): lats = np.array([51.0, 52.0]) lons = np.array([-1.0, -1.0]) away = fm._distance_field((51.0, -1.0), lats, lons) assert away[0, 0] == pytest.approx(0.0, abs=0.01) # A degree of latitude is sixty nautical miles, near enough. assert away[1, 0] == pytest.approx(60.0, abs=0.5) # --------------------------------------------------------------------------- # The card behind a label # --------------------------------------------------------------------------- def _labelled(opacity, shade=20): track = straight() view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0)) ground = np.full((view.height, view.width), shade, dtype=np.uint8) base = fm.background(view, unit="knots", ground=ground, brightness=1.0) img = base.copy() fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots", entry=_Entry(), opacity=opacity) return base, img def test_no_card_at_all_puts_the_words_straight_on_the_map(): """Which is what the pictures used to look like, and still can.""" base, img = _labelled(0.0) # Only pixels that are still map in both: the words themselves turn map # into ink, and that is the label being drawn rather than a card. ground = (base >= fm.GROUND) & (base < fm.GROUND + fm.GROUND_SHADES) still = ground & (img >= fm.GROUND) & (img < fm.GROUND + fm.GROUND_SHADES) assert np.array_equal(img[still], base[still]), "the map was darkened" def test_a_card_darkens_the_map_under_the_words(): base, img = _labelled(0.6) darker = (img < base) & (base >= fm.GROUND) & \ (base < fm.GROUND + fm.GROUND_SHADES) assert darker.sum() > 200, "nothing was darkened" # And the coastline still shows through: not everything went to one shade. under = img[darker] assert under.max() > under.min() or under.min() > fm.GROUND def test_the_card_gets_darker_the_more_of_it_is_asked_for(): def under(opacity): base, img = _labelled(opacity) return int(img[195:215, 295:400].astype(int).sum()) steps = [under(part) for part in (0.0, 0.3, 0.6, 0.9)] assert steps == sorted(steps, reverse=True), steps def test_a_card_the_whole_way_up_is_a_solid_panel(): base, img = _labelled(1.0) assert (img == fm.PANEL).any(), "the panel colour was never used" ground = (base >= fm.GROUND) & (base < fm.GROUND + fm.GROUND_SHADES) covered = ground & (img == fm.PANEL) assert covered.sum() > 200, "the map still shows through a solid panel" def test_the_card_fades_with_the_label_it_is_behind(): """A card at full strength under a label on its way out would be the brightest thing left of it.""" track = straight() view = fm.fit([track], width=800, box=(50.0, -3.0, 52.0, 3.0)) ground = np.full((view.height, view.width), 20, dtype=np.uint8) base = fm.background(view, unit="knots", ground=ground, brightness=1.0) def darkness(strength): img = base.copy() fm._label(img, 300, 200, track, track.fixes[0], fm.RAMP, [], "knots", entry=_Entry(), opacity=0.9, strength=strength) # How much darker, not how many pixels: a fainter card covers the # same rectangle and merely takes less out of it. return int((base.astype(int) - img.astype(int)).clip(0).sum()) assert darkness(1.0) > darkness(0.5) > 0