Skip to content

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

Preserve real-event refinement coverage at both time bounds [skip ci]

Cinna Davis064d615734cd
diff --git a/src/dopplergeist/automatic.py b/src/dopplergeist/automatic.py
index ea24118..5500f72 100644
--- a/src/dopplergeist/automatic.py
+++ b/src/dopplergeist/automatic.py
@@ -102,29 +102,52 @@ class MissingData(ValueError):
def _earliest_emission(lo, events, max_distance, c, filters):
"""Retain the complete CPA and refinement envelope of all proposals."""
original = lo - max_distance / 300 - 30
+ try:
+ # Even when the optional CPA/silence settings cannot narrow the search,
+ # refinement loads tracks 120 s before the first observed event.
+ earliest_refinement = lo + min(e["start_s"] for e in events) - max_distance / 300 - 121
+ fallback = min(original, earliest_refinement) if math.isfinite(earliest_refinement) else original
+ except (KeyError, TypeError, ValueError):
+ return original
try:
offset = float(filters.get("offset_tolerance_s", 5.0))
if not math.isfinite(offset) or offset < 0 or not math.isfinite(c) or c <= 0:
- return original
+ return fallback
silence = filters.get("silence")
if silence:
if not isinstance(silence, dict):
- return original
+ return fallback
margin = float(silence.get("edge_margin_s", 60))
if not math.isfinite(margin) or margin < 0:
- return original
+ return fallback
# Candidate association allows half the offset tolerance beyond each
# event's CPA interval, then the wide-clock scorer allows a 5 s sweep.
earliest_cpa = min(e["cpa_receive_s"] - e["quality"]["cpa_tolerance_s"] for e in events)
# Round outward relative to the differently grouped Unix-time
# calculation in _decide, including floating-point error.
- earliest_refinement = min(e["start_s"] for e in events) - max_distance / 300 - 121
candidate = earliest_cpa - offset / 2 - 5 - max_distance / c - 30
if not all(math.isfinite(x) for x in (earliest_cpa, earliest_refinement, candidate)):
- return original
- return max(original, lo + min(candidate, earliest_refinement))
+ return fallback
+ return min(lo + candidate, earliest_refinement)
except (KeyError, TypeError, ValueError):
- return original
+ return fallback
+
+
+def _latest_emission(hi, duration, events, filters):
+ """Retain whole-recording, CPA and refinement upper time envelopes."""
+ original = hi + duration + 30
+ refinement = hi + max(e["end_s"] for e in events) + 121
+ try:
+ offset = float(filters.get("offset_tolerance_s", 5.0))
+ except (TypeError, ValueError):
+ raise MissingData("Cannot establish coverage with an invalid CPA offset tolerance.") from None
+ if not math.isfinite(offset) or offset < 0:
+ raise MissingData("Cannot establish coverage with an invalid CPA offset tolerance.")
+ latest_cpa = max(e["cpa_receive_s"] + e["quality"]["cpa_tolerance_s"] for e in events)
+ candidate = hi + latest_cpa + offset / 2 + 5 + 31
+ if not all(math.isfinite(x) for x in (original, refinement, candidate)):
+ raise MissingData("Cannot establish finite event and refinement time coverage.")
+ return max(original, refinement, candidate)
def _search(request, recording, events, output, config, search_progress):
@@ -139,11 +162,22 @@ def _search(request, recording, events, output, config, search_progress):
lo, hi = (utc_timestamp(window[name]).timestamp() for name in ("start_utc", "end_utc"))
filters = {"association": "subsets", **config.get("filters", {})}
filters.setdefault("max_events", len(prepared))
+ silence = filters.get("silence")
+ if silence:
+ if not isinstance(silence, dict):
+ raise MissingData("Cannot establish coverage with an invalid silence configuration.")
+ try:
+ margin = float(silence.get("edge_margin_s", 60))
+ except (TypeError, ValueError):
+ raise MissingData("Cannot establish coverage with an invalid silence margin.") from None
+ if not math.isfinite(margin) or margin < 0:
+ raise MissingData("Cannot establish coverage with a negative or nonfinite silence margin.")
earliest = _earliest_emission(lo, prepared, max_distance, c, filters)
+ latest = _latest_emission(hi, recording.metadata["duration_s"], prepared, filters)
if not config.get("flight_indexes") and not config.get("cache_root"):
raise MissingData("Historical flight/terrain data are not configured. The operator must provide cache_root or prebuilt flight indexes with a terrain model.")
first_day = datetime.fromtimestamp(earliest, timezone.utc).date()
- last_day = datetime.fromtimestamp(hi+recording.metadata["duration_s"]+30, timezone.utc).date()
+ last_day = datetime.fromtimestamp(latest, timezone.utc).date()
acquisition_days = (last_day-first_day).days+1
if not config.get("flight_indexes") and acquisition_days > config.get("max_acquisition_days", 3):
raise MissingData("Recording time window exceeds the configured historical-data acquisition budget. Supply a narrower defensible window.")
@@ -156,14 +190,14 @@ def _search(request, recording, events, output, config, search_progress):
raise MissingData("A declared local terrain model requires prebuilt flight indexes.")
indexes = [FlightIndex(path) for path in config["flight_indexes"]]
terrain = Terrain(ground.get("rasters", []), ground.get("constant_m"), ground.get("geoid_raster"))
- time_range = (earliest, hi+recording.metadata["duration_s"]+30)
+ time_range = (earliest, latest)
bounds = request["search"].get("bounds_wsen", CONUS)
hashes["terrain_rasters"] = {str(path): _digest(path) for path in ground.get("rasters", [])}
else:
bundle = acquire_inputs(request, recording.metadata, cache_root=config.get("cache_root", output / "cache"),
index_paths=config.get("flight_indexes"), offline=config.get("offline", True),
terrain_options=ground, max_sound_range_m=max_distance,
- earliest_emission_s=earliest)
+ earliest_emission_s=earliest, latest_emission_s=latest)
indexes, terrain, time_range, bounds = bundle.indexes, bundle.terrain, bundle.time_range_s, bundle.bounds
if ground.get("geoid_raster"):
hashes["geoid_sha256"] = _digest(ground["geoid_raster"])
diff --git a/src/dopplergeist/data_access.py b/src/dopplergeist/data_access.py
index 3430d3b..9a10772 100644
--- a/src/dopplergeist/data_access.py
+++ b/src/dopplergeist/data_access.py
@@ -552,7 +552,8 @@ class AcquiredInputs:
def acquire_inputs(request, recording, *, cache_root, index_paths=None, offline=False,
- terrain_options=None, max_sound_range_m=20000.0, earliest_emission_s=None):
+ terrain_options=None, max_sound_range_m=20000.0, earliest_emission_s=None,
+ latest_emission_s=None):
"""Contract adapter for orchestration; no hand-prepared Parquet is required.
`index_paths` is an operator-owned explicit offline override, not a user
@@ -569,8 +570,17 @@ def acquire_inputs(request, recording, *, cache_root, index_paths=None, offline=
if earliest_emission_s is not None:
if not np.isfinite(earliest_emission_s):
raise ValueError("Earliest emission time must be finite")
- first = max(first, earliest_emission_s)
- times = (first, end + recording["duration_s"] + 30.0)
+ # The caller's bound covers its actual CPA and refinement queries. It
+ # can be earlier or later than the generic whole-recording estimate.
+ first = earliest_emission_s
+ last = end + recording["duration_s"] + 30.0
+ if latest_emission_s is not None:
+ if not np.isfinite(latest_emission_s):
+ raise ValueError("Latest emission time must be finite")
+ last = max(last, latest_emission_s)
+ if first > last:
+ raise ValueError("Required emission interval must be ordered")
+ times = (first, last)
root = Path(cache_root)
if index_paths:
indexes = [FlightIndex(path) for path in index_paths]
diff --git a/tests/test_real_acquisition_bounds.py b/tests/test_real_acquisition_bounds.py
new file mode 100644
index 0000000..51057f0
--- /dev/null
+++ b/tests/test_real_acquisition_bounds.py
@@ -0,0 +1,38 @@
+"""Optional regression using saved discovery results from real recordings."""
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from dopplergeist.automatic import _earliest_emission, _latest_emission
+from dopplergeist.matching import prepare_events
+
+
+def test_real_events_keep_the_full_refinement_and_cpa_envelopes():
+ source = os.environ.get("DOPPLERGEIST_REAL_DISCOVERY_RESULTS")
+ if not source:
+ pytest.skip("set DOPPLERGEIST_REAL_DISCOVERY_RESULTS to real completed job outputs")
+ checked = 0
+ for path in sorted(Path(source).glob("clip-*/**/result.json")):
+ result = json.loads(path.read_text())
+ events = result.get("events", [])
+ if not events:
+ continue
+ prepared, _ = prepare_events(events)
+ # Bounds are translation invariant; these are offsets, not a claimed
+ # UTC clock for the recordings.
+ acquisition = _earliest_emission(0., prepared, 20000., 343., {})
+ refinement = min(e["start_s"] for e in prepared) - 20000. / 300. - 120.
+ cpa = min(e["cpa_receive_s"] - e["quality"]["cpa_tolerance_s"] for e in prepared)
+ cpa -= 2.5 + 5. + 20000. / 343. + 30.
+ assert acquisition <= refinement
+ assert acquisition <= cpa
+ duration = result["recording"]["duration_s"]
+ latest = _latest_emission(0., duration, prepared, {})
+ assert latest >= duration + 30
+ assert latest >= max(e["end_s"] for e in prepared) + 120
+ latest_cpa = max(e["cpa_receive_s"] + e["quality"]["cpa_tolerance_s"] for e in prepared)
+ assert latest >= latest_cpa + 2.5 + 5 + 30
+ checked += 1
+ assert checked > 0, "No real proposal-bearing completed jobs found"