Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Integrate main's dopplergeist namespace into ridge fit reuse [skip ci]
Cinna Davis31261a7334e1
diff --cc scripts/benchmark_ridge_fit_reuse.pyindex 702d3f4,0000000..3fa17e3mode 100644,000000..100644--- a/scripts/benchmark_ridge_fit_reuse.py+++ b/scripts/benchmark_ridge_fit_reuse.py@@@ -1,90 -1,0 +1,90 @@@+"""Compare cached and uncached scoring with saved real-recording inputs.++This checks numerical equivalence and runtime at an existing candidate. Its+position and inferred clock are comparison settings, not independent truth.+No audio, trajectories or measurements are generated by this command.+"""+import argparse+import json+from pathlib import Path+import time++import pandas as pd+- from aircraft_geoloc import matching- from aircraft_geoloc.finite_search import RetentionLedger- from aircraft_geoloc.tiled_search import SearchBudget, _score- from aircraft_geoloc.tracks import load_tracks++from dopplergeist import matching++from dopplergeist.finite_search import RetentionLedger++from dopplergeist.tiled_search import SearchBudget, _score++from dopplergeist.tracks import load_tracks+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--discovery", required=True, type=Path)+ parser.add_argument("--tracks", required=True, type=Path)+ parser.add_argument("--candidates", required=True, type=Path)+ parser.add_argument("--candidate-rank", type=int, default=1)+ parser.add_argument("--recording-duration-s", required=True, type=float)+ parser.add_argument("--time-padding-s", type=float, default=120.)+ parser.add_argument("--output", required=True, type=Path)+ args = parser.parse_args()+ if args.candidate_rank < 1 or args.recording_duration_s <= 0 or args.time_padding_s < 0:+ parser.error("Need a positive candidate rank/duration and nonnegative time padding")++ args.output.mkdir(parents=True, exist_ok=False)+ proposals = json.loads(args.discovery.read_text())["events"]+ candidate = json.loads(args.candidates.read_text())[args.candidate_rank - 1]+ clock = candidate["recording_start_time_s"]+ tracks, metadata = load_tracks(args.tracks, time_range=(+ clock - args.time_padding_s, clock + args.recording_duration_s + args.time_padding_s))+ events, measurements = matching.prepare_events(proposals)+ points = pd.DataFrame([{key: candidate[key] for key in+ ("point_id", "lat", "lon", "elev_m", "x", "y")}])+ settings = {"mode": "robust_ridge", "time_origin": clock, "time_sweep_s": 0}+ summary = {"scope": "fixed-input numerical/performance comparison; no accuracy claim",+ "inputs": {name: str(getattr(args, name)) for name in+ ("discovery", "tracks", "candidates")},+ "candidate_rank": args.candidate_rank, "recording_duration_s": args.recording_duration_s,+ "time_padding_s": args.time_padding_s, "segments": len(tracks),+ "observations": metadata["rows"], "proposals": len(proposals),+ "groups": len(events), "runs": []}+ compute = matching._fit_ridge_uncached+ calls = 0++ def counted(*values, **options):+ nonlocal calls+ calls += 1+ return compute(*values, **options)++ results = []+ matching._fit_ridge_uncached = counted+ try:+ for name, score in (("uncached", _score.__wrapped__), ("cached", _score)):+ directory = args.output / name+ directory.mkdir()+ ledger = RetentionLedger(directory / "retention.sqlite", "real-fit-reuse",+ "matched_group_support_minus_normalized_residual")+ calls = 0+ started = time.perf_counter()+ rows, counts = score(points, tracks, events, measurements, SearchBudget(top_k=5),+ settings, {}, ledger=ledger, stage="coarse:reference-point")+ elapsed = time.perf_counter() - started+ evidence = ledger.evidence(rows, complete=True, spacing_m=250, refine_spacing_m=250,+ max_event_groups=len(events), expected_stages={"coarse": 1})+ results.append((rows, counts, evidence))+ result = {"mode": name, "elapsed_s": elapsed, "fit_computations": calls,+ "counts": counts, "kept": len(rows),+ "leader_groups": len(rows[0]["event_indices"]) if rows else 0}+ summary["runs"].append(result)+ print(json.dumps(result), flush=True)+ finally:+ matching._fit_ridge_uncached = compute++ summary["identical_results"] = results[0] == results[1]+ (args.output / "comparison.json").write_text(json.dumps(summary, indent=2) + "\n")+ if not summary["identical_results"]:+ raise RuntimeError("Cache changed returned rows, diagnostics, counts or retention evidence")+ print("Exact match: returned candidates, diagnostics, assessment counts and retention evidence")+++if __name__ == "__main__":+ main()diff --cc tests/test_ridge_fit_cache.pyindex efa976b,0000000..4f1a6b5mode 100644,000000..100644--- a/tests/test_ridge_fit_cache.py+++ b/tests/test_ridge_fit_cache.py@@@ -1,188 -1,0 +1,188 @@@+"""Behavioral controls for bounded, batch-local reuse of physical ridge fits."""+from types import SimpleNamespace++import numpy as np+import pytest+- from aircraft_geoloc import matching- from aircraft_geoloc.finite_search import RetentionLedger- from aircraft_geoloc.geometry import Track, ecef- from aircraft_geoloc.terrain import Terrain- from aircraft_geoloc.tiled_search import SearchBudget, _score, tile_points++from dopplergeist import matching++from dopplergeist.finite_search import RetentionLedger++from dopplergeist.geometry import Track, ecef++from dopplergeist.terrain import Terrain++from dopplergeist.tiled_search import SearchBudget, _score, tile_points+from test_tiled_search import scenario+++def test_six_event_batch_reuses_fits_without_changing_modes_or_assessments(tmp_path, monkeypatch):+ _, tracks, events, measurements, bounds, _, origin = scenario(+ tmp_path, count=6, receiver_offset=(250, 250))+ points = tile_points((1, 7601, 2, 7602), 250, bounds, Terrain(constant_m=0), "EPSG:5070")+ budget = SearchBudget(top_k=5)+ settings = {"mode": "robust_ridge", "time_origin": origin, "time_sweep_s": 0}+ compute_name = "_fit_ridge_uncached" if hasattr(matching, "_fit_ridge_uncached") else "fit_ridge"+ compute = getattr(matching, compute_name)+ calls = 0++ def counted(*args, **kwargs):+ nonlocal calls+ calls += 1+ return compute(*args, **kwargs)++ monkeypatch.setattr(matching, compute_name, counted)+ results, evidence, computations = [], [], []+ for name, score in [("reference", getattr(_score, "__wrapped__", _score)), ("cached", _score)]:+ directory = tmp_path / name+ directory.mkdir()+ ledger = RetentionLedger(directory / "retention.sqlite", "cache-control",+ "matched_group_support_minus_normalized_residual")+ calls = 0+ rows, counts = score(points, tracks, events, measurements, budget, settings, {},+ ledger=ledger, stage="coarse:point")+ results.append((rows, counts))+ evidence.append(ledger.evidence(rows, complete=True, spacing_m=250, refine_spacing_m=250,+ max_event_groups=6, expected_stages={"coarse": 1}))+ computations.append(calls)+ assert results[0] == results[1]+ assert evidence[0] == evidence[1]+ rows, counts = results[1]+ assert counts["candidates"] == 63 and counts["unclassified_score_candidates"] == 0+ assert len(rows) == 5 and len(rows[0]["event_indices"]) == 6+ assert evidence[1]["complete"] and evidence[1]["evaluated_modes"] == 63+ assert evidence[1]["discarded_count"] == 58+ assert computations == [384, 6]+++def fit_inputs(tmp_path):+ _, tracks, _, measurements, _, _, origin = scenario(tmp_path)+ observer = ecef(tracks[0].lat[len(tracks[0].lat) // 2],+ tracks[0].lon[len(tracks[0].lon) // 2], 0)+ return tracks[0], observer, measurements[0], origin, (115., 125.)+++def test_fit_cache_keys_include_physical_inputs_and_measurement_contents(tmp_path, monkeypatch):+ base = fit_inputs(tmp_path)+ track, observer, measurement, start, frequency_bounds = base+ compute = matching._fit_ridge_uncached+ calls = 0++ def counted(*args, **kwargs):+ nonlocal calls+ calls += 1+ return compute(*args, **kwargs)++ monkeypatch.setattr(matching, "_fit_ridge_uncached", counted)++ @matching._cache_ridge_fits+ def evaluate():+ arguments = dict(track=track, observer=observer, measurement=measurement, start_time=start,+ f0_bounds=frequency_bounds, c=343., sigma_hz=1., drift_fraction=.02)+ assert matching.fit_ridge(**arguments) == compute(**arguments)+ assert matching.fit_ridge(**arguments) == compute(**arguments)+ assert calls == 1+ alternate = Track(track.id, track.time, track.lat, track.lon + .001, track.altitude)+ nearby = observer.copy()+ nearby[0] = np.nextafter(nearby[0], np.inf)+ variants = [("track", alternate), ("observer", nearby), ("start_time", start + .1),+ ("f0_bounds", (116., 126.)), ("c", 342.), ("sigma_hz", 1.1), ("drift_fraction", .01)]+ for field, value in variants:+ changed = dict(arguments, **{field: value})+ assert matching.fit_ridge(**changed) == compute(**changed)+ # Reusing the same arrays after an in-place measurement edit must miss.+ for field in range(3):+ if field == 0:+ measurement[0].time[0] += .001+ else:+ measurement[field][0] += .1+ assert matching.fit_ridge(**arguments) == compute(**arguments)+ assert calls == 1 + len(variants) + 3++ evaluate()+++def test_cache_eviction_copies_results_and_releases_scope_on_error(tmp_path, monkeypatch):+ arguments = fit_inputs(tmp_path)+ compute = matching._fit_ridge_uncached+ expected = compute(*arguments)+ calls = 0++ def counted(*args, **kwargs):+ nonlocal calls+ calls += 1+ return compute(*args, **kwargs)++ monkeypatch.setattr(matching, "_fit_ridge_uncached", counted)++ def batch():+ first = matching.fit_ridge(*arguments)+ first["f0_hz"] = -999.+ assert matching.fit_ridge(*arguments) == expected+ for shift in (.1, .2):+ changed = (*arguments[:3], arguments[3] + shift, arguments[4])+ assert matching.fit_ridge(*changed) == compute(*changed)+ assert len(matching._ridge_fit_cache.get().entries) == 2+ assert matching.fit_ridge(*arguments) == expected+ assert calls == 4+ raise RuntimeError("end this batch")++ cached = matching._cache_ridge_fits(batch, max_entries=2)+ with pytest.raises(RuntimeError, match="end this batch"):+ cached()+ assert matching._ridge_fit_cache.get() is None+ assert matching.fit_ridge(*arguments) == expected+ assert calls == 5+++def test_typed_support_errors_are_never_replaced_with_cached_fit(tmp_path, monkeypatch):- from aircraft_geoloc.geometry import AcousticSupportError++ from dopplergeist.geometry import AcousticSupportError++ arguments = fit_inputs(tmp_path)+ original = matching._fit_ridge_uncached+ calls = 0++ def unavailable(*args, **kwargs):+ nonlocal calls+ calls += 1+ raise AcousticSupportError(arguments[0].id, "test_unavailable_source")++ monkeypatch.setattr(matching, "_fit_ridge_uncached", unavailable)++ @matching._cache_ridge_fits+ def batch():+ for _ in range(2):+ with pytest.raises(AcousticSupportError, match="test_unavailable_source"):+ matching.fit_ridge(*arguments)+ assert len(matching._ridge_fit_cache.get().entries) == 0++ batch()+ assert calls == 2+ monkeypatch.setattr(matching, "_fit_ridge_uncached", original)+ assert np.isfinite(matching.fit_ridge(*arguments)["score"])+++def test_invalid_scalar_measurement_does_not_reuse_a_one_sample_fit(tmp_path):+ track, observer, _, start, bounds = fit_inputs(tmp_path)+ one_sample = (SimpleNamespace(time=np.array([10.])), np.array([120.]), np.array([1.]), {})+ scalar = (SimpleNamespace(time=np.array(10.)), np.array(120.), np.array(1.), {})++ @matching._cache_ridge_fits+ def batch():+ assert matching.fit_ridge(track, observer, one_sample, start, bounds)["support_fraction"] == 0+ with pytest.raises(ValueError, match="one-dimensional arrays"):+ matching.fit_ridge(track, observer, scalar, start, bounds)++ batch()+++def test_scalar_precision_is_preserved_in_the_fit_cache_key(tmp_path):+ arguments = fit_inputs(tmp_path)+ ridge = arguments[2][1]+ ridge += .4 * (-1.) ** np.arange(len(ridge))+ single = np.float32(1.234567)+ double = float(single)+ expected = [matching._fit_ridge_uncached(*arguments, sigma_hz=value) for value in (single, double)]+ assert expected[0] != expected[1], "The fixture must expose scalar arithmetic precision"++ @matching._cache_ridge_fits+ def batch():+ assert [matching.fit_ridge(*arguments, sigma_hz=value) for value in (single, double)] == expected++ batch()