Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Keep final refinement within requested search bounds (#270)
Cinna Davisae7721b7d309
diff --git a/src/dopplergeist/automatic.py b/src/dopplergeist/automatic.pyindex a798eb0..8e3018e 100644--- a/src/dopplergeist/automatic.py+++ b/src/dopplergeist/automatic.py@@ -476,6 +476,7 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, sta# The confidence producer supplies this adapter; missing decision machinery# can never turn the highest raw score into a supported location.from .confidence import decide_location+ from .data_access import CONUSfrom .matching import _cache_ridge_fits, profile_candidate, refine_candidate# Each finalist and the complete sensitivity profile own an exact-input# cache. Profile's internal refinements share its scope; other calls do not.@@ -485,6 +486,7 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, starefined, refinement_failures = [], []window = state["recording"]["time_window"]start_window = tuple(utc_timestamp(window[key]).timestamp() for key in ("start_utc", "end_utc"))+ search_bounds = state["coverage"]["requested_area"].get("bounds_wsen", CONUS)finite = search.get("finite_search_evidence")assessed_ids = set()producer_ids = search.get("core_assessed_mode_ids")@@ -536,7 +538,8 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, starow = dict(row, altitude_basis={flight: sorted(set(getattr(track, "altitude_basis", ["unspecified"]))) for flight, track in tracks.items()})candidate = refine_candidate(row, tracks, prepared_events, measurements, terrain,radius_m=config.get("refine_radius_m", 500.0),- recording_start_window_s=start_window, c=config.get("sound_speed_mps", 343.0))+ recording_start_window_s=start_window, c=config.get("sound_speed_mps", 343.0),+ bounds_wsen=search_bounds)candidate = _comparable_refinement(candidate, row, prepared_events)refined.append(candidate)refined_keys.add(key)@@ -553,7 +556,7 @@ def _decide(search, events, prepared_events, measurements, indexes, terrain, statry:profiled = profile_candidate(leading, track_sets[mode_key(leading)], prepared_events, measurements, terrain,radius_m=config.get("refine_radius_m", 500.0), recording_start_window_s=start_window,- c=config.get("sound_speed_mps", 343.0))+ c=config.get("sound_speed_mps", 343.0), bounds_wsen=search_bounds)# Full profiling updates this exact hypothesis. Its earlier, limited# envelope must not compete with incomplete evidence or score roundoff.raw[0] = _comparable_refinement(profiled, leading, prepared_events)diff --git a/src/dopplergeist/matching.py b/src/dopplergeist/matching.pyindex 88afdcd..a36d049 100644--- a/src/dopplergeist/matching.py+++ b/src/dopplergeist/matching.py@@ -13,7 +13,7 @@ from itertools import chainimport osimport numpy as np-from pyproj import Transformer+from pyproj import Geod, Transformerfrom scipy.optimize import minimizefrom .geometry import Track, _EMISSION_ITERATION_TOLERANCE_S, ecef@@ -682,9 +682,24 @@ def _iter_acoustic_trials(tracks, measurements, observer, starts, c=343.0, max_syield batch+def _geographic_refinement_frame(candidate, radius_m, bounds_wsen):+ west, south, east, north = bounds_wsen+ lon0, lat0 = candidate["lon"], candidate["lat"]+ if (not np.isfinite(bounds_wsen).all() or west >= east or south >= north+ or not west <= lon0 <= east or not south <= lat0 <= north):+ raise ValueError("Refinement seed must lie within finite, ordered geographic bounds")+ geod = Geod(ellps="WGS84")+ lon_scale = geod.inv(lon0, lat0, lon0 + 1, lat0)[2]+ lat_scale = geod.inv(lon0, lat0, lon0, lat0 + 0.1)[2] * 10+ limits = [(max(-radius_m, (west-lon0)*lon_scale), min(radius_m, (east-lon0)*lon_scale)),+ (max(-radius_m, (south-lat0)*lat_scale), min(radius_m, (north-lat0)*lat_scale))]+ return limits, (lon_scale, lat_scale)++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, recording_start_window_s=None):+ crs="EPSG:5070", c=343.0, recording_start_window_s=None,+ bounds_wsen=None):"""Jointly refine position/shared clock and profile vertical-datum sensitivity.A vertical offset changes the observer-to-track relative height; it is a@@ -712,6 +727,13 @@ def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=raise ValueError("Refinement clock bounds do not intersect the recording-start window")fixed_clock = lower == upperbounds = [(-radius_m, radius_m), (-radius_m, radius_m)]+ if bounds_wsen is not None:+ west, south, east, north = bounds_wsen+ # Use east/north metre-scaled geographic coordinates so Powell's box+ # constraints intersect the geographic rectangle exactly. A projected+ # x/y rectangle does not align with lines of latitude and longitude.+ lon0, lat0 = candidate["lon"], candidate["lat"]+ bounds, (lon_scale, lat_scale) = _geographic_refinement_frame(candidate, radius_m, bounds_wsen)initial = np.zeros(2) if fixed_clock else np.array([0.0, 0.0, np.clip(0.0, lower, upper)])if not fixed_clock:bounds.append((lower, upper))@@ -719,8 +741,12 @@ def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=for offset in altitude_offsets_m:def evaluate(parameters):dt = lower if fixed_clock else parameters[2]- latlon = inverse.transform(x0 + parameters[0], y0 + parameters[1])- lon, lat = latlon+ if bounds_wsen is None:+ lon, lat = inverse.transform(x0 + parameters[0], y0 + parameters[1])+ else:+ # Clip only roundoff at the closed geographic boundary.+ lon = float(np.clip(lon0 + parameters[0]/lon_scale, west, east))+ lat = float(np.clip(lat0 + parameters[1]/lat_scale, south, north))elevation = float(np.asarray(terrain.sample(lat, lon)))score = score_ridges(selected, events, measurements, ecef(lat, lon, elevation + offset),start + dt, c)@@ -737,7 +763,8 @@ def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=if not np.isfinite(score["score"]):continuedt = lower if fixed_clock else parameters[2]- spatial_boundary = bool(np.any(np.abs(parameters[:2]) >= radius_m * 0.98))+ spatial_boundary = any(min(value-lo, hi-value) <= radius_m * 0.02+ for value, (lo, hi) in zip(parameters[:2], bounds[:2]))clock_boundary = bool(not fixed_clock and min(dt-lower, upper-dt) <= (upper-lower)*0.02)profiles.append(dict(score, lat=lat, lon=lon, elev_m=elevation,recording_start_time_s=float(start + dt), altitude_offset_m=float(offset),@@ -763,7 +790,7 @@ def refine_candidate(candidate, tracks, events, measurements, terrain, radius_m=def profile_candidate(candidate, tracks, events, measurements, terrain, *,recording_start_window_s=None, radius_m=500.0, clock_radius_s=5.0,altitude_uncertainty_m=150.0, sound_speed_uncertainty_mps=5.0,- c=343.0, crs="EPSG:5070"):+ c=343.0, crs="EPSG:5070", bounds_wsen=None):"""Run declared perturbations, retaining failures and boundary limitations.These finite engineering scenarios are not a calibrated confidence region.@@ -775,7 +802,7 @@ def profile_candidate(candidate, tracks, events, measurements, terrain, *,raise ValueError("Sensitivity ranges must be nonnegative and sound speed must remain positive")kwargs = dict(radius_m=radius_m, clock_radius_s=clock_radius_s,altitude_offsets_m=(0.0,), crs=crs, c=c,- recording_start_window_s=recording_start_window_s)+ recording_start_window_s=recording_start_window_s, bounds_wsen=bounds_wsen)nominal = refine_candidate(candidate, tracks, events, measurements, terrain, **kwargs)scenarios = [("nominal", "nominal", events, measurements, {})]for sign in (-1, 1):diff --git a/tests/test_refinement_geographic_bounds.py b/tests/test_refinement_geographic_bounds.pynew file mode 100644index 0000000..01a630a--- /dev/null+++ b/tests/test_refinement_geographic_bounds.py@@ -0,0 +1,36 @@+"""Geometry regressions from real regional recording searches; no flight fixtures."""++import pytest++from dopplergeist.matching import _geographic_refinement_frame+++ ("candidate", "area", "axis", "side", "edge"),+ [+ # ESID 762: finalist at the eastern edge of the Texas Hill Country box.+ ({"lat": 30.35453271220664, "lon": -98.73000004871692},+ [-98.98, 30.29, -98.73, 30.47], 0, 1, -98.73),+ # ESID 914: finalist at the northern edge of the south Dallas box.+ ({"lat": 32.63999999897584, "lon": -97.19999995501699},+ [-97.20, 32.46, -97.01, 32.64], 1, 1, 32.64),+ # The same finalist is also at the box's western edge.+ ({"lat": 32.63999999897584, "lon": -97.19999995501699},+ [-97.20, 32.46, -97.01, 32.64], 0, 0, -97.20),+ ],+)+def test_refinement_frame_intersects_real_search_edge(candidate, area, axis, side, edge):+ limits, scales = _geographic_refinement_frame(candidate, 500.0, area)+ assert all(lo <= 0 <= hi for lo, hi in limits)+ assert all(-500.0 <= lo <= hi <= 500.0 for lo, hi in limits)+ origin = (candidate["lon"], candidate["lat"])[axis]+ assert origin + limits[axis][side] / scales[axis] == pytest.approx(edge, abs=1e-12)+++def test_refinement_rejects_real_out_of_scope_seed():+ # The top candidate returned by the earlier ESID 914 run escaped both edges.+ with pytest.raises(ValueError, match="seed must lie within"):+ _geographic_refinement_frame(+ {"lat": 32.64565044189285, "lon": -97.20311082897912},+ 500.0, [-97.20, 32.46, -97.01, 32.64],+ )