Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Use every supported event with bounded temporal association pruning (#8)
Cinna Davise827f17c7ed5
diff --git a/docs/MATCHING.md b/docs/MATCHING.mdindex 4887367..fbadd4f 100644--- a/docs/MATCHING.md+++ b/docs/MATCHING.md@@ -1,5 +1,10 @@# Physical matching+The current target is up to 1,000 m point error acceptable, with 100–500 m or+better preferred. Benchmark point error and model sensitivity are different+quantities. A boundary-truncated 500 m profile is not relabelled a valid 1 km+envelope; it needs a larger declared search budget or remains limited.+`matching.prepare_events(detected_events)` adapts the shared detected-eventrecords into the existing `(events, measurements)` search arguments. It usessubsonic speed and a declared maximum audible distance rather than excluding@@ -73,10 +78,15 @@ acceptance are integration gates, not established by these replays.## Unmatched proposals-`matching.association_candidates(table, events, ..., min_events=1, max_events=3,+`matching.association_candidates(table, events, ..., min_events=1, max_events=None,max_candidates=20000)` proposes subsets instead of requiring every acousticproposal to be an aircraft. It examines subsets up to the declared event count-and fails explicitly when candidate/work budgets are exceeded. The outer driver+and defaults to all independent groups. Shared-clock intervals prune impossible+extensions before complete assignments are built. Index entries, branch visits+and stored assignments share a work/storage budget; candidate limits remain+explicit. An optional smaller event cap is reported as `event_cap_limited`, and+the outer driver must treat that cap as incomplete coverage. The hook fails+explicitly when candidate/work budgets are exceeded. The outer drivermust mark that search incomplete. All original proposals remain in the eventartifact. Each hypothesis carries ordered `event_indices`, and`score_candidate`/`refine_candidate` consume the complete event/measurement listsdiff --git a/src/aircraft_geoloc/matching.py b/src/aircraft_geoloc/matching.pyindex bc249c5..3f95898 100644--- a/src/aircraft_geoloc/matching.py+++ b/src/aircraft_geoloc/matching.py@@ -4,7 +4,7 @@ Scores are penalized residuals, never probabilities. Geometry from a straight-paaudio fit is a proposal diagnostic, not a reliable exclusion bound for real tracks."""from dataclasses import dataclass-from itertools import combinations, product+from itertools import chainimport numpy as npfrom pyproj import Transformer@@ -68,54 +68,92 @@ def predict_fitted_ridge(track, observer, receive_times_s, diagnostics, c=343.0)def association_candidates(table, events, offset_tolerance_s=5.0, time_origin=None,time_tolerance_s=5.0, silence=None, min_events=1,- max_events=3, max_candidates=20000):+ max_events=None, max_candidates=20000):"""Bounded subset hypotheses, retaining explicitly unmatched proposals.- Every subset within the declared maximum is considered; exceeding the work- budget fails explicitly so the outer search records incomplete coverage.- Geometry only proposes hypotheses. Acoustic scoring must reject poor fits.+ Default to every independent group. Intersect shared-clock intervals before+ extending a branch; do not materialize impossible Cartesian products. Index+ entries, branch visits and stored assignments share an explicit work budget.+ Exceeding it fails visibly so the outer driver reports incomplete coverage."""from .search import filter_event+ max_events = max(min_events, len(events)) if max_events is None else max_eventsif not 1 <= min_events <= max_events or max_candidates < 1:raise ValueError("Invalid association event/candidate budget")- filtered = [filter_event(table, e, time_origin, time_tolerance_s) for e in events]- grouped = [{p: frame.to_dict("records") for p, frame in f.groupby("point_id")} for f in filtered]+ candidates, examined, work = [], 0, 0+ def reserve(units):+ nonlocal work+ work += units+ if work > max_candidates*20:+ raise ValueError("Association work/storage budget exceeded; search is incomplete")+ reserve(len(table))+ table = table.reset_index(drop=True)+ records = table.to_dict("records")+ grouped, survivors = [], []+ for event in events:+ frame = filter_event(table, event, time_origin, time_tolerance_s)+ reserve(len(frame))+ survivors.append(len(frame))+ grouped.append({p: [records[i] for i in group.index] for p, group in frame.groupby("point_id")})by_point = {p: frame for p, frame in table.groupby("point_id")}- candidates, examined = [], 0- for count in range(min(max_events, len(events)), min_events-1, -1):- for indices in combinations(range(len(events)), count):- common = set.intersection(*(set(grouped[i]) for i in indices))- for point_id in sorted(common):- for passes in product(*(grouped[i][point_id] for i in indices)):- examined += 1- if examined > max_candidates * 20:- raise ValueError("Association work budget exceeded; search is incomplete")- if len({(p["flight_id"], p["emission_time"]) for p in passes}) < count:- continue- starts = [p["receive_time"]-events[i]["cpa_receive_s"] for p, i in zip(passes, indices)]- tolerance = [events[i].get("quality", {}).get("cpa_tolerance_s", 0)+offset_tolerance_s/2 for i in indices]- lower = max(t-d for t, d in zip(starts, tolerance))- upper = min(t+d for t, d in zip(starts, tolerance))- if time_origin is not None:- lower, upper = max(lower, time_origin-time_tolerance_s), min(upper, time_origin+time_tolerance_s)- if lower > upper:- continue- if silence and count > 1:- frame = by_point[point_id]- margin = silence.get("edge_margin_s", 60)- distance = max(p["distance_m"] for p in passes)*silence.get("distance_multiplier", 1)- between = frame[(frame.receive_time > passes[0]["receive_time"]+margin) &- (frame.receive_time < passes[-1]["receive_time"]-margin) &- (frame.distance_m <= distance)]- selected = {(p["flight_id"], p["emission_time"]) for p in passes}- if any((r.flight_id, r.emission_time) not in selected for r in between.itertuples()):- continue- if len(candidates) >= max_candidates:- raise ValueError("Association candidate budget exceeded; search is incomplete")- candidates.append({"point_id": point_id, "passes": passes, "event_indices": list(indices),- "recording_start_bounds_s": [float(lower), float(upper)]})- return candidates, {"per_event_survivors": [len(f) for f in filtered], "survivors": len(candidates),- "hypotheses_examined": examined, "max_matched_events": max_events,+ for point_id in sorted(set().union(*(g.keys() for g in grouped))):+ available = [i for i, group in enumerate(grouped) if point_id in group]+ if len(available) < min_events:+ continue+ lower, upper = (-np.inf, np.inf) if time_origin is None else (time_origin-time_tolerance_s, time_origin+time_tolerance_s)+ path, used = [], set()+ frames = [(0, iter(chain(grouped[available[0]][point_id], [None])), lower, upper, 0)]+ while frames:+ cursor, options, lower, upper, depth = frames[-1]+ while len(path) > depth:+ _, old = path.pop()+ used.remove((old["flight_id"], old["emission_time"]))+ try:+ row = next(options)+ except StopIteration:+ frames.pop()+ continue+ reserve(1)+ lo, hi = lower, upper+ index = available[cursor]+ if row is not None:+ identity = (row["flight_id"], row["emission_time"])+ if identity in used:+ continue+ start = row["receive_time"]-events[index]["cpa_receive_s"]+ tolerance = events[index].get("quality", {}).get("cpa_tolerance_s", 0)+offset_tolerance_s/2+ lo, hi = max(lo, start-tolerance), min(hi, start+tolerance)+ if lo > hi:+ continue+ path.append((index, row))+ used.add(identity)+ following = cursor+1+ if len(path)+len(available)-following < min_events:+ continue+ if following < len(available) and len(path) < max_events:+ frames.append((following, iter(chain(grouped[available[following]][point_id], [None])), lo, hi, len(path)))+ continue+ if len(path) < min_events:+ continue+ examined += 1+ passes = tuple(row for _, row in path)+ if silence and len(path) > 1:+ frame = by_point[point_id]+ reserve(len(frame))+ margin = silence.get("edge_margin_s", 60)+ distance = max(p["distance_m"] for p in passes)*silence.get("distance_multiplier", 1)+ between = frame[(frame.receive_time > passes[0]["receive_time"]+margin) &+ (frame.receive_time < passes[-1]["receive_time"]-margin) & (frame.distance_m <= distance)]+ if any((r.flight_id, r.emission_time) not in used for r in between.itertuples()):+ continue+ if len(candidates) >= max_candidates:+ raise ValueError("Association candidate budget exceeded; search is incomplete")+ reserve(len(path))+ candidates.append({"point_id": point_id, "passes": passes, "event_indices": [i for i, _ in path],+ "recording_start_bounds_s": [float(lo), float(hi)]})+ return candidates, {"per_event_survivors": survivors, "survivors": len(candidates),+ "hypotheses_examined": examined, "work_units": work, "max_matched_events": max_events,+ "event_cap_limited": max_events < len(events),"unmatched_proposals_allowed": True}diff --git a/tests/test_all_events.py b/tests/test_all_events.pynew file mode 100644index 0000000..5a0a661--- /dev/null+++ b/tests/test_all_events.py@@ -0,0 +1,149 @@+"""Unit fixtures for all-event association; not blind/national accuracy evidence."""+from types import SimpleNamespace++import numpy as np+import pandas as pd+import pytest+from pyproj import Transformer++from aircraft_geoloc.geometry import Track, ecef, straight_doppler+from aircraft_geoloc.matching import RidgeTimes, association_candidates, refine_candidate+from aircraft_geoloc.search import score_candidate+++class TonePass:+ def __init__(self, center):+ self.center = center++ def acoustic(self, times, observer, c):+ times = np.asarray(times)+ return 1.1-0.25*np.tanh((times-self.center)/8), times-5, np.full_like(times, 1700)++[email protected]("count", [3, 4, 6])+def test_all_supported_events_survive_a_leading_distractor(count):+ tracks, events, measurements, rows = {}, [], [], []+ for i in range(count+1):+ center, identity = 30+180*i, f"track-{i}"+ track = tracks[identity] = TonePass(center)+ times = np.arange(center-25, center+25, 1.0)+ ridge = 120*track.acoustic(times, None, 343)[0]+ if i == 0:+ ridge = np.random.default_rng(19).uniform(90, 160, len(times))+ events.append(dict(event_id=f"event-{i}", cpa_receive_s=center, f0_range_hz=[119, 121],+ speed_range_mps=[60, 100], slant_range_m=[500, 3000]))+ measurements.append((RidgeTimes(times), ridge, np.ones(len(times)), {}))+ rows.append(dict(point_id=0, flight_id=identity, receive_time=center, emission_time=center-5,+ distance_m=1700, speed_mps=80))+ candidates, counts = association_candidates(pd.DataFrame(rows), events, time_origin=0)+ point = SimpleNamespace(point_id=0, lat=40, lon=-100, elev_m=100, x=0, y=0)+ ranked = [score_candidate(c, point, tracks, events, measurements, mode="robust_ridge",+ time_origin=0, time_sweep_s=0) for c in candidates]+ best = max(ranked, key=lambda row: row["score"])+ assert best["event_indices"] == list(range(1, count+1))+ assert best["unmatched_event_ids"] == ["event-0"]+ assert len(best["event_diagnostics"]) == count+ assert abs(best["score"]-count) < 1e-7+ assert counts["max_matched_events"] == count+1+ assert not counts["event_cap_limited"]+ final = tracks[f"track-{count}"]+ tracks[f"track-{count}"] = TonePass(final.center+8)+ altered = score_candidate(next(c for c in candidates if c["event_indices"] == best["event_indices"]),+ point, tracks, events, measurements, mode="robust_ridge", time_origin=0, time_sweep_s=0)+ assert altered["score"] < best["score"]-0.1++[email protected]("count", [3, 4, 6])+def test_every_event_enters_joint_physical_refinement(count):+ observer, epoch = ecef(40, -100, 100), 1_790_000_000.0+ lat, lon = np.deg2rad([40, -100])+ east = np.array([-np.sin(lon), np.cos(lon), 0])+ north = np.array([-np.sin(lat)*np.cos(lon), -np.sin(lat)*np.sin(lon), np.cos(lat)])+ up = np.array([np.cos(lat)*np.cos(lon), np.cos(lat)*np.sin(lon), np.sin(lat)])+ inverse = Transformer.from_crs("EPSG:4978", "EPSG:4979", always_xy=True)+ tracks, events, measurements = {}, [], []+ for i in range(count):+ center, f0, angle = 70+180*i, 120+10*i, 0.4+0.9*i+ velocity = 80*(np.cos(angle)*east+np.sin(angle)*north)+ cross = 1300*(-np.sin(angle)*east+np.cos(angle)*north)+(900+100*i)*up+ times = np.arange(center-100, center+101, 1.0)+ xyz = observer+(times-center)[:, None]*velocity+cross+ track_lon, track_lat, height = inverse.transform(*xyz.T)+ identity = f"physical-{i}"+ tracks[identity] = Track(identity, times+epoch, track_lat, track_lon, height,+ velocity=np.tile(velocity, (len(times), 1)))+ receive = np.arange(center-35, center+35, 1.0)+ slant = np.linalg.norm(cross)+ ridge = straight_doppler(receive, f0, 80, slant, center+slant/343)+ measurements.append((RidgeTimes(receive), ridge, np.ones(len(receive)), {}))+ events.append(dict(f0_range_hz=[f0-1, f0+1], quality={"source_drift_fraction": 0}))+ candidate = dict(lat=40.0015, lon=-99.998, elev_m=100, recording_start_time_s=epoch,+ flight_ids=list(tracks), event_indices=list(range(count)))+ terrain = SimpleNamespace(sample=lambda lat, lon: np.array(100.0))+ kwargs = dict(recording_start_window_s=(epoch, epoch), altitude_offsets_m=(0.0,))+ result = refine_candidate(candidate, tracks, events, measurements, terrain, **kwargs)+ assert len(result["event_diagnostics"]) == count+ assert np.linalg.norm(ecef(result["lat"], result["lon"], 100)-observer) < 10+ changed = list(measurements)+ spec, ridge, weight, fit = changed[-1]+ changed[-1] = (spec, ridge+0.6*np.linspace(-1, 1, len(ridge)), weight, fit)+ moved = refine_candidate(candidate, tracks, events, changed, terrain, **kwargs)+ # Exact earlier passes can pin the location despite an inconsistent final+ # pass. Its residual must still enter the refined objective and diagnostics.+ assert moved["event_diagnostics"][-1]["rmse_hz"] > 0.1+ assert moved["score"] < result["score"]+ assert moved["recording_start_time_s"] == epoch+ changed_first = list(measurements)+ spec, ridge, weight, fit = changed_first[0]+ changed_first[0] = (spec, ridge+0.6*np.linspace(-1, 1, len(ridge)), weight, fit)+ prefix = dict(candidate, flight_ids=candidate["flight_ids"][:1], event_indices=[0])+ early = refine_candidate(prefix, tracks, events, changed_first, terrain, **kwargs)+ joint = refine_candidate(candidate, tracks, events, changed_first, terrain, **kwargs)+ early_error = np.linalg.norm(ecef(early["lat"], early["lon"], 100)-observer)+ joint_error = np.linalg.norm(ecef(joint["lat"], joint["lon"], 100)-observer)+ assert early_error > 1+ assert joint_error < early_error+++def test_explicit_event_cap_and_large_index_are_never_silent():+ rows = [dict(point_id=0, flight_id=str(i), receive_time=30+100*i, emission_time=25+100*i,+ speed_mps=80, distance_m=1700) for i in range(6)]+ events = [dict(cpa_receive_s=30+100*i, speed_range_mps=[60, 100], slant_range_m=[500, 3000]) for i in range(6)]+ _, counts = association_candidates(pd.DataFrame(rows), events, time_origin=0, max_events=3)+ assert counts["event_cap_limited"]+ with pytest.raises(ValueError, match="work/storage budget exceeded"):+ association_candidates(pd.DataFrame(rows*100), events, time_origin=0, max_candidates=2)++[email protected]("origin", [None, 90])+def test_temporal_pruning_matches_an_exhaustive_small_oracle(origin):+ from itertools import combinations, product+ from aircraft_geoloc.search import filter_event+ rows = [dict(point_id=p, flight_id=str(i%2), receive_time=t, emission_time=t-5,+ speed_mps=80, distance_m=1700) for p in (0, 1) for i, t in enumerate((100, 109, 121, 136))]+ table = pd.DataFrame(rows)+ events = [dict(cpa_receive_s=t, speed_range_mps=[60, 100], slant_range_m=[500, 3000],+ quality={"cpa_tolerance_s": i/2}) for i, t in enumerate((10, 20, 30))]+ candidates, _ = association_candidates(table, events, time_origin=origin, time_tolerance_s=4,+ offset_tolerance_s=4)+ def key(point, indices, passes):+ return point, tuple(indices), tuple((p["flight_id"], p["emission_time"]) for p in passes)+ actual = {key(c["point_id"], c["event_indices"], c["passes"]) for c in candidates}+ expected = set()+ filtered = [filter_event(table, event, origin, 4) for event in events]+ for count in (1, 2, 3):+ for indices in combinations(range(3), count):+ for point in (0, 1):+ choices = [frame[frame.point_id == point].to_dict("records") for frame in (filtered[i] for i in indices)]+ for passes in product(*choices):+ if len({(p["flight_id"], p["emission_time"]) for p in passes}) != count:+ continue+ starts = [p["receive_time"]-events[i]["cpa_receive_s"] for p, i in zip(passes, indices)]+ tolerance = [2+events[i]["quality"]["cpa_tolerance_s"] for i in indices]+ lo = max(s-d for s, d in zip(starts, tolerance))+ hi = min(s+d for s, d in zip(starts, tolerance))+ if origin is not None:+ lo, hi = max(lo, origin-4), min(hi, origin+4)+ if lo <= hi:+ expected.add(key(point, indices, passes))+ assert actual == expected