Skip to content

Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)

Infer missing aircraft velocity within each observed trajectory segment

Cinna Davisdec2c74aafbd
diff --git a/src/aircraft_geoloc/tracks.py b/src/aircraft_geoloc/tracks.py
index a0b5824..b9c81e5 100644
--- a/src/aircraft_geoloc/tracks.py
+++ b/src/aircraft_geoloc/tracks.py
@@ -6,7 +6,7 @@ from pathlib import Path
import numpy as np
import pandas as pd
-from .geometry import Track, velocity_ecef
+from .geometry import Track, ecef, velocity_ecef
def unix_time(value):
@@ -67,18 +67,46 @@ def adsblol_frame(d):
basis="ellipsoidal_interpolated"
else:
altitude,basis=p[3],"barometric"
- speed=(p[4] or 0)*0.514444
- heading=np.deg2rad(p[5] or 0)
+ # Null measurements are unavailable, not measured zero. Preserve them
+ # until position-derived velocities can be inferred after gap splitting.
+ speed=p[4]*0.514444 if p[4] is not None else np.nan
+ heading=np.deg2rad(p[5]) if p[5] is not None else np.nan
+ east,north=(0.0,0.0) if speed==0 else (speed*np.sin(heading),speed*np.cos(heading))
rate=p[11] if len(p)>11 and p[11] is not None else p[7]
rows.append({"flight_id": d["icao"],
"time_s": d["timestamp"] + p[0], "lat": p[1], "lon": p[2],
"alt_m": altitude*0.3048,"speed_mps":speed,"heading_deg":p[5],
- "east_mps":speed*np.sin(heading),"north_mps":speed*np.cos(heading),
- "up_mps":(rate or 0)*0.00508,
+ "east_mps":east,"north_mps":north,
+ "up_mps":rate*0.00508 if rate is not None else np.nan,
"typecode":metadata.get("t",d.get("t","")),"altitude_basis":basis})
return pd.DataFrame(rows)
+def _segment_velocity(chunk):
+ """Fill only missing ENU components using this gap-split segment's positions."""
+ columns=("east_mps","north_mps","up_mps")
+ enu=np.column_stack([chunk[name].to_numpy(dtype=float) if name in chunk else
+ np.full(len(chunk),np.nan) for name in columns])
+ missing=~np.isfinite(enu)
+ counts={name:int(missing[:,i].sum()) for i,name in enumerate(columns)}
+ if missing.all():
+ # Track's default derivative uses the same segment-local gradient.
+ return None,counts
+ lat,lon=chunk.lat.to_numpy(),chunk.lon.to_numpy()
+ if missing.any():
+ times=chunk.time_s.to_numpy()
+ xyz=ecef(lat,lon,chunk.alt_m.to_numpy())
+ vx,vy,vz=np.gradient(xyz,times-times[0],axis=0).T
+ phi,lam=np.deg2rad(lat),np.deg2rad(lon)
+ inferred=np.column_stack((
+ -np.sin(lam)*vx+np.cos(lam)*vy,
+ -np.sin(phi)*np.cos(lam)*vx-np.sin(phi)*np.sin(lam)*vy+np.cos(phi)*vz,
+ np.cos(phi)*np.cos(lam)*vx+np.cos(phi)*np.sin(lam)*vy+np.sin(phi)*vz,
+ ))
+ enu=np.where(missing,inferred,enu)
+ return velocity_ecef(lat,lon,*enu.T),counts
+
+
def load_tracks(path, max_gap_s=30.0, type_database=None, bounds=None, time_range=None):
path = Path(path)
if path.suffix.lower() == ".kml":
@@ -107,6 +135,7 @@ def load_tracks(path, max_gap_s=30.0, type_database=None, bounds=None, time_rang
table = pd.read_csv(type_database).fillna("")
types = dict(zip(table.designator, table.engine_type.str.lower()))
tracks, rejected = [], []
+ inferred_components={name:0 for name in ("east_mps","north_mps","up_mps")}
for flight_id, group in df.groupby("flight_id", sort=False):
group = group.sort_values("time_s").drop_duplicates("time_s")
group = group.dropna(subset=list(required))
@@ -118,13 +147,14 @@ def load_tracks(path, max_gap_s=30.0, type_database=None, bounds=None, time_rang
for index, (_, chunk) in enumerate(group.groupby(chunks)):
if len(chunk) < 3:
continue
- v = None
- if {"east_mps", "north_mps", "up_mps"}.issubset(chunk):
- v = velocity_ecef(chunk.lat.to_numpy(), chunk.lon.to_numpy(),
- chunk.east_mps.to_numpy(), chunk.north_mps.to_numpy(), chunk.up_mps.to_numpy())
+ v,counts = _segment_velocity(chunk)
+ for name,count in counts.items():
+ inferred_components[name]+=count
identifier = str(flight_id) + (f":{index}" if chunks.max() else "")
tracks.append(Track(identifier, chunk.time_s.to_numpy(), chunk.lat.to_numpy(),
chunk.lon.to_numpy(), chunk.alt_m.to_numpy(), code, v))
return tracks, {"rows": len(df), "segments": len(tracks), "known_jets_excluded": rejected,
"altitude_basis_counts":df.altitude_basis.value_counts().to_dict() if "altitude_basis" in df else {},
+ "velocity_inferred_components":inferred_components,
+ "velocity_inference_method":"position_gradient_within_gap_split_segment",
"unknown_types_retained": True}
diff --git a/tests/test_missing_velocity.py b/tests/test_missing_velocity.py
new file mode 100644
index 0000000..a2c689b
--- /dev/null
+++ b/tests/test_missing_velocity.py
@@ -0,0 +1,180 @@
+"""Missing ADS-B motion fields must not create stationary aircraft samples.
+
+The oracle is a constant Cartesian velocity, converted to readsb's geodetic
+positions and ENU measurements with pyproj and an independent basis rotation.
+Neither the package's ECEF conversion nor its velocity inference builds truth.
+"""
+import gzip
+import json
+
+import numpy as np
+import pandas as pd
+import pytest
+from numpy.testing import assert_allclose
+from pyproj import Transformer
+
+from aircraft_geoloc.tracks import adsblol_frame, load_tracks
+
+
+EPOCH = 1_790_000_000.0
+VELOCITY = np.array([82.0, -21.0, 6.0])
+OFFSETS = np.array([0.0, 2.0, 6.0, 12.0, 20.0, 27.0])
+TO_ECEF = Transformer.from_crs("EPSG:4979", "EPSG:4978", always_xy=True)
+TO_GEODETIC = Transformer.from_crs("EPSG:4978", "EPSG:4979", always_xy=True)
+ORIGIN = np.array(TO_ECEF.transform(-100.0, 40.0, 2000.0))
+NULL_FIELDS = ("speed", "heading", "vertical_rate", "all")
+
+
+def _enu_basis(lat_deg, lon_deg):
+ lat, lon = np.deg2rad([lat_deg, lon_deg])
+ return np.array([
+ [-np.sin(lon), np.cos(lon), 0.0],
+ [-np.sin(lat) * np.cos(lon), -np.sin(lat) * np.sin(lon), np.cos(lat)],
+ [np.cos(lat) * np.cos(lon), np.cos(lat) * np.sin(lon), np.sin(lat)],
+ ])
+
+
+def _trace(offsets=OFFSETS, velocity=VELOCITY, origin=ORIGIN):
+ xyz = origin + (offsets - offsets[0])[:, None] * velocity
+ lon, lat, height = TO_GEODETIC.transform(*xyz.T)
+ rows = []
+ for dt, latitude, longitude, altitude in zip(offsets, lat, lon, height):
+ east, north, up = _enu_basis(latitude, longitude) @ velocity
+ speed_knots = np.hypot(east, north) / (1852.0 / 3600.0)
+ heading_deg = np.rad2deg(np.arctan2(east, north)) % 360.0
+ altitude_ft = altitude / 0.3048
+ vertical_rate_fpm = up / 0.00508
+ rows.append([
+ float(dt), float(latitude), float(longitude), float(altitude_ft),
+ float(speed_knots), float(heading_deg), 0, float(vertical_rate_fpm),
+ {"t": "C172"}, None, float(altitude_ft), float(vertical_rate_fpm),
+ ])
+ return {"icao": "a0b1c2", "timestamp": EPOCH, "trace": rows}
+
+
+def _remove_fields(trace, fields, indices=None):
+ if indices is None:
+ indices = range(len(trace["trace"]))
+ for index in indices:
+ row = trace["trace"][index]
+ if fields in ("speed", "all"):
+ row[4] = None
+ if fields in ("heading", "all"):
+ row[5] = None
+ if fields in ("vertical_rate", "all"):
+ row[7] = row[11] = None
+
+
+def _write_trace(tmp_path, trace, compressed=False):
+ # readsb daily archives can contain gzip bytes under a .json filename.
+ path = tmp_path / "trace_full_a0b1c2.json"
+ payload = json.dumps(trace, allow_nan=False).encode()
+ path.write_bytes(gzip.compress(payload) if compressed else payload)
+ return path
+
+
+def _assert_linear_track(track, origin, velocity):
+ sample_times = np.unique(np.r_[track.time, (track.time[:-1] + track.time[1:]) / 2])
+ expected_positions = origin + (sample_times - track.time[0])[:, None] * velocity
+ # The importer currently rounds knots->m/s to six decimals. Permit that
+ # harmless sub-mm/s difference without permitting zero or invented motion.
+ assert_allclose(track.speed_vector(sample_times),
+ np.broadcast_to(velocity, (len(sample_times), 3)), atol=2e-4, rtol=0)
+ assert_allclose(track.position(sample_times), expected_positions, atol=0.003, rtol=0)
+
+
[email protected]("fields", NULL_FIELDS)
+def test_adsblol_importer_preserves_unknown_velocity_components(fields):
+ trace = _trace()
+ _remove_fields(trace, fields, indices=[2])
+ frame = adsblol_frame(trace)
+ if fields in ("speed", "all"):
+ assert pd.isna(frame.loc[2, "speed_mps"]), "unknown ground speed is not 0 m/s"
+ if fields in ("speed", "heading", "all"):
+ assert frame.loc[2, ["east_mps", "north_mps"]].isna().all(), (
+ "unknown horizontal motion must remain nullable until track-local inference"
+ )
+ if fields in ("vertical_rate", "all"):
+ assert pd.isna(frame.loc[2, "up_mps"]), "missing both climb-rate fields is not 0 m/s"
+ assert np.isfinite(frame.loc[0, ["east_mps", "north_mps", "up_mps"]].to_numpy(dtype=float)).all()
+
+
[email protected]("fields", NULL_FIELDS)
+def test_load_tracks_infers_nullable_trace_velocity_from_positions(tmp_path, fields):
+ trace = _trace()
+ _remove_fields(trace, fields)
+ tracks, report = load_tracks(_write_trace(tmp_path, trace))
+ assert report["segments"] == len(tracks) == 1
+ _assert_linear_track(tracks[0], ORIGIN, VELOCITY)
+
+
[email protected]("suffix", ["csv", "parquet"])
+def test_load_tracks_infers_partial_null_canonical_velocity(tmp_path, suffix):
+ frame = adsblol_frame(_trace())
+ # Canonical formats must work too; nulls can affect independent components
+ # in different rows even when the velocity columns exist for the whole table.
+ for row, column in [(1, "east_mps"), (2, "north_mps"), (3, "up_mps")]:
+ frame.loc[row, column] = np.nan
+ path = tmp_path / f"tracks.{suffix}"
+ if suffix == "csv":
+ frame.to_csv(path, index=False)
+ else:
+ frame.to_parquet(path, index=False)
+ tracks, _ = load_tracks(path)
+ assert len(tracks) == 1
+ _assert_linear_track(tracks[0], ORIGIN, VELOCITY)
+
+
+def test_velocity_inference_uses_each_gap_split_segment(tmp_path):
+ second_offsets = np.array([130.0, 132.0, 137.0, 143.0, 153.0])
+ second_origin = ORIGIN + np.array([5000.0, -4000.0, 3000.0])
+ second_velocity = np.array([-40.0, 15.0, -3.0])
+ trace = _trace()
+ trace["trace"].extend(_trace(second_offsets, second_velocity, second_origin)["trace"])
+ _remove_fields(trace, "all")
+ tracks, report = load_tracks(_write_trace(tmp_path, trace, compressed=True), max_gap_s=30.0)
+ assert report["segments"] == len(tracks) == 2
+ _assert_linear_track(tracks[0], ORIGIN, VELOCITY)
+ _assert_linear_track(tracks[1], second_origin, second_velocity)
+ # In particular, the last derivative before the gap and the first after it
+ # must not use the distant segment's positions. There is no interpolation
+ # through the unobserved interval either.
+ middle_of_gap = (tracks[0].time[-1] + tracks[1].time[0]) / 2
+ for track in tracks:
+ assert np.isnan(track.position(middle_of_gap)).all()
+ assert np.isnan(track.speed_vector(middle_of_gap)).all()
+
+
+def test_measured_zero_velocity_is_preserved(tmp_path):
+ trace = _trace()
+ # A reported stop is a real derivative constraint even when the positions
+ # before/after that knot would give a nonzero finite-difference slope.
+ row = trace["trace"][2]
+ row[4], row[5], row[7], row[11] = 0.0, None, 0.0, None
+ frame = adsblol_frame(trace)
+ assert_allclose(frame.loc[2, ["east_mps", "north_mps", "up_mps"]].to_numpy(dtype=float), 0.0)
+ tracks, _ = load_tracks(_write_trace(tmp_path, trace))
+ assert_allclose(tracks[0].speed_vector(EPOCH + row[0]), 0.0, atol=1e-12)
+
+
+def test_missing_horizontal_velocity_keeps_measured_zero_climb(tmp_path):
+ trace = _trace()
+ row = trace["trace"][2]
+ row[4] = row[5] = None
+ row[7] = row[11] = 0.0
+ basis = _enu_basis(row[1], row[2])
+ expected_enu = basis @ VELOCITY
+ expected_enu[2] = 0.0
+ tracks, _ = load_tracks(_write_trace(tmp_path, trace))
+ assert_allclose(tracks[0].speed_vector(EPOCH + row[0]), basis.T @ expected_enu, atol=2e-4, rtol=0)
+
+
+def test_missing_climb_keeps_measured_zero_horizontal_velocity(tmp_path):
+ trace = _trace()
+ row = trace["trace"][2]
+ row[4], row[5], row[7], row[11] = 0.0, None, None, None
+ basis = _enu_basis(row[1], row[2])
+ expected_enu = basis @ VELOCITY
+ expected_enu[:2] = 0.0
+ tracks, _ = load_tracks(_write_trace(tmp_path, trace))
+ assert_allclose(tracks[0].speed_vector(EPOCH + row[0]), basis.T @ expected_enu, atol=2e-4, rtol=0)