Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Partition overloaded association clocks into resumable tiles
Cinna Davis5e853370806c
diff --git a/src/dopplergeist/parallel_tiles.py b/src/dopplergeist/parallel_tiles.pyindex 77fd4b0..bb6b7e5 100644--- a/src/dopplergeist/parallel_tiles.py+++ b/src/dopplergeist/parallel_tiles.py@@ -6,7 +6,8 @@ import pandas as pdfrom .data_access import CachedTerrain, DataUnavailable, FlightIndexfrom .finite_search import RetentionLedger-from .tiled_search import _expanded_bounds, _sample_tile_terrain, _score, _tile_coordinates, _tracks_for_points+from .tiled_search import (_expanded_bounds, _sample_tile_terrain, _score, _tile_anchor_window,+ _tile_coordinates, _tracks_for_points)class TileFailure(DataUnavailable):@@ -77,6 +78,10 @@ def score_tile(stage, cells, score_floor=None):ledger = RetentionLedger(path, state["run_hash"], state["score_kind"])if len(points):kwargs = {"ledger": ledger, "stage": stage}+ anchor = _tile_anchor_window(stage.removeprefix("coarse:"), state["start_window"],+ state["parameters"], state["filters"], state["events"])+ if anchor is not None:+ kwargs["anchor_window"] = anchorif score_floor is not None:kwargs["score_floor"] = score_floorrows, counts = _score(points, tracks, state["events"], state["measurements"], budget,diff --git a/src/dopplergeist/tiled_search.py b/src/dopplergeist/tiled_search.pyindex f9dcc28..c6a9e05 100644--- a/src/dopplergeist/tiled_search.py+++ b/src/dopplergeist/tiled_search.py@@ -1,7 +1,8 @@"""Sequential, checkpointed national search over one global projected grid.-Only the receiver grid is partitioned. Every tile sees all overlapping original-flight segments and the same event clocks, propagation model and scoring units.+Every tile sees all overlapping original flight segments and the same event+clocks, propagation model and scoring units. Overloaded single cells may also+partition association anchors without narrowing the physical fit intervals."""from dataclasses import asdict, dataclassfrom functools import lru_cache@@ -271,8 +272,48 @@ def _association_clock_window(start_window, sweep_s):return center, tolerance+def _tile_anchor_window(tile_id, start_window, parameters, filters, events):+ """Recover a deterministic half-open anchor partition from its tile ID."""+ path = [part for part in tile_id.split("~")[1:] if part.startswith("t")]+ if not path:+ return None+ if (len(path) > 24 or any(part not in ("t0", "t1") for part in path)+ or start_window is None or parameters.get("time_origin") is not None+ or parameters.get("mode") != "robust_ridge" or filters.get("association") != "subsets"):+ raise ValueError("Invalid association-clock partition")+ center, tolerance = _association_clock_window(start_window, parameters.get("time_sweep_s", 5.0))+ margins = [event.get("quality", {}).get("cpa_tolerance_s", 0)+ + filters.get("offset_tolerance_s", 5.0) / 2 for event in events]+ if not margins or any(not math.isfinite(v) or v < 0 for v in margins):+ raise ValueError("Invalid association-clock uncertainty")+ margin = max(margins)+ lo = math.nextafter(math.nextafter(center - tolerance, -math.inf) - margin, -math.inf)+ hi = math.nextafter(math.nextafter(center + tolerance, math.inf) + margin, math.inf)+ for part in path:+ mid = lo + (hi - lo) / 2+ if not lo < mid < hi:+ raise ValueError("Association-clock partition has no representable midpoint")+ if part == "t0":+ hi = mid+ else:+ lo = mid+ return lo, hi+++def _clock_children(tile_id, cells, start_window, parameters, filters, events):+ if len([p for p in tile_id.split("~")[1:] if p.startswith("t")]) >= 24:+ return []+ children = [[f"{tile_id}~t{i}", list(cells)] for i in range(2)]+ try:+ for child, _ in children:+ _tile_anchor_window(child, start_window, parameters, filters, events)+ except ValueError:+ return []+ return children++@_cache_ridge_fits-def _score(points, tracks, events, measurements, budget, parameters, filters, start_window=None, *, ledger=None, stage=None, score_floor=None):+def _score(points, tracks, events, measurements, budget, parameters, filters, start_window=None, *, ledger=None, stage=None, score_floor=None, anchor_window=None):radius = max(e["slant_range_m"][1] for e in events)observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())tables, count = [], 0@@ -388,7 +429,7 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, sttrack_lookup = {track.id: track for track in tracks}candidates, counts = association_candidates(table, events, **kwargs,min_events=filters.get("min_events", 1), max_events=filters.get("max_events") or len(events),- max_candidates=budget.max_candidates_per_tile, pair_screen=pair_screen)+ max_candidates=budget.max_candidates_per_tile, pair_screen=pair_screen, anchor_window=anchor_window)if pair_screen is not None:counts["fixed_clock_event_pair_screen"] = {"recording_start_time_s": float(kwargs["time_origin"]),**screen_counts, "rejections": list(screen_counts["rejections"])}@@ -626,6 +667,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out"brightness": "summed_spectral_contrast"}[mode])ledger = RetentionLedger(output / "retention.sqlite", run_hash, score_kind)began, ranked, failures, done, processed_cells, resumed, points_searched = time.monotonic(), [], [], 0, 0, 0, 0+ counted_clock_cells = set()support = 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)@@ -664,11 +706,12 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif not marker.exists():yield tile_request(tile_id, cells)continue- parts = _split_tile_cells(cells)- children = [[f"{tile_id}~{i}", list(part)] for i, part in enumerate(parts)]try:record = json.loads(marker.read_text())- if not parts or record != {"run_hash": run_hash, "cells": list(cells), "children": children}:+ parts = _split_tile_cells(cells)+ children = ([[f"{tile_id}~{i}", list(part)] for i, part in enumerate(parts)] if parts else+ _clock_children(tile_id, cells, start_window, parameters, filters, events))+ if not children or record != {"run_hash": run_hash, "cells": list(cells), "children": children}:raise DataUnavailable("Corrupt tile subdivision checkpoint")except (DataUnavailable, ValueError, OSError) as error:yield f"coarse:{tile_id}", cells, error, None@@ -679,7 +722,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outdef tile_order(item):root, *path = item[0].split("~")ix, iy = map(int, root.split("_"))- return iy, ix, tuple(map(int, path))+ 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,@@ -707,12 +750,13 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out("terrain_files", "terrain_ocean_tiles", "terrain_failures")}return TileFailure(str(error), provenance)return error- advance_progress(cells)+ advance_progress(stage, cells)return checkpoint- def advance_progress(cells):+ def advance_progress(stage, cells):nonlocal processed_cells- processed_cells += (cells[2]-cells[0]) * (cells[3]-cells[1])+ clock_depth = sum(part.startswith("t") for part in stage.split("~")[1:])+ processed_cells += (cells[2]-cells[0]) * (cells[3]-cells[1]) / (2 ** clock_depth)if coarse_cells:report_search_progress(0.8 * processed_cells / coarse_cells)@@ -749,8 +793,10 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif not tracks:points = pd.DataFrame()if len(points):+ anchor = _tile_anchor_window(tile_id, start_window, parameters, filters, events)rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window,ledger=ledger, stage=stage,+ anchor_window=anchor,score_floor=(_retained_score_floor(ranked, budget.top_k)if floor_policy == "global_and_per_tile" else None))else:@@ -764,7 +810,13 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, out"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"]+ if "~t" not in tile_id:+ points_searched += payload["grid_points"]+ else:+ cell_owner = tile_id.split("~t", 1)[0]+ if cell_owner not in counted_clock_cells:+ points_searched += payload["grid_points"]+ counted_clock_cells.add(cell_owner)_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}")@@ -772,9 +824,11 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outif isinstance(error, TileFailure):restore_terrain(error.provenance)parts = _split_tile_cells(cells) if _tile_capacity_error(error) else []- if parts:+ children = [[f"{tile_id}~{i}", list(part)] for i, part in enumerate(parts)]+ if not children and str(error) == "Association candidate budget exceeded; search is incomplete":+ children = _clock_children(tile_id, cells, start_window, parameters, filters, events)+ if children:terminal = False- children = [[f"{tile_id}~{i}", list(part)] for i, part in enumerate(parts)]write_json(output / f"split-{tile_id}.json",{"run_hash": run_hash, "cells": list(cells), "children": children})total += len(children)-1@@ -782,7 +836,7 @@ def search_national(indexes, terrain, events, measurements, *, time_range_s, outelse:failures.append({"tile": tile_id, "reason": str(error)})if terminal and (pool is None or was_cached or isinstance(prepared, BaseException)):- advance_progress(cells)+ advance_progress(stage, cells)wave = sorted(next_wave, key=tile_order) if next_wave else Nonereport_search_progress(0.8, force=True)coarse = list(ranked)diff --git a/tests/test_real_clock_partitions.py b/tests/test_real_clock_partitions.pynew file mode 100644index 0000000..4ec4940--- /dev/null+++ b/tests/test_real_clock_partitions.py@@ -0,0 +1,125 @@+"""Clock partition regression on an overloaded original-audio full-day cell."""+import json+import os+from pathlib import Path++import pandas as pd+import pytest++from dopplergeist.data_access import CachedTerrain, FlightIndex, content_hash+from dopplergeist.geometry import AcousticSupportError, ecef+from dopplergeist.matching import association_candidates, prepare_events+from dopplergeist.search import cpa_table+from dopplergeist.tiled_search import (SearchBudget, _association_clock_window, _expanded_bounds,+ _split_tile_cells, _tile_anchor_window, _tracks_for_points, grid_tiles, tile_points)+++def test_full_day_cell_clock_partitions_preserve_associations():+ job, cache = (os.environ.get(name) for name in ("DOPPLERGEIST_REAL_JOB_ROOT", "DOPPLERGEIST_REAL_CACHE_ROOT"))+ if not job or not cache:+ pytest.skip("set the real job and cache roots")+ job, cache = Path(job), Path(cache)+ config = json.loads((job / "search/manifest.json").read_text())["configuration"]+ events, _ = prepare_events(json.loads((job / "discovery/discovery.json").read_text())["events"])+ budget = SearchBudget(**config["budget"])+ cells = dict(grid_tiles(config["bounds"], budget.spacing_m, budget.tile_cells, config["crs"]))["-33_51"]+ for choice in (1, 2, 0, 1, 1):+ cells = _split_tile_cells(cells)[choice]+ terrain = CachedTerrain(cache / "terrain", offline=False)+ points = tile_points(cells, budget.spacing_m, config["bounds"], terrain, config["crs"])+ assert len(points) == 1+ indexes = [FlightIndex(cache / "flights" / day / "staging-0/all-types-v2-543f483cee75.sqlite")+ for day in ("2026-09-08", "2026-09-09")]+ parameters = dict(config["scoring"])+ window = parameters.pop("recording_start_window_s")+ radius = max(event["slant_range_m"][1] for event in events)+ tracks, points = _tracks_for_points(indexes, _expanded_bounds(cells, budget.spacing_m, radius, config["crs"]),+ config["time_range_s"], budget, points, terrain, radius, parameters.get("c", 343.))+ observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())+ tables, unsupported = [], 0+ for track in tracks:+ try:+ if not track.outside_observer_radius(observers, radius, parameters.get("c", 343.)):+ table = cpa_table([track], points, radius, parameters.get("c", 343.), budget.cpa_step_s)+ if len(table):+ tables.append(table)+ except AcousticSupportError:+ unsupported += 1+ table = pd.concat(tables, ignore_index=True)+ center, tolerance = _association_clock_window(window, parameters.get("time_sweep_s", 5.))+ filters = config["filters"]+ kwargs = dict(offset_tolerance_s=filters.get("offset_tolerance_s", 5.), time_origin=center,+ time_tolerance_s=tolerance, min_events=filters.get("min_events", 1),+ max_events=filters.get("max_events") or len(events))+ with pytest.raises(ValueError, match="Association candidate budget exceeded"):+ association_candidates(table, events, max_candidates=budget.max_candidates_per_tile, **kwargs)+ baseline, _ = association_candidates(table, events, max_candidates=100000, **kwargs)+ pieces = []+ for i in range(8):+ tile = "-33_51~1~2~0~1~1" + "".join(f"~t{(i >> shift) & 1}" for shift in (2, 1, 0))+ anchor = _tile_anchor_window(tile, window, parameters, filters, events)+ result, _ = association_candidates(table, events, max_candidates=budget.max_candidates_per_tile,+ anchor_window=anchor, **kwargs)+ pieces.extend(result)+ assert sorted(content_hash(item) for item in pieces) == sorted(content_hash(item) for item in baseline)+ assert unsupported > 0+ print(f"real cell: {len(baseline)} associations preserved; {unsupported} unsupported tracks")+++def test_real_clock_partition_restart_and_scores(tmp_path, monkeypatch):+ """Inject a capacity failure into a one-cell real-data engineering replay."""+ import shutil+ import dopplergeist.tiled_search as tiled++ job, cache, reference, terrain_path, index_path = (os.environ.get(name) for name in (+ "DOPPLERGEIST_REAL_JOB_ROOT", "DOPPLERGEIST_REAL_CACHE_ROOT",+ "DOPPLERGEIST_REAL_REFERENCE_ROOT", "DOPPLERGEIST_REAL_ENGINEERING_TERRAIN",+ "DOPPLERGEIST_REAL_DEVELOPMENT_INDEX"))+ if not all((job, cache, reference, terrain_path, index_path)):+ pytest.skip("set the real job, cache, reference and engineering terrain paths")+ job, cache, reference = Path(job), Path(cache), Path(reference)+ events, measurements = prepare_events(json.loads((job / "discovery/discovery.json").read_text())["events"])+ # Two observed groups and a narrow known engineering clock keep this replay+ # small; the actual full-day upload run uses all detected groups and no clock.+ events, measurements = events[6:8], measurements[6:8]+ clock = json.loads((reference / "results/reference-local/ranked.json").read_text())[0]["recording_start_time_s"]+ index = FlightIndex(index_path)+ lon, lat = -73.53984955811066, 40.87662017144848+ bounds = (lon-.0001, lat-.0001, lon+.0001, lat+.0001)+ settings = {"mode": "robust_ridge", "time_sweep_s": 0.,+ "recording_start_window_s": [clock-10, clock+10]}+ budget = SearchBudget(spacing_m=2000, tile_cells=1, top_k=5, refine_spacing_m=2000)++ def run(name, progress=None):+ terrain = CachedTerrain(terrain_path, offline=True, adopt_existing=True)+ return tiled.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=settings, workers=1, search_progress=progress)++ baseline = run("baseline")+ original = tiled._score+ def force_split(*args, **kwargs):+ if kwargs.get("anchor_window") is None:+ raise ValueError("Association candidate budget exceeded; search is incomplete")+ return original(*args, **kwargs)+ progress = []+ with monkeypatch.context() as patch:+ patch.setattr(tiled, "_score", force_split)+ partitioned = run("partitioned", progress.append)+ keys = ("score", "lat", "lon", "flight_ids", "recording_start_time_s", "event_ids")+ project = lambda report: [{key: row.get(key) for key in keys} for row in report["ranked"]]+ assert baseline["ranked"] and project(partitioned) == project(baseline)+ assert baseline["grid_points_searched"] == partitioned["grid_points_searched"] == 1+ assert not partitioned["tile_failures"] and partitioned["tiles_completed"] == baseline["tiles_completed"] + 1+ assert progress == sorted(progress) and progress[-1] == 1.+ assert partitioned["finite_search_evidence"]["pruning_accounted_for"]+ resumed = run("partitioned")+ assert resumed["tiles_resumed"] == partitioned["tiles_completed"] and project(resumed) == project(partitioned)+ assert resumed["finite_search_evidence"] == partitioned["finite_search_evidence"]+ shutil.copytree(tmp_path / "partitioned", tmp_path / "corrupt")+ marker = next((tmp_path / "corrupt").glob("split-*.json"))+ record = json.loads(marker.read_text())+ record["children"].pop()+ marker.write_text(json.dumps(record))+ assert any("Corrupt tile subdivision checkpoint" in failure["reason"]+ for failure in run("corrupt")["tile_failures"])