Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Profile ridge clock altitude and sound-speed sensitivity (#8)
Cinna Davis41992bee4469
diff --git a/docs/MATCHING.md b/docs/MATCHING.mdindex 5cb6870..87ed3e7 100644--- a/docs/MATCHING.md+++ b/docs/MATCHING.md@@ -93,3 +93,26 @@ kinds must not be mixed in a ranking. Confidence must still consider competinglocations, matched group count, omitted proposals, source coverage and residualdiagnostics. Single-event candidates remain available for a defensible knownclock, and do not by themselves establish a supported location.++## Full sensitivity scenarios++`matching.profile_candidate(candidate, track_lookup, all_events,+all_measurements, terrain, recording_start_window_s=...)` reruns the leading+association under declared perturbations. It returns the nominal refined+candidate with a `sensitivity` artifact containing every scenario, failed+scenario, boundary flag, tested source and maximum displacement from nominal.+It checks each matched ridge with positive/negative frequency offsets and+linear tilts at the declared loss scale, a constant-source alternative, allowed+clock endpoints, relative-height offsets (default 150 m), and sound-speed+offsets (default 5 m/s). Every scenario uses one shared clock and stays inside+the request window. An exact clock remains fixed. Defaults are declared+engineering ranges, not estimated meteorology, a survey, or statistical coverage.++`complete` requires finite support for every scenario and successful local+optimization. `boundary_limited` remains separate. A missing/failed scenario+cannot silently shrink the envelope; confidence must abstain when evidence is+incomplete or exceeds its declared precision. This finite envelope does not+cover every possible model error, and distant competing modes still require+the outer search. The bounded source-frequency solve uses the exact optimum+of its two-variable convex box problem; regression tests compare it against+SciPy's independent constrained solver, including boundary optima.diff --git a/src/aircraft_geoloc/matching.py b/src/aircraft_geoloc/matching.pyindex 4beedb7..d087b93 100644--- a/src/aircraft_geoloc/matching.py+++ b/src/aircraft_geoloc/matching.py@@ -8,7 +8,7 @@ from itertools import combinations, productimport numpy as npfrom pyproj import Transformer-from scipy.optimize import lsq_linear, minimize+from scipy.optimize import minimizefrom .geometry import ecef@@ -24,6 +24,28 @@ def _frequency_scale(event):max(1.0, quality.get("frequency_uncertainty_hz", 1.0))))+def _source_fit(factor, u, y, weight, bounds, cap, scale):+ """Exact two-variable box least squares; avoid iterative bounded solves."""+ a = np.sum(weight*factor**2)+ r = np.sum(weight*factor*y)+ if not cap:+ return np.array([np.clip(r/a, *bounds), 0.0])+ b = np.sum(weight*factor**2*u)+ prior = (2*scale/cap)**2+ d = np.sum(weight*factor**2*u**2)+prior+ s = np.sum(weight*factor*u*y)+ determinant = a*d-b*b+ unconstrained = np.array([(r*d-s*b)/determinant, (s*a-r*b)/determinant])+ if bounds[0] <= unconstrained[0] <= bounds[1] and abs(unconstrained[1]) <= cap:+ return unconstrained+ # A convex quadratic's constrained minimum lies on one of these four edges.+ candidates = np.array([[f, np.clip((s-b*f)/d, -cap, cap)] for f in bounds] ++ [[np.clip((r-b*drift)/a, *bounds), drift] for drift in (-cap, cap)])+ residuals = factor*(candidates[:, :1]+candidates[:, 1:]*u)-y+ costs = np.sum(weight*residuals**2, axis=1)+prior*candidates[:, 1]**2+ return candidates[np.argmin(costs)]++def association_candidates(table, events, offset_tolerance_s=5.0, time_origin=None,time_tolerance_s=5.0, silence=None, min_events=1,max_events=3, max_candidates=20000):@@ -177,21 +199,15 @@ def fit_ridge(track, observer, measurement, start_time, f0_bounds, c=343.0,span = max(float(np.ptp(emission)), 1e-9)u = (emission - (emission.min() + emission.max()) / 2) / spancap = float(np.clip(np.median(y / factor), *f0_bounds)) * drift_fraction- design = np.column_stack((factor, factor * u)) if cap else factor[:, None]- bounds = ([f0_bounds[0], -cap], [f0_bounds[1], cap]) if cap else ([f0_bounds[0]], [f0_bounds[1]])effective = w.copy()for _ in range(6):- matrix, target = design * np.sqrt(effective[:, None]), y * np.sqrt(effective)- if cap:- matrix = np.vstack((matrix, [0, 2 * sigma_hz / cap]))- target = np.r_[target, 0.0]- fit = lsq_linear(matrix, target, bounds=bounds, tol=1e-8)- residual = design @ fit.x - y+ fit = _source_fit(factor, u, y, effective, f0_bounds, cap, sigma_hz)+ residual = factor*(fit[0]+fit[1]*u)-yeffective = w / np.sqrt(1 + (residual / sigma_hz) ** 2)loss = np.average(2 * sigma_hz**2 * (np.sqrt(1 + (residual / sigma_hz)**2) - 1), weights=w)- drift = float(fit.x[1]) if cap else 0.0+ drift = float(fit[1])penalty = (2 * sigma_hz * drift / cap)**2 / independent_samples if cap else 0.0- return {"score": -float(np.sqrt(loss + penalty)), "f0_hz": float(fit.x[0]),+ return {"score": -float(np.sqrt(loss + penalty)), "f0_hz": float(fit[0]),"source_drift_hz": drift, "source_drift_hz_s": drift / span,"drift_bound_hz": float(cap), "drift_at_bound": bool(cap and abs(drift) > 0.99 * cap),"rmse_hz": float(np.sqrt(np.average(residual**2, weights=w))),@@ -291,4 +307,80 @@ def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=sensitivity={"radius_m": radius, "kind": "sensitivity","method": "profiled_relative_altitude_offsets","profiles": profiles, "boundary_limited": any(p["boundary_limited"] for p in profiles),- "complete": len(profiles) == len(altitude_offsets_m)})+ "complete": len(profiles) == len(altitude_offsets_m) and all(p["optimizer_success"] for p in profiles)})+++def profile_candidate(candidate, tracks, events, measurements, terrain, *,+ recording_start_window_s=None, radius_m=500.0, clock_radius_s=5.0,+ altitude_uncertainty_m=150.0, sound_speed_uncertainty_mps=5.0,+ c=343.0, crs="EPSG:5070"):+ """Run declared perturbations, retaining failures and boundary limitations.++ These finite engineering scenarios are not a calibrated confidence region.+ Frequency offsets and tilts vary each matched ridge separately. Shared-clock+ endpoints, relative height, sound speed and constant-source alternatives are+ reoptimized; no scenario may leave the trusted recording-start window.+ """+ if altitude_uncertainty_m < 0 or not 0 <= sound_speed_uncertainty_mps < c:+ raise ValueError("Sensitivity ranges must be nonnegative and sound speed must remain positive")+ kwargs = dict(radius_m=radius_m, clock_radius_s=clock_radius_s,+ altitude_offsets_m=(0.0,), crs=crs, c=c,+ recording_start_window_s=recording_start_window_s)+ nominal = refine_candidate(candidate, tracks, events, measurements, terrain, **kwargs)+ scenarios = [("nominal", "nominal", events, measurements, {})]+ for sign in (-1, 1):+ scenarios.append(("altitude", f"height_{sign:+d}", events, measurements,+ {"altitude_offsets_m": (0.0, sign*altitude_uncertainty_m)}))+ scenarios.append(("sound_speed", f"sound_speed_{sign:+d}", events, measurements,+ {"c": c+sign*sound_speed_uncertainty_mps}))+ indices = candidate.get("event_indices", list(range(len(events))))+ for index in indices:+ spec, ridge, weight, fit = measurements[index]+ times = np.asarray(spec.time)+ tilt = 2*(times-(times.min()+times.max())/2)/max(float(np.ptp(times)), 1e-9)+ scale = _frequency_scale(events[index])+ for pattern, shape in (("offset", np.ones_like(times)), ("tilt", tilt)):+ for sign in (-1, 1):+ changed = list(measurements)+ changed[index] = (spec, np.asarray(ridge)+sign*scale*shape, weight, fit)+ scenarios.append(("frequency", f"event_{index}_{pattern}_{sign:+d}", events, changed, {}))+ constant = [dict(e, quality=dict(e.get("quality", {}), source_drift_fraction=0.0)) for e in events]+ scenarios.append(("source_frequency", "constant_source", constant, measurements, {}))+ lo, hi = nominal["refinement_clock_bounds_s"]+ # A trusted point window is tested exactly; it is never perturbed outward.+ for when in sorted(set((lo, hi))):+ scenarios.append(("clock", f"fixed_clock_{when:.6f}", events, measurements,+ {"recording_start_window_s": (when, when)}))+ profiles, failures = [], []+ center = ecef(nominal["lat"], nominal["lon"], 0)+ radius = 0.0+ boundary = False+ for source, label, scenario_events, scenario_measurements, overrides in scenarios:+ try:+ row = nominal if source == "nominal" else refine_candidate(candidate, tracks,+ scenario_events, scenario_measurements, terrain, **dict(kwargs, **overrides))+ # Height scenarios return a nominal plus the perturbed-height fit;+ # retain the latter rather than silently measuring the nominal twice.+ variants = row["sensitivity"]["profiles"] if source == "altitude" else [row]+ for variant in variants:+ displacement = float(np.linalg.norm(ecef(variant["lat"], variant["lon"], 0)-center))+ radius = max(radius, displacement)+ boundary |= variant["boundary_limited"]+ profiles.append({"source": source, "scenario": label,+ "lat": variant["lat"], "lon": variant["lon"], "score": variant["score"],+ "recording_start_time_s": variant["recording_start_time_s"],+ "displacement_m": displacement, "boundary_limited": variant["boundary_limited"],+ "optimizer_success": variant["optimizer_success"]})+ if not row["sensitivity"]["complete"]:+ failures.append({"source": source, "scenario": label, "reason": "Missing altitude scenario support"})+ except ValueError as exc:+ failures.append({"source": source, "scenario": label, "reason": str(exc)})+ sensitivity = {"radius_m": radius, "kind": "sensitivity", "method": "declared_perturbation_profiles",+ "sources": sorted({s[0] for s in scenarios if s[0] != "nominal"}),+ "complete": not failures and all(p["optimizer_success"] for p in profiles),+ "boundary_limited": bool(boundary), "profiles": profiles, "failures": failures,+ "settings": {"altitude_uncertainty_m": altitude_uncertainty_m,+ "sound_speed_uncertainty_mps": sound_speed_uncertainty_mps,+ "frequency_scale_hz": [_frequency_scale(events[i]) for i in indices],+ "clock_bounds_s": [lo, hi]}}+ return dict(nominal, sensitivity=sensitivity)diff --git a/tests/test_matching.py b/tests/test_matching.pyindex 62aa92f..1686e50 100644--- a/tests/test_matching.py+++ b/tests/test_matching.py@@ -120,7 +120,7 @@ def test_uncertainty_requires_one_common_recording_start_interval():assert lower <= upper-def test_joint_refinement_uses_nonparallel_passes_and_profiles_altitude():+def physical_case():observer = ecef(40, -100, 100)epoch = 1_790_000_000.0inverse = Transformer.from_crs("EPSG:4978", "EPSG:4979", always_xy=True)@@ -141,6 +141,11 @@ def test_joint_refinement_uses_nonparallel_passes_and_profiles_altitude():seed = dict(lat=40.0015, lon=-99.998, elev_m=100, recording_start_time_s=epoch + 0.5,flight_ids=["a", "b"], point_id=0)terrain = SimpleNamespace(sample=lambda lat, lon: np.array(100.0))+ return observer, epoch, seed, tracks, events, measurements, terrain+++def test_joint_refinement_uses_nonparallel_passes_and_profiles_altitude():+ observer, epoch, seed, tracks, events, measurements, terrain = physical_case()result = refine_candidate(seed, tracks, events, measurements, terrain, radius_m=500, clock_radius_s=3)error = np.linalg.norm(ecef(result["lat"], result["lon"], 100) - observer)assert error < 10@@ -167,3 +172,65 @@ def test_refinement_cannot_move_a_trusted_clock_outside_its_window(window):with pytest.raises(ValueError, match="do not intersect"):refine_candidate(seed, {"a": Flyover()}, [event], [measurement()], terrain,recording_start_window_s=(100, 101))+++def test_source_fit_matches_independent_bounded_solver_on_interior_and_edges():+ from scipy.optimize import lsq_linear+ from aircraft_geoloc.matching import _source_fit+ rng = np.random.default_rng(440)+ factor, u = rng.uniform(0.7, 1.4, 80), np.linspace(-0.5, 0.5, 80)+ for _ in range(30):+ y = factor*(rng.uniform(110, 130)+rng.uniform(-15, 15)*u)+ weight = rng.uniform(0.1, 2, len(y))+ cap, scale = 2.4, 1.0+ matrix = np.vstack((np.column_stack((factor, factor*u))*np.sqrt(weight[:, None]), [0, 2*scale/cap]))+ target = np.r_[y*np.sqrt(weight), 0]+ expected = lsq_linear(matrix, target, bounds=([119, -cap], [121, cap]), tol=1e-12).x+ actual = _source_fit(factor, u, y, weight, [119, 121], cap, scale)+ np.testing.assert_allclose(actual, expected, atol=1e-7, rtol=0)+++def test_full_sensitivity_reoptimizes_all_sources_without_moving_exact_utc():+ from aircraft_geoloc.matching import profile_candidate+ observer, epoch, seed, tracks, events, measurements, terrain = physical_case()+ for event in events:+ event["quality"]["frequency_loss_scale_hz"] = 0.05+ result = profile_candidate(seed, tracks, events, measurements, terrain,+ recording_start_window_s=(epoch, epoch), altitude_uncertainty_m=25,+ sound_speed_uncertainty_mps=1, radius_m=500, clock_radius_s=3)+ sensitivity = result["sensitivity"]+ assert set(sensitivity["sources"]) >= {"frequency", "clock", "altitude", "sound_speed", "source_frequency"}+ assert sensitivity["complete"] and not sensitivity["boundary_limited"]+ assert sensitivity["radius_m"] > 0+ assert all(p["recording_start_time_s"] == epoch for p in sensitivity["profiles"])+ assert len(sensitivity["profiles"]) >= 15+ assert np.linalg.norm(ecef(result["lat"], result["lon"], 100)-observer) < 10+++def test_missing_sensitivity_scenario_is_retained_as_incomplete_evidence():+ from aircraft_geoloc.matching import profile_candidate+ class LimitedTrack(Flyover):+ def acoustic(self, t, observer, c):+ factor, emitted, distance = super().acoustic(t, observer, c)+ return (factor if c >= 343 else np.full_like(factor, np.nan)), emitted, distance+ seed = dict(lat=40, lon=-100, recording_start_time_s=0, flight_ids=["a"])+ terrain = SimpleNamespace(sample=lambda lat, lon: np.array(100.0))+ event = dict(f0_range_hz=[119, 121])+ result = profile_candidate(seed, {"a": LimitedTrack()}, [event], [measurement()], terrain,+ recording_start_window_s=(0, 0), altitude_uncertainty_m=0)+ assert not result["sensitivity"]["complete"]+ assert any(p["source"] == "sound_speed" for p in result["sensitivity"]["failures"])+++def test_exhausted_real_optimizer_cannot_report_complete_sensitivity(monkeypatch):+ import aircraft_geoloc.matching as matching+ real_minimize = matching.minimize+ def exhausted(*args, **kwargs):+ kwargs["options"] = dict(kwargs.get("options", {}), maxiter=0)+ return real_minimize(*args, **kwargs)+ monkeypatch.setattr(matching, "minimize", exhausted)+ seed = dict(lat=40, lon=-100, recording_start_time_s=0, flight_ids=["a"])+ terrain = SimpleNamespace(sample=lambda lat, lon: np.array(100.0))+ result = refine_candidate(seed, {"a": Flyover()}, [dict(f0_range_hz=[119, 121])], [measurement()], terrain)+ assert not result["sensitivity"]["complete"]+ assert not any(p["optimizer_success"] for p in result["sensitivity"]["profiles"])