Skip to content

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

Guard continuous motion support before CPA and acoustic fitting (#64)

Cinna Davis7dd4a0f89a44
diff --git a/docs/MOTION_SUPPORT.md b/docs/MOTION_SUPPORT.md
new file mode 100644
index 0000000..c54f9cf
--- /dev/null
+++ b/docs/MOTION_SUPPORT.md
@@ -0,0 +1,53 @@
+# Trajectory motion support
+
+The emission-time model assumes subsonic three-dimensional source motion. A
+positive observer-specific arrival derivative does not establish this assumption:
+an inconsistent native position interval can pass that radial check and fit an
+acoustic ridge exactly from a side observer. No interpolation or acoustic fit
+repairs such a source inconsistency.
+
+`Track.validate_motion_support(c)` checks each native Hermite interval before CPA
+proposal generation. A quadratic Bezier velocity bound cheaply certifies ordinary
+intervals. When that bound reaches sound speed, endpoints and real stationary
+points of squared speed determine the continuous maximum. Results are cached per
+interval and rechecked against each requested sound speed. This uses floating
+point polynomial roots, not formally certified interval arithmetic; a relative
+1e-10 margin treats the sonic boundary as unsupported. Work and storage scale
+linearly with the number of native intervals, with at most one cubic root solve
+per suspicious interval over the Track's lifetime.
+
+Both sparse and dense `search.cpa_table` paths, and `Track.closest_approaches`,
+invoke the whole-source validator. An unsupported interval raises
+`AcousticSupportError(track_id, "non_subsonic_motion")`. Its additive
+`emission_intervals_s` field retains the affected native time intervals. CPA has
+no narrower receive envelope: `receive_intervals_s` is `None`. The outer search
+may preserve other track rows while recording the whole affected track/tile
+scope as lost model coverage. It must keep the search partial and finite evidence
+incomplete. Calling the CPA function directly still propagates the typed failure;
+it does not silently drop the source.
+
+Direct `Track.acoustic` scoring checks only possible arrivals from unsupported
+native intervals. Cubic Bezier position boxes bound minimum/maximum range to the
+observer; adding those travel-time bounds to the native interval encloses all
+possible arrival times without assuming monotonic motion there. An overlapping
+requested receive sample raises the same typed failure with both emission and
+conservative receive intervals. A separate, clean event outside these envelopes
+can retain its original emission-time solution even if the trace is inconsistent
+elsewhere. An entire native interval is conservatively unsupported, including
+its slower portions; this guard does not split or repair it. Existing
+`non_monotone_arrival` failures and messages are preserved.
+
+The robust clock-trial adapter records these failures as unknown, never as an
+acoustic rejection or an evaluated fit. A perfect ridge match cannot establish
+physical support. The guard does not change source observations, velocity
+inference, interpolation, altitude labels, gap rules, clock grids or acceptance
+thresholds. It does not establish source correctness, independent real accuracy
+or complete national coverage. The fresh-raw audit and preserved historical
+failures remain in [research/trajectory-motion](../research/trajectory-motion/README.md).
+
+Independent controls cover a 750 m/s interior peak hidden by zero measured knot
+velocities and monotone side-view arrival times, its incorrectly perfect old
+acoustic fit, a 300 m/s control, an unaffected separate event, actual sparse/dense
+CPA failures, sound-speed sensitivity, conservative arrival envelopes and a dense
+continuous-speed oracle. W2's outer isolation must additionally verify an actual
+bad-source plus clean-source search and all-invalid abstention.
diff --git a/scripts/check_motion_support.py b/scripts/check_motion_support.py
new file mode 100644
index 0000000..97dd5b9
--- /dev/null
+++ b/scripts/check_motion_support.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+"""Compare production support exclusions with the preserved raw-motion audit.
+
+This bounded source-only check reads no audio, receiver truth or search output.
+It neither alters the historical audit nor performs a localization replay.
+"""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+
+import pandas as pd
+
+from aircraft_geoloc.data_access import _frame_track
+from aircraft_geoloc.geometry import AcousticSupportError
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--audit", type=Path, default=Path("research/trajectory-motion/frozen"))
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ args.output.mkdir(parents=True, exist_ok=False)
+ report_path = args.audit/"report.json"
+ report = json.loads(report_path.read_text())
+ canonical_path = args.audit/"canonical-observations.json"
+ canonical = pd.read_json(canonical_path)
+ inputs = [report_path, canonical_path]
+ rows = []
+ for aircraft in report["aircraft"]:
+ identity = aircraft["identity"]
+ fresh_path = args.audit/f"fresh-{identity}.json"
+ fresh = pd.read_json(fresh_path)
+ inputs.append(fresh_path)
+ for tag, frame in (("canonical", canonical[canonical.flight_id == identity]), ("fresh", fresh)):
+ for segment in aircraft[tag]["segments"]:
+ intervals = segment["intervals"]
+ chunk = frame[frame.time_s.between(intervals[0]["start_s"], intervals[-1]["end_s"])]
+ chunk = chunk.sort_values("time_s", kind="stable").drop_duplicates("time_s")
+ track = _frame_track(segment["id"], chunk)
+ expected = [[i["start_s"], i["end_s"]] for i in intervals if i["exceeds_subsonic_speed"]]
+ try:
+ track.validate_motion_support(c=report["declaration"]["sound_speed_mps"])
+ excluded = []
+ except AcousticSupportError as error:
+ assert error.reason == "non_subsonic_motion"
+ excluded = error.emission_intervals_s
+ assert excluded == expected, (tag, track.id, expected, excluded)
+ rows.append({"source": tag, "track_id": track.id, "native_intervals": len(intervals),
+ "excluded_intervals_s": excluded, "audit_agrees": True})
+ root = Path(__file__).resolve().parents[1]
+ code = [Path(__file__), root/"src/aircraft_geoloc/geometry.py", root/"src/aircraft_geoloc/data_access.py"]
+ receipt = {"scope": "source_only_production_guard_comparison", "segments": rows,
+ "code_commit": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True, cwd=root).strip(),
+ "code_sha256": {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in code},
+ "input_sha256": {str(p): hashlib.sha256(p.read_bytes()).hexdigest() for p in inputs},
+ "excluded_native_intervals": sum(len(r["excluded_intervals_s"]) for r in rows),
+ "limitations": ["No source repair, acoustic scoring, tile replay or accuracy claim",
+ "Whole native intervals are conservative model exclusions"]}
+ (args.output/"receipt.json").write_text(json.dumps(receipt, indent=2, allow_nan=False)+"\n")
+ print(f"{len(rows)} source segments agree; {receipt['excluded_native_intervals']} excluded native intervals")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/aircraft_geoloc/geometry.py b/src/aircraft_geoloc/geometry.py
index c826f32..4a5aded 100644
--- a/src/aircraft_geoloc/geometry.py
+++ b/src/aircraft_geoloc/geometry.py
@@ -14,8 +14,10 @@ from scipy.signal import find_peaks
class AcousticSupportError(ValueError):
"""A trajectory cannot support the assumed emission-time acoustic model."""
- def __init__(self, track_id, reason):
+ def __init__(self, track_id, reason, *, emission_intervals_s=None, receive_intervals_s=None):
self.track_id, self.reason = track_id, reason
+ self.emission_intervals_s = emission_intervals_s
+ self.receive_intervals_s = receive_intervals_s
super().__init__(f"{track_id}: {reason}")
@@ -60,6 +62,14 @@ class Track:
v = np.gradient(self.xyz, self.relative_time, axis=0)
self.spline = CubicHermiteSpline(self.relative_time, self.xyz, v, extrapolate=False)
self.derivative = self.spline.derivative()
+ # The derivative's quadratic Bezier control vectors bound its speed.
+ # Most clean intervals need no polynomial roots; exact maxima are cached
+ # only when this inexpensive upper bound reaches the requested c.
+ v = np.asarray(v)
+ middle = 3*np.diff(self.xyz, axis=0)/np.diff(self.time)[:, None]-v[:-1]-v[1:]
+ self._speed_upper = np.maximum.reduce([np.linalg.norm(a, axis=1)
+ for a in (v[:-1], middle, v[1:])])
+ self._speed_peak = np.full(len(self.time)-1, np.nan)
def position(self, t):
return self.spline(np.asarray(t) - self.origin)
@@ -67,6 +77,66 @@ class Track:
def speed_vector(self, t):
return self.derivative(np.asarray(t) - self.origin)
+ def _unsupported_motion_intervals(self, c):
+ """Find non-subsonic native spline intervals, caching speed extrema.
+
+ Velocity is quadratic in normalized interval time. Its squared norm is
+ quartic, so endpoints and real roots of its cubic derivative enumerate
+ all extrema (in double precision). A small margin treats the sonic
+ boundary as unsupported.
+ """
+ limit = c*(1-1e-10)
+ suspicious = np.flatnonzero(self._speed_upper >= limit)
+ for i in suspicious:
+ dt = self.time[i+1]-self.time[i]
+ if np.isnan(self._speed_peak[i]):
+ a, b, d = self.derivative.c[:, i]
+ a, b = a*dt**2, b*dt
+ stationary = [2*np.dot(b, d), 2*(np.dot(b, b)+2*np.dot(a, d)),
+ 6*np.dot(a, b), 4*np.dot(a, a)]
+ roots = np.polynomial.polynomial.polyroots(stationary)
+ samples = [0., 1.] + [float(r.real) for r in roots
+ if abs(r.imag) <= 1e-8 and 0 < r.real < 1]
+ self._speed_peak[i] = max(np.linalg.norm((a*u+b)*u+d) for u in samples)
+ return suspicious[self._speed_peak[suspicious] >= limit]
+
+ def validate_motion_support(self, c=343.0):
+ """Require subsonic motion throughout the source used for CPA proposals.
+
+ The outer search may isolate this track and retain incomplete coverage.
+ Direct ridge scoring instead tests the time-local arrival envelope below.
+ """
+ indices = self._unsupported_motion_intervals(c)
+ if len(indices):
+ raise AcousticSupportError(self.id, "non_subsonic_motion",
+ emission_intervals_s=[[float(self.time[i]), float(self.time[i+1])] for i in indices])
+
+ def _check_motion_support(self, receive_time, observer, c):
+ """Reject possible arrivals from unsupported native emission intervals.
+
+ Bezier position boxes conservatively enclose affected arrival times,
+ without assuming monotonic propagation in an unsupported interval.
+ """
+ emissions, arrivals = [], []
+ for i in self._unsupported_motion_intervals(c):
+ dt = self.time[i+1]-self.time[i]
+ p0, p1 = self.xyz[i:i+2]
+ v0, v1 = self.speed_vector(self.time[i:i+2])
+ controls = np.array([p0, p0+dt*v0/3, p1-dt*v1/3, p1])
+ lo, hi = controls.min(axis=0), controls.max(axis=0)
+ nearest = np.maximum(np.maximum(lo-observer, observer-hi), 0)
+ farthest = np.maximum(np.abs(lo-observer), np.abs(hi-observer))
+ arrival_lo = self.time[i]+np.linalg.norm(nearest)/c
+ arrival_hi = self.time[i+1]+np.linalg.norm(farthest)/c
+ # Enlarge for Unix-epoch rounding rather than excluding an endpoint.
+ tolerance = max(1e-7, 4*abs(np.spacing(max(abs(arrival_lo), abs(arrival_hi)))))
+ if np.any((receive_time >= arrival_lo-tolerance) & (receive_time <= arrival_hi+tolerance)):
+ emissions.append([float(self.time[i]), float(self.time[i+1])])
+ arrivals.append([float(arrival_lo-tolerance), float(arrival_hi+tolerance)])
+ if emissions:
+ raise AcousticSupportError(self.id, "non_subsonic_motion",
+ emission_intervals_s=emissions, receive_intervals_s=arrivals)
+
def acoustic(self, receive_time, observer, c=343.0):
"""Return Doppler factor, emission time and range at receiver-clock times.
@@ -95,10 +165,12 @@ class Track:
distance = np.linalg.norm(delta, axis=-1)
radial = np.sum(delta * self.speed_vector(tau), axis=-1) / distance
factor = c / (c + radial)
+ self._check_motion_support(t, observer, c)
return tuple(np.where(supported, a, np.nan) for a in (factor, tau, distance))
def closest_approaches(self, observer, max_distance=np.inf, c=343.0, step=2.0):
"""All interior local 3-D minima, including repeated passes by one flight."""
+ self.validate_motion_support(c)
sample = np.unique(np.r_[np.arange(self.time[0], self.time[-1], step), self.time[-1]])
range2 = np.sum((self.position(sample) - observer) ** 2, axis=-1)
indices = find_peaks(-range2)[0]
diff --git a/src/aircraft_geoloc/search.py b/src/aircraft_geoloc/search.py
index 228ae12..30c2b46 100644
--- a/src/aircraft_geoloc/search.py
+++ b/src/aircraft_geoloc/search.py
@@ -18,6 +18,7 @@ def cpa_table_dense(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_siz
observers = ecef(points.lat.to_numpy(),points.lon.to_numpy(),points.elev_m.to_numpy())
rows = []
for track in tracks:
+ track.validate_motion_support(c)
t = np.unique(np.r_[np.arange(track.time[0],track.time[-1],step_s),track.time[-1]])
pos = track.position(t)
# Prune trajectory segments outside this observer tile before forming a
@@ -80,6 +81,7 @@ def cpa_table(tracks,points,max_distance,c=343.0,step_s=2.0,chunk_size=512):
point_ids=points.point_id.to_numpy(dtype=int)
rows=[]
for track in tracks:
+ track.validate_motion_support(c)
t=np.unique(np.r_[np.arange(track.time[0],track.time[-1],step_s),track.time[-1]])
pos=track.position(t)
max_step=np.max(np.linalg.norm(np.diff(pos,axis=0),axis=1))
diff --git a/tests/test_motion_support.py b/tests/test_motion_support.py
new file mode 100644
index 0000000..f7d82a2
--- /dev/null
+++ b/tests/test_motion_support.py
@@ -0,0 +1,131 @@
+"""Physical model boundary controls independent of acoustic-fit success."""
+from types import SimpleNamespace
+
+import numpy as np
+import pandas as pd
+import pytest
+from pyproj import Transformer
+
+from aircraft_geoloc.geometry import AcousticSupportError, Track, ecef
+from aircraft_geoloc.matching import RidgeTimes
+from aircraft_geoloc.search import score_candidate
+from aircraft_geoloc.search import cpa_table, cpa_table_dense
+
+
+def side_view(displacement=1000):
+ """Zero knot velocities hide a 1.5*displacement/2 interior peak."""
+ observer = ecef(40, -100, 100)
+ lat, lon = np.deg2rad([40, -100])
+ east = np.array([-np.sin(lon), np.cos(lon), 0])
+ north = np.array([-np.sin(lat)*np.cos(lon), -np.sin(lat)*np.sin(lon), np.cos(lat)])
+ up = np.array([np.cos(lat)*np.cos(lon), np.cos(lat)*np.sin(lon), np.sin(lat)])
+ x = np.array([-displacement/2-160, -displacement/2, displacement/2, displacement/2+160])
+ positions = observer + x[:, None]*east + 2000*north + 1000*up
+ longitude, latitude, height = Transformer.from_crs(4978, 4979, always_xy=True).transform(*positions.T)
+ track = Track("side-view", [-2, 0, 2, 4], latitude, longitude, height,
+ velocity=np.array([80, 0, 0, 80])[:, None]*east)
+ emitted = np.linspace(.1, 1.9, 37)
+ u = emitted/2
+ source_x = -displacement/2 + displacement*(3*u**2-2*u**3)
+ speed = 3*displacement*u*(1-u)
+ distance = np.sqrt(source_x**2+2000**2+1000**2)
+ received = emitted + distance/343
+ factor = 343/(343+source_x*speed/distance)
+ return track, observer, emitted, received, factor
+
+
+def test_side_view_cannot_certify_unphysical_interior_motion():
+ track, observer, emitted, received, factor = side_view()
+ assert np.linalg.norm(track.speed_vector(1)) == pytest.approx(750)
+ # Arrival remains strictly monotone, so the old radial guard accepts it.
+ assert np.all(np.diff(received) > 0)
+ assert np.all(np.isfinite(factor))
+ with pytest.raises(AcousticSupportError) as failure:
+ track.acoustic(received, observer)
+ assert failure.value.reason == "non_subsonic_motion"
+ assert failure.value.emission_intervals_s == [[0., 2.]]
+
+
+def test_unsupported_motion_is_unknown_even_when_ridge_matches_its_formula():
+ track, _, _, received, factor = side_view()
+ point = SimpleNamespace(point_id=0, lat=40, lon=-100, elev_m=100, x=0, y=0)
+ candidate = {"passes": [{"flight_id": track.id, "receive_time": 7.5}], "event_indices": [0]}
+ event = {"event_id": "automatic-proposal", "cpa_receive_s": 7.5,
+ "f0_range_hz": [119, 121], "quality": {"source_drift_fraction": 0}}
+ measurement = (RidgeTimes(received), 120*factor, np.ones_like(factor), {})
+ result = score_candidate(candidate, point, {track.id: track}, [event], [measurement],
+ mode="robust_ridge", time_origin=0, time_sweep_s=0)
+ assert result["score"] == -np.inf
+ assert not result["scoring_assessment"]["complete"]
+ assert result["scoring_assessment"]["unknown_trials"] > 0
+ assert result["scoring_assessment"]["rejected_trials"] == 0
+
+
+def test_subsonic_control_retains_original_emission_time_solution():
+ track, observer, emitted, received, factor = side_view(400)
+ actual, solved, _ = track.acoustic(received, observer)
+ np.testing.assert_allclose(actual, factor, atol=1e-10)
+ np.testing.assert_allclose(solved, emitted, atol=1e-9)
+
+
+def test_invalid_remote_interval_does_not_erase_clean_emission_support():
+ track, observer, _, _, _ = side_view()
+ # Add a later stationary segment, well separated in emission/arrival time.
+ xyz = np.vstack([track.xyz, track.xyz[-1], track.xyz[-1]])
+ lon, lat, height = Transformer.from_crs(4978, 4979, always_xy=True).transform(*xyz.T)
+ velocities = np.vstack([track.speed_vector(track.time), np.zeros((2, 3))])
+ extended = Track("separated", [-2, 0, 2, 4, 30, 60], lat, lon, height, velocity=velocities)
+ emitted = np.linspace(40, 50, 21)
+ distance = np.linalg.norm(xyz[-1]-observer)
+ factor, solved, _ = extended.acoustic(emitted+distance/343, observer)
+ np.testing.assert_allclose(factor, 1, atol=1e-12)
+ np.testing.assert_allclose(solved, emitted, atol=1e-9)
+
+
[email protected]("table", [cpa_table, cpa_table_dense])
+def test_actual_unsupported_track_reaches_cpa_typed_boundary(table):
+ bad, _, _, _, _ = side_view()
+ clean, _, _, _, _ = side_view(400)
+ points = pd.DataFrame({"point_id": [0], "lat": [40], "lon": [-100], "elev_m": [100]})
+ assert len(table([clean], points, 5000, step_s=.25)) == 1
+ with pytest.raises(AcousticSupportError) as failure:
+ table([bad], points, 5000, step_s=.25)
+ assert failure.value.track_id == bad.id
+ assert failure.value.emission_intervals_s == [[0., 2.]]
+ assert failure.value.receive_intervals_s is None
+
+
+def test_sound_speed_profile_reuses_extrema_but_rechecks_physical_boundary():
+ track, observer, _, received, _ = side_view(400)
+ track.acoustic(received, observer)
+ with pytest.raises(AcousticSupportError, match="non_subsonic_motion"):
+ track.validate_motion_support(c=290)
+ track.validate_motion_support(c=343)
+
+
+def test_conservative_arrival_box_contains_all_unsupported_interval_arrivals():
+ track, observer, _, received, _ = side_view()
+ with pytest.raises(AcousticSupportError) as failure:
+ track.acoustic(received, observer)
+ emitted = np.linspace(0, 2, 1001)
+ actual = emitted+np.linalg.norm(track.position(emitted)-observer, axis=1)/343
+ lo, hi = failure.value.receive_intervals_s[0]
+ assert lo <= actual.min() <= actual.max() <= hi
+
+
+def test_continuous_speed_extrema_cover_independent_dense_spline_oracle():
+ rng = np.random.default_rng(640311)
+ inverse = Transformer.from_crs(4978, 4979, always_xy=True)
+ observer = ecef(40, -100, 100)
+ for _ in range(25):
+ time = np.array([0., rng.uniform(.2, 5), rng.uniform(6, 10)])
+ positions = observer+rng.normal(size=(3, 3))*1000
+ velocities = rng.normal(size=(3, 3))*150
+ lon, lat, height = inverse.transform(*positions.T)
+ track = Track("oracle", time, lat, lon, height, velocity=velocities)
+ track._unsupported_motion_intervals(c=1e-6)
+ for i in range(2):
+ sample = np.linspace(time[i], time[i+1], 8193)
+ peak = np.linalg.norm(track.speed_vector(sample), axis=1).max()
+ assert track._speed_peak[i] >= peak-1e-7
+ assert track._speed_peak[i]-peak <= 1e-5*max(1, peak)