Skip to content

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

Add bounded tiled national search with deterministic merge and checkpoints (#7)

Cinna Davisd01490c60633
diff --git a/docs/DATA_AND_SCALE.md b/docs/DATA_AND_SCALE.md
new file mode 100644
index 0000000..56d1038
--- /dev/null
+++ b/docs/DATA_AND_SCALE.md
@@ -0,0 +1,95 @@
+# Historical inputs and bounded search
+
+Worker 2 owns `data_access.py` and `tiled_search.py`. These are adapters around
+the shared `contracts.py` shapes and existing physical scorer; the legacy manual
+research workflow remains reproducible.
+
+## Acquisition
+
+`acquire_inputs(request, recording, cache_root=..., offline=False)` validates the
+shared request/recording dictionaries. A defensible recording-start UTC window
+is required. Acquisition covers that window plus the complete recording and
+sound propagation guard, including adjacent UTC days. `FlightCache.acquire_day`
+obtains ADSB.lol release metadata, resumes split archive parts using checked HTTP
+ranges, checks provider size/SHA-256, and streams gzip readsb traces into an index.
+All aircraft types remain eligible. The archive is downloaded once per day/provider;
+later uploads reuse the derived index without opening/downloading the archive.
+
+The on-disk SQLite index has spatial and time indexes, source hashes, explicit
+source scope, per-payload checksums and altitude labels. Disk staging supports
+arbitrary input order. Query predicates select whole gap-split segments; they
+never clip geometry or extrapolate across a gap. Daily release namespaces prevent
+ID collisions. Segments on separate days are not joined across midnight; a ridge
+requiring unsupported geometry is rejected by the physical model.
+
+`scripts/index_flights.py` restores an index from a supplied Parquet. Its required
+bounds, UTC interval and source note describe ingestion coverage. Use
+`--all-aircraft` only for sources that retained jets and unknown types. The
+historical prop/unknown table must be declared incomplete. Corrupt/truncated
+inputs raise `DataUnavailable`; this is distinct from no acoustic events.
+
+`CachedTerrain` acquires the [GLO-90 catalogue and tiles](https://copernicus-dem-90m.s3.amazonaws.com/readme.html)
+and the [EGM2008 geoid](https://cdn.proj.org/). Each file has a checksum receipt.
+GLO-90 heights are converted to ellipsoidal heights by adding geoid undulation.
+Offline mode never fetches missing files. Only catalogue-absent tiles are treated
+as ocean; missing downloads and nodata are explicit failures. Existing terrain
+caches require the operator's explicit `adopt_existing=True` and format validation
+before receipts are created. A caller-supplied geoid must use EGM2008; the old
+regional EGM96 approximation is not the default automatic input.
+
+The returned `AcquiredInputs` has `.indexes`, `.terrain`, `.bounds`,
+`.time_range_s` (absolute emission window), `.recording_start_window_s`, and
+`.coverage`. ADS-B query coverage does not establish receiver completeness or
+prove that every audible flight was observed. Copernicus is a surface model,
+which also leaves microphone height uncertain.
+
+## Search
+
+Use `matching.prepare_events(detected_events)` to get legacy event settings and
+measurements, then call:
+
+```python
+report = search_national(
+ inputs.indexes, inputs.terrain, events, measurements,
+ time_range_s=inputs.time_range_s, output_dir=output / "search",
+ bounds=inputs.bounds, budget=SearchBudget(),
+ scoring={"mode": "robust_ridge",
+ "recording_start_window_s": inputs.recording_start_window_s},
+)
+```
+
+There is one EPSG:5070 origin and integer grid. Half-open tile cores own receiver
+cells exactly once; expanded queries retain boundary flight segments. Only the
+receiver grid is partitioned. Original flight geometry, emission-time propagation,
+event offsets and score units are identical in every tile. One shared clock is
+constrained to the supplied recording-start window. Sequential execution and hard
+limits on grid cells, tracks, samples, CPA rows and candidate combinations bound
+working allocations. An overloaded tile is reported as missing work. Reducing
+`tile_cells` trades scheduling overhead for smaller working sets.
+
+Candidate scores are merged deterministically with approach identities, then
+global finalists are refined on the same global grid in bounded subtiles. The
+coarse spacing is a computational budget, not a proof that an isolated minimum
+could not be missed between cells. Keep this limitation visible in confidence
+decisions. `top_k` limits retained candidates; raw scores are not probabilities.
+
+Manifest and tile receipts hash configuration, input index files, event
+measurements, implementation and terrain files. Interrupted jobs reuse completed
+tiles with the same identity. Changed inputs require a new output directory.
+Failed tiles are retried on resume; `max_tiles` is a fixed configuration budget.
+Reports distinguish complete/partial computation, source scope, missing tiles,
+refinement failure, runtime and Linux process peak RSS. A complete tile is never
+labelled a complete national search. The product/confidence workers translate
+this internal report to the shared coverage and result contracts.
+
+## Checks
+
+```bash
+PYTHONPATH=src /path/to/python -m pytest -q tests/test_data_access.py tests/test_tiled_search.py
+```
+
+Tests include split archive streaming, byte-range/checksum failures, explicit
+offline errors, jets/unknowns, gap/no-extrapolation behavior, whole-segment queries,
+datum conversion, tiled/untiled agreement at a boundary, deterministic repeated
+approach preservation, checkpoint reuse, and visible partial/budget failures.
+Scaling experiments and location-accuracy evidence must be labelled separately.
diff --git a/scripts/benchmark_national_search.py b/scripts/benchmark_national_search.py
new file mode 100644
index 0000000..2fb278d
--- /dev/null
+++ b/scripts/benchmark_national_search.py
@@ -0,0 +1,47 @@
+"""Measure full-CONUS bounded enumeration/scoring on a declared flight index.
+
+This is a scale fixture, not an audio localization benchmark: a deterministic
+analytic ridge has no assigned flight/location truth. The default coarse grid
+measures resource use; it does not establish 100 m accuracy or search recall.
+"""
+import argparse
+import json
+
+import numpy as np
+
+from aircraft_geoloc.audio import Spectrum
+from aircraft_geoloc.data_access import CONUS, FlightIndex, write_json
+from aircraft_geoloc.tiled_search import SearchBudget, search_national
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("index")
+ parser.add_argument("output")
+ parser.add_argument("--spacing-m", type=float, default=20000)
+ parser.add_argument("--tile-cells", type=int, default=4)
+ args = parser.parse_args()
+ from aircraft_geoloc.terrain import Terrain
+ index = FlightIndex(args.index)
+ start, end = index.report["coverage"]["time_range_s"]
+ origin = start
+ center = (end - start) / 2
+ t = np.linspace(center - 20, center + 20, 41)
+ ridge = 120 * (1 - .12 * np.tanh((t - center) / 12))
+ spec = Spectrum(t, np.array([80., 160.]), np.zeros((2, len(t))), np.zeros((2, len(t))))
+ event = {"start_s": float(t[0]), "end_s": float(t[-1]), "cpa_receive_s": center,
+ "speed_range_mps": [1, 308], "slant_range_m": [1, 20000], "f0_range_hz": [50, 250]}
+ budget = SearchBudget(spacing_m=args.spacing_m, tile_cells=args.tile_cells, top_k=100,
+ refine_spacing_m=args.spacing_m, max_candidates_per_tile=20000)
+ report = search_national([index], Terrain(constant_m=0), [event], [(spec, ridge, np.ones(len(t)), {})],
+ time_range_s=(start, end), output_dir=args.output, bounds=CONUS, budget=budget,
+ scoring={"mode": "ridge", "time_origin": origin, "time_sweep_s": 0})
+ report["experiment_scope"] = "Full CONUS all-type real flight data, analytic ridge scale fixture, constant ground, no localization truth"
+ report["limitations"] = ["No automatic audio detection in this scale fixture", "No measured location accuracy",
+ "Coarse grid can miss narrow candidate modes", "Constant ground is a computational fixture"]
+ write_json(str(args.output) + "/scale-report.json", report)
+ print(json.dumps({k: v for k, v in report.items() if k not in ("ranked", "coarse_ranked")}, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/aircraft_geoloc/tiled_search.py b/src/aircraft_geoloc/tiled_search.py
new file mode 100644
index 0000000..d90d75a
--- /dev/null
+++ b/src/aircraft_geoloc/tiled_search.py
@@ -0,0 +1,314 @@
+"""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.
+"""
+from dataclasses import asdict, dataclass
+import itertools
+import json
+import math
+from pathlib import Path
+import resource
+import time
+
+import numpy as np
+import pandas as pd
+from pyproj import Transformer
+
+from .data_access import CONUS, DataUnavailable, content_hash, sha256, write_json
+from .search import cpa_table, filter_event, pair_candidates, score_candidate
+
+
+@dataclass(frozen=True)
+class SearchBudget:
+ spacing_m: float = 2000.0
+ tile_cells: int = 32
+ max_tracks_per_tile: int = 2000
+ max_track_samples_per_tile: int = 500000
+ max_cpa_rows: int = 100000
+ max_candidates_per_tile: int = 20000
+ top_k: int = 100
+ refine_spacing_m: float = 100.0
+ refine_finalists: int = 10
+ cpa_step_s: float = 2.0
+ max_tiles: int | None = None
+
+ def __post_init__(self):
+ integer_fields = ("tile_cells", "max_tracks_per_tile", "max_track_samples_per_tile", "max_cpa_rows",
+ "max_candidates_per_tile", "top_k", "refine_finalists", "max_tiles")
+ for name, value in asdict(self).items():
+ if value is not None and (not np.isfinite(value) or value <= 0):
+ raise ValueError(f"{name} must be positive and finite")
+ if name in integer_fields and value is not None and type(value) is not int:
+ raise ValueError(f"{name} must be an integer")
+ if self.tile_cells > 256:
+ raise ValueError("tile_cells must be <=256 (65536 grid points)")
+
+
+def _key(row):
+ # Distinct approaches remain distinct even when they share flight IDs.
+ return (tuple(row.get("event_indices", range(len(row["flight_ids"])))), tuple(row["flight_ids"]),
+ tuple(round(t, 3) for t in row.get("pass_emission_times_s", [])),
+ round(row["x"], 6), round(row["y"], 6), round(row["recording_start_time_s"], 6))
+
+
+def merge_candidates(rows, top_k):
+ unique = {}
+ for row in rows:
+ if not math.isfinite(row["score"]):
+ continue
+ key = _key(row)
+ if key not in unique or row["score"] > unique[key]["score"]:
+ unique[key] = row
+ return sorted(unique.values(), key=lambda row: (-row["score"], _key(row)))[:top_k]
+
+
+def grid_tiles(bounds, spacing_m, tile_cells, crs="EPSG:5070"):
+ """Half-open integer-cell cores: each global receiver cell has one owner."""
+ forward = Transformer.from_crs("EPSG:4326", crs, always_xy=True)
+ left, bottom, right, top = forward.transform_bounds(*bounds, densify_pts=101)
+ xmin, ymin = math.floor(left / spacing_m), math.floor(bottom / spacing_m)
+ xmax, ymax = math.ceil(right / spacing_m), math.ceil(top / spacing_m)
+ for iy in range(ymin // tile_cells, ymax // tile_cells + 1):
+ for ix in range(xmin // tile_cells, xmax // tile_cells + 1):
+ yield f"{ix}_{iy}", (max(xmin, ix * tile_cells), max(ymin, iy * tile_cells),
+ min(xmax + 1, (ix + 1) * tile_cells), min(ymax + 1, (iy + 1) * tile_cells))
+
+
+def tile_points(cells, spacing, bounds, terrain, crs):
+ x0, y0, x1, y1 = cells
+ x, y = np.meshgrid(np.arange(x0, x1, dtype=np.int64), np.arange(y0, y1, dtype=np.int64))
+ x, y = x.ravel() * spacing, y.ravel() * spacing
+ lon, lat = Transformer.from_crs(crs, "EPSG:4326", always_xy=True).transform(x, y)
+ keep = (lon >= bounds[0]) & (lon <= bounds[2]) & (lat >= bounds[1]) & (lat <= bounds[3])
+ x, y, lat, lon = (a[keep] for a in (x, y, lat, lon))
+ return pd.DataFrame({"point_id": np.arange(len(x)), "x": x, "y": y, "lat": lat, "lon": lon,
+ "elev_m": terrain.sample(lat, lon) if len(lat) else np.array([])})
+
+
+def _expanded_bounds(cells, spacing, radius, crs):
+ x0, y0, x1, y1 = cells
+ # Padding includes sound range, spline excursions between gap-limited track
+ # samples and CONUS projection distortion. Full payloads remain unmodified.
+ margin = 1.6 * radius + 15000
+ box = (x0 * spacing - margin, y0 * spacing - margin, x1 * spacing + margin, y1 * spacing + margin)
+ return Transformer.from_crs(crs, "EPSG:4326", always_xy=True).transform_bounds(*box, densify_pts=101)
+
+
+def _tracks(indexes, bounds, time_range, budget):
+ tracks, identities, samples = [], set(), 0
+ for index in indexes:
+ for track in index.query(bounds, time_range):
+ # Same track from overlapping daily/source coverage must be identical;
+ # silently dropping different geometry would change the physics.
+ signature = content_hash([track.id, track.time.tolist(), track.xyz.tolist(), track.spline.c.tolist()])
+ if track.id in identities:
+ previous = next(t for t in tracks if t.id == track.id)
+ if signature != content_hash([previous.id, previous.time.tolist(), previous.xyz.tolist(), previous.spline.c.tolist()]):
+ raise DataUnavailable(f"Conflicting flight segment identity: {track.id}")
+ continue
+ identities.add(track.id)
+ tracks.append(track)
+ samples += len(track.time)
+ if len(tracks) > budget.max_tracks_per_tile or samples > budget.max_track_samples_per_tile:
+ raise DataUnavailable("Tile track/sample memory budget exceeded; reduce tile_cells")
+ return tracks
+
+
+def _score(points, tracks, events, measurements, budget, parameters, filters, start_window=None):
+ radius = max(e["slant_range_m"][1] for e in events)
+ tables, count = [], 0
+ # Bound materialized CPA rows before pairing; one track at a time keeps the
+ # national traffic count out of the CPA tensor/list allocation.
+ for track in tracks:
+ samples = math.ceil((track.time[-1] - track.time[0]) / budget.cpa_step_s) + 1
+ if samples > budget.max_track_samples_per_tile:
+ raise DataUnavailable("CPA time-sampling memory budget exceeded")
+ # Even a pathological looping track cannot allocate an unbounded list
+ # of minima before we inspect the returned table.
+ chunk_points = max(1, budget.max_cpa_rows // samples)
+ for first in range(0, len(points), chunk_points):
+ table = cpa_table([track], points.iloc[first:first + chunk_points], radius, parameters.get("c", 343.0), budget.cpa_step_s)
+ count += len(table)
+ if count > budget.max_cpa_rows:
+ raise DataUnavailable("Tile CPA-row memory budget exceeded")
+ if len(table):
+ tables.append(table)
+ if not tables:
+ return [], {"cpa_rows": 0, "candidates": 0}
+ table = pd.concat(tables, ignore_index=True)
+ kwargs = dict(offset_tolerance_s=filters.get("offset_tolerance_s", 5.0),
+ time_origin=parameters.get("time_origin"), time_tolerance_s=filters.get("time_tolerance_s", 5.0),
+ silence=filters.get("silence"))
+ subset = filters.get("association") == "subsets"
+ if subset:
+ from .matching import association_candidates
+ candidates, counts = association_candidates(table, events, **kwargs,
+ min_events=filters.get("min_events", 1), max_events=filters.get("max_events", 3),
+ max_candidates=budget.max_candidates_per_tile)
+ else:
+ per_event = [filter_event(table, e, kwargs["time_origin"], kwargs["time_tolerance_s"]).groupby("point_id").size().to_dict() for e in events]
+ upper = sum(math.prod(g.get(p, 0) for g in per_event) for p in points.point_id)
+ if upper > budget.max_candidates_per_tile:
+ raise DataUnavailable("Tile candidate memory budget exceeded; reduce tile_cells")
+ candidates, counts = pair_candidates(table, events, **kwargs)
+ # Attach approach identities before scoring, since legacy rank drops passes.
+ ranked = []
+ lookup = {row.point_id: row for row in points.itertuples()}
+ track_lookup = {track.id: track for track in tracks}
+ for candidate in candidates:
+ settings = dict(parameters)
+ if start_window:
+ anchor = settings.get("time_origin")
+ if anchor is None:
+ anchor_event = candidate.get("event_indices", [0])[0]
+ anchor = candidate["passes"][0]["receive_time"] - events[anchor_event]["cpa_receive_s"]
+ sweep = settings.get("time_sweep_s", 5.0)
+ lo, hi = max(anchor - sweep, start_window[0]), min(anchor + sweep, start_window[1])
+ if lo > hi:
+ continue
+ settings.update(time_origin=(lo + hi) / 2, time_sweep_s=(hi - lo) / 2)
+ row = score_candidate(candidate, lookup[candidate["point_id"]], track_lookup, events, measurements, **settings)
+ row["pass_emission_times_s"] = [float(p["emission_time"]) for p in candidate["passes"]]
+ ranked.append(row)
+ return merge_candidates(ranked, budget.top_k), dict(counts, cpa_rows=count, candidates=len(candidates))
+
+
+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):
+ """Bounded outer driver using existing physical CPA/locked-event scoring.
+
+ `events, measurements` come from `matching.prepare_events`. `time_range_s`
+ is the absolute *emission* data query window, expanded for sound travel and
+ the complete uncertain recording clock. `scoring.time_origin` is either a
+ trusted fixed clock or None; it is never set independently per tile/event.
+ A clock range can additionally constrain `recording_start_time_s` globally.
+ """
+ budget = budget or SearchBudget()
+ if not indexes or not events or len(events) != len(measurements):
+ raise ValueError("Supply flight indexes and one measurement per event")
+ for e in events:
+ if not 0 < e["slant_range_m"][1] < 1000000:
+ raise ValueError("Event slant range must be finite and <1000 km")
+ parameters = dict(scoring or {})
+ start_window = parameters.pop("recording_start_window_s", None)
+ filters = filters or {}
+ output = Path(output_dir)
+ output.mkdir(parents=True, exist_ok=True)
+ # Include actual acoustic measurements and implementation files in resume
+ # identity; a detector/scorer change must never reuse stale tile scores.
+ acoustic = []
+ for spec, ridge, weight, fit in measurements:
+ acoustic.append([hashlib_array(a) for a in [spec.time, getattr(spec, "frequency", []),
+ getattr(spec, "contrast", []), ridge, weight]])
+ modules = {p.name: sha256(p) for p in sorted(Path(__file__).parent.glob("*.py"))}
+ if hasattr(terrain, "files"):
+ terrain_signature = {name: value["sha256"] for name, value in terrain.files.items()
+ if name in ("tileList.txt", terrain.geoid_path.name)}
+ else:
+ rasters = list(getattr(terrain, "rasters", []))
+ if getattr(terrain, "geoid", None):
+ rasters += terrain.geoid.rasters
+ terrain_signature = {"constant_m": getattr(terrain, "constant", None),
+ "rasters": {str(r.name): sha256(r.name) for r in rasters}}
+ identity = {"indexes": [{"input_hash": i.report["input_hash"], "file_sha256": sha256(i.path)} for i in indexes],
+ "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}
+ 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})
+ began, ranked, failures, done, resumed, points_searched = time.monotonic(), [], [], 0, 0, 0
+ total = sum(1 for _ in grid_tiles(bounds, budget.spacing_m, budget.tile_cells, crs))
+ 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"
+ 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")
+ payload = record["payload"]
+ for source in payload.get("terrain_files", []):
+ if sha256(source["path"]) != source["sha256"]:
+ raise DataUnavailable("Terrain changed since tile checkpoint")
+ resumed += 1
+ 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()
+ rows, counts = _score(points, tracks, events, measurements, budget, parameters, filters, start_window) if len(points) else ([], {})
+ 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}
+ write_json(checkpoint, {"run_hash": run_hash, "payload_hash": content_hash(payload), "payload": payload})
+ done += 1
+ points_searched += payload["grid_points"]
+ ranked = merge_candidates(itertools.chain(ranked, payload["ranked"]), budget.top_k)
+ except (DataUnavailable, ValueError, OSError) as error:
+ failures.append({"tile": tile_id, "reason": str(error)})
+ coarse = list(ranked)
+ # Refine only global finalists; tile selection never controls refinement rank.
+ refinement_failure = None
+ if ranked and budget.refine_spacing_m < budget.spacing_m:
+ chosen, seen = [], set()
+ for row in ranked:
+ approach = (tuple(row["flight_ids"]), tuple(round(t) for t in row["pass_emission_times_s"]))
+ if approach not in seen:
+ chosen.append(row)
+ seen.add(approach)
+ if len(chosen) >= budget.refine_finalists:
+ break
+ try:
+ fine = budget.refine_spacing_m
+ width = math.ceil(budget.spacing_m / fine)
+ for row in chosen:
+ # Subdivide the refinement square as well, retaining hard grid limits.
+ cx, cy = round(row["x"] / fine), round(row["y"] / fine)
+ for y0 in range(cy - width, cy + width + 1, budget.tile_cells):
+ for x0 in range(cx - width, cx + width + 1, budget.tile_cells):
+ cells = (x0, y0, min(cx + width + 1, x0 + budget.tile_cells), min(cy + width + 1, y0 + budget.tile_cells))
+ tracks = _tracks(indexes, _expanded_bounds(cells, fine, radius, crs), time_range_s, budget)
+ points = tile_points(cells, fine, bounds, terrain, crs)
+ rows, _ = _score(points, tracks, events, measurements, budget, parameters, filters, start_window) if len(points) else ([], {})
+ ranked = merge_candidates(itertools.chain(ranked, rows), budget.top_k)
+ except (DataUnavailable, ValueError, OSError) as error:
+ refinement_failure = str(error)
+ coverage = [i.coverage_for(bounds, time_range_s) for i in indexes]
+ # Aircraft outside the receiver rectangle can still be audible inside it.
+ # Use a conservative geographic envelope for scope accounting as well as
+ # expanded per-tile queries; cropped CONUS inputs have visible border gaps.
+ angular = (1.6 * radius + 15000) / 110000
+ lon_margin = angular / max(0.1, math.cos(math.radians(max(abs(bounds[1]), abs(bounds[3])))))
+ flight_bounds = [max(-180, bounds[0] - lon_margin), max(-90, bounds[1] - angular),
+ min(180, bounds[2] + lon_margin), min(90, bounds[3] + angular)]
+ # Sources partitioning time can jointly cover the request; union interval
+ # coverage is checked only for all-type sources covering the whole spatial box.
+ intervals = sorted(i.report["coverage"]["time_range_s"] for i in indexes if i.coverage_for(flight_bounds, i.report["coverage"]["time_range_s"])["scope_complete"])
+ covered_until = time_range_s[0]
+ for lo, hi in intervals:
+ if lo <= covered_until:
+ covered_until = max(covered_until, hi)
+ data_complete = covered_until >= time_range_s[1]
+ complete = done == total and not failures and not refinement_failure and data_complete
+ report = {"run_hash": run_hash, "status": "complete" if complete else "partial", "ranked": ranked,
+ "coarse_ranked": coarse, "tiles_total": total, "tiles_completed": done, "tiles_resumed": resumed,
+ "tile_failures": failures, "unsearched_tiles": total - done, "grid_points_searched": points_searched,
+ "data_coverage": coverage, "data_scope_complete": data_complete, "refinement_failure": refinement_failure,
+ "required_flight_bounds": flight_bounds,
+ "candidate_retention_limit": budget.top_k, "alternative_modes_exhaustively_assessed": False,
+ "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,
+ "scoring_time_is_locked": True, "ground_truth_used_by_search": False, "scope": list(bounds)}
+ write_json(output / "search-report.json", report)
+ return report
+
+
+def hashlib_array(value):
+ import hashlib
+ array = np.asarray(value)
+ return hashlib.sha256(str(array.shape).encode() + str(array.dtype).encode() + array.tobytes()).hexdigest()
diff --git a/tests/test_tiled_search.py b/tests/test_tiled_search.py
new file mode 100644
index 0000000..da70a90
--- /dev/null
+++ b/tests/test_tiled_search.py
@@ -0,0 +1,105 @@
+from dataclasses import replace
+from types import SimpleNamespace
+
+import numpy as np
+import pandas as pd
+from pyproj import Transformer
+import pytest
+
+from aircraft_geoloc.audio import Spectrum
+from aircraft_geoloc.data_access import DataUnavailable, FlightIndex
+from aircraft_geoloc.geometry import Track, ecef
+from aircraft_geoloc.terrain import Terrain
+from aircraft_geoloc.tiled_search import SearchBudget, _score, grid_tiles, merge_candidates, search_national, tile_points
+
+
+def scenario(tmp_path):
+ inverse = Transformer.from_crs("EPSG:5070", "EPSG:4326", always_xy=True)
+ # Winning receiver x=0 is exactly on tile boundaries for all tile sizes.
+ lon, lat = inverse.transform(0, 1900000)
+ origin = 1800000000.
+ frames, tracks, events, measurements = [], [], [], []
+ observer = ecef(lat, lon, 0)
+ for number, center in enumerate([150., 650.]):
+ t = np.arange(center - 150, center + 151, 5)
+ x = (t - center) * 80
+ y = np.full(len(t), 1900000 + number * 200)
+ flon, flat = inverse.transform(x, y)
+ track = Track(f"flight{number}", t + origin, flat, flon, np.full(len(t), 1200))
+ tracks.append(track)
+ frames.append(pd.DataFrame({"flight_id": track.id, "time_s": track.time, "lat": flat,
+ "lon": flon, "alt_m": 1200, "altitude_basis": "ellipsoidal"}))
+ received = t[24:37]
+ factor, _, _ = track.acoustic(origin + received, observer)
+ spectrum = Spectrum(received, np.arange(80, 161), np.zeros((81, len(received))), np.zeros((81, len(received))))
+ ridge = factor * 120
+ measurements.append((spectrum, ridge, np.ones(len(ridge)), {}))
+ cpa = track.closest_approaches(observer, 4000)[0]["receive_time"] - origin
+ events.append({"start_s": float(received[0]), "end_s": float(received[-1]), "cpa_receive_s": cpa,
+ "speed_range_mps": [50, 110], "slant_range_m": [500, 4000], "f0_range_hz": [115, 125]})
+ bounds = inverse.transform_bounds(-2200, 1897800, 2200, 1902200, densify_pts=21)
+ times = [origin, origin + 801]
+ index = FlightIndex.build(tmp_path / "flights.sqlite", frames, sources=[],
+ coverage={"bounds": [-125, 24, -66, 50], "time_range_s": times, "all_aircraft": True})
+ return index, tracks, events, measurements, bounds, times, origin
+
+
+def compact(rows):
+ return [(tuple(r["flight_ids"]), r["x"], r["y"], round(r["score"], 8), round(r["recording_start_time_s"], 5)) for r in rows]
+
+
+def test_tiled_equals_untiled_boundary_and_locked_timing(tmp_path):
+ index, tracks, events, measurements, bounds, times, origin = scenario(tmp_path)
+ terrain = Terrain(constant_m=0)
+ budget = SearchBudget(spacing_m=1000, tile_cells=2, top_k=200, refine_spacing_m=1000)
+ settings = {"mode": "ridge", "time_origin": origin, "time_sweep_s": 0}
+ all_points = pd.concat([tile_points(cells, 1000, bounds, terrain, "EPSG:5070") for _, cells in grid_tiles(bounds, 1000, 2)], ignore_index=True)
+ all_points["point_id"] = np.arange(len(all_points))
+ expected, _ = _score(all_points, tracks, events, measurements, budget, settings, {})
+ result = search_national([index], terrain, events, measurements, time_range_s=times, output_dir=tmp_path / "run",
+ bounds=bounds, budget=budget, scoring=settings)
+ assert result["status"] == "complete"
+ assert compact(result["ranked"]) == compact(expected)
+ assert result["ranked"][0]["x"] == 0 and result["ranked"][0]["y"] == 1900000
+ replay = search_national([index], terrain, events, measurements, time_range_s=times, output_dir=tmp_path / "run",
+ bounds=bounds, budget=budget, scoring=settings)
+ assert replay["tiles_resumed"] == replay["tiles_total"]
+ assert compact(replay["ranked"]) == compact(result["ranked"])
+ with pytest.raises(DataUnavailable, match="mismatch"):
+ search_national([index], terrain, events, measurements, time_range_s=times, output_dir=tmp_path / "run",
+ bounds=bounds, budget=replace(budget, spacing_m=900), scoring=settings)
+
+
+def test_budget_exhaustion_and_source_holes_are_partial(tmp_path):
+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)
+ kwargs = dict(time_range_s=times, bounds=bounds, scoring={"mode": "ridge", "time_origin": origin, "time_sweep_s": 0})
+ limited = search_national([index], Terrain(constant_m=0), events, measurements, output_dir=tmp_path / "limited",
+ budget=SearchBudget(max_tiles=1, tile_cells=1, refine_spacing_m=2000), **kwargs)
+ assert limited["status"] == "partial" and limited["unsearched_tiles"] > 0
+ overloaded = search_national([index], Terrain(constant_m=0), events, measurements, output_dir=tmp_path / "overloaded",
+ budget=SearchBudget(max_tracks_per_tile=1, tile_cells=4, refine_spacing_m=2000), **kwargs)
+ assert overloaded["status"] == "partial" and overloaded["tile_failures"]
+ # A source scope ending before the query cannot establish complete coverage.
+ kwargs["time_range_s"] = [times[0], times[1] + 1]
+ missing = search_national([index], Terrain(constant_m=0), events, measurements, output_dir=tmp_path / "missing",
+ budget=SearchBudget(refine_spacing_m=2000), **kwargs)
+ assert not missing["data_scope_complete"] and missing["status"] == "partial"
+
+
+def test_merge_is_deterministic_and_preserves_repeat_approaches():
+ base = {"score": 1., "flight_ids": ["a"], "x": 0., "y": 0., "recording_start_time_s": 0.}
+ first = dict(base, pass_emission_times_s=[100.])
+ second = dict(base, pass_emission_times_s=[300.])
+ assert merge_candidates([second, first, first], 10) == [first, second]
+ assert merge_candidates([first, second], 10) == merge_candidates([second, first], 10)
+
+
+def test_ridge_only_adapter_and_exact_recording_clock(tmp_path):
+ index, _, events, measurements, bounds, times, origin = scenario(tmp_path)
+ measurements = [(SimpleNamespace(time=spec.time), ridge, weight, fit) for spec, ridge, weight, fit in measurements]
+ result = search_national([index], Terrain(constant_m=0), events, measurements, time_range_s=times,
+ output_dir=tmp_path / "ridge-only", bounds=bounds,
+ budget=SearchBudget(spacing_m=1000, tile_cells=4, refine_spacing_m=1000),
+ scoring={"mode": "ridge", "recording_start_window_s": [origin, origin]})
+ assert result["ranked"]
+ assert all(row["recording_start_time_s"] == origin for row in result["ranked"])