Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Reuse dense acoustic batches and expose search workers
Cinna Davis3b6a00d9c947
diff --git a/docs/DATA_AND_SCALE.md b/docs/DATA_AND_SCALE.mdindex 52b6d4c..95c355e 100644--- a/docs/DATA_AND_SCALE.md+++ b/docs/DATA_AND_SCALE.md@@ -76,13 +76,14 @@ report = search_national(```There is one EPSG:5070 origin and integer grid. Half-open tile cores own receiver-cells exactly once; expanded queries retain boundary flight segments. Only the-receiver grid is partitioned. Original flight geometry, emission-time propagation,+cells exactly once; expanded queries retain boundary flight segments. Original+flight geometry, emission-time propagation,event offsets and score units are identical in every tile. One shared clock isconstrained to the supplied recording-start window. Coarse tiles use separateworker processes for the built-in cached-terrain provider, automatically choosing-one fewer worker than the available logical CPUs, with a minimum of one. Custom-terrain providers use serial execution. Hard limits on grid cells, tracks, samples,+one fewer worker than the available logical CPUs, with a minimum of one. The+upload operator can override that count with the positive integer `search_workers`.+Custom terrain providers use serial execution. Hard limits on grid cells, tracks, samples,CPA rows and candidate combinations bound each worker's allocations; total memorygrows with the worker count. An overloaded track query is retried with the sameconservative observer-distance test used by the scorer. Tracks with unsupported@@ -119,6 +120,11 @@ retaining all 200 tracks with unsupported motion. Complete scoring with the fulland reduced sets produced identical results, support records and retentionchecksums. Other overloaded cells may still exceed the limits.+With the spline-hull proof enabled, the same cell retained 426 tracks, including+12 unsupported tracks. Full scoring with the original and filtered sets again+produced identical results and retention checksums; the retry took 40.66 CPU+seconds, compared with about 39.9 CPU seconds before the change.+For a trajectory with unsupported motion, the distance sieve can still excludeit when the bounding boxes of every cubic-spline control hull are outside theobserver set's search radius. This proof does not assume subsonic motion. In a@@ -147,6 +153,14 @@ the remaining supported clocks are fitted together. Representative batchedfits are checked against the scalar fitter, with fallback for mismatches orunsupported and numerically degenerate batches.+For association sets of at least 1,000 candidates, repeated acoustic batches+reuse exact track, receiver, time-array and sound-speed inputs in a per-worker+32 MiB cache. Sparse searches keep the ordinary path. A complete real-data clock+partition with 3,795 associations took 76.05 → 74.60 CPU seconds with identical+payloads and retention checksums. A 5,000-association sample from a denser cell+took 90.45 → 74.21 CPU seconds with identical scored rows. These measurements+are specific to those workloads, not nationwide runtime estimates.+Unperformed trials remain unknown with explicit conservative bounds in theretention ledger. A competitive candidate receives full evaluation, preservingits original fitted diagnostics. The initial zero cutoff only rejects trialsdiff --git a/docs/PRODUCT.md b/docs/PRODUCT.mdindex b0fe774..9498917 100644--- a/docs/PRODUCT.md+++ b/docs/PRODUCT.md@@ -126,6 +126,7 @@ audio without choosing trajectory files. The acquisition path delegates to"cache_root": "/absolute/path/to/dopplergeist-cache","offline": false,"terrain": {},+ "search_workers": 12,"search_budget": {"spacing_m": 2000,"tile_cells": 32,@@ -138,6 +139,9 @@ audio without choosing trajectory files. The acquisition path delegates toThis acquires public ADSB.lol all-type daily archives and Copernicus terrain/geoidinputs, then reuses their indexed cache. It can require substantial disk space andtime. `offline` defaults to true; online retrieval is an explicit operator choice.+`search_workers` is an optional positive integer for coarse-search processes;+omit it to use one fewer than the available logical CPUs. More workers increase+memory use. Custom terrain providers currently search serially.No hidden account credentials or paid fallback are used. The default acquisitionbudget is three UTC archive dates, including propagation guards and the full recording (`max_acquisition_days`); wider recording windows needa narrower defensible input or an explicit operator budget change. Do not putdiff --git a/src/dopplergeist/automatic.py b/src/dopplergeist/automatic.pyindex eb9189d..0ed79b9 100644--- a/src/dopplergeist/automatic.py+++ b/src/dopplergeist/automatic.py@@ -105,6 +105,9 @@ def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: Nexcept ImportError as exc:return finish("failed", "component_unavailable", f"Automatic audio components are not installed: {exc}")discovery_options = config.get("discovery", {})+ search_workers = config.get("search_workers")+ if search_workers is not None and (type(search_workers) is not int or search_workers < 1):+ return finish("failed", "invalid_configuration", "search_workers must be a positive integer.")if not isinstance(discovery_options, dict) or discovery_options.keys() - {"chunk_s", "overlap_s"}:return finish("failed", "invalid_configuration", "Operator discovery settings support only chunk_s and overlap_s.")try:@@ -276,6 +279,7 @@ def _search(request, recording, events, output, config, search_progress):report = search_national(indexes, terrain, prepared, measurements, time_range_s=time_range, output_dir=output / "search",bounds=bounds, budget=SearchBudget(**config.get("search_budget", {})),scoring=scoring, filters=filters, input_hashes=hashes,+ workers=config.get("search_workers"),search_progress=search_progress)write_json(output / "data-provenance.json", {"flight_indexes": [index.report for index in indexes],"terrain": terrain.provenance() if hasattr(terrain, "provenance") else hashes})diff --git a/src/dopplergeist/matching.py b/src/dopplergeist/matching.pyindex e9c5ab9..ddf8ed5 100644--- a/src/dopplergeist/matching.py+++ b/src/dopplergeist/matching.py@@ -48,6 +48,35 @@ class _RidgeFitCache:def __init__(self, max_entries):self.max_entries = max_entriesself.entries = OrderedDict()+ self.acoustic_entries = OrderedDict()+ self.acoustic_bytes = 0+ self.acoustic_limit = 32 * 1024 * 1024++ def acoustic_batch(self, track, observer, starts, times, c):+ """Reuse exact batched propagation inputs within this scoring call."""+ try:+ key = (id(track), _fit_argument_key(observer), _fit_argument_key(starts),+ _fit_argument_key(times), _fit_argument_key(c))+ except (TypeError, ValueError):+ key = None+ if key is not None and key in self.acoustic_entries:+ self.acoustic_entries.move_to_end(key)+ _, factors, emissions, _ = self.acoustic_entries[key]+ return factors.copy(), emissions.copy()+ receive = starts[:, None] + times[None, :]+ unique, inverse = np.unique(receive, return_inverse=True)+ factors, emissions, _ = track.acoustic(unique, observer, c)+ factors = factors[inverse].reshape(receive.shape)+ emissions = emissions[inverse].reshape(receive.shape)+ size = factors.nbytes + emissions.nbytes + starts.nbytes + times.nbytes + 512+ if key is not None and size <= self.acoustic_limit:+ while self.acoustic_bytes + size > self.acoustic_limit:+ _, (_, _, _, removed) = self.acoustic_entries.popitem(last=False)+ self.acoustic_bytes -= removed+ self.acoustic_entries[key] = (track, factors, emissions, size)+ self.acoustic_bytes += size+ return factors.copy(), emissions.copy()+ return factors, emissionsdef fit(self, track, observer, measurement, start_time, f0_bounds, c, sigma_hz, drift_fraction,acoustic_result=None):@@ -496,15 +525,20 @@ def _iter_acoustic_trials(tracks, measurements, observer, starts, c=343.0, max_sif measured.sum() < 10 or not np.all(np.isfinite(weight)) or np.any(weight < 0) or size > remaining:yield Nonecontinue- receive = starts[:, None] + times[measured][None, :]- unique, inverse = np.unique(receive, return_inverse=True)try:- factor, emission, _ = track.acoustic(unique, observer, c)+ cache = _ridge_fit_cache.get()+ if cache is None or cache.acoustic_limit <= 0:+ receive = starts[:, None] + times[measured][None, :]+ unique, inverse = np.unique(receive, return_inverse=True)+ factor, emission, _ = track.acoustic(unique, observer, c)+ batch = factor[inverse].reshape(receive.shape), emission[inverse].reshape(receive.shape)+ else:+ batch = cache.acoustic_batch(track, observer, starts, times[measured], c)except AcousticSupportError:yield Nonecontinueremaining -= size- yield factor[inverse].reshape(receive.shape), emission[inverse].reshape(receive.shape)+ yield batchdef refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=500.0,diff --git a/src/dopplergeist/tiled_search.py b/src/dopplergeist/tiled_search.pyindex c6a9e05..55147f5 100644--- a/src/dopplergeist/tiled_search.py+++ b/src/dopplergeist/tiled_search.py@@ -443,6 +443,12 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, straise DataUnavailable("Tile candidate memory budget exceeded; reduce tile_cells")candidates, counts = pair_candidates(table, events, **kwargs)screened = subset and parameters.get("mode") == "robust_ridge"+ # Sparse tiles showed no benefit from caching batched propagation. Keep+ # the exact-input cache for dense association sets, where repetition can+ # outweigh key and copy costs, and preserve the ordinary path elsewhere.+ if not screened or len(candidates) < 1000:+ from .matching import _ridge_fit_cache+ _ridge_fit_cache.get().acoustic_limit = 0# Every accepted association has a nonnegative score, even before K modes# exist. A strict zero floor can reject only residual-incompatible trials.cutoff = _RetainedScoreFloor(budget.top_k, 0.0 if score_floor is None else max(0.0, score_floor)) if screened else Nonediff --git a/tests/test_real_acoustic_batch_cache.py b/tests/test_real_acoustic_batch_cache.pynew file mode 100644index 0000000..3a39d58--- /dev/null+++ b/tests/test_real_acoustic_batch_cache.py@@ -0,0 +1,83 @@+"""Exact propagation reuse with actual recorded ridges and historical tracks."""+import json+import os+from pathlib import Path++import numpy as np+import pandas as pd+import pytest++from dopplergeist.data_access import FlightIndex+from dopplergeist.geometry import ecef+from dopplergeist.matching import (_cache_ridge_fits, _ridge_fit_cache,+ batch_acoustic_trials, prepare_events)+++def test_real_acoustic_batches_reuse_exact_inputs_and_preserve_fallback(monkeypatch):+ fixture_path = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")+ if not fixture_path:+ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to the real CPA diagnostic")+ fixture = json.loads(Path(fixture_path).read_text())+ events, measurements = prepare_events(fixture["events"])+ tracks = {track.id: track for track in FlightIndex(fixture["real_index"]).query(+ fixture["query_bounds"], fixture["query_time_s"])}+ point = fixture["point"]+ observer = ecef(point["lat"], point["lon"], point["elev_m"])+ for event, measurement in zip(events, measurements):+ for row in pd.DataFrame(fixture["cpa_rows"]).itertuples():+ if row.flight_id not in tracks:+ continue+ track = tracks[row.flight_id]+ starts = row.receive_time - event["cpa_receive_s"] + np.linspace(-5, 5, 21)+ baseline = batch_acoustic_trials([track], [measurement], observer, starts)[0]+ if baseline is not None and all(np.all(np.isfinite(part)) for part in baseline):+ break+ else:+ continue+ break+ else:+ pytest.fail("No supported real flight/event pair in the fixture")+ calls = 0+ original = track.acoustic+ def counted(*args, **kwargs):+ nonlocal calls+ calls += 1+ return original(*args, **kwargs)+ monkeypatch.setattr(track, "acoustic", counted)++ @_cache_ridge_fits+ def cached():+ first = batch_acoustic_trials([track], [measurement], observer, starts)[0]+ first[0][0, 0] = -1 # Cache entries must not share mutable results.+ again = batch_acoustic_trials([track], [measurement], observer, starts)[0]+ assert all(np.array_equal(a, b) for a, b in zip(again, baseline))+ assert calls == 1+ shifted = starts.copy()+ shifted[0] = np.nextafter(shifted[0], np.inf)+ batch_acoustic_trials([track], [measurement], observer, shifted)+ assert calls == 2+ assert batch_acoustic_trials([track], [measurement], observer, starts, max_samples=1) == [None]+ cached()++ @_cache_ridge_fits+ def without_capacity():+ _ridge_fit_cache.get().acoustic_limit = 0+ return [batch_acoustic_trials([track], [measurement], observer, starts)[0] for _ in range(2)]+ before = calls+ uncached = without_capacity()+ assert calls == before + 2+ assert all(all(np.array_equal(a, b) for a, b in zip(value, baseline)) for value in uncached)++ @_cache_ridge_fits+ def evicted():+ cache = _ridge_fit_cache.get()+ batch_acoustic_trials([track], [measurement], observer, starts)+ cache.acoustic_limit = cache.acoustic_bytes+ shifted = starts.copy()+ shifted[0] = np.nextafter(shifted[0], np.inf)+ batch_acoustic_trials([track], [measurement], observer, shifted)+ batch_acoustic_trials([track], [measurement], observer, starts)+ assert len(cache.acoustic_entries) == 1 and cache.acoustic_bytes <= cache.acoustic_limit+ before = calls+ evicted()+ assert calls == before + 3diff --git a/tests/test_real_clock_partitions.py b/tests/test_real_clock_partitions.pyindex 4ec4940..903f972 100644--- a/tests/test_real_clock_partitions.py+++ b/tests/test_real_clock_partitions.py@@ -96,7 +96,13 @@ def test_real_clock_partition_restart_and_scores(tmp_path, monkeypatch):time_range_s=index.report["coverage"]["time_range_s"], output_dir=tmp_path / name, bounds=bounds,budget=budget, scoring=settings, workers=1, search_progress=progress)- baseline = run("baseline")+ # The sparse real replay must retain the ordinary propagation path.+ from dopplergeist.matching import _RidgeFitCache+ with monkeypatch.context() as patch:+ def unexpected_cache(*args, **kwargs):+ pytest.fail("sparse search should not use the acoustic batch cache")+ patch.setattr(_RidgeFitCache, "acoustic_batch", unexpected_cache)+ baseline = run("baseline")original = tiled._scoredef force_split(*args, **kwargs):if kwargs.get("anchor_window") is None:diff --git a/tests/test_real_search_workers.py b/tests/test_real_search_workers.pynew file mode 100644index 0000000..88100e3--- /dev/null+++ b/tests/test_real_search_workers.py@@ -0,0 +1,39 @@+"""Worker-count configuration using the saved original upload and real index."""+import json+import os+from pathlib import Path+from types import SimpleNamespace++import pytest++from dopplergeist.automatic import _search, analyze+import dopplergeist.tiled_search as tiled+++def test_real_upload_worker_setting_reaches_search(tmp_path, monkeypatch):+ source, index, reference, terrain = (os.environ.get(name) for name in (+ 'DOPPLERGEIST_REAL_JOB_ROOT', 'DOPPLERGEIST_REAL_DEVELOPMENT_INDEX',+ 'DOPPLERGEIST_REAL_REFERENCE_ROOT', 'DOPPLERGEIST_REAL_ENGINEERING_TERRAIN'))+ if not all((source, index, reference, terrain)):+ pytest.skip('set the real job, development index, reference and terrain paths')+ job, reference, terrain = Path(source), Path(reference), Path(terrain)+ request = json.loads((job / 'request.json').read_text())+ metadata = json.loads((job / 'intake/recording.json').read_text())+ events = json.loads((job / 'discovery/discovery.json').read_text())['events']+ config = {'search_workers': 12, 'flight_indexes': [index], 'terrain': {+ 'rasters': [str(reference / 'data/terrain/copernicus90/Copernicus_DSM_COG_30_N40_00_W074_00_DEM.tif')],+ 'geoid_raster': str(terrain / 'us_nga_egm08_25.tif')}}+ captured = []+ class StopBeforeScoring(Exception):+ pass+ def stop(*args, **kwargs):+ captured.append(kwargs['workers'])+ raise StopBeforeScoring+ monkeypatch.setattr(tiled, 'search_national', stop)+ with pytest.raises(StopBeforeScoring):+ _search(request, SimpleNamespace(metadata=metadata), events, tmp_path, config, lambda *_: None)+ assert captured == [12]++ for i, invalid in enumerate((0, -1, True, 1.5, '12')):+ result = analyze(request, tmp_path / str(i), {'search_workers': invalid})+ assert result['status'] == 'failed' and result['reason_code'] == 'invalid_configuration'