Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Associate bounded event subsets and retain unmatched proposals (#8)
Cinna Davis8b2dec8377b5
diff --git a/docs/MATCHING.md b/docs/MATCHING.mdindex e4a1e35..5cb6870 100644--- a/docs/MATCHING.md+++ b/docs/MATCHING.md@@ -27,11 +27,15 @@ The score is negative penalized robust residual in Hz, summed over independentevent groups. Higher is better; values and gaps are not probabilities, nor arethey interchangeable with the legacy brightness/RMSE score scales.-Numeric `quality` settings used by matching are `frequency_sigma_hz` (default+Numeric `quality` settings used by matching are `frequency_loss_scale_hz` (default1 Hz), `source_drift_fraction` (default 0.02 over the event, maximum 0.1),`cpa_tolerance_s`, `speed_tolerance_mps` and `slant_tolerance_m` (default zero).`prepare_events` sets CPA tolerance to span the detected window. These aremeasurement/proposal settings, not post-hoc parameters selected using truth.+It consumes discovery's `frequency_uncertainty_hz` as a loss scale with a 1 Hz+floor when no explicit scale is supplied and preserves the diagnostic key;+this is not a calibrated noise model. `frequency_sigma_hz` remains a legacy+alias for explicitly supplied loss scales, without claiming statistical sigma.Pairing intersects the permitted recording-start intervals of all events,including any absolute-time constraint, so pairwise compatibility cannotmanufacture a joint clock. Legacy scoring modes are preserved for replay.@@ -66,3 +70,26 @@ finished. Those source-informed windows, bands, region and the faint event'sderived clock remain development limitations. Both failures and successes mustbe reported. Automatic full-recording discovery and independent real/nationalacceptance are integration gates, not established by these replays.++## Unmatched proposals++`matching.association_candidates(table, events, ..., min_events=1, max_events=3,+max_candidates=20000)` proposes subsets instead of requiring every acoustic+proposal 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+must mark that search incomplete. All original proposals remain in the event+artifact. Each hypothesis carries ordered `event_indices`, and+`score_candidate`/`refine_candidate` consume the complete event/measurement lists+and select the corresponding subset internally. Scored rows expose matched and+unmatched event IDs; repeated approaches retain their separate emission times.++Partial associations use a separate score kind,+`matched_group_support_minus_normalized_residual`. A matched group contributes+`1 - robust_loss/(3*frequency_loss_scale_hz)` and must have loss below that threshold.+This rewards multiple consistent independent events without promoting a perfect+single-event fit over a good joint fit. It is an explicit ranking heuristic,+not a likelihood, probability or calibrated false-match test. Different score+kinds must not be mixed in a ranking. Confidence must still consider competing+locations, matched group count, omitted proposals, source coverage and residual+diagnostics. Single-event candidates remain available for a defensible known+clock, and do not by themselves establish a supported location.diff --git a/src/aircraft_geoloc/matching.py b/src/aircraft_geoloc/matching.pyindex a1ca14e..4beedb7 100644--- a/src/aircraft_geoloc/matching.py+++ b/src/aircraft_geoloc/matching.py@@ -4,6 +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, productimport numpy as npfrom pyproj import Transformer@@ -17,6 +18,80 @@ class RidgeTimes:time: np.ndarray+def _frequency_scale(event):+ quality = event.get("quality", {})+ return quality.get("frequency_loss_scale_hz", quality.get("frequency_sigma_hz",+ max(1.0, quality.get("frequency_uncertainty_hz", 1.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):+ """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.+ """+ from .search import filter_event+ if 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]+ 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,+ "unmatched_proposals_allowed": True}+++def association_score(result, events):+ """Compare different matched subsets using bounded normalized support.++ One well-fitted independent event contributes up to one unit. A poor event+ invalidates that hypothesis; another subset can leave it unmatched. This is+ a ranking heuristic, not a likelihood or a calibrated confidence statistic.+ """+ limits = [3 * _frequency_scale(e) for e in events]+ losses = [-s for s in result["event_scores"]]+ supported = all(np.isfinite(v) and v <= limit for v, limit in zip(losses, limits))+ return dict(result, residual_score=result["score"],+ score=float(sum(1-v/limit for v, limit in zip(losses, limits))) if supported else -np.inf,+ score_kind="matched_group_support_minus_normalized_residual")++def prepare_events(detected_events, c=343.0, max_distance_m=20000.0):"""Adapt contract ridge points to existing search inputs without truth hints.@@ -59,6 +134,7 @@ def prepare_events(detected_events, c=343.0, max_distance_m=20000.0):start, end = min(e["start_s"] for e in members), max(e["end_s"] for e in members)center = float(reference.get("cpa_receive_s", (start + end) / 2))quality = dict(reference.get("quality", {}))+ quality.setdefault("frequency_loss_scale_hz", _frequency_scale(reference))quality["cpa_tolerance_s"] = max(center - start, end - center)# A subsonic source gives f_source = f_received * (1 + v_radial/c).# These broad bounds are independent of an unreliable straight-pass fit.@@ -132,7 +208,7 @@ def score_ridges(tracks, events, measurements, observer, recording_start_s, c=34for track, event, measurement in zip(tracks, events, measurements):quality = event.get("quality", {})diagnostics.append(fit_ridge(track, observer, measurement, recording_start_s,- event["f0_range_hz"], c, quality.get("frequency_sigma_hz", 1.0),+ event["f0_range_hz"], c, _frequency_scale(event),quality.get("source_drift_fraction", 0.02)))return {"score": float(sum(d["score"] for d in diagnostics)),"event_scores": [d["score"] for d in diagnostics],@@ -155,6 +231,9 @@ def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=x0, y0 = forward.transform(candidate["lon"], candidate["lat"])start = candidate["recording_start_time_s"]selected = [tracks[f] for f in candidate["flight_ids"]]+ if "event_indices" in candidate:+ events = [events[i] for i in candidate["event_indices"]]+ measurements = [measurements[i] for i in candidate["event_indices"]]if radius_m <= 0 or clock_radius_s < 0 or 0.0 not in altitude_offsets_m:raise ValueError("Need positive spatial/nonnegative clock bounds and a nominal zero-altitude scenario")lower, upper = -clock_radius_s, clock_radius_s@@ -179,6 +258,8 @@ def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=elevation = float(np.asarray(terrain.sample(lat, lon)))score = score_ridges(selected, events, measurements, ecef(lat, lon, elevation + offset),start + dt, c)+ if "event_indices" in candidate:+ score = association_score(score, events)return score, lat, lon, elevationdef objective(parameters):value = evaluate(parameters)[0]["score"]diff --git a/src/aircraft_geoloc/search.py b/src/aircraft_geoloc/search.pyindex 522f1f8..050124e 100644--- a/src/aircraft_geoloc/search.py+++ b/src/aircraft_geoloc/search.py@@ -212,6 +212,18 @@ def event_score(track, observer, spectrum, ridge, weight, start_time, f0_bounds,def score_candidate(candidate, point, tracks, events, measurements, mode="brightness",time_origin=None, time_sweep_s=5.0, time_step_s=0.5, c=343.0):+ association = "event_indices" in candidate+ association_fields = {}+ if association:+ if mode != "robust_ridge":+ raise ValueError("Partial-event association requires robust_ridge scoring")+ indices = candidate["event_indices"]+ if not indices or indices != sorted(set(indices)) or any(i < 0 or i >= len(events) for i in indices):+ raise ValueError("Association event indices must be unique, ordered and in range")+ association_fields = {"event_indices": indices,+ "event_ids": [events[i].get("event_id", str(i)) for i in indices],+ "unmatched_event_ids": [e.get("event_id", str(i)) for i, e in enumerate(events) if i not in indices]}+ events, measurements = [events[i] for i in indices], [measurements[i] for i in indices]if not events or len(events) != len(measurements) or len(events) != len(candidate["passes"]):raise ValueError("Need exactly one pass and measurement for each event")if mode not in ("brightness", "ridge", "robust_ridge"):@@ -240,6 +252,9 @@ def score_candidate(candidate, point, tracks, events, measurements, mode="brightfrom .matching import score_ridgesresult = score_ridges([tracks[p["flight_id"]] for p in candidate["passes"]],events,measurements,observer,anchor+shift,c)+ if association:+ from .matching import association_score+ result = association_score(result, events)if result["score"] > best["score"]:best = dict(result,recording_start_time_s=float(anchor+shift),time_adjustment_s=float(shift))continue@@ -254,7 +269,7 @@ def score_candidate(candidate, point, tracks, events, measurements, mode="brightif total>best["score"]:best = {"score":total,"event_scores":scores,"f0_hz":f0s,"recording_start_time_s":float(anchor+shift),"time_adjustment_s":float(shift)}- return dict(best,point_id=int(point.point_id),lat=float(point.lat),lon=float(point.lon),elev_m=float(point.elev_m),+ return dict(best,**association_fields,point_id=int(point.point_id),lat=float(point.lat),lon=float(point.lon),elev_m=float(point.elev_m),x=float(point.x),y=float(point.y),flight_ids=[p["flight_id"] for p in candidate["passes"]])diff --git a/tests/test_association.py b/tests/test_association.pynew file mode 100644index 0000000..a76c034--- /dev/null+++ b/tests/test_association.py@@ -0,0 +1,83 @@+from types import SimpleNamespace++import numpy as np+import pandas as pd+import pytest++from aircraft_geoloc.matching import RidgeTimes, association_candidates, refine_candidate+from aircraft_geoloc.search import score_candidate+++class Flyover:+ def __init__(self, center):+ self.center = center++ def acoustic(self, t, observer, c):+ t = np.asarray(t)+ return 1.1 - 0.25*np.tanh((t-self.center)/8), t-5, np.full_like(t, 1700)+++def case():+ centers = [30, 500, 950]+ tracks, events, measurements, rows = {}, [], [], []+ for i, center in enumerate(centers):+ identity = f"track-{i}"+ tracks[identity] = Flyover(center)+ times = np.arange(center-25, center+25, 0.5)+ frequency = 120*tracks[identity].acoustic(times, None, 343)[0]+ if i == 1:+ frequency = np.random.default_rng(12).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), frequency, np.ones(len(times)), {}))+ rows.append(dict(point_id=0, flight_id=identity, receive_time=center, emission_time=center-5,+ speed_mps=80, distance_m=1700))+ return pd.DataFrame(rows), tracks, events, measurements+++def test_unmatched_false_proposal_does_not_suppress_two_locked_real_events():+ table, tracks, events, measurements = case()+ candidates, counts = association_candidates(table, 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]+ winner = max(ranked, key=lambda row: row["score"])+ assert winner["event_indices"] == [0, 2]+ assert winner["unmatched_event_ids"] == ["event-1"]+ assert winner["flight_ids"] == ["track-0", "track-2"]+ assert winner["recording_start_time_s"] == 0+ assert abs(winner["score"]-2) < 1e-7+ assert winner["score_kind"] == "matched_group_support_minus_normalized_residual"+ assert counts["unmatched_proposals_allowed"]+ assert counts["max_matched_events"] == 3+ assert not np.isfinite(next(r for r in ranked if r["event_indices"] == [0, 1, 2])["score"])+ terrain = SimpleNamespace(sample=lambda lat, lon: np.array(100.0))+ refined = refine_candidate(winner, tracks, events, measurements, terrain,+ recording_start_window_s=(0.0, 0.0), altitude_offsets_m=(0.0,))+ assert refined["event_indices"] == [0, 2]+ assert refined["unmatched_event_ids"] == ["event-1"]+ assert abs(refined["score"]-winner["score"]) < 1e-7+ assert refined["score_kind"] == winner["score_kind"]+++def test_association_budget_and_noise_only_hypotheses_fail_explicitly():+ table, tracks, events, measurements = case()+ with pytest.raises(ValueError, match="budget exceeded"):+ association_candidates(table, events, time_origin=0, max_candidates=1)+ candidates, _ = association_candidates(table, events[1:2], time_origin=0)+ point = SimpleNamespace(point_id=0, lat=40, lon=-100, elev_m=100, x=0, y=0)+ rows = [score_candidate(c, point, tracks, events[1:2], measurements[1:2],+ mode="robust_ridge", time_origin=0, time_sweep_s=0) for c in candidates]+ assert rows and not any(np.isfinite(row["score"]) for row in rows)+++def test_repeated_passes_remain_distinct_and_one_pass_cannot_explain_two_events():+ table, tracks, events, measurements = case()+ table["flight_id"] = "one-aircraft"+ candidates, _ = association_candidates(table, events, time_origin=0)+ triple = next(c for c in candidates if c["event_indices"] == [0, 1, 2])+ assert len({p["emission_time"] for p in triple["passes"]}) == 3+ overlapping = [dict(events[0], quality={"cpa_tolerance_s": 1000}),+ dict(events[1], quality={"cpa_tolerance_s": 1000})]+ candidates, _ = association_candidates(table.iloc[:1], overlapping, min_events=2)+ assert not candidatesdiff --git a/tests/test_matching.py b/tests/test_matching.pyindex 468e9cd..62aa92f 100644--- a/tests/test_matching.py+++ b/tests/test_matching.py@@ -85,13 +85,16 @@ def detected(identity="a", harmonic=1):def test_adapter_retains_jet_with_misleading_straight_geometry_and_merges_harmonics():- events, measurements = prepare_events([detected(), detected("harmonic", 2)])+ primary = dict(detected(), quality={"frequency_uncertainty_hz": 1.5})+ events, measurements = prepare_events([primary, detected("harmonic", 2)])table = pd.DataFrame([dict(point_id=0, flight_id="jet", receive_time=42, emission_time=28,speed_mps=155, distance_m=4900)])assert len(events) == 1assert len(measurements[0][1]) == 200assert len(filter_event(table, events[0], time_origin=0)) == 1assert events[0]["event_ids"] == ["a", "harmonic"]+ assert events[0]["quality"]["frequency_loss_scale_hz"] == 1.5+ assert events[0]["quality"]["frequency_uncertainty_hz"] == 1.5# Duplicating harmonic evidence changes neither the fit nor its normalization.single, sm = prepare_events([detected()])one = fit_ridge(Flyover(), None, sm[0], 0, single[0]["f0_range_hz"])