Skip to content

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

perf: avoid repeated trajectory and CPA preparation (#7)

Cinna Davis15e49b2a3368
diff --git a/.github/workflows/real-performance.yml b/.github/workflows/real-performance.yml
index 2794633..f7ce090 100644
--- a/.github/workflows/real-performance.yml
+++ b/.github/workflows/real-performance.yml
@@ -3,31 +3,34 @@ on:
workflow_dispatch:
inputs:
baseline:
- description: Scalar-consistent baseline commit
- default: d7cc1dd2e8089768253492b3269dfae97b3ad1a4
+ description: Exact baseline commit for both real-input comparisons
+ default: 833c96c98366e18cc93562499f169d45bc0a9e06
required: true
+ regional:
+ description: Also compare the complete regional HTTP workflow
+ type: boolean
+ default: true
push:
- branches: [perf/measured-hotpath-20261103]
+ branches: [perf/measured-hotpath-20261103, perf/single-pass-motion-20261103]
paths:
- .github/workflows/real-performance.yml
- - src/dopplergeist/geometry.py
- - src/dopplergeist/matching.py
- - src/dopplergeist/batch_ridge.py
- - src/dopplergeist/search.py
+ - src/dopplergeist/**
- scripts/benchmark_prepared_measurements.py
+ - scripts/benchmark_real_cpa_rows.py
+ - scripts/benchmark_real_regional_upload.py
- tests/test_real_*.py
permissions:
contents: read
+env:
+ OPENBLAS_NUM_THREADS: '1'
+ OMP_NUM_THREADS: '1'
+ MKL_NUM_THREADS: '1'
+ PYTHONPATH: src
+ BASELINE_REF: ${{ inputs.baseline || '833c96c98366e18cc93562499f169d45bc0a9e06' }}
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:
@@ -35,8 +38,8 @@ jobs:
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- - name: Install runtime
- run: python -m pip install '.[test]'
+ - name: Install runtime and source-tree extensions
+ run: python -m pip install --editable '.[test]'
- name: Restore public recorded observations
env:
GH_TOKEN: ${{ github.token }}
@@ -46,6 +49,9 @@ jobs:
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"
+ if [ -f "$RUNNER_TEMP/baseline/setup.py" ]; then
+ (cd "$RUNNER_TEMP/baseline" && python setup.py build_ext --inplace)
+ fi
- name: Freeze real workloads
run: |
for width in 120 10; do
@@ -54,17 +60,24 @@ jobs:
- 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
+ run: python -m pytest -q tests/test_real_prepared_measurements.py tests/test_real_geometry_kinematics.py tests/test_real_batch_scalar_parity.py tests/test_real_motion_support_batch.py tests/test_real_single_pass_sieve.py
+ - name: Compare real CPA preparation
+ run: python scripts/benchmark_real_cpa_rows.py --baseline-source "$RUNNER_TEMP/baseline/src" --output results/cpa-rows.json --repeats 5 --iterations 20
- name: Compare complete payloads and timings
run: |
+ native_option=()
+ if [ -f src/dopplergeist/_native_ridge.c ]; then
+ native_option=(--require-current-native)
+ fi
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"
+ 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" "${native_option[@]}"
done
- uses: actions/upload-artifact@v4
if: always()
with:
name: real-performance-summary
path: |
+ results/cpa-rows.json
results/performance-*/comparison.json
results/performance-*/*/summary.json
if-no-files-found: ignore
@@ -76,3 +89,70 @@ jobs:
path: results/performance-*
if-no-files-found: ignore
retention-days: 3
+ regional:
+ if: github.ref == 'refs/heads/perf/single-pass-motion-20261103' || (github.event_name == 'workflow_dispatch' && inputs.regional)
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ - name: Install runtime and source-tree extensions
+ run: |
+ python -m pip install --editable '.[test]'
+ if ! command -v ffmpeg >/dev/null; then
+ sudo apt-get update
+ sudo apt-get install -y ffmpeg
+ fi
+ - name: Restore the complete real recording and observed inputs
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: python scripts/restore_artifacts.py --bundle data-source --bundle data-adsb-derived --bundle data-terrain
+ - name: Prepare common inputs and the 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"
+ if [ -f "$RUNNER_TEMP/baseline/setup.py" ]; then
+ (cd "$RUNNER_TEMP/baseline" && python setup.py build_ext --inplace)
+ fi
+ python - <<'PY'
+ import json
+ from pathlib import Path
+ path = Path("benchmark-inputs/operator.json")
+ operator = json.loads(path.read_text())
+ operator["search_workers"] = 1
+ path.write_text(json.dumps(operator, indent=2) + "\n")
+ PY
+ ffmpeg -nostdin -i data/source/reference-recording.wav -ac 1 -ar 48000 -c:a libmp3lame -b:a 96k benchmark-inputs/reference.mp3
+ - name: Measure both complete HTTP arms
+ run: |
+ python scripts/benchmark_real_regional_upload.py --source "$RUNNER_TEMP/baseline/src" --audio benchmark-inputs/reference.mp3 --request benchmarks/reference-regional-upload-request.json --operator benchmark-inputs/operator.json --output results/regional-baseline --timeout-s 600 --threads 1
+ python scripts/benchmark_real_regional_upload.py --source src --audio benchmark-inputs/reference.mp3 --request benchmarks/reference-regional-upload-request.json --operator benchmark-inputs/operator.json --output results/regional-current --timeout-s 600 --threads 1
+ - name: Require complete scientific parity
+ run: python scripts/benchmark_real_regional_upload.py --compare results/regional-baseline results/regional-current --output results/regional-comparison.json
+ - uses: actions/upload-artifact@v4
+ if: always()
+ with:
+ name: real-regional-summary
+ path: |
+ results/regional-*/timing.json
+ results/regional-*/result.json
+ results/regional-*/http-verification.json
+ results/regional-*/pipeline-evidence.json
+ results/regional-comparison.json
+ if-no-files-found: ignore
+ retention-days: 14
+ - uses: actions/upload-artifact@v4
+ if: failure()
+ with:
+ name: real-regional-failure-diagnostics
+ path: |
+ results/regional-*/jobs/*/search/search-report.json
+ results/regional-*/jobs/*/provenance.json
+ results/regional-*/*.log
+ if-no-files-found: ignore
+ retention-days: 3
diff --git a/scripts/benchmark_prepared_measurements.py b/scripts/benchmark_prepared_measurements.py
index 3c3094c..700b461 100644
--- a/scripts/benchmark_prepared_measurements.py
+++ b/scripts/benchmark_prepared_measurements.py
@@ -9,6 +9,7 @@ from __future__ import annotations
import argparse
from dataclasses import asdict
import json
+import math
import os
from pathlib import Path
import statistics
@@ -129,6 +130,10 @@ def worker(args):
if Path(dopplergeist.__file__).resolve().parent != source / "dopplergeist":
raise RuntimeError("Comparison imported a different source tree")
+ native_fit = getattr(matching, "_native_fit_irls", None)
+ backend = getattr(matching, "RIDGE_FIT_BACKEND", "python-irls-v1")
+ if args.require_native and not callable(native_fit):
+ raise RuntimeError("The source-tree native fitter is unavailable; build it in place before timing")
fixture = json.loads(args.fixture.read_text())
index = FlightIndex(args.index or fixture["real_index"])
if index.report["input_hash"] != fixture["index_input_hash"]:
@@ -146,7 +151,8 @@ def worker(args):
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}
+ operations = {"scalar_fit_calls": 0, "acoustic_calls": 0, "scored_candidates": 0,
+ "native_fit_calls": 0, "native_fit_successes": 0}
all_rows = []
original_fit, original_acoustic = matching._fit_ridge_uncached, Track.acoustic
original_score = tiled_search.score_candidate
@@ -159,6 +165,13 @@ def worker(args):
operations["acoustic_calls"] += 1
return original_acoustic(*values, **options)
+ def counted_native(*values, **options):
+ operations["native_fit_calls"] += 1
+ result = native_fit(*values, **options)
+ if result is not None and all(math.isfinite(value) for value in result):
+ operations["native_fit_successes"] += 1
+ return result
+
def captured_score(*values, **options):
operations["scored_candidates"] += 1
try:
@@ -170,6 +183,8 @@ def worker(args):
return result
matching._fit_ridge_uncached, Track.acoustic = counted_fit, counted_acoustic
+ if callable(native_fit):
+ matching._native_fit_irls = counted_native
tiled_search.score_candidate = captured_score
began, cpu = time.perf_counter(), time.process_time()
try:
@@ -179,6 +194,8 @@ def worker(args):
finally:
elapsed, cpu_seconds = time.perf_counter() - began, time.process_time() - cpu
matching._fit_ridge_uncached, Track.acoustic = original_fit, original_acoustic
+ if callable(native_fit):
+ matching._native_fit_irls = native_fit
tiled_search.score_candidate = original_score
expected_counts = fixture.get("expected_counts")
if expected_counts is not None:
@@ -197,6 +214,8 @@ def worker(args):
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")
+ if args.require_native and not operations["native_fit_successes"]:
+ raise AssertionError("The native fitter was available but no successful native fit was timed")
with ledger.connect() as database:
retention = {name: database.execute(f"SELECT * FROM {name} ORDER BY 1,2").fetchall()
for name in ("records", "bounds", "stages")}
@@ -204,6 +223,7 @@ def worker(args):
"all_scored_candidates": all_rows, "retention": retention})
summary = {"wall_seconds": elapsed, "cpu_seconds": cpu_seconds,
"load_seconds_excluded": load_seconds, "operations": operations,
+ "ridge_fit_backend": backend, "native_extension_available": callable(native_fit),
"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"),
@@ -227,6 +247,8 @@ def compare(args):
"--fixture", str(args.fixture.resolve()), "--output", str(output.resolve())]
if args.index:
command.extend(["--index", str(args.index.resolve())])
+ if name == "current" and args.require_current_native:
+ command.append("--require-native")
subprocess.run(command, check=True, env=environment, timeout=args.timeout_s)
payload = canonical(json.loads((output / "results.json").read_text()))
if expected is None:
@@ -274,11 +296,14 @@ def main():
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)
+ comparison.add_argument("--require-current-native", action="store_true",
+ help="Fail unless the timed current worker actually uses its native fitter")
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)
+ internal.add_argument("--require-native", action="store_true", help=argparse.SUPPRESS)
args = parser.parse_args()
if args.command == "prepare":
if args.clock_half_width_s < 0:
@@ -295,3 +320,4 @@ def main():
if __name__ == "__main__":
main()
+
diff --git a/scripts/benchmark_real_cpa_rows.py b/scripts/benchmark_real_cpa_rows.py
new file mode 100644
index 0000000..e2d632b
--- /dev/null
+++ b/scripts/benchmark_real_cpa_rows.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+"""Compare CPA preparation on archived aircraft observations, without fake tracks."""
+from __future__ import annotations
+
+import argparse
+import importlib.util
+import json
+from pathlib import Path
+import statistics
+import sys
+import time
+
+import numpy as np
+import pandas as pd
+
+from dopplergeist.geometry import AcousticSupportError, Track, ecef
+from dopplergeist import search
+from dopplergeist.tracks import _segment_velocity
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def recorded_tracks():
+ """Use the normal gap split and velocity inference on frozen real traces."""
+ tracks = []
+ for source in sorted((ROOT / "research/trajectory-motion/frozen").glob("fresh-*.json")):
+ frame = pd.DataFrame(json.loads(source.read_text())).sort_values("time_s")
+ for part, (_, rows) in enumerate(frame.groupby((frame.time_s.diff() > 30.).cumsum())):
+ if len(rows) < 3:
+ continue
+ velocity, _ = _segment_velocity(rows)
+ tracks.append(Track(f"{rows.flight_id.iloc[0]}:{part}", rows.time_s.to_numpy(),
+ rows.lat.to_numpy(), rows.lon.to_numpy(), rows.alt_m.to_numpy(),
+ str(rows.typecode.iloc[0]), velocity))
+ if not tracks:
+ raise ValueError("Archived real observation inputs are missing")
+ return tracks
+
+
+def recorded_points(tracks, count):
+ """Candidate coordinates sampled from the real traces; no accuracy claim."""
+ locations = np.concatenate([np.column_stack((track.lat, track.lon)) for track in tracks])
+ selected = locations[np.linspace(0, len(locations)-1, count, dtype=int)]
+ return pd.DataFrame({"point_id": np.arange(count), "lat": selected[:, 0],
+ "lon": selected[:, 1], "elev_m": np.zeros(count)})
+
+
+def cpa_stage(module, tracks, points, radius=20000., c=343., step=2., chunk_size=512,
+ row_mode=False):
+ """The bounded track-isolation loop, before acoustic candidate scoring."""
+ observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())
+ point_ids = points.point_id.to_numpy(dtype=int)
+ tables, batches, unsupported = [], [], []
+ for track in tracks:
+ try:
+ if track.outside_observer_radius(observers, radius, c):
+ continue
+ if row_mode:
+ result = module._cpa_rows([track], observers, point_ids, radius, c, step, chunk_size)
+ else:
+ result = module.cpa_table([track], points, radius, c, step, chunk_size)
+ except AcousticSupportError as error:
+ unsupported.append(vars(error))
+ continue
+ if row_mode:
+ if result:
+ batches.append(np.array(result, dtype=search._CPA_DTYPE))
+ elif len(result):
+ tables.append(result)
+ if row_mode:
+ table = (pd.DataFrame.from_records(np.concatenate(batches)) if batches else
+ pd.DataFrame(columns=search._CPA_COLUMNS))
+ else:
+ table = pd.concat(tables, ignore_index=True) if tables else pd.DataFrame(columns=search._CPA_COLUMNS)
+ return table, unsupported
+
+
+def compare(before, after):
+ pd.testing.assert_frame_equal(before[0], after[0], check_exact=True)
+ assert before[1] == after[1], "Unsupported-track accounting changed"
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--baseline-source", type=Path, required=True,
+ help="Baseline src directory from a separate checkout")
+ parser.add_argument("--output", type=Path, required=True)
+ parser.add_argument("--repeats", type=int, default=5)
+ parser.add_argument("--iterations", type=int, default=20)
+ args = parser.parse_args()
+ if args.output.exists():
+ parser.error("Use a new output path")
+ if args.repeats < 1 or args.iterations < 1:
+ parser.error("repeats and iterations must be positive")
+ path = args.baseline_source / "dopplergeist/search.py"
+ spec = importlib.util.spec_from_file_location("dopplergeist._cpa_before", path)
+ baseline = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = baseline
+ spec.loader.exec_module(baseline)
+ tracks = recorded_tracks()
+ workloads = {str(count): recorded_points(tracks, count) for count in (1, 32, 128)}
+ checks = 0
+ for points in workloads.values():
+ wide_ids = pd.concat([points.iloc[:1], points.iloc[:1]], ignore_index=True)
+ wide_ids["point_id"] = [2**53, 2**53+1]
+ for radius, c, step, chunk_size in ((1000., 343., 2., 512), (20000., 343., 2., 512),
+ (20000., 338., 1., 7), (20000., 348., 8., 1),
+ (20000., 343., np.float32(2), 512)):
+ for candidate_points in (points, points.iloc[::-1], pd.concat([points, points], ignore_index=True), wide_ids):
+ old = cpa_stage(baseline, tracks, candidate_points, radius, c, step, chunk_size)
+ new = cpa_stage(search, tracks, candidate_points, radius, c, step, chunk_size, True)
+ compare(old, new)
+ checks += 1
+ supported = []
+ for track in tracks:
+ try:
+ track.validate_motion_support(c)
+ supported.append(track)
+ except AcousticSupportError:
+ pass
+ pd.testing.assert_frame_equal(
+ baseline.cpa_table(supported, candidate_points, radius, c, step, chunk_size),
+ search.cpa_table(supported, candidate_points, radius, c, step, chunk_size),
+ check_exact=True)
+ checks += 1
+ timings = []
+ for name, points in workloads.items():
+ runs = {"baseline": [], "current": []}
+ final = None
+ for repeat in range(args.repeats):
+ arms = [("baseline", baseline, False), ("current", search, True)]
+ if repeat % 2:
+ arms.reverse()
+ for label, module, row_mode in arms:
+ start = time.process_time()
+ for _ in range(args.iterations):
+ result = cpa_stage(module, tracks, points, row_mode=row_mode)
+ runs[label].append(time.process_time()-start)
+ final = result
+ medians = {name: statistics.median(values) for name, values in runs.items()}
+ timings.append({"receiver_points": int(name), "cpa_rows": len(final[0]),
+ "unsupported_tracks": len(final[1]), "iterations_per_trial": args.iterations,
+ "cpu_s": runs, "median_cpu_s": medians,
+ "speedup": medians["baseline"]/medians["current"]})
+ result = {"scope": "CPA preparation on archived real ADS-B observations; excludes acoustic fitting, downloads, and localization accuracy.",
+ "baseline_source": str(args.baseline_source), "tracks": len(tracks),
+ "observed_samples": sum(len(track.time) for track in tracks),
+ "exact_comparisons": checks, "timings": timings}
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ with args.output.open("x") as stream:
+ json.dump(result, stream, indent=2)
+ stream.write("\n")
+ print(json.dumps(result, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/benchmark_real_motion_support.py b/scripts/benchmark_real_motion_support.py
new file mode 100644
index 0000000..33c5cba
--- /dev/null
+++ b/scripts/benchmark_real_motion_support.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python3
+"""Compare motion-support checks on the archived real trajectory audit."""
+import argparse
+from collections import defaultdict
+import importlib.util
+import json
+from pathlib import Path
+import platform
+import statistics
+import sys
+import time
+
+import numpy as np
+
+
+def load_geometry(name, path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def observed_tracks(module, observations):
+ grouped = defaultdict(list)
+ for row in observations:
+ grouped[row["flight_id"]].append(row)
+ tracks = []
+ for identity, rows in sorted(grouped.items()):
+ rows.sort(key=lambda row: row["time_s"])
+ values = {name: np.array([row[name] for row in rows]) for name in
+ ("time_s", "lat", "lon", "alt_m", "east_mps", "north_mps", "up_mps")}
+ velocity = module.velocity_ecef(values["lat"], values["lon"],
+ values["east_mps"], values["north_mps"], values["up_mps"])
+ tracks.append(module.Track(identity, values["time_s"], values["lat"], values["lon"],
+ values["alt_m"], rows[0]["typecode"], velocity))
+ return tracks
+
+
+def arrival_outcome(module, track, receive, observer):
+ try:
+ track._check_motion_support(receive, observer, 343.)
+ except module.AcousticSupportError as error:
+ return {key: getattr(error, key) for key in
+ ("track_id", "reason", "emission_intervals_s", "receive_intervals_s")}
+ return None
+
+
+def main():
+ root = Path(__file__).resolve().parents[1]
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--baseline-geometry", type=Path, required=True)
+ parser.add_argument("--current-geometry", type=Path, default=root/"src/dopplergeist/geometry.py")
+ parser.add_argument("--observations", type=Path,
+ default=root/"research/trajectory-motion/frozen/canonical-observations.json")
+ parser.add_argument("--repetitions", type=int, default=5)
+ parser.add_argument("--interval-calls", type=int, default=1000)
+ parser.add_argument("--arrival-calls", type=int, default=100)
+ parser.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ if min(args.repetitions, args.interval_calls, args.arrival_calls) < 1:
+ parser.error("repetitions and call counts must be positive")
+ if args.output.exists():
+ parser.error("output exists; use a new result path")
+ observations = json.loads(args.observations.read_text())
+ modules = {"baseline": load_geometry("motion_baseline", args.baseline_geometry),
+ "current": load_geometry("motion_current", args.current_geometry)}
+ tracks = {label: observed_tracks(module, observations) for label, module in modules.items()}
+ results = []
+ for before, after in zip(tracks["baseline"], tracks["current"]):
+ middle = len(before.time)//2
+ observer = modules["baseline"].ecef(before.lat[middle], before.lon[middle], 0.)
+ receive = before.time+np.linalg.norm(before.xyz-observer, axis=1)/343.
+ expected = before._unsupported_motion_intervals(343.)
+ actual = after._unsupported_motion_intervals(343.)
+ if not np.array_equal(expected, actual):
+ raise AssertionError(f"Motion interval mismatch for {before.id}")
+ if arrival_outcome(modules["baseline"], before, receive, observer) != arrival_outcome(
+ modules["current"], after, receive, observer):
+ raise AssertionError(f"Arrival support mismatch for {before.id}")
+ for method, count in (("intervals", args.interval_calls), ("arrivals", args.arrival_calls)):
+ runs = {"baseline": [], "current": []}
+ for repetition in range(args.repetitions):
+ order = [("baseline", before), ("current", after)]
+ if repetition % 2:
+ order.reverse()
+ for label, track in order:
+ cpu, wall = time.process_time(), time.perf_counter()
+ for _ in range(count):
+ if method == "intervals":
+ track._unsupported_motion_intervals(343.)
+ else:
+ arrival_outcome(modules[label], track, receive, observer)
+ runs[label].append({"cpu_s": time.process_time()-cpu,
+ "wall_s": time.perf_counter()-wall})
+ medians = {label: {clock: statistics.median(row[clock] for row in trials)
+ for clock in ("cpu_s", "wall_s")}
+ for label, trials in runs.items()}
+ result = {"track_id": before.id, "observations": len(before.time),
+ "unsupported_intervals": len(expected), "method": method,
+ "calls_per_trial": count, "trials": runs, "median": medians,
+ "cpu_speedup": medians["baseline"]["cpu_s"]/medians["current"]["cpu_s"]}
+ results.append(result)
+ print(json.dumps({key: result[key] for key in
+ ("track_id", "method", "median", "cpu_speedup")}), flush=True)
+ report = {"scope": "Warm motion-support checks on four recorded aircraft with known input-motion inconsistencies. No synthesized audio or trajectories; not an end-to-end or location-accuracy benchmark.",
+ "baseline_geometry": str(args.baseline_geometry.resolve()),
+ "current_geometry": str(args.current_geometry.resolve()),
+ "python": platform.python_version(), "numpy": np.__version__,
+ "observation_count": len(observations), "repetitions": args.repetitions,
+ "exact_results": True, "results": results}
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(json.dumps(report, indent=2)+"\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/benchmark_real_regional_upload.py b/scripts/benchmark_real_regional_upload.py
index e548d44..fc200b9 100644
--- a/scripts/benchmark_real_regional_upload.py
+++ b/scripts/benchmark_real_regional_upload.py
@@ -1,8 +1,8 @@
"""Run one fresh regional HTTP arm, or compare two completed arms.
Use the same audio, request, operator, interpreter and verifier for both arms.
-The reference control expects 17 ridges in 15 groups and the original detail
-plots. It measures regional runtime, not accuracy or nationwide completion.
+The reference control expects 17 ridges in 15 groups. Both arms must use the
+same detail-plot policy. It measures regional runtime, not location accuracy.
--check-inputs performs no upload or numerical fit.
--compare requires matched controls before the strict scientific comparison.
"""
@@ -41,7 +41,22 @@ def load_script(name, path):
return module
-def assess_output(output, receipt, expected_ridges, expected_groups):
+def detail_plot_policy(source):
+ """Read the source's default without changing production discovery behavior."""
+ tree = ast.parse((source / "dopplergeist/discovery.py").read_text())
+ discover = next(node for node in tree.body if isinstance(node, ast.FunctionDef)
+ and node.name == "discover_events")
+ defaults = dict(zip((arg.arg for arg in discover.args.kwonlyargs), discover.args.kw_defaults))
+ value = defaults.get("plot_event_details")
+ if value is None:
+ # Historical discovery always produced every event detail plot.
+ return True
+ if not isinstance(value, ast.Constant) or type(value.value) is not bool:
+ raise ValueError("Discovery's detail-plot default must be an explicit boolean")
+ return value.value
+
+
+def assess_output(output, receipt, expected_ridges, expected_groups, detail_plots_enabled=True):
final_path = output / "result.json"
final = json.loads(final_path.read_text()) if final_path.exists() else {}
events = final.get("events", [])
@@ -54,10 +69,11 @@ def assess_output(output, receipt, expected_ridges, expected_groups):
all_groups = (search.get("all_event_groups_considered") is True
and search.get("event_groups_proposed") == groups)
passed = bool(receipt.get("verification_passed") and receipt.get("full_pipeline_requirements_met")
- and counts_match and all_groups and plots == len(events))
+ and counts_match and all_groups and plots == (len(events) if detail_plots_enabled else 0))
return {"control_passed": passed, "event_count": len(events), "independent_groups": groups,
"expected_recording_counts_met": counts_match, "all_groups_considered": all_groups,
- "event_detail_png_count": plots, "verification_passed": receipt.get("verification_passed", False)}
+ "event_detail_png_count": plots, "detail_plots_enabled": detail_plots_enabled,
+ "verification_passed": receipt.get("verification_passed", False)}
def compare_arms(paths, output, expected_ridges, expected_groups):
@@ -70,6 +86,10 @@ def compare_arms(paths, output, expected_ridges, expected_groups):
for key in ("python", "sqlite", "numerical_threads", "cpu_affinity", "numerical_package_versions"):
if any(key not in control for control in controls) or controls[0][key] != controls[1][key]:
raise ValueError(f"Paired runtime control differs or is missing: {key}")
+ # Older benchmark records required detail plots unconditionally.
+ plot_policies = [control.get("detail_plots_enabled", True) for control in controls]
+ if not all(type(policy) is bool for policy in plot_policies) or plot_policies[0] != plot_policies[1]:
+ raise ValueError("Paired detail-plot policies differ or are invalid")
comparator = load_script("regional_upload_comparator", Path(__file__).with_name("compare_real_upload_performance.py"))
runs = [comparator.Run(path) for path in paths] # Refuses active or unfinished workflows.
for key in ("source_sha256", "source_bytes", "request", "verifier_sha256", "python_executable", "python_version"):
@@ -78,9 +98,10 @@ def compare_arms(paths, output, expected_ridges, expected_groups):
operators = [json.loads((path / "operator.json").read_text()) for path in paths]
if operators[0] != operators[1]:
raise ValueError("Paired operator configurations differ")
- checks = [assess_output(path, run.receipt, expected_ridges, expected_groups) for path, run in zip(paths, runs)]
+ checks = [assess_output(path, run.receipt, expected_ridges, expected_groups, policy)
+ for path, run, policy in zip(paths, runs, plot_policies)]
if not all(check["control_passed"] for check in checks):
- raise ValueError("A completed arm does not preserve all expected groups and detail plots")
+ raise ValueError("A completed arm does not preserve all expected groups and its detail-plot policy")
report = comparator.compare_runs(*paths)
report["regional_control"] = {"passed": True, "arms": checks,
"source_revisions": [control["source_revision"] for control in controls]}
@@ -146,17 +167,13 @@ def main():
digest = sha256(audio)
if args.expected_audio_sha256 and digest != args.expected_audio_sha256:
parser.error("MP3 bytes differ from --expected-audio-sha256")
- tree = ast.parse((source / "dopplergeist/discovery.py").read_text())
- discover = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "discover_events")
- defaults = dict(zip((arg.arg for arg in discover.args.kwonlyargs), discover.args.kw_defaults))
- if "plot_event_details" in defaults and not (
- isinstance(defaults["plot_event_details"], ast.Constant) and defaults["plot_event_details"].value is True):
- parser.error("Use the frozen source with the original detail-plot default; opt-in plotting changes this control")
+ plots_enabled = detail_plot_policy(source)
revision = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
os.environ.update({key: str(args.threads) for key in
("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS")})
sys.path.insert(0, str(source))
import dopplergeist
+ from dopplergeist import matching
from dopplergeist.contracts import validate_request
if Path(dopplergeist.__file__).resolve().parent != source / "dopplergeist":
raise RuntimeError("Imported a different dopplergeist source tree")
@@ -166,7 +183,8 @@ def main():
"python": platform.python_version(), "sqlite": sqlite3.sqlite_version,
"numerical_package_versions": {name: importlib.metadata.version(name) for name in
("numpy", "scipy", "pandas", "pyarrow", "pyproj", "rasterio", "soundfile")},
- "numerical_threads": args.threads}
+ "numerical_threads": args.threads, "detail_plots_enabled": plots_enabled,
+ "ridge_fit_backend": getattr(matching, "RIDGE_FIT_BACKEND", "python-irls-v1")}
if args.check_inputs:
print(json.dumps({"inputs_valid": True, "http_started": False, **identity}, indent=2))
return 0
@@ -176,7 +194,7 @@ def main():
receipt = verifier.verify_http(audio, output, request=request, operator=operator,
expect_status="inconclusive", expect_reason="search_incomplete", timeout_s=args.timeout_s,
poll_interval_s=args.poll_interval_s, require_full_pipeline=True)
- assessment = assess_output(output, receipt, args.expected_ridges, args.expected_groups)
+ assessment = assess_output(output, receipt, args.expected_ridges, args.expected_groups, plots_enabled)
timing = {"scope": "Fresh complete-HTTP regional control; source-informed bounds/clock, no location-accuracy claim",
"timing_scope": "HTTP verification and output checks; input checks and imports excluded",
**identity, **assessment, "wall_s": time.perf_counter() - started,
diff --git a/src/dopplergeist/geometry.py b/src/dopplergeist/geometry.py
index ad734b5..9933e0b 100644
--- a/src/dopplergeist/geometry.py
+++ b/src/dopplergeist/geometry.py
@@ -14,6 +14,7 @@ from scipy.signal import find_peaks
_EMISSION_ITERATION_TOLERANCE_S = 1e-7
_PACKED_KINEMATICS_MAX_INTERVALS = 4096
+_MOTION_SUPPORT_INTERVAL_BATCH = 1024
@lru_cache(maxsize=8)
@@ -115,17 +116,20 @@ class Track:
"""
limit = c*(1-1e-10)
suspicious = np.flatnonzero(self._speed_upper >= limit)
- for i in suspicious:
+ if not len(suspicious):
+ return suspicious
+ # Extrema do not change with the sound-speed threshold. Only compute
+ # the intervals that have not been solved on an earlier query.
+ for i in suspicious[np.isnan(self._speed_peak[suspicious])]:
dt = self.time[i+1]-self.time[i]
- if np.isnan(self._speed_peak[i]):
- a, b, d = self.derivative.c[:, i]
- a, b = a*dt**2, b*dt
- stationary = [2*np.dot(b, d), 2*(np.dot(b, b)+2*np.dot(a, d)),
- 6*np.dot(a, b), 4*np.dot(a, a)]
- roots = np.polynomial.polynomial.polyroots(stationary)
- samples = [0., 1.] + [float(r.real) for r in roots
- if abs(r.imag) <= 1e-8 and 0 < r.real < 1]
- self._speed_peak[i] = max(np.linalg.norm((a*u+b)*u+d) for u in samples)
+ a, b, d = self.derivative.c[:, i]
+ a, b = a*dt**2, b*dt
+ stationary = [2*np.dot(b, d), 2*(np.dot(b, b)+2*np.dot(a, d)),
+ 6*np.dot(a, b), 4*np.dot(a, a)]
+ roots = np.polynomial.polynomial.polyroots(stationary)
+ samples = [0., 1.] + [float(r.real) for r in roots
+ if abs(r.imag) <= 1e-8 and 0 < r.real < 1]
+ self._speed_peak[i] = max(np.linalg.norm((a*u+b)*u+d) for u in samples)
return suspicious[self._speed_peak[suspicious] >= limit]
def validate_motion_support(self, c=343.0):
@@ -187,8 +191,59 @@ class Track:
Bezier position boxes conservatively enclose affected arrival times,
without assuming monotonic propagation in an unsupported interval.
"""
+ indices = self._unsupported_motion_intervals(c)
+ if not len(indices):
+ return
+ # Tiny queries are cheaper in the original scalar loop than through
+ # the temporary arrays and sorted-time lookup used by a larger batch.
+ if len(indices) <= 2:
+ return self._check_motion_support_scalar(indices, receive_time, observer, c)
+ query = np.asarray(receive_time).ravel()
+ if not len(query):
+ return
+ if not np.all(query[:-1] <= query[1:]):
+ query = np.sort(query)
+ emissions, arrivals = [], []
+ # Fixed-size interval blocks bound the temporary Bezier arrays while
+ # retaining every unsupported interval in its original order.
+ for first in range(0, len(indices), _MOTION_SUPPORT_INTERVAL_BATCH):
+ selected = indices[first:first+_MOTION_SUPPORT_INTERVAL_BATCH]
+ endpoints = np.column_stack((selected, selected+1))
+ times = self.time[endpoints]
+ dt = (times[:, 1]-times[:, 0])[:, None]
+ p0, p1 = self.xyz[selected], self.xyz[selected+1]
+ velocity = self.speed_vector(times)
+ controls = np.stack((p0, p0+dt*velocity[:, 0]/3,
+ p1-dt*velocity[:, 1]/3, p1), axis=1)
+ lo, hi = controls.min(axis=1), controls.max(axis=1)
+ nearest = np.maximum(np.maximum(lo-observer, observer-hi), 0)
+ farthest = np.maximum(np.abs(lo-observer), np.abs(hi-observer))
+ # Keep the scalar norm reduction used by the original interval loop.
+ # Array-axis reductions can round differently from the 1-D dot product.
+ near = np.fromiter((np.linalg.norm(row) for row in nearest), nearest.dtype, len(selected))
+ far = np.fromiter((np.linalg.norm(row) for row in farthest), farthest.dtype, len(selected))
+ arrival_lo = times[:, 0]+near/c
+ arrival_hi = times[:, 1]+far/c
+ tolerance = np.maximum(1e-7, 4*np.abs(np.spacing(
+ np.maximum(np.abs(arrival_lo), np.abs(arrival_hi)))))
+ lower, upper = arrival_lo-tolerance, arrival_hi+tolerance
+ # Any receive sample lies in an interval iff its first sample at or
+ # above the lower endpoint is also at or below the upper endpoint.
+ # This avoids an interval-by-sample comparison matrix and preserves
+ # inclusive endpoints and repeated times.
+ following = np.searchsorted(query, lower)
+ overlaps = ((following < len(query)) &
+ (query[np.minimum(following, len(query)-1)] <= upper))
+ if np.any(overlaps):
+ emissions.extend(times[overlaps].tolist())
+ arrivals.extend(np.column_stack((lower[overlaps], upper[overlaps])).astype(float).tolist())
+ if emissions:
+ raise AcousticSupportError(self.id, "non_subsonic_motion",
+ emission_intervals_s=emissions, receive_intervals_s=arrivals)
+
+ def _check_motion_support_scalar(self, indices, receive_time, observer, c):
emissions, arrivals = [], []
- for i in self._unsupported_motion_intervals(c):
+ for i in indices:
dt = self.time[i+1]-self.time[i]
p0, p1 = self.xyz[i:i+2]
v0, v1 = self.speed_vector(self.time[i:i+2])
@@ -198,7 +253,6 @@ class Track:
farthest = np.maximum(np.abs(lo-observer), np.abs(hi-observer))
arrival_lo = self.time[i]+np.linalg.norm(nearest)/c
arrival_hi = self.time[i+1]+np.linalg.norm(farthest)/c
- # Enlarge for Unix-epoch rounding rather than excluding an endpoint.
tolerance = max(1e-7, 4*abs(np.spacing(max(abs(arrival_lo), abs(arrival_hi)))))
if np.any((receive_time >= arrival_lo-tolerance) & (receive_time <= arrival_hi+tolerance)):
emissions.append([float(self.time[i]), float(self.time[i+1])])
diff --git a/src/dopplergeist/search.py b/src/dopplergeist/search.py
index 428d981..7c2c2dc 100644
--- a/src/dopplergeist/search.py
+++ b/src/dopplergeist/search.py
@@ -10,6 +10,10 @@ from scipy.spatial import cKDTree
from .geometry import AcousticSupportError, ecef
+_CPA_COLUMNS = ["point_id", "flight_id", "emission_time", "receive_time", "distance_m", "speed_mps"]
+_CPA_DTYPE = np.dtype([(name, "int64" if name == "point_id" else object if name == "flight_id" else "float64")
+ for name in _CPA_COLUMNS])
+
def cpa_table_dense(tracks, points, max_distance, c=343.0, step_s=2.0, chunk_size=256):
"""Vectorized piecewise-linear CPA prefilter; supports repeated local passes.
@@ -81,6 +85,17 @@ def cpa_table(tracks,points,max_distance,c=343.0,step_s=2.0,chunk_size=512):
"""
observers=ecef(points.lat.to_numpy(),points.lon.to_numpy(),points.elev_m.to_numpy())
point_ids=points.point_id.to_numpy(dtype=int)
+ return pd.DataFrame(_cpa_rows(tracks, observers, point_ids, max_distance, c, step_s, chunk_size),
+ columns=_CPA_COLUMNS)
+
+
+def _cpa_rows(tracks, observers, point_ids, max_distance, c=343.0, step_s=2.0, chunk_size=512):
+ """Return the same ordered CPA records without allocating per-track tables.
+
+ Tiled scoring already has ECEF observers and needs to isolate unsupported
+ tracks. It can reuse those observers and materialize one table after the
+ bounded per-track work instead of rebuilding a DataFrame for every query.
+ """
rows=[]
for track in tracks:
track.validate_motion_support(c)
@@ -133,10 +148,9 @@ def cpa_table(tracks,points,max_distance,c=343.0,step_s=2.0,chunk_size=512):
emission_intervals_s=[[float(lo), float(hi)]])
distance = np.sqrt(fit.fun)
if distance <= max_distance:
- rows.append({"point_id": int(point_ids[chosen[oi_edge[j]]]), "flight_id": track.id,
- "emission_time": float(when), "receive_time": float(when + distance/c),
- "distance_m": float(distance),
- "speed_mps": float(np.linalg.norm(track.speed_vector(when)))})
+ rows.append((int(point_ids[chosen[oi_edge[j]]]), track.id,
+ float(when), float(when + distance/c), float(distance),
+ float(np.linalg.norm(track.speed_vector(when)))))
minima=(previous&following&(distance2<=np.r_[np.inf,distance2[:-1]])&
(distance2<np.r_[distance2[1:],np.inf]))
indices=np.flatnonzero(minima)
@@ -158,17 +172,27 @@ def cpa_table(tracks,points,max_distance,c=343.0,step_s=2.0,chunk_size=512):
when=t[start]+fraction[n,edge]*(t[start+1]-t[start])
speed=np.linalg.norm(track.speed_vector(when),axis=1)
for j in np.flatnonzero(distance<=max_distance):
- rows.append({"point_id":int(point_ids[chosen[oi[j]]]),"flight_id":track.id,
- "emission_time":float(when[j]),"receive_time":float(when[j]+distance[j]/c),
- "distance_m":float(distance[j]),"speed_mps":float(speed[j])})
- result=pd.DataFrame(rows,columns=["point_id","flight_id","emission_time","receive_time","distance_m","speed_mps"])
- if not result.empty:
+ rows.append((int(point_ids[chosen[oi[j]]]), track.id,
+ float(when[j]), float(when[j]+distance[j]/c),
+ float(distance[j]), float(speed[j])))
+ if rows:
# A CPA exactly at a sample can be proposed twice under roundoff.
- result=result.sort_values(["point_id","flight_id","emission_time"])
- duplicate=(result.point_id.eq(result.point_id.shift())&result.flight_id.eq(result.flight_id.shift())&
- result.emission_time.diff().abs().lt(step_s*1.1))
- result=result[~duplicate].reset_index(drop=True)
- return result
+ rows.sort(key=lambda row: (row[0], row[1], row[2]))
+ duplicate_tolerance = step_s*1.1
+ previous, retained = None, []
+ for row in rows:
+ # Match pandas' shifted int64 IDs (which become float64) and the
+ # original float64-difference promotion against the caller's step.
+ duplicate = (previous is not None and float(row[0]) == float(previous[0])
+ and row[1] == previous[1]
+ and np.float64(abs(row[2]-previous[2])) < duplicate_tolerance)
+ if not duplicate:
+ retained.append(row)
+ # Match the original simultaneous adjacent-row mask, including a
+ # chain of close proposals: compare with the preceding raw row.
+ previous = row
+ return retained
+ return rows
def filter_event(table, event, time_origin=None, time_tolerance=5.0):
diff --git a/src/dopplergeist/tiled_search.py b/src/dopplergeist/tiled_search.py
index 6cd004b..4d00c74 100644
--- a/src/dopplergeist/tiled_search.py
+++ b/src/dopplergeist/tiled_search.py
@@ -24,7 +24,7 @@ from .finite_search import RetentionLedger, bounded_assessment, classified_asses
from .resource_usage import process_peak_rss_kib
from .geometry import AcousticSupportError, ecef
from .matching import _cache_ridge_fits
-from .search import cpa_table, filter_association_event, pair_candidates, score_candidate
+from .search import _CPA_DTYPE, _cpa_rows, filter_association_event, pair_candidates, score_candidate
def _support_error(error):
@@ -221,18 +221,27 @@ def _track_geometry_digest(track):
return digest.hexdigest()
-def _tracks(indexes, bounds, time_range, budget, *, observers=None, radius=None, c=343.0):
+def _tracks(indexes, bounds, time_range, budget, *, observers=None, radius=None, c=343.0,
+ overload_observers=None):
tracks, identities, samples = [], {}, 0
queried, queried_samples = 0, 0
+ def distant(track):
+ try:
+ return track.outside_observer_radius(observers, radius, c)
+ except AcousticSupportError:
+ # Keep unsupported tracks so the ordinary scorer records their
+ # missing support, even when they appear distant.
+ return False
+
for index in indexes:
for track in index.query(bounds, time_range):
- if observers is not None:
+ if observers is not None or overload_observers is not None:
queried += 1
queried_samples += len(track.time)
- # The retry may inspect extra distant tracks, but it must not
- # turn the original per-tile limits into unbounded work.
- if (queried > 20 * budget.max_tracks_per_tile
+ # The distance sieve may inspect extra distant tracks, but it
+ # must retain the same bounded scan as the former retry.
+ if observers is not None and (queried > 20 * budget.max_tracks_per_tile
or queried_samples > 20 * budget.max_track_samples_per_tile):
raise DataUnavailable("Tile track/sample memory budget exceeded; reduce tile_cells")
# Same track from overlapping daily/source coverage must be identical;
@@ -243,35 +252,45 @@ def _tracks(indexes, bounds, time_range, budget, *, observers=None, radius=None,
if _track_geometry_digest(track) != previous_signature:
raise DataUnavailable(f"Conflicting flight segment identity: {track.id}")
continue
- if observers is not None:
- try:
- distant = track.outside_observer_radius(observers, radius, c)
- except AcousticSupportError:
- # Keep unsupported tracks so the ordinary scorer records
- # their missing support, even when they appear distant.
- distant = False
- if distant:
- identities[track.id] = _track_geometry_digest(track)
- continue
+ if observers is not None and distant(track):
+ identities[track.id] = _track_geometry_digest(track)
+ continue
identities[track.id] = track
tracks.append(track)
samples += len(track.time)
if len(tracks) > budget.max_tracks_per_tile or samples > budget.max_track_samples_per_tile:
- raise DataUnavailable("Tile track/sample memory budget exceeded; reduce tile_cells")
+ if observers is None and overload_observers is not None:
+ # Reuse the already decoded prefix and continue this query.
+ # Sampling terrain remains lazy for ordinary and empty tiles.
+ observers = overload_observers()
+ if (queried > 20 * budget.max_tracks_per_tile
+ or queried_samples > 20 * budget.max_track_samples_per_tile):
+ raise DataUnavailable("Tile track/sample memory budget exceeded; reduce tile_cells")
+ retained, samples = [], 0
+ for buffered in tracks:
+ if distant(buffered):
+ identities[buffered.id] = _track_geometry_digest(buffered)
+ else:
+ retained.append(buffered)
+ samples += len(buffered.time)
+ tracks = retained
+ del buffered
+ if len(tracks) > budget.max_tracks_per_tile or samples > budget.max_track_samples_per_tile:
+ raise DataUnavailable("Tile track/sample memory budget exceeded; reduce tile_cells")
return tracks
def _tracks_for_points(indexes, bounds, time_range, budget, points, terrain, radius, c):
- """Retry an overloaded query after the scorer's conservative distance test."""
- try:
- return _tracks(indexes, bounds, time_range, budget), points
- except DataUnavailable as error:
- if str(error) != "Tile track/sample memory budget exceeded; reduce tile_cells":
- raise
- if "elev_m" not in points:
- points = _sample_tile_terrain(points, terrain)
- observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())
- return _tracks(indexes, bounds, time_range, budget, observers=observers, radius=radius, c=c), points
+ """Switch overloaded queries to the conservative sieve without rereading."""
+ def overload_observers():
+ nonlocal points
+ if "elev_m" not in points:
+ points = _sample_tile_terrain(points, terrain)
+ return ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())
+
+ tracks = _tracks(indexes, bounds, time_range, budget, radius=radius, c=c,
+ overload_observers=overload_observers)
+ return tracks, points
def _association_clock_window(start_window, sweep_s):
@@ -334,7 +353,8 @@ def _clock_children(tile_id, cells, start_window, parameters, filters, events):
def _score(points, tracks, events, measurements, budget, parameters, filters, start_window=None, *, ledger=None, stage=None, score_floor=None, anchor_window=None):
radius = max(e["slant_range_m"][1] for e in events)
observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())
- tables, count = [], 0
+ point_ids = points.point_id.to_numpy(dtype=int)
+ cpa_batches, count = [], 0
unsupported = []
# Bound materialized CPA rows before pairing; one track at a time keeps the
# national traffic count out of the CPA tensor/list allocation.
@@ -345,17 +365,20 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, st
# Even a pathological looping track cannot allocate an unbounded list
# of minima before we inspect the returned table.
chunk_points = max(1, budget.max_cpa_rows // samples)
- track_tables, track_rows = [], 0
+ track_batches, track_rows = [], 0
try:
if track.outside_observer_radius(observers, radius, parameters.get("c", 343.0)):
continue
for first in range(0, len(points), chunk_points):
- table = cpa_table([track], points.iloc[first:first + chunk_points], radius, parameters.get("c", 343.0), budget.cpa_step_s)
- track_rows += len(table)
+ rows = _cpa_rows([track], observers[first:first + chunk_points],
+ point_ids[first:first + chunk_points], radius,
+ parameters.get("c", 343.0), budget.cpa_step_s)
+ track_rows += len(rows)
if count + track_rows > budget.max_cpa_rows:
raise DataUnavailable("Tile CPA-row memory budget exceeded")
- if len(table):
- track_tables.append(table)
+ if rows:
+ track_batches.append(np.array(rows, dtype=_CPA_DTYPE))
+ del rows
except AcousticSupportError as error:
# The typed failure does not identify an exact bad interval. Keep
# the entire track/stage as explicitly unassessed, and retain rows
@@ -368,12 +391,13 @@ def _score(points, tracks, events, measurements, budget, parameters, filters, st
"receiver_point_count": len(points), "coverage_envelope": "whole_track_whole_stage_conservative"})
continue
count += track_rows
- tables.extend(track_tables)
- if not tables:
+ cpa_batches.extend(track_batches)
+ if not cpa_batches:
if ledger is not None:
ledger.record(stage, [], [], 0)
return [], {"cpa_rows": 0, "candidates": 0, "unsupported_cpa_tracks": unsupported}
- table = pd.concat(tables, ignore_index=True)
+ table = pd.DataFrame.from_records(np.concatenate(cpa_batches))
+ del cpa_batches, track_batches
kwargs = dict(offset_tolerance_s=filters.get("offset_tolerance_s", 5.0),
time_origin=parameters.get("time_origin"), time_tolerance_s=filters.get("time_tolerance_s", 5.0),
silence=filters.get("silence"))
diff --git a/tests/test_real_motion_support_batch.py b/tests/test_real_motion_support_batch.py
new file mode 100644
index 0000000..7c28805
--- /dev/null
+++ b/tests/test_real_motion_support_batch.py
@@ -0,0 +1,154 @@
+"""Motion-support checks on the archived four-aircraft observation audit."""
+from collections import defaultdict
+from copy import deepcopy
+import json
+from pathlib import Path
+import unittest
+from unittest.mock import patch
+
+import numpy as np
+
+from dopplergeist import geometry
+
+
+def observed_tracks(relative=False):
+ path = Path(__file__).resolve().parents[1] / "research/trajectory-motion/frozen/canonical-observations.json"
+ grouped = defaultdict(list)
+ for row in json.loads(path.read_text()):
+ grouped[row["flight_id"]].append(row)
+ tracks = []
+ for identity, rows in sorted(grouped.items()):
+ rows.sort(key=lambda row: row["time_s"])
+ values = {name: np.array([row[name] for row in rows]) for name in
+ ("time_s", "lat", "lon", "alt_m", "east_mps", "north_mps", "up_mps")}
+ if relative:
+ # The same observed trajectory expressed on a recording-relative clock.
+ values["time_s"] -= values["time_s"][0]
+ velocity = geometry.velocity_ecef(values["lat"], values["lon"],
+ values["east_mps"], values["north_mps"], values["up_mps"])
+ tracks.append(geometry.Track(identity, values["time_s"], values["lat"], values["lon"],
+ values["alt_m"], rows[0]["typecode"], velocity))
+ return tracks
+
+
+def original_indices(track, c):
+ """Original scalar traversal, including its lazy extrema cache."""
+ limit = c*(1-1e-10)
+ suspicious = np.flatnonzero(track._speed_upper >= limit)
+ for i in suspicious:
+ dt = track.time[i+1]-track.time[i]
+ if np.isnan(track._speed_peak[i]):
+ a, b, d = track.derivative.c[:, i]
+ a, b = a*dt**2, b*dt
+ stationary = [2*np.dot(b, d), 2*(np.dot(b, b)+2*np.dot(a, d)),
+ 6*np.dot(a, b), 4*np.dot(a, a)]
+ roots = np.polynomial.polynomial.polyroots(stationary)
+ samples = [0., 1.] + [float(r.real) for r in roots
+ if abs(r.imag) <= 1e-8 and 0 < r.real < 1]
+ track._speed_peak[i] = max(np.linalg.norm((a*u+b)*u+d) for u in samples)
+ return suspicious[track._speed_peak[suspicious] >= limit]
+
+
+def original_envelopes(track, observer, c):
+ """Original one-interval arithmetic is the endpoint regression oracle."""
+ envelopes = []
+ for i in original_indices(track, c):
+ dt = track.time[i+1]-track.time[i]
+ p0, p1 = track.xyz[i:i+2]
+ v0, v1 = track.speed_vector(track.time[i:i+2])
+ controls = np.array([p0, p0+dt*v0/3, p1-dt*v1/3, p1])
+ lo, hi = controls.min(axis=0), controls.max(axis=0)
+ nearest = np.maximum(np.maximum(lo-observer, observer-hi), 0)
+ farthest = np.maximum(np.abs(lo-observer), np.abs(hi-observer))
+ arrival_lo = track.time[i]+np.linalg.norm(nearest)/c
+ arrival_hi = track.time[i+1]+np.linalg.norm(farthest)/c
+ tolerance = max(1e-7, 4*abs(np.spacing(max(abs(arrival_lo), abs(arrival_hi)))))
+ envelopes.append(([float(track.time[i]), float(track.time[i+1])],
+ [arrival_lo-tolerance, arrival_hi+tolerance]))
+ return envelopes
+
+
+def check_query(track, query, observer, c, envelopes):
+ expected = [(emission, arrival) for emission, arrival in envelopes
+ if np.any((query >= arrival[0]) & (query <= arrival[1]))]
+ try:
+ track._check_motion_support(query, observer, c)
+ except geometry.AcousticSupportError as error:
+ assert expected
+ assert error.track_id == track.id and error.reason == "non_subsonic_motion"
+ assert error.emission_intervals_s == [row[0] for row in expected]
+ assert error.receive_intervals_s == [[float(value) for value in row[1]] for row in expected]
+ else:
+ assert not expected
+
+
+def check_recorded_motion_extrema(relative):
+ for track in observed_tracks(relative):
+ original = deepcopy(track)
+ for c in (343., 338., 348., 600., 1000., 343.):
+ assert np.array_equal(track._unsupported_motion_intervals(c), original_indices(original, c))
+ assert np.array_equal(track._speed_peak, original._speed_peak, equal_nan=True)
+
+
+def check_recorded_arrival_bounds(relative):
+ for track in observed_tracks(relative):
+ for c in (338., 343., 348., 1000.):
+ for location in (0, len(track.time)//2, -1):
+ observer = geometry.ecef(track.lat[location], track.lon[location], 0.)
+ envelopes = original_envelopes(track, observer, c)
+ receive = track.time+np.linalg.norm(track.xyz-observer, axis=1)/c
+ receive.setflags(write=False)
+ for query in (receive, receive[::-1], receive[len(receive)//2], receive[:0],
+ receive[:len(receive)//2*2].reshape(-1, 2),
+ np.r_[receive, receive[0], np.nan, np.inf, -np.inf]):
+ check_query(track, query, observer, c, envelopes)
+ # Test each endpoint alone; a vector containing nearby interior
+ # samples could otherwise hide an inclusive-boundary regression.
+ for _, interval in envelopes:
+ for endpoint in interval:
+ for query in (np.nextafter(endpoint, -np.inf), endpoint,
+ np.nextafter(endpoint, np.inf)):
+ check_query(track, query, observer, c, envelopes)
+
+
+def check_recorded_interval_blocks():
+ for track in observed_tracks():
+ observer = geometry.ecef(track.lat[0], track.lon[0], 0.)
+ receive = track.time+np.linalg.norm(track.xyz-observer, axis=1)/343.
+ check_query(track, receive, observer, 343., original_envelopes(track, observer, 343.))
+
+
+def check_recorded_numeric_precision():
+ for track in observed_tracks():
+ for dtype in (np.float32, np.float64, np.longdouble):
+ observer = geometry.ecef(track.lat[0], track.lon[0], 0.).astype(dtype)
+ for c in (np.float32(343), np.float64(343), np.longdouble(343)):
+ envelopes = original_envelopes(track, observer, c)
+ query = np.asarray([value for _, interval in envelopes for value in interval])
+ query.setflags(write=False)
+ check_query(track, query[::-1], observer, c, envelopes)
+
+
+class RecordedMotionSupportTests(unittest.TestCase):
+ def test_epoch_extrema_after_threshold_changes(self):
+ check_recorded_motion_extrema(False)
+
+ def test_relative_extrema_after_threshold_changes(self):
+ check_recorded_motion_extrema(True)
+
+ def test_epoch_arrival_boundaries_shapes_and_order(self):
+ check_recorded_arrival_bounds(False)
+
+ def test_relative_arrival_boundaries_shapes_and_order(self):
+ check_recorded_arrival_bounds(True)
+
+ def test_interval_block_boundaries(self):
+ with patch.object(geometry, "_MOTION_SUPPORT_INTERVAL_BATCH", 2):
+ check_recorded_interval_blocks()
+
+ def test_scalar_numeric_precision(self):
+ check_recorded_numeric_precision()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_real_single_pass_sieve.py b/tests/test_real_single_pass_sieve.py
new file mode 100644
index 0000000..5c6ab29
--- /dev/null
+++ b/tests/test_real_single_pass_sieve.py
@@ -0,0 +1,144 @@
+"""Loading-budget checks on archived aircraft observations.
+
+Receiver coordinates are calculation controls, not microphone-location truth.
+No audio or aircraft trajectory is generated by these tests.
+"""
+from dataclasses import replace
+import json
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+import pytest
+
+from dopplergeist.data_access import DataUnavailable, FlightIndex
+from dopplergeist.geometry import ecef
+from dopplergeist.tiled_search import SearchBudget, _tracks, _tracks_for_points
+
+
+class QueryProbe:
+ def __init__(self, index):
+ self.index = index
+ self.queries = self.yielded = 0
+
+ def query(self, bounds, window):
+ self.queries += 1
+ for track in self.index.query(bounds, window):
+ self.yielded += 1
+ yield track
+
+
+class NoTerrain:
+ def sample(self, *args):
+ raise AssertionError("This query must not request terrain")
+
+
+def real_query(tmp_path):
+ root = Path(__file__).resolve().parents[1]
+ observations = root / "research/trajectory-motion/frozen/canonical-observations.json"
+ frame = pd.DataFrame(json.loads(observations.read_text()))
+ bounds = [-180., -90., 180., 90.]
+ window = [float(frame.time_s.min()), float(frame.time_s.max())]
+ coverage = {"bounds": bounds, "time_range_s": window, "all_aircraft": False,
+ "source_note": "Archived real observations; incomplete excerpt"}
+ built = FlightIndex.build(tmp_path / "real.sqlite", [frame], sources=[], coverage=coverage)
+ index = FlightIndex(built.path, track_cache_bytes=0)
+ complete = list(index.query(bounds, window))
+ assert len(complete) >= 4
+ workloads = json.loads((root / "tests/data/real-search-workloads.json").read_text())
+ far = pd.DataFrame([workloads["cases"]["previous-fit"]["point"]])
+ track = complete[0]
+ midpoint = len(track.time) // 2
+ near = pd.DataFrame([{"point_id": 0, "lat": track.lat[midpoint],
+ "lon": track.lon[midpoint], "elev_m": 0.}])
+ return index, bounds, window, complete, near, far
+
+
+def assert_track_arrays_equal(got, expected):
+ assert [track.id for track in got] == [track.id for track in expected]
+ for actual, prior in zip(got, expected):
+ for name in ("time", "lat", "lon", "altitude", "xyz"):
+ np.testing.assert_array_equal(getattr(actual, name), getattr(prior, name))
+ np.testing.assert_array_equal(actual.spline.c, prior.spline.c)
+ np.testing.assert_array_equal(actual.derivative.c, prior.derivative.c)
+ assert actual.typecode == prior.typecode
+ assert actual.altitude_basis == prior.altitude_basis
+
+
[email protected]("limiting_field", ["max_tracks_per_tile", "max_track_samples_per_tile"])
+def test_overloaded_query_reads_each_real_segment_once(real_query, limiting_field):
+ index, bounds, window, complete, points, _ = real_query
+ observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())
+ generous = SearchBudget(max_tracks_per_tile=1000, max_track_samples_per_tile=1000000)
+ expected = _tracks([index], bounds, window, generous, observers=observers, radius=20000.)
+ assert 0 < len(expected) < len(complete)
+ limit = len(expected) if limiting_field == "max_tracks_per_tile" else sum(len(t.time) for t in expected)
+ budget = replace(generous, **{limiting_field: limit})
+ with pytest.raises(DataUnavailable, match="Tile track/sample memory budget exceeded"):
+ _tracks([index], bounds, window, budget)
+ probe = QueryProbe(index)
+ got, returned_points = _tracks_for_points([probe], bounds, window, budget,
+ points, NoTerrain(), 20000., 343.)
+ assert_track_arrays_equal(got, expected)
+ assert returned_points is points
+ assert probe.queries == 1
+ assert probe.yielded == len(complete)
+
+
[email protected]("empty", [False, True])
+def test_ordinary_and_empty_queries_do_not_sample_terrain(real_query, empty):
+ index, bounds, window, complete, _, far = real_query
+ if empty:
+ window = [window[0] - 100., window[0] - 50.]
+ points = far.drop(columns="elev_m")
+ probe = QueryProbe(index)
+ tracks, returned_points = _tracks_for_points([probe], bounds, window, SearchBudget(),
+ points, NoTerrain(), 20000., 343.)
+ assert returned_points is points and "elev_m" not in points
+ assert len(tracks) == (0 if empty else len(complete))
+ assert probe.queries == 1
+
+
+def test_overload_preserves_duplicates_and_bounded_scan(real_query):
+ index, bounds, window, complete, _, points = real_query
+ observers = ecef(points.lat.to_numpy(), points.lon.to_numpy(), points.elev_m.to_numpy())
+ budget = SearchBudget(max_tracks_per_tile=1)
+ assert not _tracks([index], bounds, window, SearchBudget(), observers=observers, radius=20000.)
+ probe = QueryProbe(index)
+ retained, _ = _tracks_for_points([probe, probe], bounds, window, budget,
+ points, NoTerrain(), 20000., 343.)
+ assert not retained
+ assert probe.queries == 2 and probe.yielded == 2 * len(complete)
+ probe = QueryProbe(index)
+ with pytest.raises(DataUnavailable, match="Tile track/sample memory budget exceeded"):
+ _tracks_for_points([probe] * 21, bounds, window, budget,
+ points, NoTerrain(), 20000., 343.)
+ assert probe.yielded == 21 # The inherited 20x scan budget remains inclusive.
+
+
+def test_retained_budget_failure_is_not_hidden_by_sieve(real_query):
+ index, bounds, window, complete, points, _ = real_query
+ probe = QueryProbe(index)
+ budget = SearchBudget(max_tracks_per_tile=1)
+ with pytest.raises(DataUnavailable, match="Tile track/sample memory budget exceeded"):
+ _tracks_for_points([probe], bounds, window, budget, points, NoTerrain(), 10000000., 343.)
+ assert probe.queries == 1
+ assert probe.yielded <= len(complete)
+
+
+def test_pruned_prefix_still_detects_conflicting_real_geometry(real_query):
+ index, bounds, window, complete, _, points = real_query
+
+ class ConflictingIndex:
+ def query(self, bounds, window):
+ for track in index.query(bounds, window):
+ if track.id == complete[1].id:
+ # An ID collision between two actual observed trajectories
+ # must still fail after the earlier geometry was pruned.
+ track.id = complete[0].id
+ yield track
+
+ with pytest.raises(DataUnavailable, match="Conflicting flight segment identity"):
+ _tracks_for_points([index, ConflictingIndex()], bounds, window,
+ SearchBudget(max_tracks_per_tile=1), points, NoTerrain(), 20000., 343.)