Skip to content

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

perf: fuse exact acoustic propagation and enable optional native ridge fitting

Cinna Davis4abd58b6ac9f
diff --cc .github/workflows/real-performance.yml
index 2f127b9,e7a813c..034a39f
--- a/.github/workflows/real-performance.yml
+++ b/.github/workflows/real-performance.yml
@@@ -3,21 -3,15 +3,22 @@@ on
workflow_dispatch:
inputs:
baseline:
- description: Scalar-consistent baseline commit
- default: d7cc1dd2e8089768253492b3269dfae97b3ad1a4
+ description: Exact baseline commit for both real-input comparisons
- default: d9649ee5e369b31072d40c4882a5b7e0a7bfa177
++ default: a4d27b2cacfe53fdcb4dfbce4d533d4c7eb9436d
required: true
+ regional:
+ description: Also compare the complete regional HTTP workflow
+ type: boolean
+ default: true
push:
- branches: [perf/measured-hotpath-20261103, perf/real-pipeline-throughput-20261103]
+ branches: [perf/measured-hotpath-20261103, perf/real-pipeline-throughput-20261103, perf/single-pass-motion-20261103]
paths:
- .github/workflows/real-performance.yml
- src/dopplergeist/**
- scripts/benchmark_prepared_measurements.py
+ - scripts/benchmark_real_cpa_rows.py
++ - scripts/export_real_acoustic_controls.py
+ - scripts/benchmark_real_regional_upload.py
- scripts/benchmark_real_bounded_upload.py
- scripts/prepare_reference_upload.py
- scripts/restore_artifacts.py
@@@ -30,12 -24,6 +31,14 @@@
- tests/data/reference-retention-real.json
permissions:
contents: read
+env:
+ OPENBLAS_NUM_THREADS: '1'
+ OMP_NUM_THREADS: '1'
+ MKL_NUM_THREADS: '1'
++ NUMEXPR_NUM_THREADS: '1'
++ CC: gcc
+ PYTHONPATH: src
- BASELINE_REF: ${{ inputs.baseline || 'd9649ee5e369b31072d40c4882a5b7e0a7bfa177' }}
++ BASELINE_REF: ${{ inputs.baseline || 'a4d27b2cacfe53fdcb4dfbce4d533d4c7eb9436d' }}
jobs:
compare:
if: github.event_name != 'push' || github.ref != 'refs/heads/perf/real-pipeline-throughput-20261103'
@@@ -48,8 -42,8 +51,18 @@@
- 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]'
++ run: |
++ python -m pip install --editable '.[test]'
++ python - <<'PY'
++ from dopplergeist import matching, native_acoustic
++ assert callable(matching._native_fit_irls), "Native ridge extension did not build"
++ assert matching.RIDGE_FIT_BACKEND.startswith("native-c-")
++ assert native_acoustic._native is not None, "Native acoustic extension did not build"
++ assert native_acoustic.ACOUSTIC_BACKEND.startswith("native-c-")
++ print({"ridge_fit_backend": matching.RIDGE_FIT_BACKEND,
++ "acoustic_backend": native_acoustic.ACOUSTIC_BACKEND})
++ PY
- name: Restore public recorded observations
env:
GH_TOKEN: ${{ github.token }}
@@@ -70,59 -61,19 +83,73 @@@
- 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 tests/test_real_motion_support_batch.py tests/test_real_single_pass_sieve.py tests/test_real_refinement_lookup.py tests/test_real_cpa_preparation.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
++ 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 tests/test_real_refinement_lookup.py tests/test_real_cpa_preparation.py tests/test_real_native_ridge.py tests/test_real_ridge_backend.py tests/test_real_legacy_batch_cache.py tests/test_real_native_acoustic.py tests/test_real_native_acoustic_pipeline.py
++ - name: Verify the explicit Python fallback on recorded arithmetic
++ env:
++ DOPPLERGEIST_RIDGE_BACKEND: python
++ DOPPLERGEIST_ACOUSTIC_BACKEND: python
++ run: python -m pytest -q tests/test_real_batch_scalar_parity.py tests/test_real_legacy_batch_cache.py
++ - name: Export real pipeline objective controls
++ env:
++ DOPPLERGEIST_RIDGE_BACKEND: python
++ DOPPLERGEIST_ACOUSTIC_BACKEND: python
++ run: python scripts/export_real_acoustic_controls.py --fixture benchmark-inputs/point-120.json --output results/real-acoustic-controls.json
+ - 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
++ if [ -f src/dopplergeist/_native_acoustic.c ]; then
++ native_option+=(--require-current-native-acoustic)
++ 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
+ - name: Profile remaining point work outside the timing comparison
+ run: |
- python -m cProfile -o results/current-point.prof scripts/benchmark_prepared_measurements.py _worker --source src --fixture benchmark-inputs/point-120.json --output results/current-point-profile
++ python -m cProfile -o results/current-point.prof scripts/benchmark_prepared_measurements.py _worker --source src --fixture benchmark-inputs/point-120.json --output results/current-point-profile --require-native --require-native-acoustic
+ python - <<'PY'
+ import json
+ from pathlib import Path
+ import pstats
+
+ statistics = pstats.Stats("results/current-point.prof")
+ root = Path.cwd()
+ records = []
+ for (filename, line, function), (primitive, total, own, cumulative, callers) in statistics.stats.items():
+ path = Path(filename)
+ relative = path.relative_to(root).as_posix() if path.is_relative_to(root) else filename
+ module = (relative[4:-3].replace("/", ".") if relative.startswith("src/")
+ and relative.endswith(".py") else path.stem)
+ records.append({"module": module, "file": relative, "line": line, "function": function,
+ "primitive_calls": primitive, "total_calls": total,
+ "self_seconds": own, "cumulative_seconds": cumulative})
+ records.sort(key=lambda row: (-row["cumulative_seconds"], -row["self_seconds"],
+ row["file"], row["line"], row["function"]))
+ summary = {"scope": "Separate profiled width-120 worker, including imports and input loading; excluded from timing medians",
+ "timer": "cProfile default elapsed timer; diagnostic attribution, not an uninstrumented CPU measurement",
+ "total_calls": statistics.total_calls, "primitive_calls": statistics.prim_calls,
+ "total_profiled_seconds": statistics.total_tt, "top_50": records[:50],
+ "dopplergeist_functions": [row for row in records if row["module"].startswith("dopplergeist")]}
+ output = Path("results/current-point-profile-stats.json")
+ output.write_text(json.dumps(summary, indent=2) + "\n")
+ print(json.dumps({"profile_summary": str(output), "excluded_from_timing_medians": True,
+ "top_10": records[:10]}, indent=2))
+ PY
- uses: actions/upload-artifact@v4
if: always()
with:
name: real-performance-summary
path: |
+ results/cpa-rows.json
++ results/real-acoustic-controls.json
results/performance-*/comparison.json
results/performance-*/*/summary.json
+ results/current-point.prof
+ results/current-point-profile-stats.json
if-no-files-found: ignore
retention-days: 14
- uses: actions/upload-artifact@v4
@@@ -132,74 -83,6 +159,138 @@@
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)
+ # Keep the reference FFmpeg family; a new encoder can change detected ridges.
+ runs-on: ubuntu-24.04
- timeout-minutes: 20
++ timeout-minutes: 30
+ 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]'
++ python - <<'PY'
++ from dopplergeist import matching, native_acoustic
++ assert callable(matching._native_fit_irls), "Native ridge extension did not build"
++ assert matching.RIDGE_FIT_BACKEND.startswith("native-c-")
++ assert native_acoustic._native is not None, "Native acoustic extension did not build"
++ assert native_acoustic.ACOUSTIC_BACKEND.startswith("native-c-")
++ print({"ridge_fit_backend": matching.RIDGE_FIT_BACKEND,
++ "acoustic_backend": native_acoustic.ACOUSTIC_BACKEND})
++ PY
+ 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
++ - name: Measure three alternating complete HTTP pairs and require exact parity
++ run: |
++ benchmark_cpu=$(python -c 'import os; print(min(os.sched_getaffinity(0)))')
++ for pair in 1 2 3; do
++ arms=(baseline current)
++ if [ "$pair" = 2 ]; then arms=(current baseline); fi
++ for arm in "${arms[@]}"; do
++ source=src
++ if [ "$arm" = baseline ]; then source="$RUNNER_TEMP/baseline/src"; fi
++ python scripts/benchmark_real_regional_upload.py --source "$source" --audio benchmark-inputs/reference.mp3 --request benchmarks/reference-regional-upload-request.json --operator benchmark-inputs/operator.json --output "results/regional-$pair-$arm" --timeout-s 600 --threads 1 --cpu "$benchmark_cpu" --allow-new-encoding --reference-wav data/source/reference-recording.wav
++ done
++ python scripts/benchmark_real_regional_upload.py --compare "results/regional-$pair-baseline" "results/regional-$pair-current" --output "results/regional-pair-$pair.json"
++ done
++ - name: Summarize only complete and exact paired runs
+ 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
++ python - <<'PY'
++ import json
++ from pathlib import Path
++ import statistics
++
++ root = Path("results")
++ reports = [json.loads((root / f"regional-pair-{pair}.json").read_text()) for pair in (1, 2, 3)]
++ for report in reports:
++ assert report["passed"] and report["scientific_payloads_exact"]
++ assert report["regional_control"]["passed"] and report["array_comparison"]["passed"]
++ assert all(report["full_pipeline_verified"].values())
++ samples = {arm: [json.loads((root / f"regional-{pair}-{arm}" / "timing.json").read_text())
++ for pair in (1, 2, 3)] for arm in ("baseline", "current")}
++ shared_keys = ("audio_sha256", "audio_bytes", "request_sha256", "operator_sha256", "python", "sqlite",
++ "numerical_package_versions", "numerical_threads", "cpu_affinity", "detail_plots_enabled",
++ "recording_control", "reference_wav_sha256", "ffmpeg_version", "verifier_sha256")
++ common = {key: samples["baseline"][0][key] for key in shared_keys}
++ for arm, runs in samples.items():
++ for run in runs:
++ assert run["control_passed"] and run["fresh_run"] and not run["resumed"] and run["returncode"] == 0
++ assert {key: run[key] for key in shared_keys} == common
++ for key in ("source_revision", "ridge_fit_backend", "acoustic_backend"):
++ assert run[key] == runs[0][key]
++ medians = {}
++ for arm in ("baseline", "current"):
++ receipts = [report["timings"][arm]["receipt_elapsed_s"] for report in reports]
++ medians[arm] = {"http_receipt_seconds": statistics.median(receipts),
++ "driver_wall_seconds": statistics.median(run["wall_s"] for run in samples[arm]),
++ "driver_cpu_seconds": statistics.median(run["cpu_s"] for run in samples[arm])}
++ for run, elapsed in zip(samples[arm], receipts):
++ run["http_receipt_seconds"] = elapsed
++ summary = {"passed": True, "scientific_payloads_exact": True, "array_payloads_exact": True,
++ "scope": "Three fresh complete-HTTP pairs from one real recording; source-informed bounds/clock, no location-accuracy claim",
++ "timing_scope": "Median verified HTTP receipts; driver CPU includes verifier and child processes; profiling excluded",
++ "pair_order": [["baseline", "current"], ["current", "baseline"], ["baseline", "current"]],
++ "common_input_and_runtime": common,
++ "medians": medians,
++ "speedup": {key: medians["baseline"][key] / medians["current"][key] for key in medians["baseline"]},
++ "samples": samples, "pairs": reports}
++ output = root / "regional-comparison.json"
++ with output.open("x") as stream:
++ json.dump(summary, stream, indent=2, allow_nan=False)
++ stream.write("\n")
++ print(json.dumps({"passed": True, "pairs": len(reports), "medians": medians, "speedup": summary["speedup"]}, indent=2))
++ PY
+ - 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-pair-*.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
bounded-http:
if: github.event_name == 'push' && github.ref == 'refs/heads/perf/real-pipeline-throughput-20261103'
diff --cc .gitignore
index 9d20eca,9d20eca..5842984
--- a/.gitignore
+++ b/.gitignore
@@@ -1,6 -1,6 +1,8 @@@
.venv/
__pycache__/
*.egg-info/
++*.so
++*.pyd
.pytest_cache/
.artifacts/
/build/
diff --cc scripts/benchmark_prepared_measurements.py
index 700b461,3c3094c..cd7b44e
--- a/scripts/benchmark_prepared_measurements.py
+++ b/scripts/benchmark_prepared_measurements.py
@@@ -123,17 -122,13 +123,24 @@@ def worker(args)
sys.path.insert(0, str(source))
import dopplergeist
import pandas as pd
-- from dopplergeist import matching, tiled_search
++ from dopplergeist import geometry, 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")
+ native_fit = getattr(matching, "_native_fit_irls", None)
+ backend = getattr(matching, "RIDGE_FIT_BACKEND", "python-irls-v1")
++ acoustic_backend = getattr(geometry, "ACOUSTIC_BACKEND", "python-acoustic-v1")
++ try:
++ from dopplergeist.native_acoustic import _native as native_acoustic
++ except ImportError:
++ native_acoustic = None
+ if args.require_native and not callable(native_fit):
+ raise RuntimeError("The source-tree native fitter is unavailable; build it in place before timing")
++ if args.require_native_acoustic and native_acoustic is None:
++ raise RuntimeError("The source-tree native acoustic solver 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"]:
@@@ -151,8 -146,7 +158,9 @@@
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}
++ "native_fit_calls": 0, "native_fit_successes": 0,
++ "native_acoustic_successes": 0}
all_rows = []
original_fit, original_acoustic = matching._fit_ridge_uncached, Track.acoustic
original_score = tiled_search.score_candidate
@@@ -183,9 -170,7 +191,10 @@@
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
++ native_acoustic_before = native_acoustic.successful_calls() if native_acoustic is not None else 0
began, cpu = time.perf_counter(), time.process_time()
try:
ranked, counts = tiled_search._score(
@@@ -193,9 -178,7 +202,11 @@@
start_window=fixture["recording_start_window_s"], ledger=ledger, stage=stage)
finally:
elapsed, cpu_seconds = time.perf_counter() - began, time.process_time() - cpu
++ if native_acoustic is not None:
++ operations["native_acoustic_successes"] = native_acoustic.successful_calls() - native_acoustic_before
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:
@@@ -214,8 -197,6 +225,10 @@@
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")
++ if args.require_native_acoustic and not operations["native_acoustic_successes"]:
++ raise AssertionError("The native acoustic solver was available but no successful native solve 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")}
@@@ -223,7 -204,6 +236,8 @@@
"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),
++ "acoustic_backend": acoustic_backend,
"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"),
@@@ -247,8 -227,6 +261,10 @@@ 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")
++ if name == "current" and args.require_current_native_acoustic:
++ command.append("--require-native-acoustic")
subprocess.run(command, check=True, env=environment, timeout=args.timeout_s)
payload = canonical(json.loads((output / "results.json").read_text()))
if expected is None:
@@@ -296,14 -274,11 +312,17 @@@ 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")
++ comparison.add_argument("--require-current-native-acoustic", action="store_true",
++ help="Fail unless the timed current worker actually uses its native acoustic solver")
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)
++ internal.add_argument("--require-native-acoustic", action="store_true", help=argparse.SUPPRESS)
args = parser.parse_args()
if args.command == "prepare":
if args.clock_half_width_s < 0:
diff --cc scripts/benchmark_real_regional_upload.py
index fc200b9,e548d44..100883e
--- a/scripts/benchmark_real_regional_upload.py
+++ b/scripts/benchmark_real_regional_upload.py
@@@ -1,10 -1,10 +1,13 @@@
"""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.
++--allow-new-encoding explicitly declares a different MP3 encoding of the checked
++reference WAV. Its event counts come from the paired complete runs, and cannot
++inherit the historical MP3's counts or timings.
"""
import argparse
import ast
@@@ -22,6 -22,6 +25,10 @@@ import subproces
import sys
import time
++HISTORICAL_MP3_SHA256 = "707083f0344823eeea7f130faec6c22b6628b8b9fea04d026915d93df9a07b15"
++REFERENCE_WAV_SHA256 = "262d9c4eba1c80657813c604140ba2afbbaabed2b3aebc833cba7cafdc005e9f"
++REFERENCE_DURATION_S = 3600.1845
++
def sha256(path):
with path.open("rb") as handle:
@@@ -41,22 -41,7 +48,23 @@@ 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):
++def assess_output(output, receipt, expected_ridges, expected_groups, detail_plots_enabled=True,
++ *, new_encoding=False):
final_path = output / "result.json"
final = json.loads(final_path.read_text()) if final_path.exists() else {}
events = final.get("events", [])
@@@ -65,15 -50,14 +73,22 @@@
search_path = job / "search/search-report.json"
search = json.loads(search_path.read_text()) if search_path.exists() else {}
plots = sum((job / "discovery" / f"{event['event_id']}.png").is_file() for event in events)
-- counts_match = len(events) == expected_ridges and groups == expected_groups
++ counts_match = (bool(events) and groups > 0 if new_encoding else
++ len(events) == expected_ridges and groups == expected_groups)
++ duration = final.get("recording", {}).get("duration_s")
++ duration_matches = (isinstance(duration, (int, float)) and math.isfinite(duration)
++ and math.isclose(duration, REFERENCE_DURATION_S, rel_tol=0, abs_tol=0.00025))
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) if detail_plots_enabled else 0))
- and counts_match and all_groups and plots == len(events))
++ and counts_match and all_groups and (duration_matches or not new_encoding)
++ 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)}
++ "expected_recording_counts_met": None if new_encoding else counts_match,
++ "nonempty_recording_counts": bool(events) and groups > 0,
++ "reference_duration_met": duration_matches, "all_groups_considered": all_groups,
+ "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):
@@@ -86,24 -70,19 +101,53 @@@
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}")
++ recording_controls = [control.get("recording_control", "fixed_counts") for control in controls]
++ if recording_controls[0] != recording_controls[1] or recording_controls[0] not in {"fixed_counts", "fresh_encoding"}:
++ raise ValueError("Paired recording-control declarations differ or are invalid")
++ new_encoding = recording_controls[0] == "fresh_encoding"
++ if controls[0].get("ffmpeg_version") != controls[1].get("ffmpeg_version"):
++ raise ValueError("Paired FFmpeg versions differ")
+ # 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"):
if any(key not in run.receipt for run in runs) or runs[0].receipt[key] != runs[1].receipt[key]:
raise ValueError(f"Paired input/verifier identity differs or is missing: {key}")
++ for control, run in zip(controls, runs):
++ if (control.get("audio_sha256") != run.receipt["source_sha256"]
++ or control.get("audio_bytes") != run.receipt["source_bytes"]):
++ raise ValueError("Timing metadata does not identify the verified audio input")
++ historical_input = runs[0].receipt["source_sha256"] == HISTORICAL_MP3_SHA256
++ if historical_input:
++ if new_encoding or (expected_ridges, expected_groups) != (17, 15):
++ raise ValueError("The historical MP3 retains its fixed 17-ridge/15-group control")
++ if new_encoding and any(control.get("reference_wav_sha256") != REFERENCE_WAV_SHA256
++ or not control.get("ffmpeg_version") for control in controls):
++ raise ValueError("New encodings require the canonical WAV identity and explicit FFmpeg runtime")
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, policy)
- 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,
++ new_encoding=new_encoding)
+ 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")
++ if any(checks[0][key] != checks[1][key] for key in ("event_count", "independent_groups")):
++ raise ValueError("Paired recording counts differ")
report = comparator.compare_runs(*paths)
++ array_comparator = load_script("regional_array_comparator", Path(__file__).with_name("check_real_upload_arrays.py"))
++ report["array_comparison"] = array_comparator.compare_runs(*paths)
++ report["passed"] = report["passed"] and report["array_comparison"]["passed"]
++ if not report["passed"]:
++ report["verified_full_workflow_speedup"] = None
report["regional_control"] = {"passed": True, "arms": checks,
++ "recording_control": recording_controls[0],
++ "historical_mp3_input": historical_input,
++ "scope": ("New encoding: no historical event-count or timing claim"
++ if new_encoding else "Fixed recorded-input count control"),
"source_revisions": [control["source_revision"] for control in controls]}
output.parent.mkdir(parents=True, exist_ok=True)
with output.open("x") as handle:
@@@ -111,6 -90,6 +155,7 @@@
handle.write("\n")
print(json.dumps({"report": str(output), "paired_control_passed": report["passed"],
"semantic_differences": report["differences"]["count"],
++ "array_differences": report["array_comparison"]["difference_count"],
"verified_full_workflow_speedup": report["verified_full_workflow_speedup"]}))
return 0 if report["passed"] else 1
@@@ -126,23 -105,23 +171,33 @@@ def main()
parser.add_argument("--output", type=Path, required=True,
help="New run directory, or a new JSON report with --compare")
parser.add_argument("--expected-audio-sha256", help="Optional measured-input identity; encoder builds can change bytes")
++ parser.add_argument("--allow-new-encoding", action="store_true",
++ help="Declare a fresh MP3 encoding; complete paired output parity remains mandatory")
++ parser.add_argument("--reference-wav", type=Path,
++ help="Canonical real WAV used to produce a fresh MP3 encoding")
parser.add_argument("--expected-ridges", type=int, default=17)
parser.add_argument("--expected-groups", type=int, default=15)
parser.add_argument("--timeout-s", type=float, default=7200)
parser.add_argument("--poll-interval-s", type=float, default=0.25)
parser.add_argument("--threads", type=int, default=1)
++ parser.add_argument("--cpu", type=int, help="Pin this arm and its child processes to one available CPU")
parser.add_argument("--check-inputs", action="store_true", help="Validate setup without running HTTP")
args = parser.parse_args()
if min(args.threads, args.expected_ridges, args.expected_groups) < 1 or any(
not math.isfinite(value) or value <= 0 for value in (args.timeout_s, args.poll_interval_s)):
parser.error("Counts, thread limits, timeout and polling interval must be positive")
if args.compare:
-- if any((args.source, args.audio, args.request, args.operator, args.check_inputs, args.expected_audio_sha256)):
++ if any((args.source, args.audio, args.request, args.operator, args.check_inputs, args.expected_audio_sha256,
++ args.allow_new_encoding, args.reference_wav, args.cpu is not None)):
parser.error("--compare cannot be combined with run input flags")
return compare_arms([path.resolve() for path in args.compare], args.output.resolve(),
args.expected_ridges, args.expected_groups)
if not all((args.source, args.audio, args.request, args.operator)):
parser.error("A run requires --source, --audio, --request and --operator")
++ if args.cpu is not None:
++ if not hasattr(os, "sched_getaffinity") or args.cpu not in os.sched_getaffinity(0):
++ parser.error("--cpu must identify an available CPU on a platform with affinity controls")
++ os.sched_setaffinity(0, {args.cpu})
source, audio, output = args.source.resolve(), args.audio.resolve(), args.output.resolve()
if output.exists():
parser.error("Use a new output directory")
@@@ -167,13 -146,17 +222,21 @@@
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")
++ if digest == HISTORICAL_MP3_SHA256 and (args.expected_ridges, args.expected_groups) != (17, 15):
++ parser.error("The historical MP3 requires exactly 17 ridges and 15 groups")
++ new_encoding = args.allow_new_encoding and digest != HISTORICAL_MP3_SHA256
++ if new_encoding and args.reference_wav is None:
++ parser.error("A new encoding requires its canonical --reference-wav")
++ reference_digest = sha256(args.reference_wav) if args.reference_wav is not None else None
++ if reference_digest is not None and reference_digest != REFERENCE_WAV_SHA256:
++ parser.error("The encoding source differs from the canonical real reference WAV")
+ 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")})
++ ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS")})
sys.path.insert(0, str(source))
import dopplergeist
- from dopplergeist import matching
++ from dopplergeist import geometry, matching
from dopplergeist.contracts import validate_request
if Path(dopplergeist.__file__).resolve().parent != source / "dopplergeist":
raise RuntimeError("Imported a different dopplergeist source tree")
@@@ -183,8 -166,7 +246,12 @@@
"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")}
++ "recording_control": "fresh_encoding" if new_encoding else "fixed_counts",
++ "reference_wav_sha256": reference_digest,
++ "ffmpeg_version": subprocess.check_output(["ffmpeg", "-version"], text=True).splitlines()[0],
++ "ridge_fit_backend": getattr(matching, "RIDGE_FIT_BACKEND", "python-irls-v1"),
++ "acoustic_backend": getattr(geometry, "ACOUSTIC_BACKEND", "python-acoustic-v1")}
if args.check_inputs:
print(json.dumps({"inputs_valid": True, "http_started": False, **identity}, indent=2))
return 0
@@@ -194,7 -176,7 +261,8 @@@
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, plots_enabled)
- assessment = assess_output(output, receipt, args.expected_ridges, args.expected_groups)
++ assessment = assess_output(output, receipt, args.expected_ridges, args.expected_groups, plots_enabled,
++ new_encoding=new_encoding)
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 --cc scripts/compare_real_upload_performance.py
index 0d5727f,0d5727f..38075ae
--- a/scripts/compare_real_upload_performance.py
+++ b/scripts/compare_real_upload_performance.py
@@@ -144,6 -144,6 +144,10 @@@ class Run
reason = "operator configuration digest; full normalized operator.json is compared"
elif not root and relative == "search/manifest.json" and here == ("configuration", "code"):
reason = "search implementation files"
++ elif not root and relative == "search/manifest.json" and here in {
++ ("configuration", "runtime", "ridge_fit_backend"),
++ ("configuration", "runtime", "acoustic_backend")}:
++ reason = "search native implementation metadata:" + key
elif not root and relative == "provenance.json" and here == ("resumed_from",):
reason = "explicit resume metadata: resumed_from"
elif not root and relative == "search/search-report.json" and here == ("tiles_resumed",):
@@@ -325,6 -325,6 +329,8 @@@ def compare_runs(baseline, current, max
left.continuation["cumulative_active_wall_s"] / right.receipt["elapsed_s"]
if passed and left.continuation is not None else None),
"normalization": {"implementation_fields": sorted(IMPLEMENTATION_FIELDS),
++ "native_backend_metadata": ["search/manifest.json/configuration/runtime/ridge_fit_backend",
++ "search/manifest.json/configuration/runtime/acoustic_backend"],
"performance_fields": sorted(PERFORMANCE_FIELDS),
"path_rule": "Only each run directory, job directory and exact job identifier are replaced.",
"sqlite_rule": "Compare all logical tables, columns and rows; ignore only run.identity and physical SQLite/index layout.",
diff --cc scripts/export_real_acoustic_controls.py
index 0000000,0000000..596f8a8
new file mode 100644
--- /dev/null
+++ b/scripts/export_real_acoustic_controls.py
@@@ -1,0 -1,0 +1,112 @@@
++"""Export two supported real pipeline track/ridge controls with provenance."""
++import argparse
++import hashlib
++import importlib.metadata
++import json
++import os
++from pathlib import Path
++import platform
++
++
++def digest(path):
++ with Path(path).open("rb") as stream:
++ return hashlib.file_digest(stream, "sha256").hexdigest()
++
++
++def main():
++ parser = argparse.ArgumentParser(description=__doc__)
++ parser.add_argument("--fixture", type=Path, required=True)
++ parser.add_argument("--output", type=Path, required=True)
++ args = parser.parse_args()
++ if args.output.exists():
++ parser.error("Use a new output path")
++ import numpy as np
++ from dopplergeist import geometry, matching, tracks as track_module
++ from dopplergeist.data_access import FlightIndex
++ from dopplergeist.geometry import AcousticSupportError, ecef
++
++ fixture = json.loads(args.fixture.read_text())
++ index = FlightIndex(fixture["real_index"])
++ if index.report["input_hash"] != fixture["index_input_hash"]:
++ raise ValueError("The restored index differs from the prepared real fixture")
++ names = sorted({row["flight_id"] for row in fixture["cpa_rows"]})
++ tracks = {track.id: track for track in index.lookup(names, max_tracks=max(1, len(names)),
++ max_samples=fixture["budget"]["max_track_samples_per_tile"],
++ bounds=fixture["query_bounds"], time_range=fixture["query_time_s"])}
++ events, measurements = matching.prepare_events(fixture["events"])
++ point = fixture["point"]
++ observer = ecef(point["lat"], point["lon"], point["elev_m"])
++ cases, chosen = [], set()
++ for i in sorted(range(len(events)), key=lambda i: -len(measurements[i][1])):
++ event, measurement = events[i], measurements[i]
++ sigma = matching._frequency_scale(event)
++ drift = event.get("quality", {}).get("source_drift_fraction", 0.02)
++ times, ridge, weight = matching._ridge_fit_inputs(measurement, sigma, drift)
++ measured = np.isfinite(times) & np.isfinite(ridge) & (weight > 0)
++ for row in fixture["cpa_rows"]:
++ track = tracks.get(row["flight_id"])
++ if track is None or track.id in chosen:
++ continue
++ start = row["receive_time"] - event["cpa_receive_s"]
++ receive = start + times[measured]
++ try:
++ factors, emissions, distance = track.acoustic(receive, observer, 343.0)
++ except AcousticSupportError:
++ continue
++ if not all(np.isfinite(values).all() for values in (factors, emissions, distance)):
++ continue
++ fit = matching.fit_ridge(track, observer, measurement, start,
++ event["f0_range_hz"], 343.0, sigma, drift)
++ if not np.isfinite(fit["score"]):
++ continue
++ score = matching.score_ridges([track], [event], [measurement], observer, start, 343.0)
++ cases.append({
++ "track": {key: getattr(track, key) for key in
++ ("id", "time", "lat", "lon", "altitude", "typecode", "velocity")},
++ "track_metadata": {key: getattr(track, key, None) for key in
++ ("altitude_basis", "aircraft_class", "velocity_inferred_components")},
++ "receiver_point": point, "observer_ecef_m": observer,
++ "c_mps": 343.0, "recording_start_s": start, "event_index": i, "event": event,
++ "measurement": {"time_s": times, "ridge_hz": ridge, "weight": weight},
++ "scoring_parameters": {"f0_bounds_hz": event["f0_range_hz"],
++ "sigma_hz": sigma, "drift_fraction": drift},
++ "measured_mask": measured, "receive_times_s": receive,
++ "expected_acoustic": {"factor": factors, "emission_time_s": emissions, "distance_m": distance},
++ "expected_fit": fit, "expected_score_ridges": score, "cpa_source_row": row,
++ })
++ chosen.add(track.id)
++ if len(cases) == 2:
++ break
++ if len(cases) == 2:
++ break
++ if len(cases) != 2:
++ raise ValueError("Two distinct supported recorded track/ridge controls are required")
++ output = {
++ "schema_version": 1,
++ "scope": "Real indexed aircraft observations and recorded ridges; source-informed receiver/clock, no location-accuracy claim",
++ "selection": "Longest recorded groups first, original CPA-row order, distinct tracks with complete finite acoustic support; no fit-score ranking",
++ "velocity_reference_frame": "ECEF; null preserves Track's ordinary position-gradient inference",
++ "provenance": {
++ "source_commit": os.environ.get("GITHUB_SHA"),
++ "fixture": str(args.fixture), "fixture_sha256": digest(args.fixture),
++ "discovery_source": fixture["discovery_source"],
++ "discovery_sha256": digest(fixture["discovery_source"]),
++ "index_report": index.report, "query_bounds": fixture["query_bounds"],
++ "query_time_s": fixture["query_time_s"], "python": platform.python_version(),
++ "ridge_fit_backend": getattr(matching, "RIDGE_FIT_BACKEND", "python-irls-v1"),
++ "acoustic_backend": getattr(geometry, "ACOUSTIC_BACKEND", "python-acoustic-v1"),
++ "packages": {name: importlib.metadata.version(name) for name in ("numpy", "scipy", "pandas")},
++ "implementation_sha256": {Path(module.__file__).name: digest(module.__file__)
++ for module in (geometry, matching, track_module)},
++ }, "cases": cases,
++ }
++ args.output.parent.mkdir(parents=True, exist_ok=True)
++ with args.output.open("x") as stream:
++ json.dump(output, stream, indent=2, default=lambda value: value.tolist(), allow_nan=False)
++ stream.write("\n")
++ print(json.dumps({"output": str(args.output), "tracks": sorted(chosen),
++ "recorded_ridge_samples": [len(case["measurement"]["time_s"]) for case in cases]}))
++
++
++if __name__ == "__main__":
++ main()
diff --cc scripts/verify_upload_http.py
index 6fbeb78,6fbeb78..8287a2e
--- a/scripts/verify_upload_http.py
+++ b/scripts/verify_upload_http.py
@@@ -13,6 -13,6 +13,7 @@@ from __future__ import annotation
import argparse
from datetime import datetime, timezone
import hashlib
++from importlib.machinery import EXTENSION_SUFFIXES
import http.client
import json
import math
@@@ -31,6 -31,6 +32,13 @@@ from dopplergeist.contracts import utc_
from dopplergeist.jobs import TERMINAL, write_json
++def _implementation_files(package):
++ """Independently cover Python sources, native C, and loaded-format binaries."""
++ return sorted(path for path in package.iterdir()
++ if path.is_file() and (path.suffix in {".py", ".c"}
++ or any(path.name.endswith(suffix) for suffix in EXTENSION_SUFFIXES)))
++
++
def sha256(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
@@@ -921,7 -921,7 +929,7 @@@ def verify_http(audio, output, *, reque
write_json(output / "upload-request.json", wire)
write_json(output / "operator.json", operator)
package = Path(dopplergeist.__file__).resolve().parent
-- implementation = {path.name: sha256(path) for path in sorted(package.glob("*.py"))}
++ implementation = {path.relative_to(package).as_posix(): sha256(path) for path in _implementation_files(package)}
began, process, final, log = time.monotonic(), None, None, None
deadline = began + timeout_s
receipt = {"schema_version": 1, "scope": "actual_local_http_upload_verification",
@@@ -1006,7 -1006,7 +1014,7 @@@
termination.interruptible = True
termination.raise_if_interrupted()
receipt["implementation_unchanged"] = implementation == {
-- path.name: sha256(path) for path in sorted(package.glob("*.py"))}
++ path.relative_to(package).as_posix(): sha256(path) for path in _implementation_files(package)}
if final is not None:
directory = output / "jobs" / final["job_id"]
receipt["terminal_result_preserved_after_shutdown"] = json.loads((directory / "result.json").read_text()) == final
diff --cc setup.py
index 0000000,0000000..d8f2687
new file mode 100644
--- /dev/null
+++ b/setup.py
@@@ -1,0 -1,0 +1,24 @@@
++import os
++
++from setuptools import Extension, setup
++
++
++extension = Extension(
++ "dopplergeist._native_ridge",
++ ["src/dopplergeist/_native_ridge.c"],
++ optional=True,
++ extra_compile_args=["/O2", "/fp:strict"] if os.name == "nt" else
++ ["-O3", "-ffp-contract=off", "-fno-fast-math"],
++ libraries=[] if os.name == "nt" else ["m"],
++)
++
++acoustic_extension = Extension(
++ "dopplergeist._native_acoustic",
++ ["src/dopplergeist/_native_acoustic.c"],
++ optional=True,
++ extra_compile_args=["/O2", "/fp:strict"] if os.name == "nt" else
++ ["-O3", "-ffp-contract=off", "-fno-fast-math"],
++ libraries=[] if os.name == "nt" else ["m"],
++)
++
++setup(ext_modules=[extension, acoustic_extension])
diff --cc src/dopplergeist/_native_acoustic.c
index 0000000,0000000..a591139
new file mode 100644
--- /dev/null
+++ b/src/dopplergeist/_native_acoustic.c
@@@ -1,0 -1,0 +1,214 @@@
++/* Optional exact-order acoustic solver for canonical float64 buffers.
++ * NumPy/SciPy remain the reference path for unsupported representations and
++ * all exceptional arithmetic. No NumPy C headers or runtime compilation.
++ */
++#include <math.h>
++#include <stddef.h>
++#include <stdint.h>
++#include <fenv.h>
++#include <string.h>
++
++/* Compile without contraction or reassociation. SciPy PPoly uses
++ * increasing powers, not Horner evaluation. Preserve that arithmetic exactly.
++ */
++static size_t interval_at(const double *x, size_t m, double value) {
++ size_t lo = 0, hi = m - 1;
++ if (value == x[m]) return m - 1;
++ while (lo < hi) {
++ size_t mid = lo + (hi - lo) / 2;
++ if (value < x[mid + 1]) hi = mid;
++ else lo = mid + 1;
++ }
++ return lo;
++}
++
++static int evaluate(const double *coefficients, const double *x, size_t m,
++ size_t width, double origin, double t, double *values) {
++ double relative = t - origin;
++ if (!(relative >= x[0] && relative <= x[m])) return 1;
++ size_t i = interval_at(x, m, relative);
++ double s = relative - x[i];
++ double z = 1.0;
++ for (size_t j = 0; j < width; ++j) values[j] = 0.0;
++ for (size_t k = 0; k < 4; ++k) {
++ for (size_t j = 0; j < width; ++j)
++ values[j] = values[j] + coefficients[((3-k)*m+i)*width+j]*z;
++ if (k < 3) z *= s;
++ }
++ return 0;
++}
++
++
++
++static double clip(double t, double start, double end) {
++ if (t < start) return start;
++ if (t > end) return end;
++ return t;
++}
++
++static double norm3(const double *a) {
++ return sqrt((a[0]*a[0] + a[1]*a[1]) + a[2]*a[2]);
++}
++
++static int kinematics(const double *coefficients, const double *x,
++ size_t m, double origin, double tau, const double *observer,
++ double *distance, double *radial) {
++ double values[6], delta[3];
++ if (evaluate(coefficients, x, m, 6, origin, tau, values)) return 1;
++ for (size_t j = 0; j < 3; ++j) delta[j] = values[j] - observer[j];
++ *distance = norm3(delta);
++ *radial = (((0.0 + delta[0]*values[3]) + delta[1]*values[4])
++ + delta[2]*values[5]) / *distance;
++ return !isfinite(*distance) || !isfinite(*radial) || *distance == 0.0;
++}
++
++static int dg_acoustic(const double *t, size_t n, const double *observer,
++ const double *p, const double *x, size_t m,
++ const double *packed, const double *packed_x, size_t packed_m,
++ double origin, double start, double end, double c,
++ double arrival_start, double arrival_end,
++ double *factor, double *tau, double *distance) {
++ if (n == 0 || m == 0 || m > 4096) return 1;
++ for (size_t i = 0; i < n; ++i) {
++ double position[3], delta[3];
++ if (!isfinite(t[i])) return 1;
++ if (evaluate(p, x, m, 3, origin, clip(t[i], start, end), position)) return 1;
++ for (size_t j = 0; j < 3; ++j) delta[j] = position[j] - observer[j];
++ double initial_distance = norm3(delta);
++ if (!isfinite(initial_distance)) return 1;
++ double initial_delay = initial_distance/c;
++ double estimate = t[i] - initial_delay;
++ if (!isfinite(initial_delay) || !isfinite(estimate)) return 1;
++ tau[i] = clip(estimate, start, end);
++ }
++ int unchanged = 0;
++ for (size_t iteration = 0; iteration < 10; ++iteration) {
++ unchanged = 1;
++ double maximum = 0.0;
++ for (size_t i = 0; i < n; ++i) {
++ if (kinematics(packed, packed_x, packed_m, origin, tau[i], observer, distance+i, factor+i)) return 1;
++ double derivative = 1.0 + factor[i]/c;
++ if (!isfinite(derivative) || !(derivative > 0.0)) return 1;
++ double correction = ((tau[i] - t[i]) + distance[i]/c)/derivative;
++ if (!isfinite(correction)) return 1;
++ double estimate = tau[i] - correction;
++ if (!isfinite(estimate)) return 1;
++ double updated = clip(estimate, start, end);
++ if (updated != tau[i]) unchanged = 0;
++ tau[i] = updated;
++ double absolute = fabs(correction);
++ if (absolute > maximum) maximum = absolute;
++ }
++ if (maximum < 1e-7 || unchanged) break;
++ }
++ if (!unchanged) {
++ for (size_t i = 0; i < n; ++i) {
++ if (kinematics(packed, packed_x, packed_m, origin, tau[i], observer, distance+i, factor+i)) return 1;
++ }
++ }
++ for (size_t i = 0; i < n; ++i) {
++ double radial = factor[i];
++ double denominator = c+radial;
++ if (!isfinite(denominator)) return 1;
++ factor[i] = c/denominator;
++ double derivative = 1.0 + radial/c;
++ if (!isfinite(factor[i]) || !isfinite(derivative) || !(derivative > 0.0)) return 1;
++ double residual = ((tau[i]-t[i])+distance[i]/c)/derivative;
++ if (!isfinite(residual)) return 1;
++ int supported = t[i] >= arrival_start && t[i] <= arrival_end;
++ double spacing = nextafter(t[i],copysign(INFINITY,t[i])) - t[i];
++ double tolerance = fmax(1e-7,4.0*fabs(spacing));
++ if (!isfinite(tolerance)) return 1;
++ if (supported && fabs(residual) > tolerance) return 1;
++ if (!supported) factor[i] = tau[i] = distance[i] = NAN;
++ }
++ return 0;
++}
++#define PY_SSIZE_T_CLEAN
++#include <Python.h>
++
++typedef struct { unsigned long long successful_calls; } module_state;
++
++static int view_double(PyObject *object, Py_buffer *view, int writable) {
++ int flags = PyBUF_FORMAT | PyBUF_ND | PyBUF_STRIDES;
++ if (writable) flags |= PyBUF_WRITABLE;
++ if (PyObject_GetBuffer(object, view, flags) < 0) return 0;
++ return view->itemsize == (Py_ssize_t)sizeof(double)
++ && view->format && strcmp(view->format, "d") == 0
++ && PyBuffer_IsContiguous(view, 'C')
++ && (uintptr_t)view->buf % sizeof(double) == 0;
++}
++
++static int same_shape(const Py_buffer *a, const Py_buffer *b) {
++ if (a->ndim != b->ndim) return 0;
++ for (int i = 0; i < a->ndim; ++i)
++ if (a->shape[i] != b->shape[i]) return 0;
++ return 1;
++}
++
++static int spline_shape(const Py_buffer *c, const Py_buffer *x, int width) {
++ return c->ndim == 3 && x->ndim == 1
++ && c->shape[0] == 4 && c->shape[2] == width
++ && c->shape[1] > 0 && c->shape[1] <= 4096
++ && x->shape[0] == c->shape[1] + 1;
++}
++
++static int increasing_knots(const Py_buffer *view) {
++ const double *x = view->buf;
++ for (Py_ssize_t i = 0; i < view->shape[0]-1; ++i)
++ if (!isfinite(x[i]) || !(x[i] < x[i+1])) return 0;
++ return isfinite(x[view->shape[0]-1]);
++}
++
++static PyObject *solve(PyObject *self, PyObject *args) {
++ PyObject *objects[9];
++ Py_buffer views[9] = {{0}};
++ double origin, start, end, c, arrival_start, arrival_end;
++ int success = 0;
++ if (!PyArg_ParseTuple(args,"OOOOOOddddddOOO",
++ &objects[0],&objects[1],&objects[2],&objects[3],&objects[4],&objects[5],
++ &origin,&start,&end,&c,&arrival_start,&arrival_end,
++ &objects[6],&objects[7],&objects[8])) return NULL;
++ if (fegetround() != FE_TONEAREST || !isfinite(origin) || !isfinite(start)
++ || !isfinite(end) || start > end || !isfinite(c) || c <= 0.0)
++ Py_RETURN_FALSE;
++ for (int i = 0; i < 9; ++i)
++ if (!view_double(objects[i], views+i, i >= 6)) goto done;
++ if (views[0].len <= 0 || views[1].ndim != 1 || views[1].shape[0] != 3
++ || !spline_shape(views+2,views+3,3)
++ || !spline_shape(views+4,views+5,6)
++ || !increasing_knots(views+3) || !increasing_knots(views+5)) goto done;
++ for (int i = 6; i < 9; ++i)
++ if (!same_shape(views,views+i)) goto done;
++ const double *observer = views[1].buf;
++ for (int j = 0; j < 3; ++j) if (!isfinite(observer[j])) goto done;
++ /* A failed probe must not leak arithmetic flags into the NumPy fallback. */
++ fenv_t previous_environment;
++ if (fegetenv(&previous_environment) != 0) goto done;
++ Py_BEGIN_ALLOW_THREADS
++ success = !dg_acoustic(views[0].buf,(size_t)(views[0].len/sizeof(double)),
++ observer,views[2].buf,views[3].buf,(size_t)views[2].shape[1],
++ views[4].buf,views[5].buf,(size_t)views[4].shape[1],origin,start,end,c,
++ arrival_start,arrival_end,views[6].buf,views[7].buf,views[8].buf);
++ if (fesetenv(&previous_environment) != 0) success = 0;
++ Py_END_ALLOW_THREADS
++done:
++ for (int i = 0; i < 9; ++i) if (views[i].obj) PyBuffer_Release(views+i);
++ if (PyErr_Occurred()) PyErr_Clear();
++ if (success) ((module_state *)PyModule_GetState(self))->successful_calls++;
++ return PyBool_FromLong(success);
++}
++
++static PyObject *successful_calls(PyObject *self, PyObject *unused) {
++ return PyLong_FromUnsignedLongLong(((module_state *)PyModule_GetState(self))->successful_calls);
++}
++
++static PyMethodDef methods[] = {
++ {"solve", solve, METH_VARARGS, "Solve a canonical float64 acoustic batch."},
++ {"successful_calls", successful_calls, METH_NOARGS, "Count successful native numerical solves."},
++ {NULL, NULL, 0, NULL}
++};
++static struct PyModuleDef module = {
++ PyModuleDef_HEAD_INIT, "_native_acoustic", NULL, sizeof(module_state), methods
++};
++PyMODINIT_FUNC PyInit__native_acoustic(void) { return PyModule_Create(&module); }
diff --cc src/dopplergeist/_native_ridge.c
index 0000000,0000000..c424624
new file mode 100644
--- /dev/null
+++ b/src/dopplergeist/_native_ridge.c
@@@ -1,0 -1,0 +1,283 @@@
++#define PY_SSIZE_T_CLEAN
++#include <Python.h>
++#include <math.h>
++#include <string.h>
++
++static int
++get_vector(PyObject *object, Py_buffer *view)
++{
++ if (PyObject_GetBuffer(object, view, PyBUF_FORMAT | PyBUF_ND | PyBUF_STRIDES) < 0) {
++ return -1;
++ }
++ if (view->ndim != 1 || view->itemsize != (Py_ssize_t)sizeof(double) ||
++ view->shape == NULL || view->strides == NULL || view->format == NULL ||
++ strcmp(view->format, "d") != 0) {
++ PyBuffer_Release(view);
++ view->obj = NULL;
++ PyErr_SetString(PyExc_TypeError, "expected a native float64 vector");
++ return -1;
++ }
++ return 0;
++}
++
++static double
++at(const Py_buffer *view, Py_ssize_t index)
++{
++ double value;
++ memcpy(&value, (const char *)view->buf + index * view->strides[0], sizeof(value));
++ return value;
++}
++
++static double
++clip(double value, double lower, double upper)
++{
++ if (value < lower) return lower;
++ if (value > upper) return upper;
++ return value;
++}
++
++/* Match NumPy's float64 reduction tree rather than a serial running sum. */
++static double
++pairwise_sum(const double *values, Py_ssize_t count)
++{
++ if (count < 8) {
++ double result = -0.0;
++ for (Py_ssize_t i = 0; i < count; ++i) result += values[i];
++ return result;
++ }
++ if (count <= 128) {
++ double r0 = values[0], r1 = values[1], r2 = values[2], r3 = values[3];
++ double r4 = values[4], r5 = values[5], r6 = values[6], r7 = values[7];
++ Py_ssize_t i = 8;
++ for (; i < count - count % 8; i += 8) {
++ r0 += values[i]; r1 += values[i + 1];
++ r2 += values[i + 2]; r3 += values[i + 3];
++ r4 += values[i + 4]; r5 += values[i + 5];
++ r6 += values[i + 6]; r7 += values[i + 7];
++ }
++ double result = ((r0 + r1) + (r2 + r3)) + ((r4 + r5) + (r6 + r7));
++ for (; i < count; ++i) result += values[i];
++ return result;
++ }
++ Py_ssize_t half = count / 2;
++ half -= half % 8;
++ return pairwise_sum(values, half) + pairwise_sum(values + half, count - half);
++}
++
++static double
++scalar_square(double value)
++{
++ /* Python float ** 2 calls libm pow. Keep that rounding, not x * x. */
++ volatile double exponent = 2.0;
++ return pow(value, exponent);
++}
++
++static void
++source_fit(const Py_buffer *factor, const Py_buffer *u, const Py_buffer *y,
++ const double *effective, double *scratch, Py_ssize_t count,
++ double lower, double upper, double cap, double prior,
++ double *f0, double *drift)
++{
++ *f0 = NAN;
++ *drift = NAN;
++ double *a_terms = scratch, *r_terms = scratch + count;
++ double *b_terms = scratch + 2 * count, *d_terms = scratch + 3 * count;
++ double *s_terms = scratch + 4 * count;
++
++ for (Py_ssize_t i = 0; i < count; ++i) {
++ double fi = at(factor, i), ui = at(u, i), yi = at(y, i);
++ double wi = effective[i], factor2 = fi * fi;
++ double wf = wi * fi, wf2 = wi * factor2;
++ a_terms[i] = wf2;
++ r_terms[i] = wf * yi;
++ if (cap != 0.0) {
++ b_terms[i] = wf2 * ui;
++ d_terms[i] = wf2 * (ui * ui);
++ s_terms[i] = (wf * ui) * yi;
++ }
++ }
++ double a = 0.0 + pairwise_sum(a_terms, count);
++ double r = 0.0 + pairwise_sum(r_terms, count);
++ if (!(a > 0.0) || !isfinite(a) || !isfinite(r) || !isfinite(prior)) return;
++ if (cap == 0.0) {
++ *f0 = clip(r / a, lower, upper);
++ *drift = 0.0;
++ return;
++ }
++
++ double b = 0.0 + pairwise_sum(b_terms, count);
++ double d = (0.0 + pairwise_sum(d_terms, count)) + prior;
++ double s = 0.0 + pairwise_sum(s_terms, count);
++ double determinant = a * d - b * b;
++ if (!(determinant > 0.0) || !isfinite(determinant) ||
++ !isfinite(b) || !isfinite(d) || !isfinite(s)) return;
++ double unconstrained_f = (r * d - s * b) / determinant;
++ double unconstrained_drift = (s * a - r * b) / determinant;
++ if (!isfinite(unconstrained_f) || !isfinite(unconstrained_drift)) return;
++ if (lower <= unconstrained_f && unconstrained_f <= upper && fabs(unconstrained_drift) <= cap) {
++ *f0 = unconstrained_f;
++ *drift = unconstrained_drift;
++ return;
++ }
++
++ double candidate_f[4] = {lower, upper, 0.0, 0.0};
++ double candidate_drift[4] = {
++ clip((s - b * lower) / d, -cap, cap),
++ clip((s - b * upper) / d, -cap, cap), -cap, cap
++ };
++ candidate_f[2] = clip((r - b * candidate_drift[2]) / a, lower, upper);
++ candidate_f[3] = clip((r - b * candidate_drift[3]) / a, lower, upper);
++
++ double best_cost = INFINITY;
++ for (int candidate = 0; candidate < 4; ++candidate) {
++ for (Py_ssize_t i = 0; i < count; ++i) {
++ double fi = at(factor, i), ui = at(u, i), yi = at(y, i);
++ double residual = fi * (candidate_f[candidate] + candidate_drift[candidate] * ui) - yi;
++ double residual2 = residual * residual;
++ scratch[i] = effective[i] * residual2;
++ }
++ double cost = (0.0 + pairwise_sum(scratch, count)) +
++ prior * (candidate_drift[candidate] * candidate_drift[candidate]);
++ if (!isfinite(cost)) {
++ *f0 = NAN;
++ *drift = NAN;
++ return;
++ }
++ if (cost < best_cost) {
++ best_cost = cost;
++ *f0 = candidate_f[candidate];
++ *drift = candidate_drift[candidate];
++ }
++ }
++}
++
++static PyObject *
++fit_irls(PyObject *self, PyObject *args)
++{
++ PyObject *objects[4];
++ double lower, upper, cap, sigma;
++ Py_ssize_t independent_samples;
++ Py_buffer views[4] = {{0}};
++ int acquired = 0;
++ double *effective = NULL;
++ PyObject *result = NULL;
++
++ if (!PyArg_ParseTuple(args, "OOOOddddn", &objects[0], &objects[1],
++ &objects[2], &objects[3], &lower, &upper, &cap,
++ &sigma, &independent_samples)) {
++ return NULL;
++ }
++ for (int i = 0; i < 4; ++i) {
++ if (get_vector(objects[i], &views[i]) < 0) goto done;
++ ++acquired;
++ }
++ Py_ssize_t count = views[0].shape[0];
++ if (count == 0 || views[1].shape[0] != count || views[2].shape[0] != count ||
++ views[3].shape[0] != count || !isfinite(lower) || !isfinite(upper) ||
++ lower > upper || !isfinite(cap) || cap < 0.0 || !isfinite(sigma) ||
++ sigma <= 0.0 || independent_samples < 1) {
++ PyErr_SetString(PyExc_ValueError, "invalid robust ridge-fit inputs");
++ goto done;
++ }
++ if ((size_t)count > SIZE_MAX / (6 * sizeof(double))) {
++ PyErr_NoMemory();
++ goto done;
++ }
++ effective = PyMem_Malloc((size_t)count * 6 * sizeof(double));
++ if (effective == NULL) {
++ PyErr_NoMemory();
++ goto done;
++ }
++ int valid = 1;
++ for (Py_ssize_t i = 0; i < count; ++i) {
++ double fi = at(&views[0], i), ui = at(&views[1], i);
++ double yi = at(&views[2], i), wi = at(&views[3], i);
++ if (!isfinite(fi) || fi <= 0.0 || !isfinite(ui) || !isfinite(yi) ||
++ !isfinite(wi) || wi <= 0.0) {
++ valid = 0;
++ break;
++ }
++ effective[i] = wi;
++ }
++ if (!valid) {
++ Py_INCREF(Py_None);
++ result = Py_None;
++ goto done;
++ }
++
++ double f0 = NAN, drift = NAN, loss = NAN, rmse = NAN, outlier_fraction = NAN;
++ double *scratch = effective + count;
++ double prior = cap == 0.0 ? 0.0 : scalar_square(2.0 * sigma / cap);
++ double loss_scale = 2.0 * scalar_square(sigma);
++ valid = 1;
++ Py_BEGIN_ALLOW_THREADS
++ for (int iteration = 0; iteration < 6; ++iteration) {
++ source_fit(&views[0], &views[1], &views[2], effective, scratch, count,
++ lower, upper, cap, prior, &f0, &drift);
++ if (!isfinite(f0) || !isfinite(drift)) {
++ valid = 0;
++ break;
++ }
++ if (iteration == 5) break;
++ for (Py_ssize_t i = 0; i < count; ++i) {
++ double residual = at(&views[0], i) * (f0 + drift * at(&views[1], i)) - at(&views[2], i);
++ double scaled = residual / sigma;
++ if (!isfinite(residual)) {
++ valid = 0;
++ break;
++ }
++ effective[i] = at(&views[3], i) / sqrt(1.0 + scaled * scaled);
++ }
++ if (!valid) break;
++ }
++ if (valid) {
++ double *loss_terms = scratch, *squared_terms = scratch + count;
++ double *outlier_terms = scratch + 2 * count, *weight_terms = scratch + 3 * count;
++ for (Py_ssize_t i = 0; i < count; ++i) {
++ double residual = at(&views[0], i) * (f0 + drift * at(&views[1], i)) - at(&views[2], i);
++ double wi = at(&views[3], i), scaled = residual / sigma;
++ loss_terms[i] = (loss_scale * (sqrt(1.0 + scaled * scaled) - 1.0)) * wi;
++ squared_terms[i] = (residual * residual) * wi;
++ outlier_terms[i] = fabs(residual) > 3.0 * sigma ? wi : 0.0;
++ weight_terms[i] = wi;
++ }
++ double loss_sum = 0.0 + pairwise_sum(loss_terms, count);
++ double squared_sum = 0.0 + pairwise_sum(squared_terms, count);
++ double outlier_sum = 0.0 + pairwise_sum(outlier_terms, count);
++ double weight_sum = 0.0 + pairwise_sum(weight_terms, count);
++ double penalty = cap ? scalar_square(2.0 * sigma * drift / cap) /
++ (double)independent_samples : 0.0;
++ loss = loss_sum / weight_sum;
++ rmse = sqrt(squared_sum / weight_sum);
++ outlier_fraction = outlier_sum / weight_sum;
++ loss = -sqrt(loss + penalty);
++ valid = isfinite(loss) && isfinite(rmse) && isfinite(outlier_fraction);
++ }
++ Py_END_ALLOW_THREADS
++
++ if (valid) result = Py_BuildValue("(ddddd)", loss, f0, drift, rmse, outlier_fraction);
++ else {
++ Py_INCREF(Py_None);
++ result = Py_None;
++ }
++
++done:
++ PyMem_Free(effective);
++ for (int i = 0; i < acquired; ++i) PyBuffer_Release(&views[i]);
++ return result;
++}
++
++static PyMethodDef methods[] = {
++ {"fit_irls", fit_irls, METH_VARARGS, "Run six robust ridge-fit iterations in C."},
++ {NULL, NULL, 0, NULL}
++};
++
++static struct PyModuleDef module = {
++ PyModuleDef_HEAD_INIT, "_native_ridge", NULL, -1, methods
++};
++
++PyMODINIT_FUNC
++PyInit__native_ridge(void)
++{
++ return PyModule_Create(&module);
++}
diff --cc src/dopplergeist/automatic.py
index 5ca9974,5ca9974..a798eb0
--- a/src/dopplergeist/automatic.py
+++ b/src/dopplergeist/automatic.py
@@@ -68,7 -68,7 +68,9 @@@ def analyze(request, output_dir, config
if (output / "provenance.json").exists() and not resume:
raise FileExistsError("Analysis output exists; use a new directory")
began = time.monotonic()
-- sources = {p.name: _digest(p) for p in sorted(Path(__file__).parent.glob("*.py"))}
++ from .provenance import implementation_files
++ sources = {p.relative_to(Path(__file__).parent).as_posix(): _digest(p)
++ for p in implementation_files(Path(__file__).parent, recursive=False)}
provenance = {"request": request, "operator_configuration_sha256": hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest(),
"source_sha256": _digest(request["audio_path"]), "implementation_files": sources,
"ground_truth_used_by_search": False, "event_selection": "automatic_whole_recording"}
diff --cc src/dopplergeist/batch_ridge.py
index 1434448,1434448..bce2523
--- a/src/dopplergeist/batch_ridge.py
+++ b/src/dopplergeist/batch_ridge.py
@@@ -4,6 -4,6 +4,7 @@@ import pickl
import numpy as np
++from . import matching
from .audio import Spectrum
from .matching import (RidgeTimes, _fit_argument_key, _fit_ridge_uncached,
_frequency_scale, _ridge_fit_cache, _ridge_fit_inputs)
@@@ -98,6 -98,6 +99,7 @@@ def _first_event_fits_uncached(measurem
return None
y, w = ridge[measured], weights[measured]
independent = len(np.unique(times[measured]))
++ diagnostic_error_policy = np.geterr()
with np.errstate(over="ignore", invalid="ignore", divide="ignore", under="ignore"):
w = w * independent / w.sum()
span = np.maximum(np.ptp(emissions, axis=1), 1e-9)
@@@ -106,6 -106,6 +108,33 @@@
cap = np.clip(np.median(y[None, :] / factors, axis=1), low, high) * fraction
if not np.all(np.isfinite(cap) & (cap > 0)) or not np.all(np.isfinite(u)):
return None
++ native = matching._native_fit_irls
++ # Contiguous rows use the native kernel's same pairwise reduction order.
++ # Other layouts and scalar promotion rules retain the vectorized path.
++ # Saved first-group batches must keep their original array powers and
++ # scalar compatibility checks even when the native fitter is installed.
++ if (not legacy_arithmetic and native is not None
++ and all(type(value) is float for value in (sigma, fraction, low, high))
++ and factors.flags.c_contiguous and emissions.flags.c_contiguous
++ and factors.flags.aligned and emissions.flags.aligned):
++ native_rows = []
++ try:
++ for factor, normalized_time, bound in zip(factors, u, cap):
++ fit = native(factor, normalized_time, y, w, low, high,
++ float(bound), sigma, independent)
++ if fit is None:
++ break
++ native_rows.append(fit)
++ if len(native_rows) == len(factors):
++ score, alpha, beta, rmse, outlier = np.asarray(native_rows, dtype=float).T
++ if all(np.all(np.isfinite(value)) for value in
++ (span, reference, score, alpha, beta, rmse, outlier)):
++ # Metadata is normally assembled after the ignored-error block.
++ with np.errstate(**diagnostic_error_policy):
++ return _fit_diagnostics(score, alpha, beta, rmse, outlier,
++ span, reference, cap, len(y), independent)
++ except (BufferError, TypeError, ValueError, OverflowError):
++ pass
factor2, u2 = factors**2, u**2
effective = np.broadcast_to(w, factors.shape).copy()
# The scalar fitter squares Python floats here. NumPy's array square
@@@ -163,13 -163,13 +192,7 @@@
outlier = np.average(np.abs(residual) > 3 * sigma, weights=w, axis=1)
if not all(np.all(np.isfinite(value)) for value in (span, reference, score, rmse, outlier)):
return None
-- results = [{"score": float(score[i]), "f0_hz": float(alpha[i]),
-- "source_drift_hz": float(beta[i]), "source_drift_hz_s": float(beta[i]/span[i]),
-- "source_reference_emission_time_s": float(reference[i]), "source_span_s": float(span[i]),
-- "drift_bound_hz": float(cap[i]), "drift_at_bound": bool(cap[i] and abs(beta[i]) > 0.99*cap[i]),
-- "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))]
++ results = _fit_diagnostics(score, alpha, beta, rmse, outlier, span, reference, cap, len(y), independent)
if legacy_arithmetic:
# Saved searches before the scalar-consistent correction used this
# array arithmetic and these three fallback checks for the first group.
@@@ -180,3 -180,3 +203,13 @@@
if results[i] != scalar:
return None
return results
++
++
++def _fit_diagnostics(score, alpha, beta, rmse, outlier, span, reference, cap, sample_count, independent):
++ return [{"score": float(score[i]), "f0_hz": float(alpha[i]),
++ "source_drift_hz": float(beta[i]), "source_drift_hz_s": float(beta[i]/span[i]),
++ "source_reference_emission_time_s": float(reference[i]), "source_span_s": float(span[i]),
++ "drift_bound_hz": float(cap[i]), "drift_at_bound": bool(cap[i] and abs(beta[i]) > 0.99*cap[i]),
++ "rmse_hz": float(rmse[i]), "support_fraction": 1.0, "sample_count": int(sample_count),
++ "independent_sample_count": independent, "outlier_fraction": float(outlier[i])}
++ for i in range(len(alpha))]
diff --cc src/dopplergeist/checkpoint_resume.py
index a3a3e13,a3a3e13..5ff63b4
--- a/src/dopplergeist/checkpoint_resume.py
+++ b/src/dopplergeist/checkpoint_resume.py
@@@ -33,7 -33,7 +33,7 @@@ def upgrade_legacy_job(directory)
staged batching with the saved first-group arithmetic and fallback checks.
"""
from .automatic import _audio_identity, _digest
-- from . import matching
++ from . import geometry, matching
directory = Path(directory)
search = directory / "search"
@@@ -45,6 -45,6 +45,8 @@@
return None
if getattr(matching, "_native_fit_irls", None) is not None:
raise ValueError("Legacy checkpoint continuation requires the Python ridge fitter")
++ if geometry.ACOUSTIC_BACKEND != "python-acoustic-v1":
++ raise ValueError("Legacy checkpoint continuation requires the Python acoustic solver")
if (old["scoring"].get("mode") != "robust_ridge" or old.get("coarse_floor_policy") != "per_tile"
or old["scoring"].get("time_origin") is not None
or old.get("filters", {}).get("association") != "subsets"):
@@@ -70,7 -70,7 +72,10 @@@
if events != old["events"]:
raise ValueError("Prepared events no longer match the saved search")
current = deepcopy(old)
-- current["code"] = {p.name: _digest(p) for p in sorted(Path(__file__).parent.glob("*.py"))}
++ from .provenance import implementation_files
++ package_root = Path(__file__).parent
++ current["code"] = {p.relative_to(package_root).as_posix(): _digest(p)
++ for p in implementation_files(package_root, recursive=False)}
current["scoring"]["legacy_first_batch"] = True
new_hash = content_hash(current)
suffix = uuid.uuid4().hex[:12]
diff --cc src/dopplergeist/geometry.py
index 9933e0b,ad734b5..737a83f
--- a/src/dopplergeist/geometry.py
+++ b/src/dopplergeist/geometry.py
@@@ -12,9 -12,8 +12,11 @@@ from scipy.interpolate import CubicHerm
from scipy.optimize import minimize_scalar
from scipy.signal import find_peaks
++from .native_acoustic import ACOUSTIC_BACKEND, try_acoustic as _try_native_acoustic
++
_EMISSION_ITERATION_TOLERANCE_S = 1e-7
_PACKED_KINEMATICS_MAX_INTERVALS = 4096
+_MOTION_SUPPORT_INTERVAL_BATCH = 1024
@lru_cache(maxsize=8)
@@@ -271,6 -217,6 +273,15 @@@ class Track
start, end = self.time[[0, -1]]
arrival_start = start + np.linalg.norm(self.xyz[0] - observer) / c
arrival_end = end + np.linalg.norm(self.xyz[-1] - observer) / c
++ if (type(self) is Track and len(self.time)-1 <= _PACKED_KINEMATICS_MAX_INTERVALS
++ and Track.position is _NATIVE_POSITION
++ and Track._position_velocity is _NATIVE_POSITION_VELOCITY
++ and "position" not in self.__dict__ and "_position_velocity" not in self.__dict__
++ and _EMISSION_ITERATION_TOLERANCE_S == 1e-7):
++ result = _try_native_acoustic(self, t, observer, c, start, end,
++ arrival_start, arrival_end, _packed_kinematics)
++ if result is not None:
++ return result
supported = (t >= arrival_start) & (t <= arrival_end)
initial = self.position(np.clip(t, start, end))
tau = np.clip(t - np.linalg.norm(initial - observer, axis=-1) / c, start, end)
@@@ -347,6 -293,6 +358,10 @@@
return sorted(events, key=lambda event: event["emission_time"])
++_NATIVE_POSITION = Track.position
++_NATIVE_POSITION_VELOCITY = Track._position_velocity
++
++
def straight_doppler(t_receive, f0, speed, slant, cpa_receive, c=343.0):
"""Exact retarded-time solution for a constant-speed straight flyover."""
# Relative emission t=0 is geometric CPA; its sound arrives at slant/c.
diff --cc src/dopplergeist/matching.py
index b17cfa2,b17cfa2..6f6b3ac
--- a/src/dopplergeist/matching.py
+++ b/src/dopplergeist/matching.py
@@@ -10,6 -10,6 +10,7 @@@ from dataclasses import dataclas
from functools import wraps
import hashlib
from itertools import chain
++import os
import numpy as np
from pyproj import Transformer
@@@ -17,6 -17,6 +18,29 @@@ from scipy.optimize import minimiz
from .geometry import Track, _EMISSION_ITERATION_TOLERANCE_S, ecef
++_ridge_backend_choice = os.environ.get("DOPPLERGEIST_RIDGE_BACKEND", "auto")
++if _ridge_backend_choice not in {"auto", "python"}:
++ raise ValueError("DOPPLERGEIST_RIDGE_BACKEND must be 'auto' or 'python'")
++_native_ridge_module = None
++_native_fit_irls = None
++if _ridge_backend_choice == "auto":
++ try:
++ from . import _native_ridge as _native_ridge_module
++ from ._native_ridge import fit_irls as _native_fit_irls
++ except ImportError:
++ _native_ridge_module = None
++ _native_fit_irls = None
++
++if _native_ridge_module is None:
++ RIDGE_FIT_BACKEND = "python-irls-v1"
++else:
++ from pathlib import Path
++
++ _native_binary_hash = hashlib.sha256(Path(_native_ridge_module.__file__).read_bytes()).hexdigest()
++ RIDGE_FIT_BACKEND = f"native-c-irls-v2-pairwise:{_native_binary_hash}"
++
++_NATIVE_RIDGE_ERROR_POLICY = {"divide": "warn", "over": "warn", "under": "ignore", "invalid": "warn"}
++
@dataclass
class RidgeTimes:
@@@ -531,6 -531,6 +555,27 @@@ def _fit_ridge_uncached(track, observer
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
++ # NumPy scalar parameters can use different promotion and power rules.
++ # Preserve those callers and explicit NumPy error policies on the Python path.
++ if (_native_fit_irls is not None and type(sigma_hz) is float and type(cap) is float
++ and all(type(bound) is float for bound in f0_bounds)
++ and np.geterr() == _NATIVE_RIDGE_ERROR_POLICY):
++ try:
++ native = _native_fit_irls(factor, u, y, w, float(f0_bounds[0]),
++ float(f0_bounds[1]), cap, float(sigma_hz),
++ independent_samples)
++ except (BufferError, TypeError, ValueError, OverflowError):
++ native = None
++ if native is not None and all(np.isfinite(value) for value in native):
++ score, f0, drift, rmse, outlier_fraction = native
++ return {"score": float(score), "f0_hz": float(f0),
++ "source_drift_hz": float(drift), "source_drift_hz_s": float(drift/span),
++ "source_reference_emission_time_s": float((emission.min()+emission.max())/2),
++ "source_span_s": span, "drift_bound_hz": float(cap),
++ "drift_at_bound": bool(cap and abs(drift) > 0.99*cap),
++ "rmse_hz": float(rmse), "support_fraction": 1.0,
++ "sample_count": int(len(y)), "independent_sample_count": independent_samples,
++ "outlier_fraction": float(outlier_fraction)}
effective = w.copy()
basis = (factor**2, u**2)
for iteration in range(6):
diff --cc src/dopplergeist/native_acoustic.py
index 0000000,0000000..2427b41
new file mode 100644
--- /dev/null
+++ b/src/dopplergeist/native_acoustic.py
@@@ -1,0 -1,0 +1,64 @@@
++"""Optional exact-order acceleration for the emission-time acoustic solver."""
++import hashlib
++import os
++from pathlib import Path
++
++import numpy as np
++from scipy.interpolate import CubicHermiteSpline
++
++_backend_choice = os.environ.get("DOPPLERGEIST_ACOUSTIC_BACKEND", "auto")
++if _backend_choice not in {"auto", "python"}:
++ raise ValueError("DOPPLERGEIST_ACOUSTIC_BACKEND must be 'auto' or 'python'")
++_native = None
++if _backend_choice == "auto":
++ try:
++ from . import _native_acoustic as _native
++ except ImportError:
++ _native = None
++
++if _native is None:
++ ACOUSTIC_BACKEND = "python-acoustic-v1"
++else:
++ _binary_hash = hashlib.sha256(Path(_native.__file__).read_bytes()).hexdigest()
++ ACOUSTIC_BACKEND = f"native-c-acoustic-v1:{_binary_hash}"
++
++_ERROR_POLICY = {"divide": "warn", "over": "warn", "under": "ignore", "invalid": "warn"}
++
++
++def try_acoustic(track, t, observer, c, start, end, arrival_start, arrival_end, packed_factory):
++ """Return exact outputs, or None to continue through the Python solver.
++
++ Arrival endpoints retain NumPy's scalar BLAS norm. The existing packed
++ spline object preserves its bounded cache and mutable-coefficient behavior.
++ Motion-support validation stays in Python, including its diagnostic data.
++ """
++ if (_native is None or type(observer) is not np.ndarray
++ or observer.dtype != np.float64 or observer.shape != (3,)
++ or not t.size or not t.flags.c_contiguous or not observer.flags.c_contiguous
++ or type(c) not in (float, int, np.float64)
++ or type(track.origin) not in (float, np.float64)
++ or any(type(value) not in (float, np.float64)
++ for value in (start, end, arrival_start, arrival_end))
++ or type(track.spline) is not CubicHermiteSpline
++ or type(track.derivative) is not CubicHermiteSpline
++ or type(track.spline.axis) is not int or type(track.derivative.axis) is not int
++ or track.spline.axis != 0 or track.derivative.axis != 0
++ or track.spline.extrapolate is not False or track.derivative.extrapolate is not False
++ or np.geterr() != _ERROR_POLICY):
++ return None
++ source = (track.spline.c, track.spline.x, track.derivative.c)
++ if any(type(array) is not np.ndarray or array.dtype != np.float64
++ or not array.flags.c_contiguous or not array.flags.aligned for array in source):
++ return None
++ packed = packed_factory(track.spline, track.derivative)
++ arrays = (track.spline.c, track.spline.x, packed.c, packed.x)
++ if (type(packed.axis) is not int or packed.axis != 0 or packed.extrapolate is not False
++ or any(type(array) is not np.ndarray for array in arrays)):
++ return None
++ output = tuple(np.empty(t.shape) for _ in range(3))
++ success = _native.solve(t, observer, *arrays, track.origin, start, end, c,
++ arrival_start, arrival_end, *output)
++ if not success:
++ return None
++ track._check_motion_support(t, observer, c)
++ return output
diff --cc src/dopplergeist/provenance.py
index 7e3c704,7e3c704..5a4d176
--- a/src/dopplergeist/provenance.py
+++ b/src/dopplergeist/provenance.py
@@@ -4,9 -4,9 +4,19 @@@ Hashes identify supplied inputs. They d
windows, physical bounds, or a search area independently of a known location.
"""
import hashlib
++from importlib.machinery import EXTENSION_SUFFIXES
from pathlib import Path
++def implementation_files(package_root, *, recursive=True):
++ """Include optional native sources and binaries in the existing identity."""
++ root = Path(package_root)
++ paths = root.rglob("*") if recursive else root.iterdir()
++ return sorted(path for path in paths
++ if path.is_file() and (path.suffix in {".py", ".c"}
++ or any(path.name.endswith(suffix) for suffix in EXTENSION_SUFFIXES)))
++
++
def implementation_provenance(code_root):
"""Hash this package, retaining legacy paths relative to its install parent.
@@@ -19,7 -19,7 +29,7 @@@
raise FileNotFoundError(f"Implementation package is absent: {package_root}")
digest = hashlib.sha256()
sources = []
-- for path in sorted(package_root.rglob("*.py")):
++ for path in implementation_files(package_root):
relative = str(path.relative_to(root))
data = path.read_bytes()
# Preserve the existing aggregate digest format for downstream readers.
diff --cc src/dopplergeist/tiled_search.py
index cb22fe4,bb5b55f..3faa01a
--- a/src/dopplergeist/tiled_search.py
+++ b/src/dopplergeist/tiled_search.py
@@@ -22,10 -22,9 +22,10 @@@ from pyproj import Transforme
from .data_access import CONUS, DataUnavailable, content_hash, sha256, write_json
from .finite_search import RetentionLedger, bounded_assessment, classified_assessment, identify_mode, mode_seed
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 .geometry import ACOUSTIC_BACKEND, AcousticSupportError, ecef
++from .matching import RIDGE_FIT_BACKEND, _cache_ridge_fits
+from .search import (_CPA_DTYPE, _PreparedCPATrack, _ordered_cpa_rows,
+ filter_association_event, pair_candidates, score_candidate)
def _support_error(error):
@@@ -694,7 -686,7 +715,10 @@@ def search_national(indexes, terrain, e
for spec, ridge, weight, fit in measurements:
acoustic.append([hashlib_array(a) for a in [spec.time, getattr(spec, "frequency", []),
getattr(spec, "contrast", []), ridge, weight]])
-- modules = {p.name: sha256(p) for p in sorted(Path(__file__).parent.glob("*.py"))}
++ from .provenance import implementation_files
++ package_root = Path(__file__).parent
++ modules = {p.relative_to(package_root).as_posix(): sha256(p)
++ for p in implementation_files(package_root, recursive=False)}
if hasattr(terrain, "files"):
terrain_signature = {name: value["sha256"] for name, value in terrain.files.items()
if name in ("tileList.txt", terrain.geoid_path.name)}
@@@ -704,13 -696,13 +728,18 @@@
rasters += terrain.geoid.rasters
terrain_signature = {"constant_m": getattr(terrain, "constant", None),
"rasters": {str(r.name): sha256(r.name) for r in rasters}}
++ runtime_identity = {"python": platform.python_version(), "machine": platform.machine(),
++ "packages": {name: version(name) for name in ("numpy", "scipy", "pandas", "pyproj", "rasterio", "pyarrow")}}
++ if RIDGE_FIT_BACKEND != "python-irls-v1":
++ runtime_identity["ridge_fit_backend"] = RIDGE_FIT_BACKEND
++ if ACOUSTIC_BACKEND != "python-acoustic-v1":
++ runtime_identity["acoustic_backend"] = ACOUSTIC_BACKEND
identity = {"indexes": [{"input_hash": i.report["input_hash"], "file_sha256": sha256(i.path)} for i in indexes],
"terrain": terrain_signature, "additional_input_hashes": input_hashes or {},
"events": events, "acoustic_hashes": acoustic, "bounds": list(bounds), "time_range_s": list(time_range_s),
"budget": asdict(budget), "scoring": scoring or {}, "filters": filters, "crs": crs, "code": modules,
"coarse_floor_policy": floor_policy,
-- "runtime": {"python": platform.python_version(), "machine": platform.machine(),
-- "packages": {name: version(name) for name in ("numpy", "scipy", "pandas", "pyproj", "rasterio", "pyarrow")}}}
++ "runtime": runtime_identity}
run_hash = content_hash(identity)
if manifest.exists() and json.loads(manifest.read_text())["run_hash"] != run_hash:
raise DataUnavailable("Checkpoint configuration/input/implementation mismatch; use a new output directory")
diff --cc tests/test_real_native_acoustic.py
index 0000000,0000000..74ed1e4
new file mode 100644
--- /dev/null
+++ b/tests/test_real_native_acoustic.py
@@@ -1,0 -1,0 +1,187 @@@
++"""Optional native propagation checks on archived aircraft observations."""
++import json
++import os
++from pathlib import Path
++import subprocess
++import sys
++import unittest
++from unittest.mock import patch
++import warnings
++
++import numpy as np
++import pandas as pd
++
++from dopplergeist import geometry, native_acoustic
++from dopplergeist.provenance import implementation_files
++from dopplergeist.tracks import _segment_velocity
++
++
++def _outcome(track, query, observer, c=343.):
++ with warnings.catch_warnings(record=True) as caught:
++ warnings.simplefilter("always")
++ try:
++ values = track.acoustic(query, observer, c)
++ result = ("ok", tuple((a.dtype.str, a.shape, a.tobytes()) for a in values))
++ except Exception as error:
++ result = ("error", type(error).__name__, str(error), vars(error))
++ return result, [(str(item.message), item.category.__name__) for item in caught]
++
++
++def _clone(track):
++ return geometry.Track(track.id, track.time.copy(), track.lat.copy(), track.lon.copy(),
++ track.altitude.copy(), track.typecode,
++ None if track.velocity is None else track.velocity.copy())
++
++
++class NativeAcousticBackendTests(unittest.TestCase):
++ def test_backend_selector_and_actual_binary_provenance(self):
++ code = "from dopplergeist.geometry import ACOUSTIC_BACKEND; print(ACOUSTIC_BACKEND)"
++ environment = dict(os.environ, DOPPLERGEIST_ACOUSTIC_BACKEND="python")
++ python = subprocess.run([sys.executable, "-c", code], env=environment,
++ text=True, capture_output=True, check=True)
++ self.assertEqual(python.stdout.strip(), "python-acoustic-v1")
++ environment["DOPPLERGEIST_ACOUSTIC_BACKEND"] = "auto"
++ automatic = subprocess.run([sys.executable, "-c", code], env=environment,
++ text=True, capture_output=True, check=True)
++ self.assertTrue(automatic.stdout.strip() == "python-acoustic-v1"
++ or automatic.stdout.strip().startswith("native-c-acoustic-v1:"))
++ environment["DOPPLERGEIST_ACOUSTIC_BACKEND"] = "unknown"
++ invalid = subprocess.run([sys.executable, "-c", code], env=environment,
++ text=True, capture_output=True)
++ self.assertNotEqual(invalid.returncode, 0)
++ self.assertIn("DOPPLERGEIST_ACOUSTIC_BACKEND must be", invalid.stderr)
++ if native_acoustic._native is not None:
++ binary = Path(native_acoustic._native.__file__)
++ self.assertIn(binary, implementation_files(binary.parent))
++
++
[email protected](native_acoustic._native is None, "optional acoustic extension is not built")
++class RealNativeAcousticTests(unittest.TestCase):
++ @classmethod
++ def setUpClass(cls):
++ root = Path(__file__).resolve().parents[1]
++ cls.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 number, (_, rows) in enumerate(frame.groupby((frame.time_s.diff() > 30.).cumsum())):
++ if len(rows) < 3:
++ continue
++ velocity, _ = _segment_velocity(rows)
++ cls.tracks.append(geometry.Track(f"{rows.flight_id.iloc[0]}:{number}",
++ rows.time_s.to_numpy(), rows.lat.to_numpy(), rows.lon.to_numpy(),
++ rows.alt_m.to_numpy(), str(rows.typecode.iloc[0]), velocity))
++ cls.supported, cls.unsupported = [], []
++ for track in cls.tracks:
++ try:
++ track.validate_motion_support()
++ cls.supported.append(track)
++ except geometry.AcousticSupportError:
++ cls.unsupported.append(track)
++ ridge = json.loads((root / "tests/data/real-ridge-batch-arithmetic.json").read_text())
++ cls.ridge_times = np.asarray(ridge["times"])
++
++ def assert_parity(self, track, query, observer, c=343.):
++ with patch.object(native_acoustic, "_native", None):
++ expected = _outcome(track, query, observer, c)
++ actual = _outcome(track, query, observer, c)
++ self.assertEqual(actual, expected)
++
++ def test_recorded_queries_boundaries_and_global_newton_stop(self):
++ self.assertTrue(self.supported)
++ before = native_acoustic._native.successful_calls()
++ for track in self.supported:
++ for index in (0, len(track.time)//2, -1):
++ observer = geometry.ecef(track.lat[index], track.lon[index], 0.)
++ receive = track.time + np.linalg.norm(track.xyz-observer, axis=1)/343.
++ endpoints = receive[[0, -1]]
++ boundary = np.r_[np.nextafter(endpoints, -np.inf), endpoints,
++ np.nextafter(endpoints, np.inf)]
++ measured = receive[len(receive)//2] + self.ridge_times - np.median(self.ridge_times)
++ readonly = receive.copy()
++ readonly.flags.writeable = False
++ for query in (receive, receive[1], receive[::-1], readonly, boundary,
++ measured, measured.reshape(1, -1), np.r_[receive, np.nan],
++ np.r_[receive, np.inf], receive[:0]):
++ for c in (338., 343., 348.):
++ self.assert_parity(track, query, observer, c)
++ self.assertGreater(native_acoustic._native.successful_calls(), before)
++
++ def test_unsupported_tracks_keep_error_details(self):
++ self.assertTrue(self.unsupported)
++ for track in self.unsupported:
++ observer = geometry.ecef(track.lat[len(track.time)//2], track.lon[len(track.time)//2], 0.)
++ receive = track.time + np.linalg.norm(track.xyz-observer, axis=1)/343.
++ self.assert_parity(track, receive, observer)
++ # An extreme sound-speed argument must retain NumPy overflow warnings,
++ # even when an infinite intermediate would leave the final outputs NaN.
++ track = self.supported[0]
++ velocity = track.speed_vector(track.time[0])
++ observer = track.xyz[0] - np.copysign(np.abs(np.spacing(track.xyz[0])), velocity)
++ before = native_acoustic._native.successful_calls()
++ self.assert_parity(track, track.time[0], observer, 1e-312)
++ self.assertEqual(native_acoustic._native.successful_calls(), before)
++
++ def test_noncanonical_policy_layout_and_method_overrides_fall_back(self):
++ track = _clone(self.supported[0])
++ observer = geometry.ecef(track.lat[0], track.lon[0], 0.)
++ receive = track.time + np.linalg.norm(track.xyz-observer, axis=1)/343.
++ for c in (np.float32(343.), np.longdouble(343.)):
++ before = native_acoustic._native.successful_calls()
++ # Longdouble storage can contain padding; compare numerical values.
++ with patch.object(native_acoustic, "_native", None):
++ expected = track.acoustic(receive, observer, c)
++ actual = track.acoustic(receive, observer, c)
++ for a, b in zip(expected, actual):
++ self.assertEqual(a.dtype, b.dtype)
++ self.assertTrue(np.array_equal(a, b, equal_nan=True))
++ self.assertEqual(native_acoustic._native.successful_calls(), before)
++ for policy in ("raise", "ignore"):
++ before = native_acoustic._native.successful_calls()
++ with np.errstate(all=policy):
++ self.assert_parity(track, receive, observer)
++ self.assertEqual(native_acoustic._native.successful_calls(), before)
++ for name in ("position", "_position_velocity"):
++ before = native_acoustic._native.successful_calls()
++ with patch.object(track, name, wraps=getattr(track, name)) as wrapped:
++ self.assert_parity(track, receive, observer)
++ self.assertGreater(wrapped.call_count, 0)
++ self.assertEqual(native_acoustic._native.successful_calls(), before)
++ original_position = geometry.Track.position
++ def position(self, query):
++ return original_position(self, query)
++ before = native_acoustic._native.successful_calls()
++ with patch.object(geometry.Track, "position", position):
++ self.assert_parity(track, receive, observer)
++ self.assertEqual(native_acoustic._native.successful_calls(), before)
++ for name, value in (("axis", 1), ("extrapolate", True)):
++ before = native_acoustic._native.successful_calls()
++ with patch.object(track.spline, name, value):
++ self.assert_parity(track, receive, observer)
++ self.assertEqual(native_acoustic._native.successful_calls(), before)
++ # Read-only inputs are supported, while strided arrays take the reference path.
++ before = native_acoustic._native.successful_calls()
++ self.assert_parity(track, receive[::-1], observer)
++ self.assertEqual(native_acoustic._native.successful_calls(), before)
++
++ def test_cold_and_mutable_packed_spline_cache(self):
++ a, b = (_clone(self.supported[0]) for _ in range(2))
++ observer = geometry.ecef(a.lat[0], a.lon[0], 0.)
++ receive = a.time + np.linalg.norm(a.xyz-observer, axis=1)/343.
++ geometry._packed_kinematics.cache_clear()
++ for mutation in ("none", "source", "packed", "layout"):
++ for track in (a, b):
++ if mutation == "source":
++ track.spline.c[3, 0, 0] = np.nextafter(track.spline.c[3, 0, 0], np.inf)
++ elif mutation == "packed":
++ packed = geometry._packed_kinematics(track.spline, track.derivative)
++ packed.c[3, 0, 0] = np.nextafter(packed.c[3, 0, 0], np.inf)
++ elif mutation == "layout":
++ track.spline.c = np.asfortranarray(track.spline.c)
++ track.time.flags.writeable = False
++ with patch.object(native_acoustic, "_native", None):
++ expected = _outcome(a, receive, observer)
++ self.assertEqual(_outcome(b, receive, observer), expected)
++
++
++if __name__ == "__main__":
++ unittest.main()
diff --cc tests/test_real_native_acoustic_pipeline.py
index 0000000,0000000..7956e40
new file mode 100644
--- /dev/null
+++ b/tests/test_real_native_acoustic_pipeline.py
@@@ -1,0 -1,0 +1,92 @@@
++"""Native propagation parity through real ridge fits and candidate scoring."""
++import json
++import os
++from pathlib import Path
++from types import SimpleNamespace
++
++import numpy as np
++import pandas as pd
++import pytest
++
++from dopplergeist import native_acoustic
++from dopplergeist.data_access import FlightIndex
++from dopplergeist.geometry import AcousticSupportError, ecef
++from dopplergeist.matching import (_cache_ridge_fits, _fit_ridge_uncached, _frequency_scale,
++ association_candidates, prepare_events)
++from dopplergeist.search import filter_association_event, score_candidate
++
++
[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 a real recorded-input diagnostic")
++ if native_acoustic._native is None:
++ pytest.skip("optional native acoustic extension is not built")
++ 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 = SimpleNamespace(**{"x": 0., "y": 0., **fixture["point"]})
++ return fixture, events, measurements, table, tracks, point
++
++
++def _fit_outcome(*args):
++ try:
++ return _fit_ridge_uncached(*args)
++ except AcousticSupportError as error:
++ return {"acoustic_error": vars(error)}
++
++
++def test_recorded_scalar_fits_and_batch_geometry_are_bit_exact(recorded, monkeypatch):
++ _, events, measurements, table, tracks, point = recorded
++ observer = ecef(point.lat, point.lon, point.elev_m)
++ cases = []
++ for event, measurement in zip(events, measurements):
++ rows = filter_association_event(table, event, 5., None, 5.)
++ for row in list(rows.itertuples())[:3]:
++ if row.flight_id not in tracks:
++ continue
++ for offset in (-5., 0., 5.):
++ cases.append((tracks[row.flight_id], observer, measurement,
++ row.receive_time-event["cpa_receive_s"]+offset, event["f0_range_hz"],
++ 343., _frequency_scale(event), event.get("quality", {}).get("source_drift_fraction", .02)))
++ assert cases
++ extension = native_acoustic._native
++ before = extension.successful_calls()
++ with monkeypatch.context() as context:
++ context.setattr(native_acoustic, "_native", None)
++ expected = [_fit_outcome(*args) for args in cases]
++ actual = [_fit_outcome(*args) for args in cases]
++ assert extension.successful_calls() > before
++ assert json.dumps(actual, sort_keys=True, allow_nan=True) == json.dumps(expected, sort_keys=True, allow_nan=True)
++ assert sum(result.get("support_fraction") == 1. for result in actual) > 0
++
++
++def test_recorded_complete_candidate_scoring_is_exact(recorded, monkeypatch):
++ fixture, events, measurements, table, tracks, point = recorded
++ options = {}
++ if "recording_start_window_s" in fixture:
++ from dopplergeist.tiled_search import _association_clock_window
++ center, tolerance = _association_clock_window(
++ fixture["recording_start_window_s"], fixture.get("scoring", {}).get("time_sweep_s", 5.))
++ options = {"time_origin": center, "time_tolerance_s": tolerance}
++ candidates, _ = association_candidates(table, events, max_candidates=20000, **options)
++ assert candidates
++ selected = sorted({0, len(candidates)//5, 2*len(candidates)//5,
++ 3*len(candidates)//5, 4*len(candidates)//5, len(candidates)-1})
++
++ @_cache_ridge_fits
++ def run():
++ return [score_candidate(candidates[i], point, tracks, events, measurements,
++ mode="robust_ridge") for i in selected]
++
++ extension = native_acoustic._native
++ before = extension.successful_calls()
++ with monkeypatch.context() as context:
++ context.setattr(native_acoustic, "_native", None)
++ expected = run()
++ actual = run()
++ assert extension.successful_calls() > before
++ assert json.dumps(actual, sort_keys=True, allow_nan=True) == json.dumps(expected, sort_keys=True, allow_nan=True)
diff --cc tests/test_real_native_ridge.py
index 0000000,0000000..316c36d
new file mode 100644
--- /dev/null
+++ b/tests/test_real_native_ridge.py
@@@ -1,0 -1,0 +1,246 @@@
++"""Exact native arithmetic checks using captured recorded-ridge/ADS-B inputs.
++
++Prefixes and fitting parameters exercise reduction tails and model branches;
++the test does not generate recordings or trajectories.
++"""
++import json
++from pathlib import Path
++
++import numpy as np
++import pytest
++
++from dopplergeist import matching
++
++
++def test_native_ridge_matches_python_on_recorded_samples(monkeypatch):
++ native = getattr(matching, "_native_fit_irls", None)
++ if native is None:
++ pytest.skip("optional native ridge extension is not installed")
++ root = Path(__file__).parent
++ fixture = json.loads((root / "data/real-ridge-batch-arithmetic.json").read_text())
++ times = np.asarray(fixture["times"], dtype=float)
++ ridge = np.asarray(fixture["ridge"], dtype=float)
++ weight = np.asarray(fixture["weight"], dtype=float)
++ factors = np.asarray(fixture["factors"], dtype=float)
++ emissions = np.asarray(fixture["emissions"], dtype=float)
++ bounds = fixture["event"]["f0_range_hz"]
++ checked = 0
++ for count in range(10, len(times) + 1):
++ measurement = (matching.RidgeTimes(times[:count]), ridge[:count], weight[:count], {})
++ for factor, emitted in zip(factors[:, :count], emissions[:, :count]):
++ for sigma in (0.5, 1.0, 3.7, 18.001973492902533):
++ for fraction in (0.0, 0.02, 0.1):
++ arguments = (None, None, measurement, 0.0, bounds, 343.0, sigma, fraction)
++ with monkeypatch.context() as patch:
++ patch.setattr(matching, "_native_fit_irls", None)
++ expected = matching._fit_ridge_uncached(*arguments,
++ acoustic_result=(factor, emitted))
++ actual = matching._fit_ridge_uncached(*arguments,
++ acoustic_result=(factor, emitted))
++ assert json.dumps(actual, sort_keys=True) == json.dumps(expected, sort_keys=True), (count, sigma, fraction, actual, expected)
++ checked += 1
++ assert checked == (len(times) - 9) * len(factors) * 12
++
++
[email protected]("sigma", [np.float32(0.7), np.float64(0.7), 1])
++def test_noncanonical_scalar_parameters_keep_python_arithmetic(monkeypatch, sigma):
++ if getattr(matching, "_native_fit_irls", None) is None:
++ pytest.skip("optional native ridge extension is not installed")
++ fixture = json.loads((Path(__file__).parent / "data/real-ridge-batch-arithmetic.json").read_text())
++ measurement = (matching.RidgeTimes(np.asarray(fixture["times"], dtype=float)),
++ np.asarray(fixture["ridge"], dtype=float),
++ np.asarray(fixture["weight"], dtype=float), {})
++ acoustic = (np.asarray(fixture["factors"][0], dtype=float),
++ np.asarray(fixture["emissions"][0], dtype=float))
++ arguments = (None, None, measurement, 0.0, fixture["event"]["f0_range_hz"], 343.0, sigma, 0.02)
++ with monkeypatch.context() as patch:
++ patch.setattr(matching, "_native_fit_irls", None)
++ expected = matching._fit_ridge_uncached(*arguments, acoustic_result=acoustic)
++
++ def unexpected_native_call(*args):
++ raise AssertionError("Noncanonical scalar parameter reached the native backend")
++
++ monkeypatch.setattr(matching, "_native_fit_irls", unexpected_native_call)
++ actual = matching._fit_ridge_uncached(*arguments, acoustic_result=acoustic)
++ assert json.dumps(actual, sort_keys=True) == json.dumps(expected, sort_keys=True)
++
++
++def test_custom_numpy_error_policy_uses_python_backend(monkeypatch):
++ if getattr(matching, "_native_fit_irls", None) is None:
++ pytest.skip("optional native ridge extension is not installed")
++ fixture = json.loads((Path(__file__).parent / "data/real-ridge-batch-arithmetic.json").read_text())
++ measurement = (matching.RidgeTimes(np.asarray(fixture["times"], dtype=float)),
++ np.asarray(fixture["ridge"], dtype=float),
++ np.asarray(fixture["weight"], dtype=float), {})
++ acoustic = (np.asarray(fixture["factors"][0], dtype=float),
++ np.asarray(fixture["emissions"][0], dtype=float))
++ arguments = (None, None, measurement, 0.0, fixture["event"]["f0_range_hz"], 343.0, 1.0, 0.02)
++ with monkeypatch.context() as patch:
++ patch.setattr(matching, "_native_fit_irls", None)
++ with np.errstate(all="raise"):
++ expected = matching._fit_ridge_uncached(*arguments, acoustic_result=acoustic)
++
++ def unexpected_native_call(*args):
++ raise AssertionError("Custom NumPy error policy reached the native backend")
++
++ monkeypatch.setattr(matching, "_native_fit_irls", unexpected_native_call)
++ with np.errstate(all="raise"):
++ actual = matching._fit_ridge_uncached(*arguments, acoustic_result=acoustic)
++ assert json.dumps(actual, sort_keys=True) == json.dumps(expected, sort_keys=True)
++
++
++def _recorded_native_batch():
++ fixture = json.loads((Path(__file__).parent / "data/real-ridge-batch-arithmetic.json").read_text())
++ measurement = (matching.RidgeTimes(np.asarray(fixture["times"], dtype=float)),
++ np.asarray(fixture["ridge"], dtype=float),
++ np.asarray(fixture["weight"], dtype=float), {})
++ return (measurement, fixture["event"], np.asarray(fixture["factors"], dtype=float),
++ np.asarray(fixture["emissions"], dtype=float))
++
++
[email protected]("order", ["C", "F", "reversed"])
[email protected]("error_policy", ["default", "raise"])
++def test_native_batch_matches_recorded_vectorized_fits(monkeypatch, order, error_policy):
++ from dopplergeist.batch_ridge import _first_event_fits_uncached
++
++ native = getattr(matching, "_native_fit_irls", None)
++ if native is None:
++ pytest.skip("optional native ridge extension is not installed")
++ measurement, event, factors, emissions = _recorded_native_batch()
++ if order == "reversed":
++ factors, emissions = factors[::-1], emissions[::-1]
++ else:
++ factors, emissions = np.array(factors, order=order), np.array(emissions, order=order)
++ policy = {} if error_policy == "default" else {"all": "raise"}
++ with monkeypatch.context() as patch:
++ patch.setattr(matching, "_native_fit_irls", None)
++ with np.errstate(**policy):
++ expected = _first_event_fits_uncached(measurement, event, factors, emissions)
++ calls = 0
++
++ def counted(*args):
++ nonlocal calls
++ calls += 1
++ return native(*args)
++
++ monkeypatch.setattr(matching, "_native_fit_irls", counted)
++ with np.errstate(**policy):
++ actual = _first_event_fits_uncached(measurement, event, factors, emissions)
++ assert json.dumps(actual, sort_keys=True) == json.dumps(expected, sort_keys=True)
++ assert calls == (len(factors) if order == "C" else 0)
++
++
[email protected]("failure", ["none", "type_error"])
[email protected]("failure_row", [0, 2])
++def test_native_batch_failure_keeps_vectorized_fallback(monkeypatch, failure, failure_row):
++ from dopplergeist.batch_ridge import _first_event_fits_uncached
++
++ if getattr(matching, "_native_fit_irls", None) is None:
++ pytest.skip("optional native ridge extension is not installed")
++ native = matching._native_fit_irls
++ inputs = _recorded_native_batch()
++ with monkeypatch.context() as patch:
++ patch.setattr(matching, "_native_fit_irls", None)
++ expected = _first_event_fits_uncached(*inputs)
++ calls = 0
++
++ def unavailable(*args):
++ nonlocal calls
++ calls += 1
++ if calls <= failure_row:
++ return native(*args)
++ if failure == "type_error":
++ raise TypeError("Native buffer is unavailable")
++ return None
++
++ monkeypatch.setattr(matching, "_native_fit_irls", unavailable)
++ actual = _first_event_fits_uncached(*inputs)
++ assert json.dumps(actual, sort_keys=True) == json.dumps(expected, sort_keys=True)
++ assert calls == failure_row + 1
++
++
[email protected]("field", ["sigma", "fraction", "lower", "upper"])
[email protected]("scalar_type", [int, np.float32, np.float64])
++def test_noncanonical_batch_parameters_keep_vectorized_arithmetic(monkeypatch, field, scalar_type):
++ from dopplergeist.batch_ridge import _first_event_fits_uncached
++
++ if getattr(matching, "_native_fit_irls", None) is None:
++ pytest.skip("optional native ridge extension is not installed")
++ measurement, event, factors, emissions = _recorded_native_batch()
++ if field == "sigma":
++ event["quality"]["frequency_loss_scale_hz"] = scalar_type(1)
++ elif field == "fraction":
++ event["quality"]["source_drift_fraction"] = scalar_type(0.02)
++ else:
++ index = 0 if field == "lower" else 1
++ event["f0_range_hz"][index] = scalar_type(event["f0_range_hz"][index])
++ with monkeypatch.context() as patch:
++ patch.setattr(matching, "_native_fit_irls", None)
++ expected = _first_event_fits_uncached(measurement, event, factors, emissions)
++
++ def unexpected_native_call(*args):
++ raise AssertionError("Noncanonical batch parameter reached the native backend")
++
++ monkeypatch.setattr(matching, "_native_fit_irls", unexpected_native_call)
++ actual = _first_event_fits_uncached(measurement, event, factors, emissions)
++ assert json.dumps(actual, sort_keys=True) == json.dumps(expected, sort_keys=True)
++
++
[email protected]("unsupported", ["short", "empty", "nonfinite_factor", "nonfinite_emission"])
++def test_unsupported_recorded_batches_keep_none_fallback(monkeypatch, unsupported):
++ from dopplergeist.batch_ridge import _first_event_fits_uncached
++
++ measurement, event, factors, emissions = _recorded_native_batch()
++ if unsupported == "short":
++ measurement = (matching.RidgeTimes(measurement[0].time[:9]),
++ measurement[1][:9], measurement[2][:9], {})
++ factors, emissions = factors[:, :9], emissions[:, :9]
++ elif unsupported == "empty":
++ factors, emissions = factors[:0], emissions[:0]
++ elif unsupported == "nonfinite_factor":
++ factors[0, 0] = np.nan
++ else:
++ emissions[0, 0] = np.nan
++
++ def unexpected_native_call(*args):
++ raise AssertionError("Unsupported batch reached the native backend")
++
++ monkeypatch.setattr(matching, "_native_fit_irls", unexpected_native_call)
++ with np.errstate(all="raise"):
++ assert _first_event_fits_uncached(measurement, event, factors, emissions) is None
++
++
[email protected]("single_changed_row", [False, True], ids=["legacy-cache", "legacy-fallback"])
++def test_native_batch_preserves_recorded_legacy_arithmetic(monkeypatch, single_changed_row):
++ from dopplergeist import batch_ridge
++
++ if getattr(matching, "_native_fit_irls", None) is None:
++ pytest.skip("optional native ridge extension is not installed")
++ measurement, event, factors, emissions = _recorded_native_batch()
++ if single_changed_row:
++ factors, emissions = factors[1:2], emissions[1:2]
++ inputs = (measurement, event, factors, emissions)
++ with monkeypatch.context() as patch:
++ patch.setattr(matching, "_native_fit_irls", None)
++ canonical = batch_ridge._first_event_fits_uncached(*inputs)
++ legacy = batch_ridge._first_event_fits_uncached(*inputs, legacy_arithmetic=True)
++ assert canonical is not None
++ if single_changed_row:
++ # This row now participates in the legacy scalar validation.
++ assert legacy is None
++ else:
++ assert legacy is not None
++ # The captured second row differs by one ULP in fitted frequency.
++ old, current = legacy[1]["f0_hz"], canonical[1]["f0_hz"]
++ assert old != current and np.nextafter(old, current) == current
++
++ @matching._cache_ridge_fits
++ def check():
++ for _ in range(2):
++ actual = batch_ridge.first_event_fits(*inputs)
++ assert json.dumps(actual, sort_keys=True) == json.dumps(canonical, sort_keys=True)
++ actual = batch_ridge.first_event_fits(*inputs, legacy_arithmetic=True)
++ assert json.dumps(actual, sort_keys=True) == json.dumps(legacy, sort_keys=True)
++ assert len(matching._ridge_fit_cache.get().batch_fit_entries) == 1 + int(legacy is not None)
++
++ check()
diff --cc tests/test_real_ridge_backend.py
index 0000000,0000000..5f3a901
new file mode 100644
--- /dev/null
+++ b/tests/test_real_ridge_backend.py
@@@ -1,0 -1,0 +1,68 @@@
++"""Select the fitter in fresh processes without changing recorded fit results."""
++import json
++import os
++from pathlib import Path
++import subprocess
++import sys
++
++from dopplergeist import matching
++
++
++_RECORDED_FITS = """
++import json
++from pathlib import Path
++import sys
++import numpy as np
++from dopplergeist import batch_ridge, matching
++
++fixture = json.loads(Path(sys.argv[1]).read_text())
++measurement = (matching.RidgeTimes(np.asarray(fixture['times'])),
++ np.asarray(fixture['ridge']), np.asarray(fixture['weight']), {})
++event = fixture['event']
++factors, emissions = np.asarray(fixture['factors']), np.asarray(fixture['emissions'])
++arguments = (None, None, measurement, 0., event['f0_range_hz'], 343.,
++ matching._frequency_scale(event), event['quality'].get('source_drift_fraction', 0.02))
++fits = [matching._fit_ridge_uncached(*arguments, acoustic_result=(factor, emitted))
++ for factor, emitted in zip(factors, emissions)]
++legacy = batch_ridge._first_event_fits_uncached(measurement, event, factors[1:2],
++ emissions[1:2], legacy_arithmetic=True)
++print(json.dumps({'backend': matching.RIDGE_FIT_BACKEND,
++ 'native': matching._native_fit_irls is not None,
++ 'fits': fits, 'legacy': legacy}, sort_keys=True))
++"""
++
++
++def _run_backend(choice, program=_RECORDED_FITS):
++ root = Path(__file__).resolve().parents[1]
++ environment = os.environ.copy()
++ package_parent = Path(matching.__file__).resolve().parents[1]
++ environment["PYTHONPATH"] = os.pathsep.join((str(package_parent), environment.get("PYTHONPATH", "")))
++ if choice is None:
++ environment.pop("DOPPLERGEIST_RIDGE_BACKEND", None)
++ else:
++ environment["DOPPLERGEIST_RIDGE_BACKEND"] = choice
++ return subprocess.run([sys.executable, "-c", program,
++ str(root / "tests/data/real-ridge-batch-arithmetic.json")],
++ env=environment, text=True, capture_output=True, timeout=30)
++
++
++def test_python_backend_selector_preserves_recorded_fits_and_identity():
++ outputs = []
++ for choice in (None, "auto", "python"):
++ result = _run_backend(choice)
++ assert result.returncode == 0, result.stderr
++ outputs.append(json.loads(result.stdout))
++ default, automatic, python = outputs
++ assert default == automatic
++ assert python["backend"] == "python-irls-v1"
++ assert python["native"] is False
++ assert automatic["native"] is (matching._native_fit_irls is not None)
++ assert automatic["native"] == automatic["backend"].startswith("native-c-irls-v2-pairwise:")
++ assert automatic["fits"] == python["fits"]
++ assert automatic["legacy"] is python["legacy"] is None
++
++
++def test_unknown_backend_selector_fails_clearly():
++ result = _run_backend("native", "from dopplergeist import matching")
++ assert result.returncode != 0
++ assert "DOPPLERGEIST_RIDGE_BACKEND must be 'auto' or 'python'" in result.stderr