Skip to content

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

[skip ci] Validate fit domain before certified screening and reuse fixed fit terms

Cinna Davisf62aecf0ea9e
diff --cc src/dopplergeist/matching.py
index 5740633,5740633..77cd2b5
--- a/src/dopplergeist/matching.py
+++ b/src/dopplergeist/matching.py
@@@ -106,16 -106,16 +106,19 @@@ def _frequency_scale(event)
max(1.0, quality.get("frequency_uncertainty_hz", 1.0))))
--def _source_fit(factor, u, y, weight, bounds, cap, scale):
++def _source_fit(factor, u, y, weight, bounds, cap, scale, basis=None):
"""Exact two-variable box least squares; avoid iterative bounded solves."""
-- a = np.sum(weight*factor**2)
-- r = np.sum(weight*factor*y)
++ factor2, u2 = (factor**2, u**2) if basis is None else basis
++ weighted_factor2 = weight*factor2
++ weighted_factor = weight*factor
++ a = np.sum(weighted_factor2)
++ r = np.sum(weighted_factor*y)
if not cap:
return np.array([np.clip(r/a, *bounds), 0.0])
-- b = np.sum(weight*factor**2*u)
++ b = np.sum(weighted_factor2*u)
prior = (2*scale/cap)**2
-- d = np.sum(weight*factor**2*u**2)+prior
-- s = np.sum(weight*factor*u*y)
++ d = np.sum(weighted_factor2*u2)+prior
++ s = np.sum(weighted_factor*u*y)
determinant = a*d-b*b
unconstrained = np.array([(r*d-s*b)/determinant, (s*a-r*b)/determinant])
if bounds[0] <= unconstrained[0] <= bounds[1] and abs(unconstrained[1]) <= cap:
@@@ -355,14 -355,14 +358,8 @@@ def prepare_events(detected_events, c=3
return [settings[i] for i in order], [measurements[i] for i in order]
--def _fit_ridge_uncached(track, observer, measurement, start_time, f0_bounds, c=343.0,
-- sigma_hz=1.0, drift_fraction=0.02, acoustic_result=None):
-- """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.
-- """
++def _ridge_fit_inputs(measurement, sigma_hz, drift_fraction):
++ """Validate the same measurement/model domain for fits and score ceilings."""
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:
@@@ -371,6 -371,6 +368,18 @@@
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")
++ return times, ridge, weight
++
++
++def _fit_ridge_uncached(track, observer, measurement, start_time, f0_bounds, c=343.0,
++ sigma_hz=1.0, drift_fraction=0.02, acoustic_result=None):
++ """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.
++ """
++ times, ridge, weight = _ridge_fit_inputs(measurement, sigma_hz, drift_fraction)
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:
@@@ -390,8 -390,8 +399,9 @@@
u = (emission - (emission.min() + emission.max()) / 2) / span
cap = float(np.clip(np.median(y / factor), *f0_bounds)) * drift_fraction
effective = w.copy()
++ basis = (factor**2, u**2)
for _ in range(6):
-- fit = _source_fit(factor, u, y, effective, f0_bounds, cap, sigma_hz)
++ fit = _source_fit(factor, u, y, effective, f0_bounds, cap, sigma_hz, basis)
residual = factor*(fit[0]+fit[1]*u)-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)
diff --cc src/dopplergeist/search.py
index 7760e5e,7760e5e..1a34d04
--- a/src/dopplergeist/search.py
+++ b/src/dopplergeist/search.py
@@@ -376,18 -376,18 +376,6 @@@ def score_candidate(candidate, point, t
raise ValueError("score_floor must be finite") from error
if not np.isfinite(score_floor):
raise ValueError("score_floor must be finite")
-- # The group-count ceiling is valid only for the normalized score's positive loss scales.
-- from .matching import _frequency_scale
-- for event in events:
-- value = _frequency_scale(event)
-- if isinstance(value, (bool, np.bool_)):
-- raise ValueError("Frequency loss scales must be finite and positive")
-- try:
-- scale = float(value)
-- except (TypeError, ValueError, OverflowError) as error:
-- raise ValueError("Frequency loss scales must be finite and positive") from error
-- if not np.isfinite(scale) or scale <= 0:
-- raise ValueError("Frequency loss scales must be finite and positive")
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.
@@@ -422,6 -422,6 +410,19 @@@
# Every accepted group contributes at most one; a strict comparison keeps ties eligible.
floor_pruned = bool(score_floor is not None and len(shifts) > 0 and len(events) < score_floor)
if floor_pruned:
++ # A ceiling must not turn malformed fit inputs into a successful assessment.
++ from .matching import _frequency_scale, _ridge_fit_inputs
++ for event, measurement in zip(events, measurements):
++ value = _frequency_scale(event)
++ if isinstance(value, (bool, np.bool_)):
++ raise ValueError("Frequency loss scales must be finite and positive")
++ try:
++ scale = float(value)
++ except (TypeError, ValueError, OverflowError) as error:
++ raise ValueError("Frequency loss scales must be finite and positive") from error
++ if not np.isfinite(scale) or scale <= 0 or not np.isfinite(3*scale):
++ raise ValueError("Frequency loss scales must be finite and positive")
++ _ridge_fit_inputs(measurement, scale, event.get("quality", {}).get("source_drift_fraction", 0.02))
best["score"] = None
assessment["unknown_trials"] = len(shifts)
reasons.add("matched_group_count_below_score_floor")
diff --cc tests/test_real_score_ceiling_validation.py
index 0000000,53918b5..baa471d
mode 000000,100644..100644
--- a/tests/test_real_score_ceiling_validation.py
+++ b/tests/test_real_score_ceiling_validation.py
@@@ -1,0 -1,38 +1,62 @@@
+ """Validate bound records produced from actual audio and flight candidates."""
+ import copy
+ import json
+ import os
+ from pathlib import Path
+ from types import SimpleNamespace
+
+ import pandas as pd
+ import pytest
+
++from dopplergeist.data_access import FlightIndex
+ from dopplergeist.finite_search import bounded_assessment
+ from dopplergeist.matching import association_candidates, prepare_events
+ from dopplergeist.search import score_candidate
+
+
+ def test_real_score_ceiling_rejects_malformed_support_claims():
+ source = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")
+ if not source:
+ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to the real reference diagnostic")
+ fixture = json.loads(Path(source).read_text())
+ events, measurements = prepare_events(fixture["events"])
+ candidates, _ = association_candidates(pd.DataFrame(fixture["cpa_rows"]), events, max_candidates=20000)
+ singleton = next(candidate for candidate in candidates if len(candidate["event_indices"]) == 1)
+ point = SimpleNamespace(**fixture["point"], x=0.0, y=0.0)
+ row = score_candidate(singleton, point, {}, events, measurements, mode="robust_ridge", score_floor=2.0)
+ assert bounded_assessment(row)
+
+ # A no-fit ceiling cannot certify that unknown trials are rejections.
+ malformed = copy.deepcopy(row)
+ assessment = malformed["scoring_assessment"]
+ assessment["bounded_unknown_rejections"] = assessment["bounded_unknown_trials"]
+ assessment["unknown_score_upper_bound"] = None
+ assert not bounded_assessment(malformed)
+
+ # bool compares equal to one in Python but is not a numeric score ceiling.
+ malformed = copy.deepcopy(row)
+ malformed["scoring_assessment"]["unknown_score_upper_bound"] = True
+ assert not bounded_assessment(malformed)
++
++
++def test_real_singleton_retains_source_drift_parameter_errors():
++ source = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")
++ if not source:
++ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to the real reference diagnostic")
++ fixture = json.loads(Path(source).read_text())
++ events, measurements = prepare_events(fixture["events"])
++ candidates, _ = association_candidates(pd.DataFrame(fixture["cpa_rows"]), events, max_candidates=20000)
++ singleton = next(candidate for candidate in candidates if len(candidate["event_indices"]) == 1)
++ tracks = {track.id: track for track in FlightIndex(fixture["real_index"]).lookup(
++ [singleton["passes"][0]["flight_id"]])}
++ point = SimpleNamespace(**fixture["point"], x=0.0, y=0.0)
++ index = singleton["event_indices"][0]
++ for fraction in (-0.1, 0.2, float("nan")):
++ configured = list(events)
++ configured[index] = dict(events[index], quality=dict(events[index]["quality"],
++ source_drift_fraction=fraction))
++ for floor in (None, 2.0):
++ with pytest.raises(ValueError, match="drift fraction"):
++ score_candidate(singleton, point, tracks, configured, measurements,
++ mode="robust_ridge", score_floor=floor)
++