Skip to content

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

Batch surviving clock trials and reuse validated score bounds

Cinna Davis3725e9d2027d
diff --git a/.github/workflows/perf-replay-inputs.yml b/.github/workflows/perf-replay-inputs.yml
deleted file mode 100644
index d6b5ea3..0000000
--- a/.github/workflows/perf-replay-inputs.yml
+++ /dev/null
@@ -1,43 +0,0 @@
-name: Real performance replay inputs
-on:
- push:
- branches: [perf/measured-hotpath-20261103]
- paths: [.github/workflows/perf-replay-inputs.yml]
-permissions:
- contents: read
-jobs:
- inputs:
- runs-on: ubuntu-latest
- timeout-minutes: 20
- steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-python@v5
- with:
- python-version: '3.12'
- - name: Install runtime
- run: python -m pip install .
- - name: Restore public real observations
- env:
- GH_TOKEN: ${{ github.token }}
- run: python scripts/restore_artifacts.py --bundle data-source --bundle data-adsb-derived --bundle data-terrain
- - name: Prepare reusable regional index
- run: python scripts/prepare_reference_upload.py --data-root data --output performance-inputs
- - name: Download public offline dependency wheels
- run: python -m pip download --dest performance-inputs/wheels pyproj pyarrow rasterio soundfile pytest
- - name: Package inputs
- run: |
- python - <<'PY'
- from pathlib import Path
- import json, tarfile
- root = Path('.')
- with tarfile.open('real-performance-inputs.tar.gz', 'w:gz', compresslevel=3) as out:
- for name in ('performance-inputs', 'data/source', 'data/terrain'):
- out.add(root / name, arcname=name)
- print('bundle_bytes', Path('real-performance-inputs.tar.gz').stat().st_size)
- PY
- - uses: actions/upload-artifact@v4
- with:
- name: real-performance-inputs
- path: real-performance-inputs.tar.gz
- compression-level: 0
- retention-days: 3
diff --git a/.github/workflows/real-performance.yml b/.github/workflows/real-performance.yml
new file mode 100644
index 0000000..f7863d7
--- /dev/null
+++ b/.github/workflows/real-performance.yml
@@ -0,0 +1,71 @@
+name: Real performance comparison
+on:
+ workflow_dispatch:
+ inputs:
+ baseline:
+ description: Scalar-consistent baseline commit
+ default: d7cc1dd2e8089768253492b3269dfae97b3ad1a4
+ required: true
+ push:
+ branches: [perf/measured-hotpath-20261103]
+ paths: [.github/workflows/real-performance.yml]
+permissions:
+ contents: read
+jobs:
+ compare:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ env:
+ OPENBLAS_NUM_THREADS: '1'
+ OMP_NUM_THREADS: '1'
+ MKL_NUM_THREADS: '1'
+ PYTHONPATH: src
+ BASELINE_REF: ${{ inputs.baseline || 'd7cc1dd2e8089768253492b3269dfae97b3ad1a4' }}
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Install runtime
+ run: python -m pip install '.[test]'
+ - name: Restore public recorded observations
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: python scripts/restore_artifacts.py --bundle data-adsb-derived --bundle data-terrain
+ - name: Prepare index and baseline
+ run: |
+ python scripts/prepare_reference_upload.py --data-root data --output benchmark-inputs
+ baseline_commit=$(git rev-parse --verify --end-of-options "${BASELINE_REF}^{commit}")
+ git worktree add --detach "$RUNNER_TEMP/baseline" "$baseline_commit"
+ - name: Freeze real workloads
+ run: |
+ for width in 120 10; do
+ python scripts/benchmark_prepared_measurements.py prepare --discovery evidence/audio/w1-sensitivity-20261102/reference/discovery.json --index benchmark-inputs/reference-region.sqlite --clock-half-width-s "$width" --output "benchmark-inputs/point-$width.json"
+ done
+ - name: Real-input regression tests
+ env:
+ DOPPLERGEIST_REAL_CPA_FIXTURE: benchmark-inputs/point-120.json
+ run: python -m pytest -q tests/test_real_prepared_measurements.py tests/test_real_geometry_kinematics.py tests/test_real_batch_scalar_parity.py
+ - name: Compare complete payloads and timings
+ run: |
+ for width in 10 120; do
+ python scripts/benchmark_prepared_measurements.py compare --fixture "benchmark-inputs/point-$width.json" --baseline-source "$RUNNER_TEMP/baseline/src" --current-source src --repeats 2 --timeout-s 600 --output "results/performance-$width"
+ done
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: real-performance-summary
+ path: |
+ results/performance-*/comparison.json
+ results/performance-*/*/summary.json
+ if-no-files-found: ignore
+ retention-days: 14
+ - uses: actions/upload-artifact@v4
+ if: failure()
+ with:
+ name: real-performance-failure-diagnostics
+ path: results/performance-*
+ if-no-files-found: ignore
+ retention-days: 3
diff --git a/scripts/benchmark_prepared_measurements.py b/scripts/benchmark_prepared_measurements.py
new file mode 100644
index 0000000..dc42c9a
--- /dev/null
+++ b/scripts/benchmark_prepared_measurements.py
@@ -0,0 +1,291 @@
+"""Compare complete point scoring on recorded ridges and historical trajectories.
+
+The archived research candidate supplies workload coordinates and a clock, not
+independent truth. Each source runs in a separate interpreter with bounded work
+and identical observed inputs. This script generates no audio or trajectories.
+"""
+from __future__ import annotations
+
+import argparse
+from dataclasses import asdict
+import json
+import os
+from pathlib import Path
+import statistics
+import subprocess
+import sys
+import time
+
+try:
+ import resource
+except ImportError: # Windows does not provide the Unix resource module.
+ resource = None
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def json_scalar(value):
+ if hasattr(value, "tolist"):
+ return value.tolist()
+ raise TypeError(f"Cannot serialize {type(value).__name__}")
+
+
+def write_new(path, value):
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("x") as output:
+ json.dump(value, output, indent=2, allow_nan=True, default=json_scalar)
+ output.write("\n")
+
+
+def canonical(value):
+ return json.dumps(value, sort_keys=True, separators=(",", ":"),
+ allow_nan=True, default=json_scalar)
+
+
+def prepare(args):
+ import pandas as pd
+ from dopplergeist.data_access import FlightIndex
+ from dopplergeist.geometry import AcousticSupportError, ecef
+ from dopplergeist.matching import prepare_events
+ from dopplergeist.search import cpa_table
+ from dopplergeist.tiled_search import SearchBudget, _support_error
+
+ if args.output.exists():
+ raise FileExistsError(f"Choose a new fixture path: {args.output}")
+ discovery = json.loads(args.discovery.read_text())
+ report = json.loads(args.reference_report.read_text())
+ seed = report[0] if isinstance(report, list) else report["best"]
+ point = {key: seed[key] for key in ("point_id", "lat", "lon", "elev_m", "x", "y")}
+ clock = float(seed["recording_start_time_s"])
+ events, measurements = prepare_events(discovery["events"])
+ index = FlightIndex(args.index)
+ window = [clock - args.clock_half_width_s, clock + args.clock_half_width_s]
+ query_time = [window[0] - 120.0, window[1] + max(e["end_s"] for e in events) + 120.0]
+ if args.full_day:
+ query_time = list(index.report["coverage"]["time_range_s"])
+ query_bounds = list(index.report["coverage"]["bounds"])
+ budget = SearchBudget(max_tracks_per_tile=args.max_tracks,
+ max_track_samples_per_tile=args.max_samples,
+ max_candidates_per_tile=args.max_candidates, top_k=args.top_k)
+ tracks, samples = [], 0
+ for track in index.query(query_bounds, query_time):
+ tracks.append(track)
+ samples += len(track.time)
+ if len(tracks) > args.max_tracks or samples > args.max_samples:
+ raise ValueError("Declared trajectory budget exceeded; no input was silently truncated")
+ if not tracks:
+ raise ValueError("The declared real-data query returned no trajectories")
+ points = pd.DataFrame([point])
+ observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())
+ radius = max(e["slant_range_m"][1] for e in events)
+ tables, unsupported, row_count = [], [], 0
+ for track in tracks:
+ try:
+ if track.outside_observer_radius(observers, radius):
+ continue
+ table = cpa_table([track], points, radius, step_s=budget.cpa_step_s)
+ except AcousticSupportError as error:
+ unsupported.append(_support_error(error))
+ continue
+ row_count += len(table)
+ if row_count > budget.max_cpa_rows:
+ raise ValueError("Declared CPA budget exceeded; no rows were silently truncated")
+ if len(table):
+ tables.append(table)
+ if not tables:
+ raise ValueError("The real-data point has no supported CPA rows")
+ fixture = {
+ "scope": "Recorded-input computation comparison; source-informed receiver/clock, no accuracy claim",
+ "discovery_source": str(args.discovery.resolve()),
+ "reference_report": str(args.reference_report.resolve()),
+ "real_index": str(args.index.resolve()), "index_input_hash": index.report["input_hash"],
+ "events": discovery["events"], "point": point,
+ "query_bounds": query_bounds, "query_time_s": query_time,
+ "track_ids": [track.id for track in tracks],
+ "cpa_rows": pd.concat(tables, ignore_index=True).to_dict(orient="records"),
+ "unsupported_cpa_tracks": unsupported,
+ "budget": asdict(budget), "scoring": {"mode": "robust_ridge"},
+ "recording_start_window_s": None if args.full_day else window,
+ "counts": {"trajectories": len(tracks), "trajectory_samples": samples,
+ "ridge_records": len(discovery["events"]), "independent_groups": len(events),
+ "ridge_samples": sum(len(measurement[1]) for measurement in measurements),
+ "cpa_rows": row_count, "unsupported_cpa_tracks": len(unsupported)},
+ }
+ write_new(args.output, fixture)
+ print(json.dumps({"fixture": str(args.output), **fixture["counts"],
+ "scope": fixture["scope"]}), flush=True)
+
+
+def worker(args):
+ source = args.source.resolve()
+ sys.path.insert(0, str(source))
+ import dopplergeist
+ import pandas as pd
+ from dopplergeist import matching, tiled_search
+ from dopplergeist.data_access import FlightIndex
+ from dopplergeist.finite_search import RetentionLedger
+ from dopplergeist.geometry import AcousticSupportError, Track
+
+ if Path(dopplergeist.__file__).resolve().parent != source / "dopplergeist":
+ raise RuntimeError("Comparison imported a different source tree")
+ fixture = json.loads(args.fixture.read_text())
+ index = FlightIndex(args.index or fixture["real_index"])
+ if index.report["input_hash"] != fixture["index_input_hash"]:
+ raise ValueError("The real trajectory index no longer matches the fixture")
+ budget = tiled_search.SearchBudget(**fixture["budget"])
+ loaded_at = time.perf_counter()
+ tracks = list(index.lookup(fixture["track_ids"], max_tracks=budget.max_tracks_per_tile,
+ max_samples=budget.max_track_samples_per_tile))
+ if sorted(track.id for track in tracks) != sorted(fixture["track_ids"]):
+ raise ValueError("The index is missing a recorded trajectory")
+ events, measurements = matching.prepare_events(fixture["events"])
+ points = pd.DataFrame([fixture["point"]])
+ load_seconds = time.perf_counter() - loaded_at
+ args.output.mkdir(parents=True, exist_ok=False)
+ ledger = RetentionLedger(args.output / "retention.sqlite", "recorded-point-benchmark",
+ "matched_group_support_minus_normalized_residual")
+ stage = "coarse:recorded-point"
+ operations = {"scalar_fit_calls": 0, "acoustic_calls": 0, "scored_candidates": 0}
+ all_rows = []
+ original_fit, original_acoustic = matching._fit_ridge_uncached, Track.acoustic
+ original_score = tiled_search.score_candidate
+
+ def counted_fit(*values, **options):
+ operations["scalar_fit_calls"] += 1
+ return original_fit(*values, **options)
+
+ def counted_acoustic(*values, **options):
+ operations["acoustic_calls"] += 1
+ return original_acoustic(*values, **options)
+
+ def captured_score(*values, **options):
+ operations["scored_candidates"] += 1
+ try:
+ result = original_score(*values, **options)
+ except AcousticSupportError as error:
+ all_rows.append({"support_failure": tiled_search._support_error(error)})
+ raise
+ all_rows.append(result)
+ return result
+
+ matching._fit_ridge_uncached, Track.acoustic = counted_fit, counted_acoustic
+ tiled_search.score_candidate = captured_score
+ began, cpu = time.perf_counter(), time.process_time()
+ try:
+ ranked, counts = tiled_search._score(
+ points, tracks, events, measurements, budget, fixture["scoring"], {},
+ start_window=fixture["recording_start_window_s"], ledger=ledger, stage=stage)
+ finally:
+ elapsed, cpu_seconds = time.perf_counter() - began, time.process_time() - cpu
+ matching._fit_ridge_uncached, Track.acoustic = original_fit, original_acoustic
+ tiled_search.score_candidate = original_score
+ # macOS reports bytes and Linux reports KiB. Keep scoring usable where
+ # resource or its unit convention is unavailable, without guessing a value.
+ peak_rss_mib = None
+ if resource is not None and (sys.platform == "darwin" or sys.platform.startswith("linux")):
+ rss_divisor = 1024 * 1024 if sys.platform == "darwin" else 1024
+ peak_rss_mib = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / rss_divisor
+ checksum = ledger.checksum(stage)
+ if not ledger.stage_valid(stage, checksum):
+ raise AssertionError("The scoring pass produced an invalid retention ledger")
+ if not operations["scored_candidates"]:
+ raise AssertionError("The benchmark did not score any real associations")
+ with ledger.connect() as database:
+ retention = {name: database.execute(f"SELECT * FROM {name} ORDER BY 1,2").fetchall()
+ for name in ("records", "bounds", "stages")}
+ write_new(args.output / "results.json", {"ranked": ranked, "counts": counts,
+ "all_scored_candidates": all_rows, "retention": retention})
+ summary = {"wall_seconds": elapsed, "cpu_seconds": cpu_seconds,
+ "load_seconds_excluded": load_seconds, "operations": operations,
+ "peak_rss_mib": peak_rss_mib,
+ "peak_rss_scope": ("Worker lifetime through scoring, including imports and input loading"
+ if peak_rss_mib is not None else "Unavailable on this platform"),
+ "retained": len(ranked), "independent_groups": len(events), "scope": fixture["scope"]}
+ write_new(args.output / "summary.json", summary)
+ print(json.dumps(summary), flush=True)
+
+
+def compare(args):
+ args.output.mkdir(parents=True, exist_ok=False)
+ sources = {"baseline": args.baseline_source.resolve(), "current": args.current_source.resolve()}
+ environment = dict(os.environ)
+ for variable in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"):
+ environment[variable] = "1"
+ runs, expected = [], None
+ for repetition in range(args.repeats):
+ order = ("baseline", "current") if repetition % 2 == 0 else ("current", "baseline")
+ for name in order:
+ output = args.output / f"{repetition + 1}-{name}"
+ command = [sys.executable, str(Path(__file__).resolve()), "_worker", "--source", str(sources[name]),
+ "--fixture", str(args.fixture.resolve()), "--output", str(output.resolve())]
+ if args.index:
+ command.extend(["--index", str(args.index.resolve())])
+ subprocess.run(command, check=True, env=environment, timeout=args.timeout_s)
+ payload = canonical(json.loads((output / "results.json").read_text()))
+ if expected is None:
+ expected = payload
+ elif payload != expected:
+ raise AssertionError(f"Exact candidate, diagnostic, support, or retention mismatch: {output}")
+ summary = json.loads((output / "summary.json").read_text())
+ runs.append({"source": name, "repetition": repetition + 1, **summary})
+ medians = {}
+ for name in sources:
+ medians[name] = {}
+ for metric in ("wall_seconds", "cpu_seconds", "peak_rss_mib"):
+ values = [row[metric] for row in runs if row["source"] == name and row[metric] is not None]
+ medians[name][metric] = statistics.median(values) if values else None
+ report = {"identical_results": True, "repeats": args.repeats,
+ "fixture": str(args.fixture.resolve()),
+ "sources": {name: str(path) for name, path in sources.items()}, "medians": medians,
+ "speedup": {metric: medians["baseline"][metric] / medians["current"][metric]
+ for metric in ("wall_seconds", "cpu_seconds")},
+ "scope": runs[0]["scope"], "runs": runs}
+ write_new(args.output / "comparison.json", report)
+ print(json.dumps({key: report[key] for key in ("identical_results", "medians", "speedup", "scope")}), flush=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+ preparation = commands.add_parser("prepare", help="Freeze a real observed-data scoring workload")
+ preparation.add_argument("--discovery", required=True, type=Path)
+ preparation.add_argument("--index", required=True, type=Path)
+ preparation.add_argument("--reference-report", type=Path,
+ default=ROOT / "evidence/results/reference-local/report.json")
+ preparation.add_argument("--clock-half-width-s", type=float, default=120.0)
+ preparation.add_argument("--full-day", action="store_true", help="Use all indexed times with an unknown clock")
+ preparation.add_argument("--max-tracks", type=int, default=5000)
+ preparation.add_argument("--max-samples", type=int, default=1000000)
+ preparation.add_argument("--max-candidates", type=int, default=20000)
+ preparation.add_argument("--top-k", type=int, default=100)
+ preparation.add_argument("--output", required=True, type=Path)
+ comparison = commands.add_parser("compare", help="Require exact output parity before reporting speedup")
+ comparison.add_argument("--fixture", required=True, type=Path)
+ comparison.add_argument("--index", type=Path)
+ comparison.add_argument("--baseline-source", required=True, type=Path, help="Baseline src/ directory")
+ comparison.add_argument("--current-source", type=Path, default=ROOT / "src")
+ comparison.add_argument("--repeats", type=int, default=3)
+ comparison.add_argument("--timeout-s", type=float, default=600.0)
+ comparison.add_argument("--output", required=True, type=Path)
+ internal = commands.add_parser("_worker", help=argparse.SUPPRESS)
+ internal.add_argument("--source", required=True, type=Path)
+ internal.add_argument("--fixture", required=True, type=Path)
+ internal.add_argument("--index", type=Path)
+ internal.add_argument("--output", required=True, type=Path)
+ args = parser.parse_args()
+ if args.command == "prepare":
+ if args.clock_half_width_s < 0:
+ parser.error("--clock-half-width-s must be nonnegative")
+ sys.path.insert(0, str(ROOT / "src"))
+ prepare(args)
+ elif args.command == "compare":
+ if args.repeats < 1 or args.timeout_s <= 0:
+ parser.error("--repeats and --timeout-s must be positive")
+ compare(args)
+ else:
+ worker(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/dopplergeist/batch_ridge.py b/src/dopplergeist/batch_ridge.py
index fd3c208..78995bd 100644
--- a/src/dopplergeist/batch_ridge.py
+++ b/src/dopplergeist/batch_ridge.py
@@ -1,7 +1,7 @@
-"""Batched versions of the existing robust first-event ridge fits."""
+"""Batched robust ridge fits with the scalar model's arithmetic order."""
import numpy as np
-from .matching import _fit_ridge_uncached, _frequency_scale, _ridge_fit_inputs
+from .matching import _frequency_scale, _ridge_fit_inputs
def first_event_fits(measurement, event, factors, emissions):
@@ -22,6 +22,7 @@ def first_event_fits(measurement, event, factors, emissions):
or not np.all(np.isfinite(emissions)) or fraction <= 0):
return None
low, high = event["f0_range_hz"]
+ # Keep scalar numeric promotion for noncanonical parameter types.
if any(type(value) not in (int, float) for value in (sigma, fraction, low, high)):
return None
y, w = ridge[measured], weights[measured]
@@ -36,17 +37,18 @@ def first_event_fits(measurement, event, factors, emissions):
return None
factor2, u2 = factors**2, u**2
effective = np.broadcast_to(w, factors.shape).copy()
- for _ in range(6):
+ # The scalar fitter squares Python floats here. NumPy's array square
+ # can differ by one ULP, which changes later IRLS steps and mode scores.
+ try:
+ prior = np.fromiter(((2 * sigma / float(value))**2 for value in cap),
+ dtype=float, count=len(cap))
+ except (OverflowError, ZeroDivisionError):
+ return None
+ for iteration in range(6):
weighted_factor2, weighted_factor = effective * factor2, effective * factors
a = np.sum(weighted_factor2, axis=1)
r = np.sum(weighted_factor * y, axis=1)
b = np.sum(weighted_factor2 * u, axis=1)
- # Preserve the scalar fitter's Python-float exponent rounding.
- try:
- prior = np.fromiter(((2 * sigma / float(value))**2 for value in cap),
- dtype=float, count=len(cap))
- except (OverflowError, ZeroDivisionError):
- return None
d = np.sum(weighted_factor2 * u2, axis=1) + prior
s = np.sum(weighted_factor * u * y, axis=1)
determinant = a*d - b*b
@@ -73,11 +75,14 @@ def first_event_fits(measurement, event, factors, emissions):
chosen = candidates[np.arange(len(outside)), np.argmin(costs, axis=1)]
alpha[outside], beta[outside] = chosen[:, 0], chosen[:, 1]
residual = factors * (alpha[:, None] + beta[:, None] * u) - y
- effective = w / np.sqrt(1 + (residual / sigma)**2)
- loss = np.average(2 * sigma**2 * (np.sqrt(1 + (residual / sigma)**2) - 1), weights=w, axis=1)
+ residual_scale = np.sqrt(1 + (residual / sigma)**2)
+ if iteration < 5:
+ effective = w / residual_scale
+ loss = np.average(2 * sigma**2 * (residual_scale - 1), weights=w, axis=1)
try:
- penalty = np.fromiter(((2 * sigma * float(drift) / float(bound))**2 / independent
- for drift, bound in zip(beta, cap)), dtype=float, count=len(cap))
+ penalty = np.fromiter(
+ ((2 * sigma * float(drift) / float(bound))**2 / independent
+ for drift, bound in zip(beta, cap)), dtype=float, count=len(cap))
except (OverflowError, ZeroDivisionError):
return None
score = -np.sqrt(loss + penalty)
@@ -92,12 +97,4 @@ def first_event_fits(measurement, event, factors, emissions):
"rmse_hz": float(rmse[i]), "support_fraction": 1.0, "sample_count": int(len(y)),
"independent_sample_count": independent, "outlier_fraction": float(outlier[i])}
for i in range(len(alpha))]
- # Check representative clocks with the existing fitter. This catches a
- # platform or arithmetic discrepancy and sends the whole batch down the
- # established path instead of using inconsistent fit diagnostics.
- for i in {0, len(results)//2, len(results)-1}:
- scalar = _fit_ridge_uncached(None, None, measurement, 0., event["f0_range_hz"],
- 343., sigma, fraction, acoustic_result=(factors[i], emissions[i]))
- if results[i] != scalar:
- return None
return results
diff --git a/src/dopplergeist/geometry.py b/src/dopplergeist/geometry.py
index 07bc666..ad734b5 100644
--- a/src/dopplergeist/geometry.py
+++ b/src/dopplergeist/geometry.py
@@ -5,13 +5,30 @@ use the same vertical datum. ECEF treats those heights as ellipsoidal; supplying
orthometric heights to both is a documented common-datum approximation.
"""
from dataclasses import dataclass
+from functools import lru_cache
import numpy as np
-from scipy.interpolate import CubicHermiteSpline
+from scipy.interpolate import CubicHermiteSpline, PPoly
from scipy.optimize import minimize_scalar
from scipy.signal import find_peaks
_EMISSION_ITERATION_TOLERANCE_S = 1e-7
+_PACKED_KINEMATICS_MAX_INTERVALS = 4096
+
+
+@lru_cache(maxsize=8)
+def _packed_kinematics(position, velocity):
+ """Evaluate fixed position/velocity splines with one interval lookup.
+
+ Padding the quadratic velocity coefficients with a leading zero keeps the
+ existing polynomial arithmetic. Only small splines enter this cache: eight
+ entries add at most 6 MiB of coefficients and keep eight source pairs alive.
+ Track changes construct new splines, including altitude-bias trials.
+ """
+ coefficients = np.zeros((4, position.c.shape[1], 6))
+ coefficients[:, :, :3] = position.c
+ coefficients[1:, :, 3:] = velocity.c
+ return PPoly.construct_fast(coefficients, position.x, extrapolate=False)
class AcousticSupportError(ValueError):
@@ -82,6 +99,12 @@ class Track:
def speed_vector(self, t):
return self.derivative(np.asarray(t) - self.origin)
+ def _position_velocity(self, t):
+ if len(self.time)-1 > _PACKED_KINEMATICS_MAX_INTERVALS:
+ return self.position(t), self.speed_vector(t)
+ values = _packed_kinematics(self.spline, self.derivative)(np.asarray(t)-self.origin)
+ return values[..., :3], values[..., 3:]
+
def _unsupported_motion_intervals(self, c):
"""Find non-subsonic native spline intervals, caching speed extrema.
@@ -198,9 +221,10 @@ class Track:
initial = self.position(np.clip(t, start, end))
tau = np.clip(t - np.linalg.norm(initial - observer, axis=-1) / c, start, end)
for _ in range(10):
- delta = self.position(tau) - observer
+ position, velocity = self._position_velocity(tau)
+ delta = position - observer
distance = np.linalg.norm(delta, axis=-1)
- radial = np.sum(delta * self.speed_vector(tau), axis=-1) / distance
+ radial = np.sum(delta * velocity, axis=-1) / distance
derivative = 1 + radial / c
if np.any(derivative <= 0):
raise AcousticSupportError(self.id, "non_monotone_arrival")
@@ -212,9 +236,13 @@ class Track:
# even when its unrounded correction exceeds the tolerance.
if np.max(np.abs(correction)) < _EMISSION_ITERATION_TOLERANCE_S or unchanged:
break
- delta = self.position(tau) - observer
- distance = np.linalg.norm(delta, axis=-1)
- radial = np.sum(delta * self.speed_vector(tau), axis=-1) / distance
+ # An unchanged Newton iterate already has these exact values. Otherwise
+ # evaluate the final updated time, including tolerance/iteration exits.
+ if not unchanged:
+ position, velocity = self._position_velocity(tau)
+ delta = position - observer
+ distance = np.linalg.norm(delta, axis=-1)
+ radial = np.sum(delta * velocity, axis=-1) / distance
factor = c / (c + radial)
self._check_motion_support(t, observer, c)
arrival_derivative = 1+radial/c
@@ -273,3 +301,4 @@ def straight_doppler(t_receive, f0, speed, slant, cpa_receive, c=343.0):
tau = (u - np.sqrt((beta * u) ** 2 + (1 - beta ** 2) * (slant / c) ** 2)) / (1 - beta ** 2)
radial = speed ** 2 * tau / np.sqrt(slant ** 2 + (speed * tau) ** 2)
return f0 * c / (c + radial)
+
diff --git a/src/dopplergeist/matching.py b/src/dopplergeist/matching.py
index 65f4e31..b71f393 100644
--- a/src/dopplergeist/matching.py
+++ b/src/dopplergeist/matching.py
@@ -6,7 +6,6 @@ audio fit is a proposal diagnostic, not a reliable exclusion bound for real trac
from collections import OrderedDict
from bisect import bisect_left, bisect_right
from contextvars import ContextVar
-from copy import deepcopy
from dataclasses import dataclass
from functools import wraps
import hashlib
@@ -51,6 +50,26 @@ class _RidgeFitCache:
self.acoustic_entries = OrderedDict()
self.acoustic_bytes = 0
self.acoustic_limit = 32 * 1024 * 1024
+ self.measurement_entries = OrderedDict()
+ self.measurement_bytes = 0
+ self.measurement_limit = 4 * 1024 * 1024
+
+ def prepared_measurement(self, measurement, sigma_hz, drift_fraction, key):
+ """Reuse selected samples only after checking their current content key."""
+ if key in self.measurement_entries:
+ self.measurement_entries.move_to_end(key)
+ return self.measurement_entries[key][0]
+ prepared = _prepare_ridge_fit_inputs(measurement, sigma_hz, drift_fraction)
+ # Include the lazily normalized weights in the bound before allocation.
+ size = prepared.times.nbytes + prepared.ridge.nbytes + 2 * prepared.weight.nbytes + 512
+ if size <= self.measurement_limit and self.max_entries > 0:
+ while (self.measurement_bytes + size > self.measurement_limit or
+ len(self.measurement_entries) >= self.max_entries):
+ _, (_, removed) = self.measurement_entries.popitem(last=False)
+ self.measurement_bytes -= removed
+ self.measurement_entries[key] = (prepared, size)
+ self.measurement_bytes += size
+ return prepared
def acoustic_batch(self, track, observer, starts, times, c):
"""Reuse exact batched propagation inputs within this scoring call."""
@@ -105,14 +124,19 @@ class _RidgeFitCache:
values = np.asarray(values, dtype=float)
observed.update(repr(values.shape).encode())
observed.update(values.tobytes())
- key = (id(track), parameters, observed.digest(), acoustic_key)
+ measurement_key = observed.digest()
+ key = (id(track), parameters, measurement_key, acoustic_key)
if key in self.entries:
self.entries.move_to_end(key)
- return deepcopy(self.entries[key][1])
- result = _fit_ridge_uncached(*arguments, acoustic_result=acoustic_result)
+ return self.entries[key][1].copy()
+ prepared = self.prepared_measurement(measurement, sigma_hz, drift_fraction,
+ (measurement_key, parameters[-2:]))
+ result = _fit_ridge_uncached(*arguments, acoustic_result=acoustic_result, _prepared=prepared)
# Keep the track alive so a different trajectory cannot reuse its id.
+ # Fit diagnostics contain only immutable scalar values, so a shallow copy
+ # gives each caller an independent dictionary without recursive copying.
# The enclosing batch already owns these tracks. Exceptions are not cached.
- self.entries[key] = (track, deepcopy(result))
+ self.entries[key] = (track, result.copy())
if len(self.entries) > self.max_entries:
self.entries.popitem(last=False)
return result
@@ -429,40 +453,65 @@ def _ridge_fit_inputs(measurement, sigma_hz, drift_fraction):
return times, ridge, weight
+@dataclass
+class _PreparedRidge:
+ times: np.ndarray
+ ridge: np.ndarray
+ weight: np.ndarray
+ independent_samples: int | None = None
+ normalized_weight: np.ndarray | None = None
+
+ def fit_values(self):
+ # Preserve the original order: normalization is needed only after the
+ # acoustic model has supplied finite values for all measured samples.
+ if self.normalized_weight is None:
+ count = len(np.unique(self.times))
+ normalized = self.weight * count / self.weight.sum()
+ self.independent_samples = count
+ self.normalized_weight = normalized
+ return self.ridge, self.normalized_weight, self.independent_samples
+
+
+def _prepare_ridge_fit_inputs(measurement, sigma_hz, drift_fraction):
+ times, ridge, weight = _ridge_fit_inputs(measurement, sigma_hz, drift_fraction)
+ measured = np.isfinite(times) & np.isfinite(ridge) & (weight > 0)
+ return _PreparedRidge(times[measured], ridge[measured], weight[measured])
+
+
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):
+ sigma_hz=1.0, drift_fraction=0.02, acoustic_result=None, _prepared=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)
+ prepared = (_prepare_ridge_fit_inputs(measurement, sigma_hz, drift_fraction)
+ if _prepared is None else _prepared)
failed = {"score": -np.inf, "f0_hz": np.nan, "support_fraction": 0.0}
- if measured.sum() < 10:
+ if len(prepared.times) < 10:
return failed
if acoustic_result is None:
- factor, emission, _ = track.acoustic(start_time + times[measured], observer, c)
+ factor, emission, _ = track.acoustic(start_time + prepared.times, observer, c)
else:
factor, emission = acoustic_result
- if factor.shape != times[measured].shape or emission.shape != factor.shape:
+ if factor.shape != prepared.times.shape or emission.shape != factor.shape:
raise ValueError("Batched acoustic result does not match the measured ridge")
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()
+ y, w, independent_samples = prepared.fit_values()
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
effective = w.copy()
basis = (factor**2, u**2)
- for _ in range(6):
+ for iteration in range(6):
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)
+ residual_scale = np.sqrt(1 + (residual / sigma_hz) ** 2)
+ if iteration < 5:
+ effective = w / residual_scale
+ loss = np.average(2 * sigma_hz**2 * (residual_scale - 1), weights=w)
drift = float(fit[1])
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[0]),
@@ -735,3 +784,4 @@ def profile_candidate(candidate, tracks, events, measurements, terrain, *,
"frequency_scale_hz": [_frequency_scale(events[i]) for i in indices],
"clock_bounds_s": [lo, hi]}}
return dict(nominal, sensitivity=sensitivity)
+
diff --git a/src/dopplergeist/search.py b/src/dopplergeist/search.py
index 6606d25..fb717cb 100644
--- a/src/dopplergeist/search.py
+++ b/src/dopplergeist/search.py
@@ -335,6 +335,20 @@ def _ridge_trial_classification(result, events, association):
+def _association_event_ceiling(diagnostic, score, frequency, event, limit):
+ """Validate one fitted group's contribution before tightening a ceiling."""
+ single = {"score_kind": "negative_robust_ridge_loss_hz", "score": score,
+ "event_scores": [score], "f0_hz": [frequency], "event_diagnostics": [diagnostic]}
+ classification, _ = _ridge_trial_classification(single, [event], False)
+ if classification != "evaluated":
+ return 1.0
+ if -score > limit:
+ return -np.inf
+ # Preserve the scorer's operation order and upward rounding, including
+ # noncanonical numeric types handled by the original general bound helper.
+ return float(np.nextafter(1 - (-score) / limit, np.inf))
+
+
def _association_trial_bound(result, events):
"""Bound an incompletely supported association at one shared clock.
@@ -361,18 +375,10 @@ def _association_trial_bound(result, events):
return maximum
contributions = []
for diagnostic, score, frequency, event, limit in zip(diagnostics, scores, frequencies, events, limits):
- single = {"score_kind": "negative_robust_ridge_loss_hz", "score": score,
- "event_scores": [score], "f0_hz": [frequency], "event_diagnostics": [diagnostic]}
- classification, _ = _ridge_trial_classification(single, [event], False)
- if classification != "evaluated":
- contributions.append(1.0)
- continue
- if -score > limit:
+ contribution = _association_event_ceiling(diagnostic, score, frequency, event, limit)
+ if contribution == -np.inf:
return -np.inf
- # Use the scorer's per-event arithmetic, then round every contribution
- # and positive accumulation upward. Subtracting losses from k instead
- # changes the operation order and can understate a floating-point score.
- contributions.append(float(np.nextafter(1 - (-score) / limit, np.inf)))
+ contributions.append(contribution)
upper = 0.0
for contribution in contributions:
upper = float(np.nextafter(upper + contribution, np.inf))
@@ -436,6 +442,97 @@ def _screen_association_trial(tracks, events, measurements, observer, start, c,
"score_kind": "negative_robust_ridge_loss_hz"}, None
+def _ridge_result(diagnostics):
+ 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 _batched_ridge_trials(tracks, events, measurements, observer, starts, c,
+ acoustic_batches, score_floor, use_dual):
+ """Batch only clocks that survive the preceding event's existing screen.
+
+ Event order within each clock is unchanged. A later event sees precisely the
+ clocks that would reach it in the scalar loop. Unsupported batches retain
+ scalar fits, including each clock's first acoustic-support error.
+ """
+ from .acoustic_screen import ridge_trial_rejections
+ from .batch_ridge import first_event_fits
+ from .matching import _frequency_scale, fit_ridge
+
+ diagnostics = [[] for _ in starts]
+ outcomes = [None] * len(starts)
+ active = list(range(len(starts)))
+ rejected_count = floor_count = 0
+ prefixes = [0.0] * len(starts)
+ limits = [3 * _frequency_scale(event) for event in events] if score_floor is not None else []
+ bound_enabled = bool(limits) and all(np.isfinite(value) and value > 0 for value in limits)
+ batches = iter(acoustic_batches)
+ for index, (track, event, measurement) in enumerate(zip(tracks, events, measurements)):
+ if not active:
+ break
+ batch = next(batches)
+ if use_dual and batch is not None:
+ rejected, upper = ridge_trial_rejections(measurement, event, *batch,
+ score_floor=score_floor, group_count=len(events))
+ eligible = []
+ for trial in active:
+ if rejected[trial]:
+ rejected_count += 1
+ outcomes[trial] = (None, -np.inf, None)
+ elif np.isfinite(upper[trial]):
+ floor_count += 1
+ outcomes[trial] = (None, float(upper[trial]), None)
+ else:
+ eligible.append(trial)
+ else:
+ eligible = active
+ fitted = None
+ if batch is not None and len(eligible) >= 4:
+ fitted = first_event_fits(measurement, event,
+ batch[0][eligible], batch[1][eligible])
+ remaining = len(events) - index - 1
+ next_active = []
+ for fit_index, trial in enumerate(eligible):
+ try:
+ if fitted is None:
+ acoustic = None if batch is None else (batch[0][trial], batch[1][trial])
+ fit = fit_ridge(track, observer, measurement, starts[trial],
+ event["f0_range_hz"], c, _frequency_scale(event),
+ event.get("quality", {}).get("source_drift_fraction", 0.02),
+ acoustic_result=acoustic)
+ else:
+ fit = fitted[fit_index]
+ except AcousticSupportError as error:
+ outcomes[trial] = (None, None, error)
+ continue
+ diagnostics[trial].append(fit)
+ if remaining:
+ if bound_enabled:
+ contribution = _association_event_ceiling(
+ fit, fit["score"], fit["f0_hz"], event, limits[index])
+ if contribution == -np.inf:
+ outcomes[trial] = (None, -np.inf, None)
+ continue
+ # Reuse the already validated prefix. Add unperformed
+ # groups one at a time with the identical outward rounding;
+ # capping a prefix or summing losses first changes the bound.
+ prefixes[trial] = math.nextafter(prefixes[trial] + contribution, math.inf)
+ bound = prefixes[trial]
+ for _ in range(remaining):
+ bound = math.nextafter(bound + 1.0, math.inf)
+ bound = min(float(len(events)), bound)
+ if bound < score_floor:
+ outcomes[trial] = (None, bound, None)
+ continue
+ next_active.append(trial)
+ else:
+ outcomes[trial] = (_ridge_result(diagnostics[trial]), None, None)
+ active = next_active
+ return outcomes, rejected_count, floor_count
+
+
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,
score_floor=None):
@@ -524,6 +621,16 @@ def score_candidate(candidate, point, tracks, events, measurements, mode="bright
dual_flags = {}
dual_pruned = 0
floor_dual_pruned = 0
+ batched_trials = None
+ # Bound the retained per-clock diagnostics; large products keep the scalar
+ # traversal rather than allocating an unbounded event-by-clock table.
+ if (mode == "robust_ridge" and not floor_pruned and batches is not None
+ and len(shifts) >= 4 and len(shifts) * len(events) <= 4096):
+ batched_trials, dual_pruned, floor_dual_pruned = _batched_ridge_trials(
+ selected_tracks, events, measurements, observer, anchor + shifts, c,
+ lazy_batches if lazy_batches is not None else batches,
+ score_floor if association else None,
+ association and score_floor is not None and time_origin is None)
for trial, shift in enumerate(() if floor_pruned else shifts):
if mode == "robust_ridge":
from .matching import score_ridges
@@ -534,7 +641,7 @@ def score_candidate(candidate, point, tracks, events, measurements, mode="bright
batch = batches[index]
return None if batch is None else (batch[0][trial], batch[1][trial])
precomputed = ([acoustic_at(index) for index in range(len(events))]
- if batches is not None and lazy_batches is None else None)
+ if batched_trials is None and batches is not None and lazy_batches is None else None)
def dual_flags_at(index):
if index not in dual_flags:
acoustic_at(index)
@@ -560,7 +667,17 @@ def score_candidate(candidate, point, tracks, events, measurements, mode="bright
return float(upper)
return None
try:
- if association and score_floor is not None:
+ if batched_trials is not None:
+ result, upper, error = batched_trials[trial]
+ if error is not None:
+ raise error
+ if result is None:
+ partial_prunes += 1
+ assessment["unknown_trials"] += 1
+ reasons.add("partial_group_score_below_retention_floor")
+ unknown_bounds.append(upper)
+ continue
+ elif association and score_floor is not None:
if not first_batch_attempted and batches is not None and lazy_batches is not None and time_origin is None:
first_batch_attempted = True
acoustic_at(0)
@@ -673,3 +790,4 @@ def rank_candidates(candidates, points, tracks, events, measurements, **kwargs):
if i and i%100==0:
print(f"Scored {i}/{len(candidates)} candidates",flush=True)
return sorted(result,key=lambda r:r["score"],reverse=True)
+
diff --git a/tests/test_real_batch_scalar_parity.py b/tests/test_real_batch_scalar_parity.py
new file mode 100644
index 0000000..0e7d457
--- /dev/null
+++ b/tests/test_real_batch_scalar_parity.py
@@ -0,0 +1,114 @@
+"""Every fitted clock must match the scalar model on actual recorded inputs."""
+import json
+import os
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from dopplergeist.batch_ridge import first_event_fits
+from dopplergeist.data_access import FlightIndex
+from dopplergeist.geometry import ecef
+from dopplergeist.matching import (_fit_ridge_uncached, _frequency_scale,
+ batch_acoustic_trials, prepare_events)
+from dopplergeist.search import filter_association_event
+
+
[email protected](scope="module")
+def recorded():
+ source = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")
+ if not source:
+ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to an actual recorded-data diagnostic")
+ fixture = json.loads(Path(source).read_text())
+ events, measurements = prepare_events(fixture["events"])
+ identifiers = sorted({row["flight_id"] for row in fixture["cpa_rows"]})
+ tracks = {track.id: track for track in FlightIndex(fixture["real_index"]).lookup(identifiers)}
+ point = fixture["point"]
+ observer = ecef(point["lat"], point["lon"], point["elev_m"])
+ return fixture, events, measurements, tracks, observer
+
+
+def assert_all_clocks_equal(measurement, event, factors, emissions):
+ fitted = first_event_fits(measurement, event, factors, emissions)
+ if fitted is None:
+ return 0
+ sigma = _frequency_scale(event)
+ fraction = event.get("quality", {}).get("source_drift_fraction", 0.02)
+ assert len(fitted) == len(factors)
+ for clock, (actual, factor, emitted) in enumerate(zip(fitted, factors, emissions)):
+ expected = _fit_ridge_uncached(None, None, measurement, 0.0,
+ event["f0_range_hz"], 343.0, sigma, fraction,
+ acoustic_result=(factor, emitted))
+ assert actual == expected, f"Batch/scalar mismatch at clock {clock}: {actual!r} != {expected!r}"
+ return len(fitted)
+
+
+def test_every_fitted_clock_matches_scalar_for_recorded_pairs(recorded):
+ fixture, events, measurements, tracks, observer = recorded
+ table = pd.DataFrame(fixture["cpa_rows"])
+ checked = batches = 0
+ for event, measurement in zip(events, measurements):
+ # Cover every recorded CPA eligible for this event, not representative
+ # rows or a selection based on favorable fit scores.
+ for row in filter_association_event(table, event, 5.0, None, 5.0).itertuples():
+ track = tracks.get(row.flight_id)
+ if track is None:
+ continue
+ starts = row.receive_time - event["cpa_receive_s"] + np.linspace(-5.0, 5.0, 21)
+ batch = batch_acoustic_trials([track], [measurement], observer, starts)[0]
+ if batch is None:
+ continue
+ factors, emissions = batch
+ complete = np.all(np.isfinite(factors) & np.isfinite(emissions) & (factors > 0), axis=1)
+ if not np.all(complete):
+ assert first_event_fits(measurement, event, factors, emissions) is None
+ if not np.any(complete):
+ continue
+ count = assert_all_clocks_equal(measurement, event, factors[complete], emissions[complete])
+ checked += count
+ batches += count > 0
+ assert checked > 100 and batches > 1
+
+
+def test_recorded_python_power_roundoff_case(recorded):
+ _, events, measurements, tracks, observer = recorded
+ event_index = next((i for i, event in enumerate(events)
+ if event.get("event_id") == "event-0006"), None)
+ track = tracks.get("ab50b9:11")
+ if event_index is None or track is None:
+ pytest.skip("The supplied recording is not the archived reference roundoff case")
+ event, measurement = events[event_index], measurements[event_index]
+ # This clock came from an actual reference-input search. Array squaring
+ # changed its scalar prior by one ULP and then changed two association rows.
+ # Put it outside the old first/middle/last representative checks.
+ starts = 1788898677.1507423 + np.array([-1.0, 0.0, 1.0, 2.0, 3.0])
+ batch = batch_acoustic_trials([track], [measurement], observer, starts)[0]
+ assert batch is not None
+ assert assert_all_clocks_equal(measurement, event, *batch) == len(starts)
+
+
+def test_noncanonical_numeric_parameters_keep_scalar_fallback(recorded):
+ fixture, events, measurements, tracks, observer = recorded
+ for event, measurement in zip(events, measurements):
+ for row in fixture["cpa_rows"]:
+ track = tracks.get(row["flight_id"])
+ if track is None:
+ continue
+ starts = row["receive_time"] - event["cpa_receive_s"] + np.linspace(-5.0, 5.0, 5)
+ batch = batch_acoustic_trials([track], [measurement], observer, starts)[0]
+ if batch is None or first_event_fits(measurement, event, *batch) is None:
+ continue
+ quality = event.get("quality", {})
+ for key, value in (("frequency_loss_scale_hz", np.float32(_frequency_scale(event))),
+ ("source_drift_fraction", np.float32(quality.get("source_drift_fraction", 0.02)))):
+ changed = dict(event, quality=dict(quality, **{key: value}))
+ assert first_event_fits(measurement, changed, *batch) is None
+ changed = dict(event, f0_range_hz=[np.float64(value) for value in event["f0_range_hz"]])
+ assert first_event_fits(measurement, changed, *batch) is None
+ # Fault-inject a finite but overflowing uncertainty on the same
+ # observed arrays; Python powers must retain the scalar fallback.
+ changed = dict(event, quality=dict(quality, frequency_loss_scale_hz=1e200))
+ assert first_event_fits(measurement, changed, *batch) is None
+ return
+ pytest.fail("No supported real batch available for numeric-type fallback checks")
diff --git a/tests/test_real_geometry_kinematics.py b/tests/test_real_geometry_kinematics.py
new file mode 100644
index 0000000..9b0930a
--- /dev/null
+++ b/tests/test_real_geometry_kinematics.py
@@ -0,0 +1,149 @@
+"""Compare optimized geometry with the former solver on recorded inputs only."""
+import json
+import os
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+import pytest
+
+import dopplergeist.geometry as geometry
+from dopplergeist.data_access import FlightIndex
+from dopplergeist.matching import prepare_events
+from dopplergeist.search import filter_association_event
+
+
[email protected](scope="module")
+def recorded_geometry():
+ source = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")
+ if not source:
+ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to a recorded-input diagnostic")
+ fixture = json.loads(Path(source).read_text())
+ events, measurements = prepare_events(fixture["events"])
+ table = pd.DataFrame(fixture["cpa_rows"])
+ tracks = {track.id: track for track in FlightIndex(fixture["real_index"]).query(
+ fixture["query_bounds"], fixture["query_time_s"])}
+ point = fixture["point"]
+ observer = geometry.ecef(point["lat"], point["lon"], point["elev_m"])
+ calls = []
+ for event, measurement in zip(events, measurements):
+ times, ridge, weights = measurement[0].time, measurement[1], measurement[2]
+ measured = np.isfinite(times) & np.isfinite(ridge) & (weights > 0)
+ rows = filter_association_event(table, event, 5., None, 5.)
+ for row in list(rows.itertuples())[:3]:
+ if row.flight_id in tracks:
+ starts = row.receive_time - event["cpa_receive_s"] + np.linspace(-5., 5., 5)
+ calls.append((tracks[row.flight_id], starts[:, None] + times[measured]))
+ return observer, calls, list(tracks.values())
+
+
+def _original_acoustic(track, receive_time, observer, c=343.):
+ """The pre-optimization Newton loop, including its unconditional final fit.
+
+ This deliberately retains separate position/velocity evaluations as the
+ regression oracle. It uses the same recorded splines and support rules.
+ """
+ t = np.asarray(receive_time, dtype=float)
+ start, end = track.time[[0, -1]]
+ arrival_start = start + np.linalg.norm(track.xyz[0] - observer) / c
+ arrival_end = end + np.linalg.norm(track.xyz[-1] - observer) / c
+ supported = (t >= arrival_start) & (t <= arrival_end)
+ initial = track.position(np.clip(t, start, end))
+ tau = np.clip(t - np.linalg.norm(initial - observer, axis=-1) / c, start, end)
+ for _ in range(10):
+ delta = track.position(tau) - observer
+ distance = np.linalg.norm(delta, axis=-1)
+ radial = np.sum(delta * track.speed_vector(tau), axis=-1) / distance
+ derivative = 1 + radial / c
+ if np.any(derivative <= 0):
+ raise geometry.AcousticSupportError(track.id, "non_monotone_arrival")
+ correction = (tau - t + distance / c) / derivative
+ updated = np.clip(tau - correction, start, end)
+ unchanged = np.array_equal(tau, updated)
+ tau = updated
+ if np.max(np.abs(correction)) < geometry._EMISSION_ITERATION_TOLERANCE_S or unchanged:
+ break
+ delta = track.position(tau) - observer
+ distance = np.linalg.norm(delta, axis=-1)
+ radial = np.sum(delta * track.speed_vector(tau), axis=-1) / distance
+ factor = c / (c + radial)
+ track._check_motion_support(t, observer, c)
+ arrival_derivative = 1 + radial / c
+ if np.any(arrival_derivative <= 0):
+ raise geometry.AcousticSupportError(track.id, "non_monotone_arrival")
+ remaining = (tau - t + distance / c) / arrival_derivative
+ tolerance = np.maximum(1e-7, 4 * np.abs(np.spacing(t)))
+ if np.any(supported & (~np.isfinite(remaining) | (np.abs(remaining) > tolerance))):
+ raise geometry.AcousticSupportError(track.id, "emission_solver_not_converged")
+ return tuple(np.where(supported, value, np.nan) for value in (factor, tau, distance))
+
+
+def _outcome(function, track, query, observer):
+ try:
+ return function(track, query, observer)
+ except geometry.AcousticSupportError as error:
+ return {"track_id": error.track_id, "reason": error.reason,
+ "emission_intervals_s": error.emission_intervals_s,
+ "receive_intervals_s": error.receive_intervals_s}
+
+
+def _assert_same(track, query, observer):
+ expected = _outcome(_original_acoustic, track, query, observer)
+ actual = _outcome(geometry.Track.acoustic, track, query, observer)
+ if isinstance(expected, dict):
+ assert actual == expected
+ return 0
+ assert not isinstance(actual, dict)
+ for old, new in zip(expected, actual):
+ assert old.shape == new.shape
+ assert old.tobytes() == new.tobytes()
+ return int(np.isfinite(actual[0]).sum())
+
+
+def test_recorded_packed_spline_matches_native_and_cpa_grid_queries(recorded_geometry):
+ _, _, tracks = recorded_geometry
+ geometry._packed_kinematics.cache_clear()
+ checked = 0
+ for track in tracks[:12]:
+ # The same interpolation grid as cpa_table, plus archived sample times.
+ query = np.unique(np.r_[track.time,
+ np.arange(track.time[0], track.time[-1], 2.), track.time[-1]])
+ position, velocity = track._position_velocity(query)
+ assert position.tobytes() == track.position(query).tobytes()
+ assert velocity.tobytes() == track.speed_vector(query).tobytes()
+ checked += len(query)
+ assert checked > 100
+ assert 0 < geometry._packed_kinematics.cache_info().currsize <= 8
+
+
+def test_recorded_solver_matches_original_with_bounded_spline_cache(recorded_geometry):
+ observer, calls, _ = recorded_geometry
+ geometry._packed_kinematics.cache_clear()
+ checked = sum(_assert_same(track, query, observer) for track, query in calls)
+ assert checked > 100
+ assert 0 < geometry._packed_kinematics.cache_info().currsize <= 8
+
+
+def test_recorded_solver_fallback_and_native_support_errors(recorded_geometry, monkeypatch):
+ observer, calls, tracks = recorded_geometry
+ monkeypatch.setattr(geometry, "_PACKED_KINEMATICS_MAX_INTERVALS", 0)
+ before = geometry._packed_kinematics.cache_info()
+ checked = sum(_assert_same(track, query, observer) for track, query in calls[:5])
+ assert checked > 0
+ assert geometry._packed_kinematics.cache_info() == before
+
+ # Query arrival envelopes of unsupported intervals in actual archived
+ # tracks. These are solver queries, not invented aircraft observations.
+ failures = 0
+ for track in tracks:
+ for index in track._unsupported_motion_intervals(343.)[:2]:
+ emitted = (track.time[index] + track.time[index + 1]) / 2
+ receive = emitted + np.linalg.norm(track.position(emitted) - observer) / 343.
+ expected = _outcome(_original_acoustic, track, receive, observer)
+ actual = _outcome(geometry.Track.acoustic, track, receive, observer)
+ assert isinstance(expected, dict)
+ assert actual == expected
+ failures += 1
+ if failures >= 4:
+ break
+ assert failures > 0
diff --git a/tests/test_real_prepared_measurements.py b/tests/test_real_prepared_measurements.py
new file mode 100644
index 0000000..30e3d84
--- /dev/null
+++ b/tests/test_real_prepared_measurements.py
@@ -0,0 +1,105 @@
+"""Prepared-input cache invariants on measured ridges and observed trajectories."""
+import copy
+import json
+import os
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+from dopplergeist import matching
+from dopplergeist.data_access import FlightIndex
+from dopplergeist.geometry import AcousticSupportError, ecef
+
+
+def recorded_fit_inputs():
+ source = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")
+ if not source:
+ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to an actual recorded-data diagnostic")
+ fixture = json.loads(Path(source).read_text())
+ events, measurements = matching.prepare_events(fixture["events"])
+ identities = sorted({row["flight_id"] for row in fixture["cpa_rows"]})
+ tracks = {track.id: track for track in FlightIndex(fixture["real_index"]).lookup(identities)}
+ point = fixture["point"]
+ observer = ecef(point["lat"], point["lon"], point["elev_m"])
+ # Prefer a longer recorded ridge; selection never uses fit score or truth.
+ for index in sorted(range(len(events)), key=lambda i: -len(measurements[i][1])):
+ event, measurement = events[index], measurements[index]
+ for row in fixture["cpa_rows"]:
+ track = tracks.get(row["flight_id"])
+ if track is None:
+ continue
+ start = row["receive_time"] - event["cpa_receive_s"]
+ times, ridge, weight = matching._ridge_fit_inputs(measurement, 1.0, 0.02)
+ measured = np.isfinite(times) & np.isfinite(ridge) & (weight > 0)
+ try:
+ factors, emissions, _ = track.acoustic(start + times[measured], observer)
+ except AcousticSupportError:
+ continue
+ if np.all(np.isfinite(factors)) and np.all(np.isfinite(emissions)):
+ return track, observer, measurement, start, event["f0_range_hz"], (factors, emissions)
+ pytest.fail("No physically supported real ridge/trajectory candidate in the fixture")
+
+
+def same(actual, expected):
+ assert json.dumps(actual, sort_keys=True) == json.dumps(expected, sort_keys=True)
+
+
+def test_real_prepared_cache_mutations_and_return_independence(recorded_fit_inputs):
+ track, observer, measurement, start, bounds, acoustics = recorded_fit_inputs
+
+ @matching._cache_ridge_fits
+ def check():
+ def compare(measured, sigma=1.0):
+ args = (track, observer, measured, start, bounds, 343.0, sigma, 0.02)
+ expected = matching._fit_ridge_uncached(*args, acoustic_result=acoustics)
+ actual = matching.fit_ridge(*args, acoustic_result=acoustics)
+ same(actual, expected)
+ actual["f0_hz"] = -123.0
+ same(matching.fit_ridge(*args, acoustic_result=acoustics), expected)
+
+ compare(measurement)
+ # Fault-inject changes into copies of observed arrays. These are cache
+ # controls, not new field recordings or location-accuracy observations.
+ for part in (0, 1, 2):
+ changed = copy.deepcopy(measurement)
+ array = changed[0].time if part == 0 else changed[part]
+ array[0] = np.nextafter(array[0], np.inf)
+ compare(changed)
+ compare(measurement, np.float32(0.3))
+ compare(measurement, np.float64(0.3))
+ cache = matching._ridge_fit_cache.get()
+ assert len(cache.measurement_entries) == 6
+ assert cache.measurement_bytes <= cache.measurement_limit
+ check()
+
+
+def test_real_prepared_cache_capacity_and_validation(recorded_fit_inputs):
+ track, observer, measurement, start, bounds, acoustics = recorded_fit_inputs
+
+ @matching._cache_ridge_fits
+ def check():
+ cache = matching._ridge_fit_cache.get()
+ cache.max_entries = 1
+ for sigma in (1.0, 1.5, 1.0):
+ args = (track, observer, measurement, start, bounds, 343.0, sigma, 0.02)
+ same(matching.fit_ridge(*args, acoustic_result=acoustics),
+ matching._fit_ridge_uncached(*args, acoustic_result=acoustics))
+ assert len(cache.measurement_entries) == 1
+ assert cache.measurement_bytes <= cache.measurement_limit
+ cache.measurement_entries.clear()
+ cache.measurement_bytes = 0
+ cache.measurement_limit = 0
+ args = (track, observer, measurement, start, bounds, 343.0, 2.0, 0.02)
+ same(matching.fit_ridge(*args, acoustic_result=acoustics),
+ matching._fit_ridge_uncached(*args, acoustic_result=acoustics))
+ assert not cache.measurement_entries and cache.measurement_bytes == 0
+ with pytest.raises(ValueError, match="drift fraction"):
+ matching.fit_ridge(track, observer, measurement, start, bounds,
+ drift_fraction=0.2, acoustic_result=acoustics)
+ invalid = copy.deepcopy(measurement)
+ invalid[2][0] = -1.0
+ with pytest.raises(ValueError, match="weights"):
+ matching.fit_ridge(track, observer, invalid, start, bounds, acoustic_result=acoustics)
+ check()