Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Batch emission-time solves across shared-clock trials
Cinna Davise1842d2b64de
diff --git a/scripts/benchmark_real_clock_batch.py b/scripts/benchmark_real_clock_batch.pynew file mode 100644index 0000000..3a772f4--- /dev/null+++ b/scripts/benchmark_real_clock_batch.py@@ -0,0 +1,76 @@+"""Measure clock-trial scoring on real recorded ridges and historical flights.++The fixture must provide real events, CPA rows, a development receiver point,+query bounds/time and a flight-index path. This is a scoped performance check,+not an end-to-end localization or location-accuracy benchmark.+"""+import argparse+import json+import math+from pathlib import Path+import random+import time+from types import SimpleNamespace++import numpy as np+import pandas as pd++from dopplergeist.data_access import FlightIndex+from dopplergeist.geometry import Track+from dopplergeist.matching import _cache_ridge_fits, association_candidates, prepare_events+from dopplergeist.search import score_candidate+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("fixture", type=Path)+ parser.add_argument("output", type=Path, help="New output JSON file")+ args = parser.parse_args()+ if args.output.exists():+ raise FileExistsError("Use a new output file to preserve previous measurements")+ fixture = json.loads(args.fixture.read_text())+ events, measurements = prepare_events(fixture["events"])+ candidates, counts = association_candidates(pd.DataFrame(fixture["cpa_rows"]), events, max_candidates=20000)+ selected = sorted(random.Random(20261103).sample(range(len(candidates)), 100))+ tracks = {track.id: track for track in FlightIndex(fixture["real_index"]).query(+ fixture["query_bounds"], fixture["query_time_s"])}+ point = SimpleNamespace(**fixture["point"], x=0.0, y=0.0)+ acoustic = Track.acoustic+ calls = {"calls": 0, "samples": 0}++ def counted(track, times, observer, c=343.0):+ calls["calls"] += 1+ calls["samples"] += np.asarray(times).size+ return acoustic(track, times, observer, c)++ @_cache_ridge_fits+ def run():+ rows = []+ for index in selected:+ result = score_candidate(candidates[index], point, tracks, events, measurements, mode="robust_ridge")+ score = result["score"]+ rows.append({"candidate_index": index, "group_count": len(candidates[index]["event_indices"]),+ "score": float(score) if math.isfinite(score) else None,+ "recording_start_time_s": result.get("recording_start_time_s"),+ "scoring_assessment": result["scoring_assessment"]})+ return rows++ Track.acoustic = counted+ wall, cpu = time.perf_counter(), time.process_time()+ try:+ rows = run()+ finally:+ Track.acoustic = acoustic+ report = {"source": str(args.fixture), "candidate_count": len(candidates), "selection_seed": 20261103,+ "association_counts": counts, "acoustic": calls, "wall_s": time.perf_counter() - wall,+ "process_cpu_s": time.process_time() - cpu, "rows": rows}+ args.output.parent.mkdir(parents=True, exist_ok=True)+ with args.output.open("x") as output:+ json.dump(report, output, indent=2, allow_nan=False)+ output.write("\n")+ print(f"Scored {len(rows)} real associations in {report['wall_s']:.3f} s; "+ f"{calls['calls']} acoustic calls / {calls['samples']} samples")+++if __name__ == "__main__":+ main()diff --git a/src/dopplergeist/matching.py b/src/dopplergeist/matching.pyindex f0d1a9c..f5a1512 100644--- a/src/dopplergeist/matching.py+++ b/src/dopplergeist/matching.py@@ -49,14 +49,15 @@ class _RidgeFitCache:self.max_entries = max_entriesself.entries = OrderedDict()- def fit(self, track, observer, measurement, start_time, f0_bounds, c, sigma_hz, drift_fraction):+ def fit(self, track, observer, measurement, start_time, f0_bounds, c, sigma_hz, drift_fraction,+ acoustic_result=None):arguments = (track, observer, measurement, start_time, f0_bounds, c, sigma_hz, drift_fraction)try:parameters = tuple(_fit_argument_key(value) for value in(observer, start_time, f0_bounds, c, sigma_hz, drift_fraction))except (TypeError, ValueError):# Let the fitter handle custom representations and their validation.- return _fit_ridge_uncached(*arguments)+ return _fit_ridge_uncached(*arguments, acoustic_result=acoustic_result)# Measurements may be equivalent copies or modified arrays. Hash the# numeric inputs actually used by the fit, without retaining their data.spec, ridge, weight, _ = measurement@@ -69,7 +70,7 @@ class _RidgeFitCache:if key in self.entries:self.entries.move_to_end(key)return deepcopy(self.entries[key][1])- result = _fit_ridge_uncached(*arguments)+ result = _fit_ridge_uncached(*arguments, acoustic_result=acoustic_result)# Keep the track alive so a different trajectory cannot reuse its id.# The enclosing batch already owns these tracks. Exceptions are not cached.self.entries[key] = (track, deepcopy(result))@@ -355,7 +356,7 @@ def prepare_events(detected_events, c=343.0, max_distance_m=20000.0):def _fit_ridge_uncached(track, observer, measurement, start_time, f0_bounds, c=343.0,- sigma_hz=1.0, drift_fraction=0.02):+ sigma_hz=1.0, drift_fraction=0.02, acoustic_result=None):"""Bounded linear source drift at emission time, with robust residual loss.Drift is bounded to a fraction of source frequency over the measured event.@@ -374,7 +375,12 @@ def _fit_ridge_uncached(track, observer, measurement, start_time, f0_bounds, c=3failed = {"score": -np.inf, "f0_hz": np.nan, "support_fraction": 0.0}if measured.sum() < 10:return failed- factor, emission, _ = track.acoustic(start_time + times[measured], observer, c)+ if acoustic_result is None:+ factor, emission, _ = track.acoustic(start_time + times[measured], observer, c)+ else:+ factor, emission = acoustic_result+ if factor.shape != times[measured].shape or emission.shape != factor.shape:+ raise ValueError("Batched acoustic result does not match the measured ridge")if not np.all(np.isfinite(factor)) or not np.all(np.isfinite(emission)):return failedy, w = ridge[measured], weight[measured]@@ -403,29 +409,73 @@ def _fit_ridge_uncached(track, observer, measurement, start_time, f0_bounds, c=3def fit_ridge(track, observer, measurement, start_time, f0_bounds, c=343.0,- sigma_hz=1.0, drift_fraction=0.02):+ sigma_hz=1.0, drift_fraction=0.02, acoustic_result=None):"""Fit bounded source drift, optionally reusing an identical batch input."""cache = _ridge_fit_cache.get()fit = _fit_ridge_uncached if cache is None else cache.fit- return fit(track, observer, measurement, start_time, f0_bounds, c, sigma_hz, drift_fraction)+ return fit(track, observer, measurement, start_time, f0_bounds, c, sigma_hz, drift_fraction,+ acoustic_result=acoustic_result)-def score_ridges(tracks, events, measurements, observer, recording_start_s, c=343.0):+def score_ridges(tracks, events, measurements, observer, recording_start_s, c=343.0, *, acoustic_results=None):"""Score all events at exactly one recording clock; report nuisance fits."""if not events or len(tracks) != len(events) or len(measurements) != len(events):raise ValueError("Need exactly one track and measurement for each event")diagnostics = []- for track, event, measurement in zip(tracks, events, measurements):+ if acoustic_results is None:+ acoustic_results = [None] * len(events)+ if len(acoustic_results) != len(events):+ raise ValueError("Need one batched acoustic result per event")+ for track, event, measurement, acoustic_result in zip(tracks, events, measurements, acoustic_results):quality = event.get("quality", {})diagnostics.append(fit_ridge(track, observer, measurement, recording_start_s,event["f0_range_hz"], c, _frequency_scale(event),- quality.get("source_drift_fraction", 0.02)))+ quality.get("source_drift_fraction", 0.02), acoustic_result=acoustic_result))return {"score": float(sum(d["score"] for d in diagnostics)),"event_scores": [d["score"] for d in diagnostics],"f0_hz": [d["f0_hz"] for d in diagnostics], "event_diagnostics": diagnostics,"score_kind": "negative_robust_ridge_loss_hz"}+def batch_acoustic_trials(tracks, measurements, observer, starts, c=343.0, max_samples=262144):+ """Evaluate repeated receive times together, falling back on support errors."""+ from .geometry import AcousticSupportError++ starts = np.asarray(starts, dtype=float)+ if starts.ndim != 1 or not np.all(np.isfinite(starts)):+ return [None] * len(measurements)+ remaining = max_samples+ batches = []+ for track, measurement in zip(tracks, measurements):+ spec, ridge, weight, _ = measurement+ times, ridge, weight = (np.asarray(a, dtype=float) for a in (spec.time, ridge, weight))+ # The solver's 1e-7 stopping tolerance is below half a floating-point+ # ULP throughout these emission times. Once an individual trial has+ # stopped, further vector iterations therefore leave it unchanged.+ # Older epochs retain the original per-trial path.+ if track.time[0] < 2**30:+ batches.append(None)+ continue+ if times.shape != ridge.shape or times.shape != weight.shape or times.ndim != 1:+ batches.append(None)+ continue+ measured = np.isfinite(times) & np.isfinite(ridge) & (weight > 0)+ size = len(starts) * int(measured.sum())+ if measured.sum() < 10 or not np.all(np.isfinite(weight)) or np.any(weight < 0) or size > remaining:+ batches.append(None)+ continue+ receive = starts[:, None] + times[measured][None, :]+ unique, inverse = np.unique(receive, return_inverse=True)+ try:+ factor, emission, _ = track.acoustic(unique, observer, c)+ except AcousticSupportError:+ batches.append(None)+ continue+ batches.append((factor[inverse].reshape(receive.shape), emission[inverse].reshape(receive.shape)))+ remaining -= size+ return batches++def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=500.0,clock_radius_s=5.0, altitude_offsets_m=(-150.0, 0.0, 150.0),crs="EPSG:5070", c=343.0, recording_start_window_s=None):diff --git a/src/dopplergeist/search.py b/src/dopplergeist/search.pyindex a35880f..5c5a7cd 100644--- a/src/dopplergeist/search.py+++ b/src/dopplergeist/search.py@@ -387,12 +387,19 @@ def score_candidate(candidate, point, tracks, events, measurements, mode="bright"empty_clock_domain": len(shifts) == 0}reasons = set()unknown_bounds = []- for shift in shifts:+ selected_tracks = [tracks[p["flight_id"]] for p in candidate["passes"]] if mode == "robust_ridge" else None+ batches = None+ if mode == "robust_ridge" and len(shifts) > 1:+ from .matching import batch_acoustic_trials+ batches = batch_acoustic_trials(selected_tracks, measurements, observer, anchor + shifts, c)+ for trial, shift in enumerate(shifts):if mode == "robust_ridge":from .matching import score_ridges+ precomputed = ([None if batch is None else (batch[0][trial], batch[1][trial]) for batch in batches]+ if batches is not None else None)try:- result = score_ridges([tracks[p["flight_id"]] for p in candidate["passes"]],- events,measurements,observer,anchor+shift,c)+ result = score_ridges(selected_tracks, events, measurements, observer, anchor+shift, c,+ acoustic_results=precomputed)except AcousticSupportError as error:assessment["unknown_trials"] += 1reasons.add(str(error))diff --git a/tests/test_real_clock_batch.py b/tests/test_real_clock_batch.pynew file mode 100644index 0000000..7cf0df6--- /dev/null+++ b/tests/test_real_clock_batch.py@@ -0,0 +1,69 @@+"""Compare shared-clock batching with unbatched physics on real observations."""+import json+import os+from pathlib import Path+from types import SimpleNamespace++import numpy as np+import pandas as pd+import pytest++from dopplergeist.data_access import FlightIndex+from dopplergeist.geometry import AcousticSupportError, ecef+from dopplergeist.matching import _cache_ridge_fits, association_candidates, prepare_events+from dopplergeist.search import score_candidate+import dopplergeist.matching as matching+++def _json_default(value):+ if isinstance(value, np.ndarray):+ return value.tolist()+ if isinstance(value, np.generic):+ return value.item()+ raise TypeError(type(value).__name__)+++def test_real_batched_clock_scores_and_bounded_fallback(monkeypatch):+ fixture_path = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")+ if not fixture_path:+ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to the saved real-audio/flight CPA diagnostic")+ fixture = json.loads(Path(fixture_path).read_text())+ events, measurements = prepare_events(fixture["events"])+ candidates, _ = association_candidates(pd.DataFrame(fixture["cpa_rows"]), events, max_candidates=20000)+ assert len(candidates) == 10549+ tracks = {t.id: t for t in FlightIndex(fixture["real_index"]).query(+ fixture["query_bounds"], fixture["query_time_s"])}+ point = SimpleNamespace(**fixture["point"], x=0.0, y=0.0)+ selected = [candidates[i] for i in (895, 1874, 2188, 3101, 5120, 10545)]++ @_cache_ridge_fits+ def evaluate():+ rows = [score_candidate(c, point, tracks, events, measurements, mode="robust_ridge") for c in selected]+ return json.dumps(rows, sort_keys=True, default=_json_default)++ batch = matching.batch_acoustic_trials+ actual = evaluate()+ with monkeypatch.context() as patch:+ patch.setattr(matching, "batch_acoustic_trials", lambda tracks, measurements, *args, **kwargs:+ [None] * len(measurements))+ baseline = evaluate()+ assert actual == baseline+ with monkeypatch.context() as patch:+ patch.setattr(matching, "batch_acoustic_trials", lambda *args, **kwargs:+ batch(*args, **kwargs, max_samples=1))+ fallback = evaluate()+ assert fallback == baseline++ # Exercise the exception fallback with an actual unsupported trajectory+ # interval and a measured ridge sample, not a manufactured track.+ bad = next(track for track in tracks.values() if len(track._unsupported_motion_intervals(343.0)))+ interval = int(bad._unsupported_motion_intervals(343.0)[0])+ observer = ecef(point.lat, point.lon, point.elev_m)+ arrival = bad.time[interval] + np.linalg.norm(bad.xyz[interval] - observer) / 343.0+ spec, ridge, weight, _ = measurements[0]+ measured = np.isfinite(spec.time) & np.isfinite(ridge) & (weight > 0)+ sample_times = spec.time[measured]+ start = arrival - sample_times[0]+ with pytest.raises(AcousticSupportError):+ bad.acoustic(start + sample_times, observer)+ assert batch([bad], [measurements[0]], observer, np.array([start, start + 1.0])) == [None]