Skip to content

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

Preserve partial evidence and verify real MP3 controls through HTTP (#10, #11)

Cinna Davis0bbb5dd8e0b9
diff --git a/docs/PRODUCT.md b/docs/PRODUCT.md
index 65ac052..a9dccb5 100644
--- a/docs/PRODUCT.md
+++ b/docs/PRODUCT.md
@@ -64,3 +64,51 @@ curl -H 'Content-Type: application/octet-stream' \
`tests/test_service.py` checks HTTP transport, original preservation, state
readback, cancellation, interrupted jobs, path restrictions and input validation.
These transport tests do not establish scientific localization accuracy.
+
+## Provider and search configuration
+
+An operator configures data once; users upload audio without choosing trajectory
+files. The normal acquisition path delegates to `data_access.acquire_inputs`:
+
+```json
+{
+ "cache_root": "/absolute/path/to/dopplergeist-cache",
+ "offline": false,
+ "terrain": {},
+ "search_budget": {
+ "spacing_m": 2000,
+ "tile_cells": 32,
+ "top_k": 100,
+ "refine_spacing_m": 100
+ }
+}
+```
+
+This acquires public ADSB.lol all-type daily archives and Copernicus terrain/geoid
+inputs, then reuses their indexed cache. It can require substantial disk space and
+time. `offline` defaults to true; online retrieval is an explicit operator choice.
+No hidden account credentials or paid fallback are used. The default acquisition
+window budget is three days (`max_acquisition_days`); wider recording windows need
+a narrower defensible input or an explicit operator budget change. Do not put
+credentials in this configuration.
+
+For existing offline data, supply `flight_indexes` (paths to Worker 2 FlightIndex
+SQLite files). Terrain may use the cached provider options (`geoid_path`,
+`adopt_existing`) or a declared local override: `{"rasters":["/dem.tif"],
+"geoid_raster":"/geoid.tif"}`. A `{"constant_m":0}` terrain override exists for
+synthetic/flat-ground experiments and is labelled as a limitation in the result.
+Local overrides require prebuilt indexes and retain their actual coverage.
+
+`search_budget.max_tiles` bounds tile work. Reaching a tile, memory, data or wall
+time limit leaves incomplete coverage and cannot produce a supported national
+location. Full search completion does not prove the archive captured every real
+aircraft. Grid finalists undergo jointly constrained position/clock refinement;
+`refine_finalists` (default 5) limits physical sensitivity refinement. Unassessed
+retained approaches prevent an affirmative confidence decision.
+
+The automatic path always uses one shared clock inside the supplied start window
+and robust ridge loss. Every discovered event remains in the diagnostics. A
+location requires the confidence producer's evidence checks, including independent
+events, alternative hypotheses, complete coverage, residuals and measurement/model
+sensitivity. A small altitude-only profile is insufficient. The final decision
+and full candidate/refinement diagnostics are saved as downloadable JSON.
diff --git a/src/aircraft_geoloc/automatic.py b/src/aircraft_geoloc/automatic.py
index 783039d..bff57b0 100644
--- a/src/aircraft_geoloc/automatic.py
+++ b/src/aircraft_geoloc/automatic.py
@@ -18,6 +18,9 @@ def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: N
request = validate_request(request)
config = config or {}
output = Path(output_dir)
+ output.mkdir(parents=True, exist_ok=True)
+ if (output / "provenance.json").exists():
+ raise FileExistsError("Analysis output exists; use a new directory")
began = time.monotonic()
sources = {p.name: _digest(p) for p in sorted(Path(__file__).parent.glob("*.py"))}
provenance = {"request": request, "operator_configuration_sha256": hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest(),
@@ -35,7 +38,7 @@ def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: N
artifacts = {"provenance": "provenance.json", "request": "request.json"}
for name, path in (("intake", "intake/intake.json"), ("recording", "intake/recording.json"),
("discovery", "discovery/discovery.json"), ("discovery_plot", "discovery/discovery.png"),
- ("search_report", "search/search-report.json"), ("refinement", "refined-candidates.json"), ("decision", "decision.json")):
+ ("search_report", "search/search-report.json"), ("refinement", "refined-candidates.json"), ("data_provenance", "data-provenance.json"), ("decision", "decision.json")):
if (output / path).is_file():
artifacts[name] = path
for path in sorted((output / "discovery").glob("event-*.png")):
@@ -79,8 +82,8 @@ def analyze(request, output_dir, config=None, progress=lambda *args, **kwargs: N
return finish("failed", "data_unavailable", str(exc))
state["coverage"] = _coverage(request, search, config)
provenance["search_run_hash"] = search.get("run_hash")
- progress("decision", 0.9, **state)
- return _decide(search, events, prepared_events, measurements, indexes, terrain, state, output, config, finish)
+ progress("refinement", 0.85, **state)
+ return _decide(search, events, prepared_events, measurements, indexes, terrain, state, output, config, finish, lambda: progress("decision", 0.95, **state))
class MissingData(ValueError):
@@ -129,6 +132,8 @@ 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=config.get("filters", {}), input_hashes=hashes)
+ write_json(output / "data-provenance.json", {"flight_indexes": [index.report for index in indexes],
+ "terrain": terrain.provenance() if hasattr(terrain, "provenance") else hashes})
return report, prepared, measurements, indexes, terrain
@@ -143,7 +148,7 @@ def _coverage(request, search, config):
"limitations": limitations, "requested_area": request["search"], "missing_data": missing}
-def _decide(search, events, prepared_events, measurements, indexes, terrain, state, output, config, finish):
+def _decide(search, events, prepared_events, measurements, indexes, terrain, state, output, config, finish, decision_progress):
# The confidence producer supplies this adapter; missing decision machinery
# can never turn the highest raw score into a supported location.
from .confidence import decide_location
@@ -156,7 +161,7 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, sta
# The index iterator is bounded by the same local acoustic support envelope.
seen = set()
for row in raw:
- key = (tuple(row["flight_ids"]), tuple(round(t) for t in row.get("pass_emission_times_s", [])))
+ key = (tuple(row.get("event_indices", range(len(prepared_events)))), tuple(row["flight_ids"]), tuple(round(t) for t in row.get("pass_emission_times_s", [])))
if key in seen:
continue
seen.add(key)
@@ -176,6 +181,7 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, sta
tracks[track.id] = track
if needed - tracks.keys():
raise ValueError("Candidate flight segments are unavailable for refinement")
+ row = dict(row, altitude_basis={flight: sorted(set(getattr(track, "altitude_basis", ["unspecified"]))) for flight, track in tracks.items()})
candidate = refine_candidate(row, tracks, prepared_events, measurements, terrain,
radius_m=config.get("refine_radius_m", 500.0),
recording_start_window_s=start_window, c=config.get("sound_speed_mps", 343.0))
@@ -187,7 +193,8 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, sta
candidates, rows = [], []
for row in raw:
event_ids, flight_ids = [], []
- for event, flight in zip(prepared_events, row["flight_ids"]):
+ selected_events = [prepared_events[i] for i in row.get("event_indices", range(len(prepared_events)))]
+ for event, flight in zip(selected_events, row["flight_ids"]):
ids = event.get("event_ids", [event["event_id"]])
event_ids.extend(ids)
flight_ids.extend([flight]*len(ids))
@@ -203,11 +210,14 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, sta
diagnostics = {"clock_locked": search.get("scoring_time_is_locked", False), "refinement_failures": refinement_failures,
"refinement_boundary_limited": best.get("sensitivity", {}).get("boundary_limited", True),
"sensitivity": best.get("sensitivity", {}),
+ "altitude_basis": best.get("altitude_basis", {}),
"alternatives_evaluated": search.get("status") == "complete" and not refinement_failures and len(seen) <= config.get("refine_finalists", 5)}
- for event, evidence in zip(prepared_events, best.get("event_diagnostics", [])):
+ matched_events = [prepared_events[i] for i in best.get("event_indices", range(len(prepared_events)))]
+ for event, evidence in zip(matched_events, best.get("event_diagnostics", [])):
for event_id in event.get("event_ids", [event["event_id"]]):
diagnostics[event_id] = evidence
write_json(output / "refined-candidates.json", {"ranked": rows, "matching_diagnostics": diagnostics})
+ decision_progress()
decision = decide_location(events, candidates, state["coverage"], matching_diagnostics=diagnostics)
decision["candidates"] = candidates
diff --git a/src/aircraft_geoloc/jobs.py b/src/aircraft_geoloc/jobs.py
index b546193..29e8aa3 100644
--- a/src/aircraft_geoloc/jobs.py
+++ b/src/aircraft_geoloc/jobs.py
@@ -3,6 +3,7 @@ import argparse
import fcntl
import hashlib
import json
+import math
import os
from pathlib import Path
import signal
@@ -33,15 +34,21 @@ def result(job_dir, status, **fields):
return value
+def _evidence(value):
+ return {key: value[key] for key in ("recording", "events", "candidates", "coverage", "artifacts") if key in value}
+
+
class JobManager:
def __init__(self, root, config=None, *, max_pending=4, max_runtime_s=3600, max_upload_bytes=100*1024*1024):
self.root = Path(root).resolve()
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
self.config = config or {}
+ if not isinstance(self.config, dict):
+ raise ValueError("Operator configuration must be a JSON object")
self.max_pending = max_pending
self.max_runtime_s = max_runtime_s
self.max_upload_bytes = max_upload_bytes
- if min(max_pending, max_runtime_s, max_upload_bytes) <= 0:
+ if any(not math.isfinite(value) or value <= 0 for value in (max_pending, max_runtime_s, max_upload_bytes)):
raise ValueError("Job limits must be positive")
self._lockfile = (self.root / ".manager.lock").open("a")
try:
@@ -58,7 +65,7 @@ class JobManager:
for path in self.root.glob("*/result.json"):
old = read_json(path)
if old["status"] not in TERMINAL:
- result(path.parent, "failed", reason_code="interrupted", message="Service stopped before completion; submit a new job to retry.")
+ result(path.parent, "failed", reason_code="interrupted", message="Service stopped before completion; submit a new job to retry.", **_evidence(old))
def directory(self, job_id):
try:
@@ -129,14 +136,14 @@ class JobManager:
self._stop(process)
with self._mutex:
if self.get(directory.name)["status"] not in TERMINAL:
- result(directory, "inconclusive", reason_code="work_limit", message="Analysis exceeded the configured wall-time budget; inspect partial artifacts.")
+ result(directory, "inconclusive", reason_code="work_limit", message="Analysis exceeded the configured wall-time budget; inspect partial artifacts.", **_evidence(self.get(directory.name)))
with self._mutex:
if self.get(directory.name)["status"] not in TERMINAL:
- result(directory, "failed", reason_code="worker_exit", message=f"Analysis process exited ({process.returncode}); inspect worker.log.")
+ result(directory, "failed", reason_code="worker_exit", message=f"Analysis process exited ({process.returncode}); inspect worker.log.", **_evidence(self.get(directory.name)))
except Exception as exc:
with self._mutex:
if self.get(directory.name)["status"] not in TERMINAL:
- result(directory, "failed", reason_code="worker_launch", message=f"Could not run analysis: {exc}")
+ result(directory, "failed", reason_code="worker_launch", message=f"Could not run analysis: {exc}", **_evidence(self.get(directory.name)))
finally:
with self._mutex:
self._processes.pop(directory.name, None)
@@ -162,7 +169,7 @@ class JobManager:
process = self._processes.get(job_id)
if process:
self._stop(process)
- return result(directory, "cancelled", message="Cancelled by the user; partial artifacts are preserved.")
+ return result(directory, "cancelled", message="Cancelled by the user; partial artifacts are preserved.", **_evidence(self.get(job_id)))
def wait(self, job_id):
thread = self._threads.get(job_id)
@@ -207,15 +214,15 @@ def execute(directory, parent_pid=None):
progress("intake", 0.02)
final = analyze(request, directory, config, progress)
if (directory / "cancel").exists():
- result(directory, "cancelled", message="Cancelled by the user.")
+ result(directory, "cancelled", message="Cancelled by the user.", **_evidence(read_json(directory / "result.json")))
else:
result(directory, **final)
except InterruptedError:
- result(directory, "cancelled", message="Cancelled by the user.")
+ result(directory, "cancelled", message="Cancelled by the user.", **_evidence(read_json(directory / "result.json")))
except Exception as exc:
import traceback
traceback.print_exc()
- result(directory, "failed", reason_code="processing_error", message=f"{type(exc).__name__}: {exc}")
+ result(directory, "failed", reason_code="processing_error", message=f"{type(exc).__name__}: {exc}", **_evidence(read_json(directory / "result.json")))
if __name__ == "__main__":
diff --git a/src/aircraft_geoloc/web/app.js b/src/aircraft_geoloc/web/app.js
index 17d149f..b1fd365 100644
--- a/src/aircraft_geoloc/web/app.js
+++ b/src/aircraft_geoloc/web/app.js
@@ -53,6 +53,18 @@ function render(value) {
$('message').textContent = value.message || 'Analysis is running. You can return to this job using its saved link.';
$('required').hidden = !value.required_fields?.length;
$('required').textContent = value.required_fields?.length ? `Required input: ${value.required_fields.join(', ')}. Add the evidence to a new analysis; this run is preserved.` : '';
+ $('coverage').replaceChildren();
+ if (value.coverage) {
+ const coverage = value.coverage;
+ const card = node('div', undefined, 'candidate');
+ card.append(node('strong', 'Search & data coverage'));
+ const bounds = coverage.requested_area?.bounds_wsen;
+ card.append(node('p', bounds ? `Requested CONUS subset (west, south, east, north): ${bounds.join(', ')}` : 'Requested area: contiguous United States (CONUS)'));
+ card.append(node('p', `Search ${coverage.search_complete ? 'complete' : 'incomplete'} · Data ${coverage.data_status}`));
+ for (const limitation of coverage.limitations || []) card.append(node('p', limitation));
+ if (coverage.missing_data?.length) card.append(node('p', `Missing: ${coverage.missing_data.join('; ')}`));
+ $('coverage').append(card);
+ }
$('candidates').replaceChildren();
if (value.candidates?.length) {
$('candidates').append(node('h3', value.status === 'succeeded' ? 'Supported location & alternatives' : 'Location hypotheses · result remains inconclusive'));
diff --git a/src/aircraft_geoloc/web/index.html b/src/aircraft_geoloc/web/index.html
index 131d117..e4ec46f 100644
--- a/src/aircraft_geoloc/web/index.html
+++ b/src/aircraft_geoloc/web/index.html
@@ -11,7 +11,7 @@
<fieldset><legend>When did the recording start?</legend><p class="help">Enter UTC, including the date. A window is allowed. File creation and upload times do not establish recording time. Leave blank if unknown; analysis will request this evidence before searching.</p><label for="start">Earliest start (UTC)</label><input id="start" type="datetime-local" step="1"><label for="end">Latest start (UTC)</label><input id="end" type="datetime-local" step="1"><label for="time-source">How is this time known? <span class="muted">Optional</span></label><input id="time-source" type="text" maxlength="500" placeholder="For example, recorder clock synchronized before recording"></fieldset>
<p id="limits" class="help"></p><button id="submit" type="submit">Upload &amp; analyze <span aria-hidden="true">→</span></button><p id="upload-error" role="alert"></p>
</form></section>
-<section class="panel results" aria-labelledby="results-heading"><div class="section-row"><h2 id="results-heading">Analysis</h2><button id="cancel" class="secondary" hidden>Cancel job</button></div><div id="empty"><div class="wave" aria-hidden="true">∿∿∿</div><h3>Your evidence will appear here</h3><p>Detected curves, location hypotheses, uncertainty, and downloadable artifacts stay attached to each job.</p></div><div id="job" hidden><p id="job-id" class="mono"></p><div class="section-row"><strong id="status" role="status" aria-live="polite"></strong><span id="stage" class="muted"></span></div><progress id="progress" max="1" value="0" aria-label="Analysis progress"></progress><p id="message"></p><p id="required" class="notice" hidden></p><div id="candidates"></div><div id="events"></div><div id="diagnostics"></div><details id="downloads"><summary>Download run artifacts</summary><ul id="artifacts"></ul></details><p id="connection" role="alert"></p></div></section>
+<section class="panel results" aria-labelledby="results-heading"><div class="section-row"><h2 id="results-heading">Analysis</h2><button id="cancel" class="secondary" hidden>Cancel job</button></div><div id="empty"><div class="wave" aria-hidden="true">∿∿∿</div><h3>Your evidence will appear here</h3><p>Detected curves, location hypotheses, uncertainty, and downloadable artifacts stay attached to each job.</p></div><div id="job" hidden><p id="job-id" class="mono"></p><div class="section-row"><strong id="status" role="status" aria-live="polite"></strong><span id="stage" class="muted"></span></div><progress id="progress" max="1" value="0" aria-label="Analysis progress"></progress><p id="message"></p><p id="required" class="notice" hidden></p><div id="coverage"></div><div id="candidates"></div><div id="events"></div><div id="diagnostics"></div><details id="downloads"><summary>Download run artifacts</summary><ul id="artifacts"></ul></details><p id="connection" role="alert"></p></div></section>
</div>
<section id="recent-panel" class="recent" hidden><h2>Recent jobs on this browser</h2><ul id="recent"></ul></section>
<footer>Scores rank hypotheses; they are not probabilities. An inconclusive result can include alternatives without supporting a precise location.</footer>
diff --git a/tests/test_automatic.py b/tests/test_automatic.py
index 6675e28..8a982cf 100644
--- a/tests/test_automatic.py
+++ b/tests/test_automatic.py
@@ -1,6 +1,8 @@
"""Encoded audio through the real job process, intake and automatic discovery."""
import hashlib
-import io
+import json
+import threading
+import urllib.request
import subprocess
import numpy as np
@@ -8,6 +10,7 @@ import pytest
import soundfile as sf
from aircraft_geoloc.jobs import JobManager
+from aircraft_geoloc.service import JobServer
def encoded_mp3(tmp_path, *, moving=False):
@@ -27,16 +30,31 @@ def encoded_mp3(tmp_path, *, moving=False):
def submit_and_wait(tmp_path, payload, *, time_window=None):
manager = JobManager(tmp_path / "jobs")
+ server = JobServer(("127.0.0.1", 0), manager)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ base = f"http://127.0.0.1:{server.server_port}"
try:
request = {"schema_version": 1}
if time_window:
request["time_window"] = time_window
- queued = manager.submit(request, io.BytesIO(payload), len(payload))
+ upload = urllib.request.Request(base + "/api/jobs", payload,
+ headers={"Content-Type": "application/octet-stream", "X-Dopplergeist-Request": json.dumps(request)})
+ with urllib.request.urlopen(upload, timeout=10) as response:
+ assert response.status == 202
+ queued = json.load(response)
final = manager.wait(queued["job_id"])
directory = manager.directory(queued["job_id"])
+ with urllib.request.urlopen(base + f"/api/jobs/{queued['job_id']}") as response:
+ assert json.load(response) == final
+ with urllib.request.urlopen(base + f"/api/jobs/{queued['job_id']}/artifacts/input.mp3") as response:
+ assert response.read() == payload
return final, directory
finally:
+ server.shutdown()
+ server.server_close()
manager.close()
+ thread.join()
WINDOW = {"start_utc": "2026-09-08T20:00:00Z", "end_utc": "2026-09-08T20:01:00Z", "source": "user"}