Skip to content

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

Enable parallel tile workers for explicit terrain (#276)

Cinna Davis0d5a7fc6c00d
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
index 64c9251..85873d8 100644
--- a/docs/PERFORMANCE.md
+++ b/docs/PERFORMANCE.md
@@ -1568,3 +1568,32 @@ A different encoding requires an explicit declaration and the canonical WAV iden
Both new-encoding arms must still process the complete recording, consider every group, and produce exactly equal outputs.
These regional computation controls use source-informed bounds and clock evidence.
They do not establish independent location accuracy, nationwide completion time, or a cold-cache acquisition speedup.
+
+## Explicit terrain and tile workers
+
+A real MP3 replay from [Eclipse Soundscapes ESID 762](https://zenodo.org/records/21786378)
+compared one versus six tile workers with the same cached all-aircraft April 8
+index, explicit Copernicus DEM and EGM2008 geoid. The test used a source-informed
+Texas regional box `[-98.98, 30.29, -98.73, 30.47]`, the provisional
+`04:26:49–04:28:49Z` recording-start window, 750 m coarse spacing and 150 m
+finalist spacing. It used source `f898ee1` with native backends on the homelab;
+all runs searched 20 tiles and 852 grid points. Inputs and clock are not an
+independent accuracy benchmark.
+
+In three alternating pairs (1/6, 6/1, 1/6), complete upload wall times were
+13.971, 13.094 and 13.301 s with one worker, and 12.425, 12.950 and 12.280 s
+with six: medians **13.301 vs 12.425 s**, or **1.07x** on this workload.
+Median search-stage times were **6.440 vs 5.713 s**. All event lists, 105
+ordered candidates and inconclusive decisions matched exactly; the first pair
+also had 5,495 identical scored retention rows and identical assessed-mode IDs.
+Each run reported complete requested geographic search and available data. This is not a
+national runtime estimate. A separate 212-point comparison was slower with six
+workers: 16.84 vs 17.47 s end to end, one pair.
+
+Coverage accounting differed: serial global-floor pruning recorded 82,374
+unknown and 8,332 rejected trials, while parallel per-tile work recorded 26,955
+unknown and 63,751 rejected. Both sums were 90,706 and the best discarded
+score bound was identical, but the individual diagnostics and discarded counts
+were not identical. Different workloads may have different outcomes. The saved
+real-input reports and job artifacts are on the homelab under
+`/srv/homelab/datasets/dopplergeist-explicit-terrain-benchmark-20261103/`.
diff --git a/src/dopplergeist/parallel_tiles.py b/src/dopplergeist/parallel_tiles.py
index 05c66fb..954c9d8 100644
--- a/src/dopplergeist/parallel_tiles.py
+++ b/src/dopplergeist/parallel_tiles.py
@@ -109,12 +109,25 @@ _worker = None
def initialize_tile_worker(index_paths, terrain_root, terrain_options, events, measurements,
bounds, time_range, budget, parameters, filters, start_window,
- crs, ledger_directory, run_hash, score_kind):
+ crs, ledger_directory, run_hash, score_kind, terrain_kind="cached"):
"""Initialize read-only indexes and reusable terrain state inside one worker."""
global _worker
+ if terrain_kind == "cached":
+ terrain = CachedTerrain(terrain_root, **terrain_options)
+ elif terrain_kind == "explicit":
+ from atexit import register
+ from .terrain import Terrain
+ terrain = Terrain(**terrain_options)
+ rasters = list(terrain.rasters)
+ if terrain.geoid:
+ rasters.extend(terrain.geoid.rasters)
+ for raster in rasters:
+ register(raster.close)
+ else:
+ raise ValueError("Unsupported tile worker terrain")
_worker = {
"indexes": [FlightIndex(path) for path in index_paths],
- "terrain": CachedTerrain(terrain_root, **terrain_options),
+ "terrain": terrain,
"events": events, "measurements": measurements, "bounds": bounds,
"time_range": time_range, "budget": budget, "parameters": parameters,
"filters": filters, "start_window": start_window, "crs": crs,
@@ -133,14 +146,15 @@ def score_tile(stage, cells, score_floor=None):
terrain = state["terrain"]
terrain.last_sample_files = set()
terrain.last_sample_ocean_tiles = set()
- failures_before = len(terrain.failures)
+ failures_before = len(getattr(terrain, "failures", ()))
path = None
def observed_terrain():
names = getattr(terrain, "last_sample_files", set())
- return {"terrain_files": [terrain.files[name] for name in sorted(names) if name in terrain.files],
+ files = getattr(terrain, "files", {})
+ return {"terrain_files": [files[name] for name in sorted(names) if name in files],
"terrain_ocean_tiles": sorted(getattr(terrain, "last_sample_ocean_tiles", set())),
- "terrain_failures": terrain.failures[failures_before:]}
+ "terrain_failures": getattr(terrain, "failures", [])[failures_before:]}
try:
radius = max(event["slant_range_m"][1] for event in state["events"])
@@ -192,7 +206,9 @@ def score_tile(stage, cells, score_floor=None):
def score_tile_with_cache_state(stage, cells, score_floor=None):
"""Return the worker's resident DEM keys for scheduling; never persist them."""
payload, worker_path = score_tile(stage, cells, score_floor)
- cache_keys = tuple(path.stem for path in _worker["terrain"]._tile_cache)
+ terrain = _worker["terrain"]
+ cache_keys = (tuple(path.stem for path in terrain._tile_cache) if hasattr(terrain, "_tile_cache")
+ else tuple(Path(raster.name).stem for raster in terrain.rasters))
return payload, worker_path, cache_keys
diff --git a/src/dopplergeist/tiled_search.py b/src/dopplergeist/tiled_search.py
index 12c86a3..1ac735e 100644
--- a/src/dopplergeist/tiled_search.py
+++ b/src/dopplergeist/tiled_search.py
@@ -787,6 +787,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
import os
from contextlib import ExitStack, nullcontext
from .data_access import CachedTerrain
+ from .terrain import Terrain
from .parallel_retention import import_retention_stage
from .parallel_tiles import TileFailure, initialize_tile_worker, ordered_tile_results, tile_worker_lanes
xmin, ymin, xmax, ymax = _grid_extent(bounds, budget.spacing_m, crs)
@@ -814,7 +815,15 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
if type(workers) is not int or workers < 1:
raise ValueError("workers must be a positive integer")
workers = min(workers, total, budget.max_tiles or total)
- parallel = workers > 1 and type(terrain) is CachedTerrain
+ # GDAL virtual/in-memory datasets can be valid in the parent but cannot
+ # necessarily be reopened in a spawned process. Preserve the serial path
+ # for those inputs instead of turning a working search into a failed one.
+ explicit_rasters = list(terrain.rasters) if type(terrain) is Terrain else []
+ if type(terrain) is Terrain and terrain.geoid:
+ explicit_rasters.extend(terrain.geoid.rasters)
+ explicit_reopenable = (type(terrain) is Terrain and
+ all(Path(raster.name).is_file() for raster in explicit_rasters))
+ parallel = workers > 1 and (type(terrain) is CachedTerrain or explicit_reopenable)
output = Path(output_dir)
output.mkdir(parents=True, exist_ok=True)
manifest = output / "manifest.json"
@@ -929,14 +938,21 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out
return iy, ix, tuple(4 + int(p[1:]) if p.startswith("t") else int(p) for p in path)
if parallel:
- terrain_options = {"offline": terrain.offline, "geoid_path": terrain.geoid_path,
- "adopt_existing": terrain.adopt_existing}
- initargs = ([index.path for index in indexes], terrain.root, terrain_options, events, measurements,
+ if type(terrain) is CachedTerrain:
+ terrain_kind, terrain_root = "cached", terrain.root
+ terrain_options = {"offline": terrain.offline, "geoid_path": terrain.geoid_path,
+ "adopt_existing": terrain.adopt_existing}
+ dem_keys = lambda cells: _tile_dem_keys(cells, budget.spacing_m, bounds, crs, terrain.catalog)
+ else:
+ terrain_kind, terrain_root = "explicit", None
+ paths = [raster.name for raster in terrain.rasters]
+ geoid_path = terrain.geoid.rasters[0].name if terrain.geoid else None
+ terrain_options = {"paths": paths, "constant_m": terrain.constant, "geoid_path": geoid_path}
+ dem_keys = lambda cells: tuple(Path(path).stem for path in paths)
+ initargs = ([index.path for index in indexes], terrain_root, terrain_options, events, measurements,
bounds, time_range_s, budget, parameters, filters, start_window, crs,
- output / ".tile-workers", run_hash, score_kind)
- context = tile_worker_lanes(
- workers, initialize_tile_worker, initargs,
- lambda cells: _tile_dem_keys(cells, budget.spacing_m, bounds, crs, terrain.catalog))
+ output / ".tile-workers", run_hash, score_kind, terrain_kind)
+ context = tile_worker_lanes(workers, initialize_tile_worker, initargs, dem_keys)
else:
context = nullcontext(None)
def finish_tile(stage, cells, future):
diff --git a/tests/test_real_explicit_terrain_workers.py b/tests/test_real_explicit_terrain_workers.py
new file mode 100644
index 0000000..eda7aa5
--- /dev/null
+++ b/tests/test_real_explicit_terrain_workers.py
@@ -0,0 +1,102 @@
+"""Worker initialization against operator-supplied real terrain, without a search."""
+
+from concurrent.futures import ProcessPoolExecutor
+from multiprocessing import get_context
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from dopplergeist.matching import prepare_events
+from dopplergeist.parallel_tiles import initialize_tile_worker, score_tile
+from dopplergeist.terrain import Terrain
+from dopplergeist.tiled_search import SearchBudget
+
+# Published ESID 762 site and a candidate from its saved real-audio search.
+_POINTS = ((30.386361, -98.860931), (30.38874803589124, -98.87993276822816))
+_barrier = None
+
+
+def _initialize(args, barrier):
+ global _barrier
+ initialize_tile_worker(*args)
+ _barrier = barrier
+
+
+def _sample(_):
+ from dopplergeist.parallel_tiles import _worker
+
+ _barrier.wait(timeout=30)
+ return os.getpid(), [float(_worker["terrain"].sample(lat, lon)) for lat, lon in _POINTS]
+
+
+def _score_one(task):
+ _barrier.wait(timeout=30)
+ payload, _ = score_tile(*task)
+ return os.getpid(), payload
+
+
+def test_real_explicit_dem_reopened_in_two_workers(tmp_path, capfd):
+ names = ("DOPPLERGEIST_REAL_TERRAIN_DEM", "DOPPLERGEIST_REAL_TERRAIN_GEOID",
+ "DOPPLERGEIST_REAL_TERRAIN_FLIGHT_INDEX")
+ values = [os.environ.get(name) for name in names]
+ if not all(values):
+ pytest.skip("set real DEM, geoid and flight index paths to run the terrain worker check")
+ dem, geoid, index = (str(Path(value)) for value in values)
+ parent = Terrain([dem], geoid_path=geoid)
+ try:
+ expected = [float(parent.sample(lat, lon)) for lat, lon in _POINTS]
+ finally:
+ for raster in parent.rasters + parent.geoid.rasters:
+ raster.close()
+
+ context = get_context("spawn")
+ barrier = context.Barrier(2)
+ options = {"paths": [dem], "constant_m": None, "geoid_path": geoid}
+ args = ([index], None, options, [], [], None, None, None, None, None, None,
+ None, tmp_path / "worker-ledgers", "worker-check", "worker-check", "explicit")
+ with ProcessPoolExecutor(max_workers=2, mp_context=context, initializer=_initialize,
+ initargs=(args, barrier)) as pool:
+ observed = list(pool.map(_sample, range(2)))
+ assert len({pid for pid, _ in observed}) == 2
+ assert all(samples == expected for _, samples in observed)
+ assert not capfd.readouterr().err
+
+
+def test_real_explicit_tiles_match_direct_scoring(tmp_path):
+ names = ("DOPPLERGEIST_REAL_TERRAIN_DEM", "DOPPLERGEIST_REAL_TERRAIN_GEOID",
+ "DOPPLERGEIST_REAL_TERRAIN_FLIGHT_INDEX", "DOPPLERGEIST_REAL_TILE_JOB")
+ values = [os.environ.get(name) for name in names]
+ if not all(values):
+ pytest.skip("set real terrain, index and ESID 762 job paths to replay a recorded tile")
+ dem, geoid, index, saved_job = values
+ job = Path(saved_job)
+ config = json.loads((job / "search/manifest.json").read_text())["configuration"]
+ raw = json.loads((job / "discovery/discovery.json").read_text())["events"]
+ events, measurements = prepare_events(raw, c=343.0, max_distance_m=20000.0)
+ assert events == config["events"]
+ budget = SearchBudget(**config["budget"])
+ parameters = dict(config["scoring"])
+ window = parameters.pop("recording_start_window_s")
+ options = {"paths": [dem], "constant_m": None, "geoid_path": geoid}
+
+ def args(directory):
+ return ([index], None, options, events, measurements, config["bounds"], config["time_range_s"],
+ budget, parameters, config["filters"], window, config["crs"], tmp_path / directory,
+ "real-tile-replay", "matched_group_support_minus_normalized_residual", "explicit")
+
+ tiles = []
+ for identity in ("-24_68", "-23_68"):
+ original = json.loads((job / f"search/tile-{identity}.json").read_text())["payload"]
+ tiles.append((f"coarse:{identity}", tuple(original["cells"])))
+ initialize_tile_worker(*args("direct"))
+ direct = [score_tile(*tile)[0] for tile in tiles]
+ context = get_context("spawn")
+ barrier = context.Barrier(2)
+ with ProcessPoolExecutor(max_workers=2, mp_context=context, initializer=_initialize,
+ initargs=(args("worker"), barrier)) as pool:
+ workers = list(pool.map(_score_one, tiles))
+ assert len({pid for pid, _ in workers}) == 2
+ assert all(payload["grid_points"] > 0 and payload["ranked"] for payload in direct)
+ assert direct == [payload for _, payload in workers]