Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Run coarse search tiles concurrently with resumable evidence
Cinna Davis1aa2c88d9477
diff --git a/src/dopplergeist/parallel_retention.py b/src/dopplergeist/parallel_retention.pyindex 2c7788b..814f598 100644--- a/src/dopplergeist/parallel_retention.py+++ b/src/dopplergeist/parallel_retention.py@@ -21,8 +21,8 @@ def import_retention_stage(ledger, worker_path, stage, expected_checksum):try:db.execute("ATTACH DATABASE ? AS worker", (str(worker_path),))db.execute("BEGIN")- identity = db.execute("SELECT identity, score_kind FROM worker.run").fetchone()- if identity != (ledger.run_hash, ledger.score_kind):+ identity = db.execute("SELECT identity, score_kind FROM worker.run").fetchall()+ if identity != [(ledger.run_hash, ledger.score_kind)]:raise DataUnavailable("Worker retention ledger identity mismatch")stage_row = db.execute("SELECT checksum, kept, occurrences, duplicates FROM worker.stages WHERE name=?", (stage,)diff --git a/src/dopplergeist/tiled_search.py b/src/dopplergeist/tiled_search.pyindex 05baead..18fdb7a 100644--- a/src/dopplergeist/tiled_search.py+++ b/src/dopplergeist/tiled_search.py@@ -379,7 +379,8 @@ def _record_support(output, stage, counts, summary):def search_national(indexes, terrain, events, measurements, *, time_range_s, output_dir,- bounds=CONUS, budget=None, scoring=None, filters=None, crs="EPSG:5070", input_hashes=None):+ bounds=CONUS, budget=None, scoring=None, filters=None, crs="EPSG:5070", input_hashes=None,+ workers=None):"""Bounded outer driver using existing physical CPA/locked-event scoring.`events, measurements` come from `matching.prepare_events`. `time_range_s`@@ -410,8 +411,28 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif filters["association"] == "full":event_limit = len(events)event_limit_applied = filters["association"] == "subsets" and event_limit < len(events)+ import os+ from contextlib import nullcontext+ from .data_access import CachedTerrain, _index_pool+ from .parallel_retention import import_retention_stage+ from .parallel_tiles import TileFailure, initialize_tile_worker, ordered_tile_results+ xmin, ymin, xmax, ymax = _grid_extent(bounds, budget.spacing_m, crs)+ total = (xmax // budget.tile_cells - xmin // budget.tile_cells + 1) * (ymax // budget.tile_cells - ymin // budget.tile_cells + 1)+ available = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 1)+ if workers is None:+ workers = max(1, available - 1)+ 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 CachedTerrainoutput = Path(output_dir)output.mkdir(parents=True, exist_ok=True)+ manifest = output / "manifest.json"+ floor_policy = "per_tile" if parallel else "global_and_per_tile"+ if not parallel and manifest.exists():+ previous = json.loads(manifest.read_text())+ if previous.get("configuration", {}).get("coarse_floor_policy") == "per_tile":+ floor_policy = "per_tile"# Include actual acoustic measurements and implementation files in resume# identity; a detector/scorer change must never reuse stale tile scores.acoustic = []@@ -432,10 +453,10 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out"terrain": terrain_signature, "additional_input_hashes": input_hashes or {},"events": events, "acoustic_hashes": acoustic, "bounds": list(bounds), "time_range_s": list(time_range_s),"budget": asdict(budget), "scoring": scoring or {}, "filters": filters, "crs": crs, "code": modules,+ "coarse_floor_policy": floor_policy,"runtime": {"python": platform.python_version(), "machine": platform.machine(),"packages": {name: version(name) for name in ("numpy", "scipy", "pandas", "pyproj", "rasterio", "pyarrow")}}}run_hash = content_hash(identity)- manifest = output / "manifest.json"if manifest.exists() and json.loads(manifest.read_text())["run_hash"] != run_hash:raise DataUnavailable("Checkpoint configuration/input/implementation mismatch; use a new output directory")write_json(manifest, {"run_hash": run_hash, "configuration": identity})@@ -448,50 +469,107 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outsupport = dict(unsupported_cpa_track_evaluations=0, unclassified_score_candidates=0,bounded_score_candidates=0, unbounded_score_candidates=0,evaluated_trials=0, rejected_trials=0, unknown_trials=0, unreported_trial_envelopes=0)- xmin, ymin, xmax, ymax = _grid_extent(bounds, budget.spacing_m, crs)- total = (xmax // budget.tile_cells - xmin // budget.tile_cells + 1) * (ymax // budget.tile_cells - ymin // budget.tile_cells + 1)radius = max(e["slant_range_m"][1] for e in events)- for number, (tile_id, cells) in enumerate(grid_tiles(bounds, budget.spacing_m, budget.tile_cells, crs)):- if budget.max_tiles is not None and number >= budget.max_tiles:- break- checkpoint = output / f"tile-{tile_id}.json"- stage = f"coarse:{tile_id}"++ def restore_terrain(provenance):+ if type(terrain) is CachedTerrain:+ for source in provenance.get("terrain_files", []):+ terrain.files[Path(source["path"]).name] = source+ terrain.ocean_tiles.update(provenance.get("terrain_ocean_tiles", []))+ terrain.failures.extend(provenance.get("terrain_failures", []))++ def tile_requests():+ for number, (tile_id, cells) in enumerate(grid_tiles(bounds, budget.spacing_m, budget.tile_cells, crs)):+ if budget.max_tiles is not None and number >= budget.max_tiles:+ break+ stage = f"coarse:{tile_id}"+ checkpoint = output / f"tile-{tile_id}.json"+ cached = None+ try:+ if checkpoint.exists():+ record = json.loads(checkpoint.read_text())+ if record["run_hash"] != run_hash or record["payload_hash"] != content_hash(record["payload"]):+ raise DataUnavailable("Corrupt tile checkpoint")+ prior = record["payload"]+ for source in prior.get("terrain_files", []):+ if sha256(source["path"]) != source["sha256"]:+ raise DataUnavailable("Terrain changed since tile checkpoint")+ if ledger.stage_valid(stage, prior.get("retention_checksum")):+ cached = checkpoint+ except (DataUnavailable, ValueError, OSError) as error:+ cached = error+ yield stage, cells, cached, None++ 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,+ bounds, time_range_s, budget, parameters, filters, start_window, crs,+ output / ".tile-workers", run_hash, score_kind)+ context = _index_pool(workers, initialize_tile_worker, initargs)+ else:+ context = nullcontext(None)+ def finish_tile(stage, cells, future):+ checkpoint = output / f"tile-{stage[len('coarse:'):]}.json"+ payload = Nonetry:- payload = None- if checkpoint.exists():- record = json.loads(checkpoint.read_text())- if record["run_hash"] != run_hash or record["payload_hash"] != content_hash(record["payload"]):- raise DataUnavailable("Corrupt tile checkpoint")- cached = record["payload"]- for source in cached.get("terrain_files", []):- if sha256(source["path"]) != source["sha256"]:- raise DataUnavailable("Terrain changed since tile checkpoint")- if ledger.stage_valid(stage, cached.get("retention_checksum")):- payload = cached- resumed += 1- if payload is None:- tracks = _tracks(indexes, _expanded_bounds(cells, budget.spacing_m, radius, crs), time_range_s, budget)- points = tile_points(cells, budget.spacing_m, bounds, terrain, crs) if tracks else pd.DataFrame()- if len(points):- rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window,- ledger=ledger, stage=stage,- score_floor=_retained_score_floor(ranked, budget.top_k))- else:- rows, counts = [], {}- ledger.record(stage, [], [], 0)- used = getattr(terrain, "last_sample_files", set()) if len(points) else set()- terrain_files = [terrain.files[name] for name in sorted(used)] if used else []- payload = {"ranked": rows, "counts": counts, "grid_points": len(points), "tracks": len(tracks),- "cells": list(cells), "terrain_files": terrain_files,- "retention_checksum": ledger.checksum(stage)}- write_json(checkpoint, {"run_hash": run_hash, "payload_hash": content_hash(payload), "payload": payload})- done += 1- points_searched += payload["grid_points"]- _record_support(output, stage, payload["counts"], support)- ranked = merge_candidates(itertools.chain(ranked, payload["ranked"]), budget.top_k,- ledger=ledger, stage=f"global:{tile_id}")+ payload, worker_path = future.result()+ import_retention_stage(ledger, worker_path, stage, payload["retention_checksum"])+ write_json(checkpoint, {"run_hash": run_hash, "payload_hash": content_hash(payload), "payload": payload})+ try:+ Path(worker_path).unlink()+ except OSError:+ pass+ return checkpointexcept (DataUnavailable, ValueError, OSError) as error:- failures.append({"tile": tile_id, "reason": str(error)})+ if payload is not None and not isinstance(error, TileFailure):+ provenance = {key: payload.get(key, []) for key in+ ("terrain_files", "terrain_ocean_tiles", "terrain_failures")}+ return TileFailure(str(error), provenance)+ return error++ with context as pool:+ requests = tile_requests()+ results = (ordered_tile_results(pool, requests, workers, finish_tile) if pool is not None else+ ((stage, cells, cached, cached is not None) for stage, cells, cached, _ in requests))+ for stage, cells, prepared, was_cached in results:+ tile_id = stage[len("coarse:"):]+ checkpoint = output / f"tile-{tile_id}.json"+ try:+ if isinstance(prepared, BaseException):+ raise prepared+ if prepared is not None:+ payload = json.loads(prepared.read_text())["payload"]+ if was_cached:+ resumed += 1+ restore_terrain(payload)+ else:+ tracks = _tracks(indexes, _expanded_bounds(cells, budget.spacing_m, radius, crs), time_range_s, budget)+ points = tile_points(cells, budget.spacing_m, bounds, terrain, crs) if tracks else pd.DataFrame()+ if len(points):+ rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window,+ ledger=ledger, stage=stage,+ score_floor=(_retained_score_floor(ranked, budget.top_k)+ if floor_policy == "global_and_per_tile" else None))+ else:+ rows, counts = [], {}+ ledger.record(stage, [], [], 0)+ used = getattr(terrain, "last_sample_files", set()) if len(points) else set()+ terrain_files = [terrain.files[name] for name in sorted(used)] if used else []+ oceans = sorted(getattr(terrain, "last_sample_ocean_tiles", set())) if len(points) else []+ payload = {"ranked": rows, "counts": counts, "grid_points": len(points), "tracks": len(tracks),+ "cells": list(cells), "terrain_files": terrain_files, "terrain_ocean_tiles": oceans,+ "terrain_failures": [], "retention_checksum": ledger.checksum(stage)}+ write_json(checkpoint, {"run_hash": run_hash, "payload_hash": content_hash(payload), "payload": payload})+ done += 1+ points_searched += payload["grid_points"]+ _record_support(output, stage, payload["counts"], support)+ ranked = merge_candidates(itertools.chain(ranked, payload["ranked"]), budget.top_k,+ ledger=ledger, stage=f"global:{tile_id}")+ except (DataUnavailable, ValueError, OSError) as error:+ if isinstance(error, TileFailure):+ restore_terrain(error.provenance)+ failures.append({"tile": tile_id, "reason": str(error)})coarse = list(ranked)# Refine only global finalists; tile selection never controls refinement rank.refinement_failure = None@@ -598,7 +676,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out"all_event_groups_considered": not event_limit_applied,"event_limit_reason": "Configured event cap prevents assessing every independent group" if event_limit_applied else None,"elapsed_s": time.monotonic() - began, "process_peak_rss_mib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024,- "bounded_concurrency": 1, "max_grid_points_per_tile": budget.tile_cells ** 2,+ "bounded_concurrency": workers if parallel else 1, "max_grid_points_per_tile": budget.tile_cells ** 2,"scoring_time_is_locked": True, "ground_truth_used_by_search": False, "scope": list(bounds)}write_json(output / "search-report.json", report)return reportdiff --git a/tests/test_real_parallel_retention.py b/tests/test_real_parallel_retention.pyindex 78bf72f..48f389f 100644--- a/tests/test_real_parallel_retention.py+++ b/tests/test_real_parallel_retention.py@@ -10,6 +10,18 @@ from dopplergeist.finite_search import RetentionLedgerfrom dopplergeist.parallel_retention import import_retention_stage+def _run_real_search_in_new_group(index_paths, terrain_root, events, measurements,+ times, output, bounds, budget, scoring):+ from dopplergeist.data_access import CachedTerrain, FlightIndex+ from dopplergeist.tiled_search import search_national++ os.setsid()+ terrain = CachedTerrain(terrain_root, offline=True)+ search_national([FlightIndex(path) for path in index_paths], terrain, events, measurements,+ time_range_s=times, output_dir=output, bounds=bounds, budget=budget,+ scoring=scoring, workers=2)++def test_real_retention_stages_survive_worker_import(tmp_path):source = os.environ.get("DOPPLERGEIST_REAL_RETENTION_LEDGER")if not source:@@ -151,3 +163,199 @@ def test_real_terrain_tracks_ocean_tiles_per_sample():assert terrain.last_sample_ocean_tiles == {tag}terrain.sample([land["lat"]], [land["lon"]])assert not terrain.last_sample_ocean_tiles and tag in terrain.ocean_tiles+++def test_real_search_parallel_resume_and_terrain_failures(tmp_path):+ import json+ import shutil++ from dopplergeist.data_access import CachedTerrain, FlightIndex+ from dopplergeist.matching import prepare_events+ from dopplergeist.tiled_search import SearchBudget, search_national++ source = os.environ.get("DOPPLERGEIST_REAL_JOB_ROOT")+ cache = os.environ.get("DOPPLERGEIST_REAL_CACHE_ROOT")+ reference = os.environ.get("DOPPLERGEIST_REAL_REFERENCE_ROOT")+ index_path = os.environ.get("DOPPLERGEIST_REAL_DEVELOPMENT_INDEX")+ if not all((source, cache, reference, index_path)):+ pytest.skip("set the real job, cache, reference and development index paths")+ job, cache, reference = Path(source), Path(cache), Path(reference)+ index = FlightIndex(index_path)+ events, measurements = prepare_events(json.loads((job / "discovery/discovery.json").read_text())["events"])+ # This fitted clock and small regional index are for an engineering replay,+ # not evidence for the recording's actual location or complete coverage.+ clock = json.loads((reference / "results/reference-local/ranked.json").read_text())[0]["recording_start_time_s"]+ budget = SearchBudget(spacing_m=2000, tile_cells=4, top_k=5, refine_spacing_m=2000)+ bounds = (-73.56, 40.85, -73.50, 40.90)+ scoring = {"mode": "robust_ridge", "time_origin": clock, "time_sweep_s": 0.,+ "recording_start_window_s": [clock, clock]}+ geoid = cache / "terrain/us_nga_egm08_25.tif"+ raster = "Copernicus_DSM_COG_30_N40_00_W074_00_DEM.tif"+ roots = {name: tmp_path / name for name in ("terrain", "missing-terrain")}+ for root in roots.values():+ root.mkdir()+ for name in ("tileList.txt", "tileList.txt.sha256.json"):+ shutil.copy2(cache / "terrain" / name, root / name)+ shutil.copy2(reference / "data/terrain/copernicus90" / raster, roots["terrain"] / raster)++ def run(name, workers, terrain_root):+ terrain = CachedTerrain(terrain_root, offline=True, geoid_path=geoid, adopt_existing=True)+ result = search_national([index], terrain, events, measurements,+ time_range_s=index.report["coverage"]["time_range_s"],+ output_dir=tmp_path / name, bounds=bounds, budget=budget,+ scoring=scoring, workers=workers)+ provenance = terrain.provenance()+ provenance["files"] = sorted(provenance["files"], key=lambda item: item["path"])+ return result, provenance++ serial, serial_sources = run("serial", 1, roots["terrain"])+ parallel, parallel_sources = run("parallel", 2, roots["terrain"])+ resumed, resumed_sources = run("parallel", 3, roots["terrain"])+ resumed_one, resumed_one_sources = run("parallel", 1, roots["terrain"])+ automatic, automatic_sources = run("automatic", None, roots["terrain"])+ for key in ("ranked", "coarse_ranked", "status", "tiles_completed", "grid_points_searched",+ "core_assessed_mode_ids", "scope"):+ assert json.dumps(serial[key], sort_keys=True, allow_nan=True) == json.dumps(parallel[key], sort_keys=True, allow_nan=True)+ for key in ("pruning_accounted_for", "complete", "best_discarded_score", "discarded_bound_status", "retained_modes"):+ assert serial["finite_search_evidence"][key] == parallel["finite_search_evidence"][key]+ assert serial_sources == parallel_sources == resumed_sources == resumed_one_sources == automatic_sources+ assert parallel["bounded_concurrency"] == 2 and resumed["bounded_concurrency"] == 3+ assert resumed["tiles_resumed"] == parallel["tiles_completed"] and resumed["ranked"] == parallel["ranked"]+ assert resumed_one["bounded_concurrency"] == 1+ assert resumed_one["tiles_resumed"] == parallel["tiles_completed"] and resumed_one["ranked"] == parallel["ranked"]+ available = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else (os.cpu_count() or 1)+ assert automatic["bounded_concurrency"] == min(max(1, available - 1), automatic["tiles_total"])+ assert automatic["ranked"] == parallel["ranked"]++ serial_missing, serial_failure_sources = run("serial-missing", 1, roots["missing-terrain"])+ parallel_missing, parallel_failure_sources = run("parallel-missing", 2, roots["missing-terrain"])+ assert serial_missing["tile_failures"]+ assert serial_missing["tile_failures"] == parallel_missing["tile_failures"]+ assert serial_failure_sources == parallel_failure_sources+++def test_real_ocean_provenance_survives_parallel_resume(tmp_path):+ import json+ import math+ import multiprocessing+ import signal+ import time++ from dopplergeist.data_access import CachedTerrain, FlightIndex+ from dopplergeist.matching import prepare_events+ from dopplergeist.tiled_search import SearchBudget, search_national++ source = os.environ.get("DOPPLERGEIST_REAL_JOB_ROOT")+ cache = os.environ.get("DOPPLERGEIST_REAL_CACHE_ROOT")+ if not source or not cache:+ pytest.skip("set the real job and cache roots")+ job, cache = Path(source), Path(cache)+ terrain = CachedTerrain(cache / "terrain", offline=True)+ rows = json.loads((job / "search/tile-0_2.json").read_text())["payload"]["ranked"]+ for row in rows:+ north, east = math.floor(row["lat"]-1/2400), math.floor(row["lon"]+1/2400)+ tag = (f"Copernicus_DSM_COG_30_{'N' if north >= 0 else 'S'}{abs(north):02d}_00_"+ f"{'E' if east >= 0 else 'W'}{abs(east):03d}_00_DEM")+ if tag not in terrain.catalog:+ break+ else:+ pytest.fail("the saved real tile no longer contains the expected ocean point")+ # This is a previously evaluated search hypothesis, not location truth.+ clock = row["recording_start_time_s"]+ times = (clock-120, clock+3720)+ config = json.loads((job / "search/manifest.json").read_text())["configuration"]+ available = {FlightIndex(path).report["input_hash"]: path+ for path in (cache / "flights").glob("*/staging-0/*.sqlite")}+ indexes = [FlightIndex(available[item["input_hash"]]) for item in config["indexes"]]+ enclosing = [index for index in indexes+ if index.report["coverage"]["time_range_s"][0] <= times[0]+ and index.report["coverage"]["time_range_s"][1] >= times[1]]+ indexes = enclosing or indexes+ events, measurements = prepare_events(json.loads((job / "discovery/discovery.json").read_text())["events"])+ budget = SearchBudget(spacing_m=2000, tile_cells=1, top_k=5, refine_spacing_m=2000)+ bounds = (row["lon"]-.00005, row["lat"]-.00005, row["lon"]+.00005, row["lat"]+.00005)+ scoring = {"mode": "robust_ridge", "time_origin": clock, "time_sweep_s": 0.,+ "recording_start_window_s": [clock, clock]}++ def run(name, workers):+ terrain = CachedTerrain(cache / "terrain", offline=True)+ result = search_national(indexes, terrain, events, measurements, time_range_s=times,+ output_dir=tmp_path / name, bounds=bounds, budget=budget,+ scoring=scoring, workers=workers)+ provenance = terrain.provenance()+ provenance["files"] = sorted(provenance["files"], key=lambda item: item["path"])+ return result, provenance++ serial, serial_sources = run("serial-ocean", 1)+ parallel, parallel_sources = run("parallel-ocean", 2)+ resumed, resumed_sources = run("parallel-ocean", 3)+ assert serial["grid_points_searched"] > 0 and serial["ranked"] == parallel["ranked"] == resumed["ranked"]+ assert serial["status"] == parallel["status"] == resumed["status"]+ assert parallel["tiles_completed"] == resumed["tiles_resumed"]+ assert serial_sources == parallel_sources == resumed_sources+ assert tag in resumed_sources["catalogue_absent_ocean_tiles"]++ if not hasattr(os, "setsid") or not Path("/proc").is_dir():+ pytest.skip("process-group interruption check requires Linux")+ output = tmp_path / "interrupted-ocean"+ child = multiprocessing.get_context("spawn").Process(+ target=_run_real_search_in_new_group,+ args=([index.path for index in indexes], cache / "terrain", events, measurements,+ times, output, bounds, budget, scoring),+ )+ child.start()+ checkpoints = []+ children = []+ try:+ deadline = time.monotonic() + 45+ while time.monotonic() < deadline and child.is_alive():+ children_file = Path(f"/proc/{child.pid}/task/{child.pid}/children")+ children = [int(pid) for pid in children_file.read_text().split()] if children_file.exists() else []+ workers = [pid for pid in children if Path(f"/proc/{pid}/cmdline").exists()+ and b"spawn_main" in Path(f"/proc/{pid}/cmdline").read_bytes()]+ checkpoints = list(output.glob("tile-*.json")) if output.exists() else []+ if workers and checkpoints and os.getpgid(child.pid) == child.pid:+ break+ time.sleep(.05)+ else:+ pytest.fail("parallel search ended or did not checkpoint before interruption")+ os.killpg(child.pid, signal.SIGTERM)+ child.join(15)+ assert not child.is_alive()+ live = []+ for _ in range(50):+ live = []+ for proc in Path("/proc").iterdir():+ if not proc.name.isdigit():+ continue+ try:+ fields = (proc / "stat").read_text().split(") ", 1)[1].split()+ if int(fields[2]) == child.pid and fields[0] != "Z":+ live.append(int(proc.name))+ except (OSError, ValueError, IndexError):+ pass+ if not live:+ break+ time.sleep(.1)+ assert not live+ finally:+ if child.is_alive():+ if os.getpgid(child.pid) == child.pid:+ os.killpg(child.pid, signal.SIGTERM)+ else:+ child.terminate()+ child.join(15)+ # If the parent exited unexpectedly, stop only its observed, still+ # matching multiprocessing children; never signal an unrelated group.+ for pid in children:+ try:+ fields = Path(f"/proc/{pid}/stat").read_text().split(") ", 1)[1].split()+ command = Path(f"/proc/{pid}/cmdline").read_bytes()+ if fields[0] != "Z" and int(fields[2]) == child.pid and b"multiprocessing." in command:+ os.kill(pid, signal.SIGTERM)+ except (OSError, ValueError, IndexError):+ pass+ interrupted, interrupted_sources = run("interrupted-ocean", 3)+ assert interrupted["tiles_resumed"] >= len(checkpoints)+ assert interrupted["ranked"] == parallel["ranked"] and interrupted["status"] == parallel["status"]+ assert interrupted_sources == parallel_sources