Skip to content

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

Add conservative event adaptation and robust locked-clock physical matching (#8)

Cinna Davisb66411ed954e
diff --git a/docs/MATCHING.md b/docs/MATCHING.md
new file mode 100644
index 0000000..df7e2e0
--- /dev/null
+++ b/docs/MATCHING.md
@@ -0,0 +1,63 @@
+# Physical matching
+
+`matching.prepare_events(detected_events)` adapts the shared detected-event
+records into the existing `(events, measurements)` search arguments. It uses
+subsonic speed and a declared maximum audible distance rather than excluding
+tracks using a straight-pass speed/slant estimate. It does not filter aircraft
+type. The 20 km default is an explicit search envelope, not guaranteed acoustic
+coverage. The outer search must use these same bounds when acquiring tracks and
+constructing corridors. Increasing a filter tolerance after corridor generation
+cannot restore already excluded data.
+
+Compatible integer harmonic ridges in a `harmonic_group_id` contribute to one
+pass and one event clock. Each ridge has equal aggregate weight. Ratios must be
+consistent with an integer multiple of the lowest observed ridge. Unsupported
+groups fail explicitly; discovery should split them rather than invent a
+fundamental or treat them as independent flyovers. `event_ids` on the prepared
+internal record maps the merged evidence back to original contract events.
+
+`search.rank_candidates(..., mode="robust_ridge")` fits the actual trajectory at
+emission time. One recording start is swept for every event together. A bounded
+linear source-frequency change can absorb modest engine drift, with a weak
+zero-drift penalty; it cannot fit an arbitrary curve or a separate event clock.
+The pseudo-Huber residual reduces the influence of tracing outliers. Every
+positive-weight measured sample requires trajectory support. Results include
+per-event RMSE, outlier fraction, drift parameters/boundary flags and support.
+The score is negative penalized robust residual in Hz, summed over independent
+event groups. Higher is better; values and gaps are not probabilities, nor are
+they interchangeable with the legacy brightness/RMSE score scales.
+
+Numeric `quality` settings used by matching are `frequency_sigma_hz` (default
+1 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 are
+measurement/proposal settings, not post-hoc parameters selected using truth.
+Pairing intersects the permitted recording-start intervals of all events,
+including any absolute-time constraint, so pairwise compatibility cannot
+manufacture a joint clock. Legacy scoring modes are preserved for replay.
+
+`matching.refine_candidate(candidate, track_lookup, events, measurements,
+terrain)` refines position and a shared recording clock in a bounded local
+search. It repeats the fit over declared relative-height scenarios (default
+-150/0/+150 m) and returns `sensitivity` profiles and boundary flags. This
+tests vertical-datum/altitude degeneracy; it is neither a calibrated confidence
+interval nor a complete spatial ambiguity assessment. The nominal result's
+score remains evaluated at the actual terrain height. Missing profiles and
+boundary optima must be considered by confidence handling. Competing flight
+associations and distant spatial modes still need the outer search.
+
+Verification:
+
+```bash
+PYTHONPATH=src .venv/bin/python -m pytest -q
+PYTHONPATH=src .venv/bin/python scripts/benchmark_matching.py \
+ --source-root /path/to/restored/data/source --output results/new-matching-run
+```
+
+The benchmark replays both original regional cases in the original scoring mode
+and robust mode. It refuses to overwrite its output directory, hashes inputs and
+implementation, and reads evaluation coordinates only after every search has
+finished. Those source-informed windows, bands, region and the faint event's
+derived clock remain development limitations. Both failures and successes must
+be reported. Automatic full-recording discovery and independent real/national
+acceptance are integration gates, not established by these replays.
diff --git a/scripts/benchmark_matching.py b/scripts/benchmark_matching.py
new file mode 100644
index 0000000..998b952
--- /dev/null
+++ b/scripts/benchmark_matching.py
@@ -0,0 +1,86 @@
+"""Replay both regional development cases before/after robust matching.
+
+Truth is loaded only after every search completes. The original manually
+configured windows/bounds are preserved and clearly labelled as development.
+Run with PYTHONPATH=src python scripts/benchmark_matching.py --help.
+"""
+import argparse
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+
+import numpy as np
+
+from aircraft_geoloc.geometry import ecef
+from aircraft_geoloc.pipeline import run
+
+
+def digest(path):
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def absolute_config(path):
+ config = json.loads(path.read_text())
+ def local(value):
+ return str((path.parent / value).resolve())
+ config["audio"] = local(config["audio"])
+ config["tracks"] = [local(p) for p in config["tracks"]]
+ if config.get("type_database"):
+ config["type_database"] = local(config["type_database"])
+ for name in ("geoid_raster", "copernicus_cache"):
+ if config["terrain"].get(name):
+ config["terrain"][name] = local(config["terrain"][name])
+ config["terrain"]["rasters"] = [local(p) for p in config["terrain"].get("rasters", [])]
+ return config
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source-root", type=Path, required=True, help="Restored data/source directory")
+ parser.add_argument("--output", type=Path, required=True, help="New output directory; must not exist")
+ args = parser.parse_args()
+ args.output.mkdir(parents=True, exist_ok=False)
+ root = Path(__file__).resolve().parents[1]
+ cases = [("two-events", "reproduce-local.json", "reference-local"),
+ ("faint", "reproduce-faint-alltypes-local.json", "reference-faint-alltypes-local")]
+ outcomes = []
+ for name, filename, evidence in cases:
+ source = args.source_root / filename
+ config = absolute_config(source)
+ for mode in (config["scoring"]["mode"], "robust_ridge"):
+ directory = args.output / f"{name}-{mode}"
+ directory.mkdir()
+ configured = json.loads(json.dumps(config))
+ configured["scoring"]["mode"] = mode
+ path = directory / "config.json"
+ path.write_text(json.dumps(configured, indent=2) + "\n")
+ report = run(path, directory / "search")
+ outcomes.append(dict(case=name, mode=mode, best=report["best"],
+ elapsed_s=report["elapsed_s"], flight_combinations=report["flight_combinations"],
+ implementation_sha256=report["implementation_sha256"],
+ source_config_sha256=digest(source), config_sha256=digest(path), evidence=evidence))
+ # Evaluation boundary: no reference coordinates were available to search.
+ for result in outcomes:
+ evaluation = json.loads((root / "evidence/results" / result.pop("evidence") / "evaluation.json").read_text())
+ lat, lon = evaluation["reference_coordinate"]
+ best = result["best"]
+ result["error_m"] = float(np.linalg.norm(ecef(lat, lon, 0) - ecef(best["lat"], best["lon"], 0)))
+ result["meets_100m"] = result["error_m"] <= 100
+ combinations = json.loads((args.output / f"{result['case']}-{result['mode']}" / "search/flight-combinations.json").read_text())
+ result["ranked_flight_combinations"] = [r["flight_ids"] for r in combinations]
+ summary = dict(scope="regional, manually configured development replays; no independent/national accuracy claim",
+ truth_read_after_search=True,
+ commit=subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip(),
+ working_tree_diff_sha256=hashlib.sha256(subprocess.check_output(["git", "diff", "HEAD"], cwd=root)).hexdigest(),
+ outcomes=outcomes)
+ path = args.output / "summary.json"
+ path.write_text(json.dumps(summary, indent=2, allow_nan=False) + "\n")
+ print(path)
+ for result in outcomes:
+ print(result["case"], result["mode"], f"{result['error_m']:.2f} m", result["best"]["flight_ids"])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/aircraft_geoloc/matching.py b/src/aircraft_geoloc/matching.py
new file mode 100644
index 0000000..e8305cd
--- /dev/null
+++ b/src/aircraft_geoloc/matching.py
@@ -0,0 +1,194 @@
+"""Conservative detected-event adapters and robust emission-time ridge matching.
+
+Scores are penalized residuals, never probabilities. Geometry from a straight-pass
+audio fit is a proposal diagnostic, not a reliable exclusion bound for real tracks.
+"""
+from dataclasses import dataclass
+
+import numpy as np
+from pyproj import Transformer
+from scipy.optimize import lsq_linear, minimize
+
+from .geometry import ecef
+
+
+@dataclass
+class RidgeTimes:
+ time: np.ndarray
+
+
+def prepare_events(detected_events, c=343.0, max_distance_m=20000.0):
+ """Adapt contract ridge points to existing search inputs without truth hints.
+
+ Keep every ridge in a harmonic group as evidence for one pass. Integer
+ harmonics are normalized to its lowest observed band; no fundamental needs
+ to be present. Groups with inconsistent ratios must be fixed by discovery.
+ Timing uncertainty spans the observed window, because a curved track need
+ not have its geometric CPA at a fitted straight-pass center.
+ """
+ groups = {}
+ for event in detected_events:
+ key = event.get("harmonic_group_id") or event["event_id"]
+ groups.setdefault(key, []).append(event)
+ settings, measurements = [], []
+ for members in groups.values():
+ reference = min(members, key=lambda e: np.median([p["frequency_hz"] for p in e["ridge"]]))
+ reference_time = np.array([p["time_s"] for p in reference["ridge"]])
+ reference_frequency = np.array([p["frequency_hz"] for p in reference["ridge"]])
+ times, frequencies, weights = [], [], []
+ for member in members:
+ t = np.array([p["time_s"] for p in member["ridge"]], dtype=float)
+ f = np.array([p["frequency_hz"] for p in member["ridge"]], dtype=float)
+ w = np.array([p.get("weight", 1.0) for p in member["ridge"]], dtype=float)
+ overlapping = (t >= reference_time[0]) & (t <= reference_time[-1])
+ if not overlapping.any():
+ raise ValueError("Harmonic-group ridges must overlap in recording time")
+ ratio = np.median(f[overlapping] / np.interp(t[overlapping], reference_time, reference_frequency))
+ harmonic = max(1, round(ratio))
+ if abs(ratio / harmonic - 1) > 0.05:
+ raise ValueError("Harmonic group does not have consistent integer frequency ratios")
+ times.extend(t)
+ frequencies.extend(f / harmonic)
+ # Equal aggregate weight per ridge prevents duplicated harmonics
+ # from manufacturing additional independent events.
+ weights.extend(w / max(np.sum(w), 1e-12))
+ order = np.argsort(times, kind="stable")
+ t, f, w = (np.asarray(a)[order] for a in (times, frequencies, weights))
+ if len(t) < 10 or not np.all(np.isfinite(np.column_stack((t, f, w)))) or np.any(w < 0):
+ raise ValueError("Matching requires at least ten finite, nonnegative-weight ridge samples")
+ 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["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.
+ event = dict(reference, start_s=start, end_s=end, cpa_receive_s=center,
+ speed_range_mps=[1.0, 0.9 * c], slant_range_m=[1.0, max_distance_m],
+ f0_range_hz=[float(f.min() * 0.1), float(f.max() * 1.9)], quality=quality)
+ event["event_ids"] = [e["event_id"] for e in members]
+ settings.append(event)
+ measurements.append((RidgeTimes(t), f, w, {}))
+ order = np.argsort([e["cpa_receive_s"] for e in settings])
+ return [settings[i] for i in order], [measurements[i] for i in order]
+
+
+def fit_ridge(track, observer, measurement, start_time, f0_bounds, c=343.0,
+ sigma_hz=1.0, drift_fraction=0.02):
+ """Bounded linear source drift at emission time, with robust residual loss.
+
+ Drift is bounded to a fraction of source frequency over the measured event.
+ It cannot supply independent event time shifts or arbitrary curve warping.
+ Zero-weight samples are missing evidence; negative/nonfinite weights fail.
+ """
+ spec, ridge, weight, _ = measurement
+ times, ridge, weight = (np.asarray(a, dtype=float) for a in (spec.time, ridge, weight))
+ if times.shape != ridge.shape or times.shape != weight.shape or times.ndim != 1:
+ raise ValueError("Ridge time, frequency and weight must be matching one-dimensional arrays")
+ if not np.isfinite(sigma_hz) or sigma_hz <= 0 or not 0 <= drift_fraction <= 0.1:
+ raise ValueError("Need positive frequency uncertainty and drift fraction in [0, 0.1]")
+ if not np.all(np.isfinite(weight)) or np.any(weight < 0):
+ raise ValueError("Ridge weights must be finite and nonnegative")
+ measured = np.isfinite(times) & np.isfinite(ridge) & (weight > 0)
+ failed = {"score": -np.inf, "f0_hz": np.nan, "support_fraction": 0.0}
+ if measured.sum() < 10:
+ return failed
+ factor, emission, _ = track.acoustic(start_time + times[measured], observer, c)
+ if not np.all(np.isfinite(factor)) or not np.all(np.isfinite(emission)):
+ return failed
+ y, w = ridge[measured], weight[measured]
+ independent_samples = len(np.unique(times[measured]))
+ w = w * independent_samples / w.sum()
+ span = max(float(np.ptp(emission)), 1e-9)
+ u = (emission - (emission.min() + emission.max()) / 2) / span
+ cap = float(np.clip(np.median(y / factor), *f0_bounds)) * drift_fraction
+ design = np.column_stack((factor, factor * u)) if cap else factor[:, None]
+ bounds = ([f0_bounds[0], -cap], [f0_bounds[1], cap]) if cap else ([f0_bounds[0]], [f0_bounds[1]])
+ effective = w.copy()
+ for _ in range(6):
+ matrix, target = design * np.sqrt(effective[:, None]), y * np.sqrt(effective)
+ if cap:
+ matrix = np.vstack((matrix, [0, 2 * sigma_hz / cap]))
+ target = np.r_[target, 0.0]
+ fit = lsq_linear(matrix, target, bounds=bounds, tol=1e-8)
+ residual = design @ fit.x - y
+ effective = w / np.sqrt(1 + (residual / sigma_hz) ** 2)
+ loss = np.average(2 * sigma_hz**2 * (np.sqrt(1 + (residual / sigma_hz)**2) - 1), weights=w)
+ drift = float(fit.x[1]) if cap else 0.0
+ penalty = (2 * sigma_hz * drift / cap)**2 / independent_samples if cap else 0.0
+ return {"score": -float(np.sqrt(loss + penalty)), "f0_hz": float(fit.x[0]),
+ "source_drift_hz": drift, "source_drift_hz_s": drift / span,
+ "drift_bound_hz": float(cap), "drift_at_bound": bool(cap and abs(drift) > 0.99 * cap),
+ "rmse_hz": float(np.sqrt(np.average(residual**2, weights=w))),
+ "support_fraction": 1.0, "sample_count": int(len(y)),
+ "independent_sample_count": independent_samples,
+ "outlier_fraction": float(np.average(np.abs(residual) > 3 * sigma_hz, weights=w))}
+
+
+def score_ridges(tracks, events, measurements, observer, recording_start_s, c=343.0):
+ """Score all events at exactly one recording clock; report nuisance fits."""
+ if not events or len(tracks) != len(events) or len(measurements) != len(events):
+ raise ValueError("Need exactly one track and measurement for each event")
+ diagnostics = []
+ for 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),
+ 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],
+ "f0_hz": [d["f0_hz"] for d in diagnostics], "event_diagnostics": diagnostics,
+ "score_kind": "negative_robust_ridge_loss_hz"}
+
+
+def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=500.0,
+ clock_radius_s=5.0, altitude_offsets_m=(-150.0, 0.0, 150.0),
+ crs="EPSG:5070", c=343.0):
+ """Jointly refine position/shared clock and profile vertical-datum sensitivity.
+
+ A vertical offset changes the observer-to-track relative height; it is a
+ sensitivity scenario, not a new terrain measurement or calibrated interval.
+ Returned radius describes the explored alternatives only. A boundary optimum
+ warns callers that this local search has not enclosed the possible solution.
+ """
+ forward = Transformer.from_crs("EPSG:4326", crs, always_xy=True)
+ inverse = Transformer.from_crs(crs, "EPSG:4326", always_xy=True)
+ x0, y0 = forward.transform(candidate["lon"], candidate["lat"])
+ start = candidate["recording_start_time_s"]
+ selected = [tracks[f] for f in candidate["flight_ids"]]
+ if radius_m <= 0 or clock_radius_s <= 0 or 0.0 not in altitude_offsets_m:
+ raise ValueError("Need positive refinement bounds and a nominal zero-altitude scenario")
+ bounds = [(-radius_m, radius_m), (-radius_m, radius_m), (-clock_radius_s, clock_radius_s)]
+ profiles = []
+ for offset in altitude_offsets_m:
+ def evaluate(parameters):
+ latlon = inverse.transform(x0 + parameters[0], y0 + parameters[1])
+ lon, lat = latlon
+ elevation = float(np.asarray(terrain.sample(lat, lon)))
+ score = score_ridges(selected, events, measurements, ecef(lat, lon, elevation + offset),
+ start + parameters[2], c)
+ return score, lat, lon, elevation
+ def objective(parameters):
+ value = evaluate(parameters)[0]["score"]
+ return -value if np.isfinite(value) else 1e6
+ result = minimize(objective, np.zeros(3), method="Powell", bounds=bounds,
+ options={"xtol": 0.01, "ftol": 1e-7, "maxiter": 60})
+ parameters = result.x if objective(result.x) < objective(np.zeros(3)) else np.zeros(3)
+ score, lat, lon, elevation = evaluate(parameters)
+ if not np.isfinite(score["score"]):
+ continue
+ profiles.append(dict(score, lat=lat, lon=lon, elev_m=elevation,
+ recording_start_time_s=float(start + parameters[2]), altitude_offset_m=float(offset),
+ boundary_limited=bool(np.any(np.abs(parameters) >= np.array([radius_m, radius_m, clock_radius_s]) * 0.98)),
+ optimizer_success=bool(result.success)))
+ nominal = next((p for p in profiles if p["altitude_offset_m"] == 0), None)
+ if nominal is None:
+ raise ValueError("No complete trajectory support for local refinement")
+ center = ecef(nominal["lat"], nominal["lon"], 0)
+ radius = max(float(np.linalg.norm(ecef(p["lat"], p["lon"], 0) - center)) for p in profiles)
+ return dict(candidate, **{k: v for k, v in nominal.items() if k != "altitude_offset_m"},
+ x=float(forward.transform(nominal["lon"], nominal["lat"])[0]),
+ y=float(forward.transform(nominal["lon"], nominal["lat"])[1]),
+ sensitivity={"radius_m": radius, "kind": "sensitivity",
+ "method": "profiled_relative_altitude_offsets",
+ "profiles": profiles, "boundary_limited": any(p["boundary_limited"] for p in profiles),
+ "complete": len(profiles) == len(altitude_offsets_m)})
diff --git a/src/aircraft_geoloc/search.py b/src/aircraft_geoloc/search.py
index 2261f9b..522f1f8 100644
--- a/src/aircraft_geoloc/search.py
+++ b/src/aircraft_geoloc/search.py
@@ -133,9 +133,14 @@ def cpa_table(tracks,points,max_distance,c=343.0,step_s=2.0,chunk_size=512):
def filter_event(table, event, time_origin=None, time_tolerance=5.0):
speed, distance = event["speed_range_mps"],event["slant_range_m"]
- keep = table.speed_mps.between(*speed) & table.distance_m.between(*distance)
+ quality = event.get("quality", {})
+ dv, dd = quality.get("speed_tolerance_mps", 0), quality.get("slant_tolerance_m", 0)
+ dt = quality.get("cpa_tolerance_s", 0)
+ if not all(np.isfinite(v) and v >= 0 for v in (dv, dd, dt)):
+ raise ValueError("Proposal tolerances must be finite and nonnegative")
+ keep = table.speed_mps.between(max(0, speed[0]-dv), speed[1]+dv) & table.distance_m.between(max(0, distance[0]-dd), distance[1]+dd)
if time_origin is not None:
- keep &= np.abs(table.receive_time-(time_origin+event["cpa_receive_s"])) <= time_tolerance
+ keep &= np.abs(table.receive_time-(time_origin+event["cpa_receive_s"])) <= time_tolerance + dt
return table.loc[keep]
@@ -151,8 +156,12 @@ def pair_candidates(table, events, offset_tolerance_s=5.0, time_origin=None,
for point_id in sorted(common):
for combination in product(*(list(g[point_id].to_dict("records")) for g in group)):
anchor = combination[0]["receive_time"]
- if any(abs((row["receive_time"]-anchor)-(events[i]["cpa_receive_s"]-events[0]["cpa_receive_s"]))
- > offset_tolerance_s for i,row in enumerate(combination[1:],1)):
+ starts = np.array([row["receive_time"]-event["cpa_receive_s"] for row,event in zip(combination,events)])
+ tolerance = np.array([event.get("quality", {}).get("cpa_tolerance_s", 0) for event in events]) + offset_tolerance_s/2
+ lower, upper = float(np.max(starts-tolerance)), float(np.min(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 len(combination)>1 and len({(r["flight_id"],round(r["emission_time"],1)) for r in combination})<len(combination):
continue
@@ -169,7 +178,8 @@ def pair_candidates(table, events, offset_tolerance_s=5.0, time_origin=None,
if len(between):
rejected += 1
continue
- candidates.append({"point_id":point_id,"passes":combination})
+ candidates.append({"point_id":point_id,"passes":combination,
+ "recording_start_bounds_s":[lower,upper]})
return candidates,{"per_event_survivors":[len(f) for f in filtered],
"pairs_before_silence":before,"silence_rejected":rejected,"survivors":len(candidates)}
@@ -202,13 +212,37 @@ 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):
+ 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"):
+ raise ValueError(f"Unknown scoring mode: {mode}")
+ if time_step_s <= 0 or time_sweep_s < 0:
+ raise ValueError("Need positive clock step and nonnegative sweep")
observer = ecef(point.lat,point.lon,point.elev_m)
# Derive one recording start from the first event; all other events retain
# their true absolute geometry/time. This implements the locked offset.
anchor = time_origin if time_origin is not None else candidate["passes"][0]["receive_time"]-events[0]["cpa_receive_s"]
shifts = np.linspace(-time_sweep_s,time_sweep_s,max(1,int(np.ceil(2*time_sweep_s/time_step_s)))+1)
+ if mode == "robust_ridge" and "recording_start_bounds_s" in candidate:
+ lower, upper = candidate["recording_start_bounds_s"]
+ # CPA intervals propose a shared clock; the physical model may move it
+ # within the same declared sweep used by legacy scoring.
+ lower, upper = lower-time_sweep_s, upper+time_sweep_s
+ if time_origin is not None:
+ lower, upper = max(lower,anchor-time_sweep_s), min(upper,anchor+time_sweep_s)
+ if lower > upper:
+ shifts = []
+ else:
+ shifts = np.linspace(lower-anchor,upper-anchor,max(1,int(np.ceil((upper-lower)/time_step_s)))+1)
best = {"score":-np.inf}
for shift in shifts:
+ if mode == "robust_ridge":
+ from .matching import score_ridges
+ result = score_ridges([tracks[p["flight_id"]] for p in candidate["passes"]],
+ events,measurements,observer,anchor+shift,c)
+ if result["score"] > best["score"]:
+ best = dict(result,recording_start_time_s=float(anchor+shift),time_adjustment_s=float(shift))
+ continue
scores,f0s = [],[]
for event,measurement,flyover in zip(events,measurements,candidate["passes"]):
spec,ridge,weight,_ = measurement
diff --git a/tests/test_matching.py b/tests/test_matching.py
new file mode 100644
index 0000000..8a1c713
--- /dev/null
+++ b/tests/test_matching.py
@@ -0,0 +1,148 @@
+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, fit_ridge, prepare_events, refine_candidate
+from aircraft_geoloc.search import event_score, filter_event, pair_candidates, score_candidate
+
+
+class Flyover:
+ def __init__(self, center=30, support=None):
+ self.center, self.support = center, support
+
+ def acoustic(self, t, observer, c):
+ t = np.asarray(t)
+ factor = 1.1 - 0.25 * np.tanh((t - self.center) / 8)
+ if self.support is not None:
+ factor = np.where(t <= self.support, factor, np.nan)
+ return factor, t - 5, np.ones_like(t) * 1700
+
+
+def measurement(center=30, drift=0.0, noisy=False):
+ t = np.arange(center - 25, center + 25, 0.5)
+ factor = Flyover(center).acoustic(t, None, 343)[0]
+ ridge = factor * (120 + drift * (t - (t[0] + t[-1]) / 2) / np.ptp(t))
+ if noisy:
+ ridge += np.random.default_rng(17).normal(0, 0.15, len(t))
+ ridge[::11] += 18
+ return RidgeTimes(t), ridge, np.ones(len(t)), {}
+
+
+def test_robust_source_drift_and_outliers_preserve_wrong_track_penalty():
+ measured = measurement(drift=1.8, noisy=True)
+ correct = fit_ridge(Flyover(), None, measured, 0, [118, 122])
+ wrong = fit_ridge(Flyover(38), None, measured, 0, [118, 122])
+ legacy = event_score(Flyover(), None, *measured[:3], 0, [118, 122], "ridge")
+ assert abs(correct["f0_hz"] - 120) < 0.2
+ assert abs(correct["source_drift_hz"] - 1.8) < 0.5
+ assert correct["score"] > legacy[0]
+ assert correct["score"] > wrong["score"] + 1
+ assert correct["outlier_fraction"] > 0.05
+ assert correct["support_fraction"] == 1
+ noise = list(measured)
+ noise[1] = np.random.default_rng(3).uniform(90, 160, len(measured[1]))
+ assert fit_ridge(Flyover(), None, noise, 0, [118, 122])["score"] < correct["score"] - 1
+
+
+def test_drift_is_bounded_and_incomplete_support_cannot_win():
+ measured = measurement(drift=18)
+ fit = fit_ridge(Flyover(), None, measured, 0, [118, 122])
+ assert fit["drift_at_bound"]
+ assert abs(fit["source_drift_hz"]) <= fit["drift_bound_hz"]
+ assert not np.isfinite(fit_ridge(Flyover(support=54), None, measured, 0, [118, 122])["score"])
+ zero = list(measured)
+ zero[2] = np.zeros(len(measured[1]))
+ assert not np.isfinite(fit_ridge(Flyover(), None, zero, 0, [118, 122])["score"])
+
+
+def test_robust_mode_locks_all_event_clocks_and_rejects_missing_passes():
+ point = SimpleNamespace(point_id=0, lat=40, lon=-100, elev_m=0, x=0, y=0)
+ events = [{"cpa_receive_s": t, "f0_range_hz": [119.9, 120.1]} for t in (30, 950)]
+ candidate = {"passes": [{"flight_id": "a", "receive_time": 30}, {"flight_id": "b", "receive_time": 950}]}
+ kwargs = dict(mode="robust_ridge", time_origin=0, time_sweep_s=10, time_step_s=1)
+ good = score_candidate(candidate, point, {"a": Flyover(30), "b": Flyover(950)},
+ events, [measurement(30), measurement(950)], **kwargs)
+ bad = score_candidate(candidate, point, {"a": Flyover(30), "b": Flyover(958)},
+ events, [measurement(30), measurement(950)], **kwargs)
+ assert abs(good["score"]) < 1e-8
+ assert bad["score"] < -2
+ assert len(bad["event_diagnostics"]) == 2
+ with pytest.raises(ValueError, match="exactly one"):
+ score_candidate({"passes": candidate["passes"][:1]}, point, {}, events, [], **kwargs)
+
+
+def detected(identity="a", harmonic=1):
+ m = measurement()
+ return {"event_id": identity, "start_s": 4, "end_s": 56, "band_hz": [80 * harmonic, 170 * harmonic],
+ "harmonic_group_id": "group", "cpa_receive_s": 30,
+ "speed_range_mps": [70, 90], "slant_range_m": [800, 1400],
+ "ridge": [{"time_s": float(t), "frequency_hz": float(f * harmonic), "weight": 2}
+ for t, f in zip(m[0].time, m[1])]}
+
+
+def test_adapter_retains_jet_with_misleading_straight_geometry_and_merges_harmonics():
+ events, measurements = prepare_events([detected(), 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) == 1
+ assert len(measurements[0][1]) == 200
+ assert len(filter_event(table, events[0], time_origin=0)) == 1
+ assert events[0]["event_ids"] == ["a", "harmonic"]
+ # 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"])
+ two = fit_ridge(Flyover(), None, measurements[0], 0, events[0]["f0_range_hz"])
+ assert abs(one["score"] - two["score"]) < 1e-8
+ inconsistent = detected("bad", 2)
+ for p in inconsistent["ridge"]:
+ p["frequency_hz"] *= 0.75
+ with pytest.raises(ValueError, match="integer"):
+ prepare_events([detected(), inconsistent])
+
+
+def test_uncertainty_requires_one_common_recording_start_interval():
+ events = [dict(cpa_receive_s=t, speed_range_mps=[70, 90], slant_range_m=[800, 1400],
+ quality={"cpa_tolerance_s": 1}) for t in (30, 130, 230)]
+ rows = [dict(point_id=0, flight_id=str(i), receive_time=t + delta, emission_time=t + delta - 5,
+ speed_mps=80, distance_m=1000) for i, (t, delta) in enumerate(zip((30, 130, 230), (100, 103, 97)))]
+ assert pair_candidates(pd.DataFrame(rows), events, offset_tolerance_s=2)[0] == []
+ rows[-1]["receive_time"] += 6
+ candidates, _ = pair_candidates(pd.DataFrame(rows), events, offset_tolerance_s=2)
+ assert len(candidates) == 1
+ lower, upper = candidates[0]["recording_start_bounds_s"]
+ assert lower <= upper
+
+
+def test_joint_refinement_uses_nonparallel_passes_and_profiles_altitude():
+ observer = ecef(40, -100, 100)
+ epoch = 1_790_000_000.0
+ inverse = Transformer.from_crs("EPSG:4978", "EPSG:4979", always_xy=True)
+ tracks, events, measurements = {}, [], []
+ for identity, center, f0, velocity, cross in [
+ ("a", 70, 120, [80, 0, 0], [0, 1600, 800]),
+ ("b", 250, 160, [0, 80, 0], [1700, 0, 1000])]:
+ t = np.arange(center - 120, center + 121, 1.0)
+ xyz = observer + (t - center)[:, None] * np.array(velocity) + cross
+ lon, lat, altitude = inverse.transform(*xyz.T)
+ tracks[identity] = Track(identity, t + epoch, lat, lon, altitude,
+ velocity=np.tile(velocity, (len(t), 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}))
+ seed = dict(lat=40.0015, lon=-99.998, elev_m=100, recording_start_time_s=epoch + 0.5,
+ flight_ids=["a", "b"], point_id=0)
+ terrain = SimpleNamespace(sample=lambda lat, lon: np.array(100.0))
+ result = refine_candidate(seed, tracks, events, measurements, terrain, radius_m=500, clock_radius_s=3)
+ error = np.linalg.norm(ecef(result["lat"], result["lon"], 100) - observer)
+ assert error < 10
+ assert abs(result["recording_start_time_s"] - epoch) < 0.1
+ assert len(result["sensitivity"]["profiles"]) == 3
+ assert result["sensitivity"]["radius_m"] > 0
+ assert result["sensitivity"]["kind"] == "sensitivity"
+ assert result["sensitivity"]["complete"]