Skip to content

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

Reuse cached DEM raster metadata during clustered searches

Cinna Davisb58be40115e3
diff --git a/benchmarks/results/dem-locality-20261103.json b/benchmarks/results/dem-locality-20261103.json
new file mode 100644
index 0000000..9cb958b
--- /dev/null
+++ b/benchmarks/results/dem-locality-20261103.json
@@ -0,0 +1,137 @@
+{
+ "input": "Original public MP3 national search, 12 saved coarse grid tiles with cached GLO-90 terrain",
+ "method": "Single sequential baseline and optimized process runs under load, each warming its cache and sampling the same 12 grids three times in each order.",
+ "baseline_terrain_source_commit": "225bf6b",
+ "optimized_terrain_source": "cache-hit metadata reuse",
+ "baseline": {
+ "actual_saved_tiles": [
+ "tile--14_7.json",
+ "tile--17_3.json",
+ "tile--18_6.json",
+ "tile--19_9.json",
+ "tile--21_5.json",
+ "tile--23_3.json",
+ "tile--25_4.json",
+ "tile--27_4.json",
+ "tile--28_9.json",
+ "tile--32_5.json",
+ "tile-31_7.json",
+ "tile-35_6.json"
+ ],
+ "points": [
+ 1024,
+ 1024,
+ 1024,
+ 1024,
+ 1024,
+ 637,
+ 1024,
+ 987,
+ 1024,
+ 1003,
+ 1024,
+ 1024
+ ],
+ "repetitions": 3,
+ "clustered": {
+ "cpu_s": 2.4611824769999995,
+ "elapsed_s": 2.56626691101701,
+ "raster_opens": {
+ "total": 117,
+ "dem": 81
+ },
+ "cache_bytes": 28800000
+ },
+ "interleaved": {
+ "cpu_s": 5.559028949999998,
+ "elapsed_s": 5.745901759015396,
+ "raster_opens": {
+ "total": 117,
+ "dem": 81
+ },
+ "cache_bytes": 28800000
+ },
+ "elevation_arrays_equal": true,
+ "elevation_sha256": {
+ "0": "ab89c86583610a4420a75925a239925797e38b9779de83ca8614aeb4b0112ad0",
+ "1": "c636ec2148b65d11f79f426482f8916e31ce930ab7f328c408f4fbd02757d54e",
+ "2": "47c1693b9eb0cdcc3cf13124fe6bc398a69295862afaa5c76451bd5c054f5d9a",
+ "3": "b869ec457a5091d01d9fafd0ef377c76c7a8ecb38ec6a1133191205f1cf3c6ff",
+ "4": "f0fcc339a96d7886903da320add06a0ca8756edb17d8dae225261934086e8f7d",
+ "5": "e1c09fd11c0e862c9822e84659cf8d0ecfbb1543169621f71f617d46b1ebe380",
+ "6": "c53e1bf21b0b0c097718bfbd1dbd776acafbfe6275f79399d4aac5bd66f17186",
+ "7": "a646e1d6b2ca1a0d7dce4ea335e21d56a2df7641a03f5e6db372659e47ee3eeb",
+ "8": "ec9be89330b455dca60e75aaaa247f1a5ee0eb888f40ad88b740092ae9e37ed0",
+ "9": "831305b8361115706555f1fff3c4d0cc9585b81e7d2f0b10bcecc33b44968bf2",
+ "10": "24b1afd33176765f85e626da4a4cc98f3470b55fa2333782caf47cb371225b91",
+ "11": "d282456d840d20eee5fa86ee1eb99d5341811b8b68dd9cfedd8e3bff53b07ae8"
+ },
+ "note": "Cached-terrain locality microbenchmark; not a complete search speed estimate."
+ },
+ "optimized": {
+ "actual_saved_tiles": [
+ "tile--14_7.json",
+ "tile--17_3.json",
+ "tile--18_6.json",
+ "tile--19_9.json",
+ "tile--21_5.json",
+ "tile--23_3.json",
+ "tile--25_4.json",
+ "tile--27_4.json",
+ "tile--28_9.json",
+ "tile--32_5.json",
+ "tile-31_7.json",
+ "tile-35_6.json"
+ ],
+ "points": [
+ 1024,
+ 1024,
+ 1024,
+ 1024,
+ 1024,
+ 637,
+ 1024,
+ 987,
+ 1024,
+ 1003,
+ 1024,
+ 1024
+ ],
+ "repetitions": 3,
+ "clustered": {
+ "cpu_s": 2.1033095700000004,
+ "elapsed_s": 2.146612634998746,
+ "raster_opens": {
+ "total": 62,
+ "dem": 26
+ },
+ "cache_bytes": 28800000
+ },
+ "interleaved": {
+ "cpu_s": 5.407419108999999,
+ "elapsed_s": 5.5337040849844925,
+ "raster_opens": {
+ "total": 114,
+ "dem": 78
+ },
+ "cache_bytes": 28800000
+ },
+ "elevation_arrays_equal": true,
+ "elevation_sha256": {
+ "0": "ab89c86583610a4420a75925a239925797e38b9779de83ca8614aeb4b0112ad0",
+ "1": "c636ec2148b65d11f79f426482f8916e31ce930ab7f328c408f4fbd02757d54e",
+ "2": "47c1693b9eb0cdcc3cf13124fe6bc398a69295862afaa5c76451bd5c054f5d9a",
+ "3": "b869ec457a5091d01d9fafd0ef377c76c7a8ecb38ec6a1133191205f1cf3c6ff",
+ "4": "f0fcc339a96d7886903da320add06a0ca8756edb17d8dae225261934086e8f7d",
+ "5": "e1c09fd11c0e862c9822e84659cf8d0ecfbb1543169621f71f617d46b1ebe380",
+ "6": "c53e1bf21b0b0c097718bfbd1dbd776acafbfe6275f79399d4aac5bd66f17186",
+ "7": "a646e1d6b2ca1a0d7dce4ea335e21d56a2df7641a03f5e6db372659e47ee3eeb",
+ "8": "ec9be89330b455dca60e75aaaa247f1a5ee0eb888f40ad88b740092ae9e37ed0",
+ "9": "831305b8361115706555f1fff3c4d0cc9585b81e7d2f0b10bcecc33b44968bf2",
+ "10": "24b1afd33176765f85e626da4a4cc98f3470b55fa2333782caf47cb371225b91",
+ "11": "d282456d840d20eee5fa86ee1eb99d5341811b8b68dd9cfedd8e3bff53b07ae8"
+ },
+ "note": "Cached-terrain locality microbenchmark; not a complete search speed estimate."
+ },
+ "limitation": "Terrain-only stress measurement; no nationwide or end-to-end speedup established."
+}
diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md
index 9ba6093..f137283 100644
--- a/docs/PERFORMANCE.md
+++ b/docs/PERFORMANCE.md
@@ -253,3 +253,28 @@ The scientific result was **`inconclusive / search_incomplete`**.
Incomplete regional flight coverage and remaining search/model limitations still prevent an accepted location.
The bounded replay verifies the complete application path, not nationwide completion or a speed ratio against the timed-out run.
The CI measurement record preserves both HTTP outcomes and their separate source revisions.
+
+## DEM cache locality (2026-11-03)
+
+A terrain-only stress check sampled 12 actual saved coarse tiles from the public
+original-MP3 search, three times each. With the existing 32 MiB per-worker DEM
+cache, clustered calls took 2.46 CPU seconds and interleaved calls took 5.56 CPU
+seconds in the baseline run. Reusing cached raster metadata and decoded pixels
+reduced clustered raster opens from 81 to 26 and CPU time to 2.10 seconds;
+interleaved CPU time was 5.41 seconds with 78 opens. The twelve elevation arrays
+matched bit-for-bit across implementations. Each figure is one loaded-machine
+observation, and this is not a whole-search speed estimate. A separate exploratory
+128 MiB cache run did not materially improve the interleaved workload, so the
+32 MiB cap is unchanged. See [the recorded measurements](../benchmarks/results/dem-locality-20261103.json).
+
+To repeat on a real saved job and populated terrain cache:
+
+```bash
+OPENBLAS_NUM_THREADS=1 PYTHONPATH=src python scripts/benchmark_dem_locality.py \
+ --job /path/to/job --cache /path/to/cache --output /path/to/result.json
+```
+
+Each search worker retains its own bounded cache; row-major tile scheduling does
+not guarantee that neighboring work reaches the same worker. Grouping work by
+geography remains a separate scheduling opportunity requiring a full search and
+load-balance comparison.
diff --git a/scripts/benchmark_dem_locality.py b/scripts/benchmark_dem_locality.py
new file mode 100644
index 0000000..01733bf
--- /dev/null
+++ b/scripts/benchmark_dem_locality.py
@@ -0,0 +1,75 @@
+"""Measure clustered versus interleaved sampling of actual saved search tiles."""
+import argparse
+import hashlib
+import json
+import time
+from pathlib import Path
+
+import numpy as np
+import rasterio
+
+from dopplergeist.data_access import CachedTerrain
+from dopplergeist.tiled_search import _tile_coordinates
+
+parser = argparse.ArgumentParser(description=__doc__)
+parser.add_argument('--job', type=Path, required=True, help='real job with saved tile receipts')
+parser.add_argument('--cache', type=Path, required=True, help='real data cache containing terrain/')
+parser.add_argument('--output', type=Path, required=True)
+args = parser.parse_args()
+JOB = args.job
+config = json.loads((JOB/'search/manifest.json').read_text())['configuration']
+eligible = []
+for path in sorted((JOB/'search').glob('tile-*.json')):
+ try:
+ payload = json.loads(path.read_text())['payload']
+ if payload.get('grid_points', 0) >= 500 and len(payload.get('terrain_files', [])) >= 3:
+ eligible.append((path.name, payload['cells']))
+ except (OSError, ValueError, KeyError):
+ pass
+assert len(eligible) >= 12
+chosen = [eligible[i] for i in np.linspace(0, len(eligible)-1, 12, dtype=int)]
+points = [_tile_coordinates(tuple(cells), config['budget']['spacing_m'], config['bounds'], config['crs'])
+ for _, cells in chosen]
+original_open = rasterio.open
+
+
+def run(order):
+ terrain = CachedTerrain(args.cache/'terrain', offline=True, adopt_existing=True)
+ # The same cache is visited in the same order before either measurement.
+ for point in points:
+ terrain.sample(point.lat.to_numpy(), point.lon.to_numpy())
+ opened = {'total':0, 'dem':0}
+ def instrumented_open(path, *args, **kwargs):
+ opened['total'] += 1
+ opened['dem'] += Path(path).name.startswith('Copernicus_DSM_COG_30_')
+ return original_open(path, *args, **kwargs)
+ results = {}
+ cpu, wall = time.process_time(), time.perf_counter()
+ rasterio.open = instrumented_open
+ try:
+ for i in order:
+ point = points[i]
+ result = terrain.sample(point.lat.to_numpy(), point.lon.to_numpy())
+ if i in results:
+ np.testing.assert_array_equal(results[i], result)
+ else:
+ results[i] = result
+ finally:
+ rasterio.open = original_open
+ return results, {'cpu_s':time.process_time()-cpu, 'elapsed_s':time.perf_counter()-wall,
+ 'raster_opens':opened, 'cache_bytes':terrain._tile_cache_bytes}
+
+
+clustered = [i for i in range(len(points)) for _ in range(3)]
+interleaved = list(range(len(points)))*3
+first, a = run(clustered)
+second, b = run(interleaved)
+for key in first:
+ np.testing.assert_array_equal(first[key], second[key])
+output = {'actual_saved_tiles':[name for name, _ in chosen], 'points':[len(p) for p in points],
+ 'repetitions':3, 'clustered':a, 'interleaved':b, 'elevation_arrays_equal':True,
+ 'elevation_sha256':{str(key): hashlib.sha256(value.tobytes()).hexdigest() for key, value in first.items()},
+ 'note':'Cached-terrain locality microbenchmark; not a complete search speed estimate.'}
+args.output.parent.mkdir(parents=True, exist_ok=True)
+args.output.write_text(json.dumps(output, indent=2)+'\n')
+print(json.dumps(output, indent=2), flush=True)
diff --git a/src/dopplergeist/data_access.py b/src/dopplergeist/data_access.py
index eee6dfd..ca8c5e9 100644
--- a/src/dopplergeist/data_access.py
+++ b/src/dopplergeist/data_access.py
@@ -731,6 +731,21 @@ class CachedTerrain:
try:
stat = path.stat()
signature = (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns)
+ entry = self._tile_cache.get(path)
+ if entry is not None:
+ if entry[0] != signature:
+ raise DataUnavailable(f"Terrain raster changed after caching: {path}")
+ self._tile_cache.move_to_end(path)
+ _, pixels, mask, crs, inverse, width, height = entry
+ x, y = _terrain_transformer(crs).transform(lon, lat)
+ col, row = inverse @ (np.asarray(x), np.asarray(y))
+ col, row = np.floor(col).astype(int), np.floor(row).astype(int)
+ if np.any((col < 0) | (col >= width) | (row < 0) | (row >= height)):
+ raise DataUnavailable(f"Raster extent missing candidate points: {path}")
+ values = np.ma.array(pixels[row, col], mask=mask[row, col])
+ if np.ma.getmaskarray(values).any() or not np.isfinite(values).all():
+ raise DataUnavailable(f"Raster nodata at candidate points: {path}")
+ return np.asarray(values, dtype=float)
with rasterio.open(path) as raster:
x, y = _terrain_transformer(raster.crs).transform(lon, lat)
col, row = (~raster.transform) @ (np.asarray(x), np.asarray(y))
@@ -742,22 +757,16 @@ class CachedTerrain:
limit = 32 * 1024 * 1024
size = raster.width * raster.height * (np.dtype(raster.dtypes[0]).itemsize + 1)
if path.name.startswith("Copernicus_DSM_COG_30_") and size <= limit:
- entry = self._tile_cache.pop(path, None)
- if entry is not None:
- self._tile_cache_bytes -= entry[1].nbytes + entry[2].nbytes
- if entry[0] != signature:
- raise DataUnavailable(f"Terrain raster changed after caching: {path}")
- if entry is None:
- while self._tile_cache and self._tile_cache_bytes + size > limit:
- _, old = self._tile_cache.popitem(last=False)
- self._tile_cache_bytes -= old[1].nbytes + old[2].nbytes
- del old
- tile = raster.read(1, masked=True)
- pixels, mask = np.asarray(tile), np.ma.getmaskarray(tile)
- after = path.stat()
- if signature != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns):
- raise DataUnavailable(f"Terrain raster changed while reading: {path}")
- entry = (signature, pixels, mask)
+ while self._tile_cache and self._tile_cache_bytes + size > limit:
+ _, old = self._tile_cache.popitem(last=False)
+ self._tile_cache_bytes -= old[1].nbytes + old[2].nbytes
+ del old
+ tile = raster.read(1, masked=True)
+ pixels, mask = np.asarray(tile), np.ma.getmaskarray(tile)
+ after = path.stat()
+ if signature != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns):
+ raise DataUnavailable(f"Terrain raster changed while reading: {path}")
+ entry = (signature, pixels, mask, raster.crs, ~raster.transform, raster.width, raster.height)
self._tile_cache[path] = entry
self._tile_cache_bytes += entry[1].nbytes + entry[2].nbytes
values = np.ma.array(entry[1][row, col], mask=entry[2][row, col])
diff --git a/tests/test_real_terrain_cache_hits.py b/tests/test_real_terrain_cache_hits.py
new file mode 100644
index 0000000..a5ba7b3
--- /dev/null
+++ b/tests/test_real_terrain_cache_hits.py
@@ -0,0 +1,64 @@
+"""Cache-hit behavior on a saved search tile and the corresponding real DEM."""
+import json
+import os
+from pathlib import Path
+import shutil
+
+import numpy as np
+import pytest
+import rasterio
+
+from dopplergeist.data_access import CachedTerrain, DataUnavailable
+from dopplergeist.tiled_search import _tile_coordinates
+
+
+def real_terrain():
+ root = os.environ.get('DOPPLERGEIST_REAL_JOB_ROOT')
+ cache = os.environ.get('DOPPLERGEIST_REAL_CACHE_ROOT')
+ if not root or not cache:
+ pytest.skip('set the real job and cache paths')
+ job = Path(root)
+ config = json.loads((job/'search/manifest.json').read_text())['configuration']
+ payload = json.loads((job/'search/tile--14_7.json').read_text())['payload']
+ points = _tile_coordinates(tuple(payload['cells']), config['budget']['spacing_m'], config['bounds'], config['crs'])
+ terrain = CachedTerrain(Path(cache)/'terrain', offline=True, adopt_existing=True)
+ return terrain, points
+
+
+def test_real_cached_rasters_match_and_do_not_reopen(real_terrain, monkeypatch):
+ terrain, points = real_terrain
+ lat, lon = points.lat.to_numpy(), points.lon.to_numpy()
+ first = terrain.sample(lat, lon)
+ assert terrain._tile_cache
+ opened = []
+ original = rasterio.open
+ def record(path, *args, **kwargs):
+ opened.append(Path(path).name)
+ return original(path, *args, **kwargs)
+ monkeypatch.setattr(rasterio, 'open', record)
+ second = terrain.sample(lat, lon)
+ np.testing.assert_array_equal(first, second)
+ assert not any(name.startswith('Copernicus_DSM_COG_30_') for name in opened)
+ assert terrain._tile_cache_bytes <= 32 * 1024 * 1024
+
+
+def test_real_cached_raster_rejects_change_and_out_of_bounds(real_terrain, tmp_path):
+ terrain, points = real_terrain
+ lat, lon = points.lat.to_numpy(), points.lon.to_numpy()
+ terrain.sample(lat, lon)
+ path = next(iter(terrain._tile_cache))
+ tag = path.name
+ north = int(tag.split('_N')[1][:2])
+ east = -int(tag.split('_W')[1][:3])
+ selection = ((np.floor(lat - 1/2400) == north) & (np.floor(lon + 1/2400) == east))
+ assert selection.any()
+ copied = tmp_path/path.name
+ shutil.copyfile(path, copied)
+ terrain._raster_sample(copied, lat[selection], lon[selection])
+ with pytest.raises(DataUnavailable, match='extent'):
+ terrain._raster_sample(copied, np.array([0.0]), np.array([0.0]))
+ stat = copied.stat()
+ os.utime(copied, ns=(stat.st_atime_ns, stat.st_mtime_ns+1_000_000_000))
+ with pytest.raises(DataUnavailable, match='changed after caching'):
+ terrain._raster_sample(copied, lat[selection], lon[selection])