Skip to content

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

perf: reuse batch validation and exact acoustic screening evidence

Cinna Davis41d06469935f
diff --cc .github/workflows/real-performance.yml
index 034a39f,e7a813c..1af3218
--- a/.github/workflows/real-performance.yml
+++ b/.github/workflows/real-performance.yml
@@@ -3,15 -3,11 +3,15 @@@ on
workflow_dispatch:
inputs:
baseline:
- description: Scalar-consistent baseline commit
- default: d7cc1dd2e8089768253492b3269dfae97b3ad1a4
+ description: Exact baseline commit for both real-input comparisons
- default: a4d27b2cacfe53fdcb4dfbce4d533d4c7eb9436d
++ default: fec518e51f14afe8d36203e6c5e1be1277dea14e
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/**
@@@ -31,14 -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 || 'a4d27b2cacfe53fdcb4dfbce4d533d4c7eb9436d' }}
++ BASELINE_REF: ${{ inputs.baseline || 'fec518e51f14afe8d36203e6c5e1be1277dea14e' }}
jobs:
compare:
if: github.event_name != 'push' || github.ref != 'refs/heads/perf/real-pipeline-throughput-20261103'
@@@ -80,65 -58,15 +80,65 @@@
for width in 120 10; do
python scripts/benchmark_prepared_measurements.py prepare --discovery evidence/audio/w1-sensitivity-20261102/reference/discovery.json --index benchmark-inputs/reference-region.sqlite --clock-half-width-s "$width" --output "benchmark-inputs/point-$width.json"
done
++ - name: 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: 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 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
- 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 tests/test_real_batch_ceilings.py tests/test_real_acoustic_screen_cache.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 --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:
diff --cc README.md
index 99d9686,973167a..e7d076f
--- a/README.md
+++ b/README.md
@@@ -37,6 -37,6 +37,8 @@@ python -m venv .ven
To install the CLI without keeping a checkout, create a virtual environment and run `.venv/bin/python -m pip install "git+https://github.com/1337isnot1337/DOPPLERGEIST.git"`.
++Installation builds optional acoustic and ridge acceleration when a compatible C compiler is available. Python fallbacks remain available. See [native backend checks and reproducible timing](docs/PERFORMANCE.md#reproduce-the-optional-native-backends) to verify which implementations are active and compare complete recorded-input jobs.
++
Native Windows execution is unverified.
### Analyze from the command line
diff --cc docs/PERFORMANCE.md
index 3af8a95,3af8a95..508d24f
--- a/docs/PERFORMANCE.md
+++ b/docs/PERFORMANCE.md
@@@ -838,3 -838,3 +838,90 @@@ terrain-stage evidence, not a full-sear
Applying this scheduler to a saved search changes the package identity and
requires its validated checkpoint compatibility path before resuming that job.
++
++## Reproduce the optional native backends
++
++Installation builds the acoustic and ridge extensions when a compatible C compiler is available.
++The package remains usable when either optional extension cannot build.
++A source checkout used for timing must contain its own built extensions; an installed copy elsewhere does not establish native use.
++
++```bash
++. .venv/bin/activate
++CC=gcc python -m pip install --editable '.[test]'
++python - <<'PY'
++from dopplergeist.geometry import ACOUSTIC_BACKEND
++from dopplergeist.matching import RIDGE_FIT_BACKEND
++print("Acoustic:", ACOUSTIC_BACKEND)
++print("Ridge:", RIDGE_FIT_BACKEND)
++assert ACOUSTIC_BACKEND.startswith("native-c-")
++assert RIDGE_FIT_BACKEND.startswith("native-c-")
++PY
++```
++
++The native acoustic solver retains polynomial evaluation order, global Newton stopping, and Python motion-support diagnostics.
++The ridge extension retains the six IRLS iterations and reduction order.
++Both extensions disable floating-point reassociation and contraction.
++Incompatible numeric representations use the existing Python implementations.
++Acoustic and scalar ridge calls also fall back for unsupported NumPy error policies.
++Batched ridge arithmetic retains its existing ignored-error block and restores the caller's policy for diagnostics.
++The optional ridge implementation is integrated from [PR228](https://github.com/1337isnot1337/DOPPLERGEIST/pull/228).
++
++Set `DOPPLERGEIST_ACOUSTIC_BACKEND=python` and `DOPPLERGEIST_RIDGE_BACKEND=python` before starting a process to force both Python implementations.
++The default for each selector is `auto`; invalid selector values fail explicitly.
++The legacy checkpoint upgrade requires both Python backends and its original runtime and input controls.
++Ordinary checkpoints include the selected native binary identities and reject an implementation mismatch.
++
++### Recorded-input scoring comparison
++
++Install the GitHub CLI (`gh`) before restoring the published input bundles; the restoration script uses `gh release download`.
++Use a fresh output directory and preserve the baseline checkout for the entire comparison.
++The following commands freeze the same real observations and source-informed receiver/clock workload for both implementations:
++
++```bash
++export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 NUMEXPR_NUM_THREADS=1
++export PYTHONPATH=src
++git worktree add --detach ../DOPPLERGEIST-perf-baseline fec518e51f14afe8d36203e6c5e1be1277dea14e
++python scripts/restore_artifacts.py --bundle data-adsb-derived --bundle data-terrain
++python scripts/prepare_reference_upload.py --data-root data --output benchmark-inputs
++for width in 10 120; do
++ python scripts/benchmark_prepared_measurements.py prepare \
++ --discovery evidence/audio/w1-sensitivity-20261102/reference/discovery.json \
++ --index benchmark-inputs/reference-region.sqlite \
++ --clock-half-width-s "$width" --output "benchmark-inputs/point-$width.json"
++ python scripts/benchmark_prepared_measurements.py compare \
++ --fixture "benchmark-inputs/point-$width.json" \
++ --baseline-source ../DOPPLERGEIST-perf-baseline/src --current-source src \
++ --repeats 3 --require-current-native --require-current-native-acoustic \
++ --output "results/native-scoring-$width"
++done
++```
++
++The comparison alternates arm order in fresh worker processes.
++It compares every candidate, diagnostic, support record, ranking, and logical retention row exactly before reporting a speedup.
++Native success counters must increase inside the timed scoring call.
++Input loading is reported separately, and the RSS measurement covers the worker lifetime through scoring.
++
++The complete-fit cache shares its existing 4 MiB serialized-payload budget with validated batch ceilings.
++The separate screening cache permits at most 8 MiB of conservatively charged private loss evidence per scoring context.
++It never retains a candidate's ranking cutoff: every call applies its current cutoff and group count.
++These caches help repeated workloads; first-use hashing and serialization have a cost, so complete-job measurements decide whether they help a workload.
++
++### Complete HTTP methodology
++
++The `Real performance comparison` workflow also replays the complete recording through the HTTP application.
++Select an exact baseline commit and enable the regional comparison.
++Its three pairs run in baseline/current, current/baseline, and baseline/current order, with fresh directories and one shared MP3, request, operator configuration, index, and terrain set.
++Both arms use the same pinned CPU and one numerical thread.
++Input restoration, index preparation, and MP3 encoding happen before the timed arms.
++
++Every pair must pass whole-recording intake, discovery, acquisition, search, refinement, and decision checks.
++The comparison requires exact scientific JSON, logical SQLite contents, decoded audio, CSV/array values, and PNG pixels.
++Only declared path, run identity, timing, and native implementation metadata are normalized; scientific floats have no tolerance.
++Medians are emitted only after all pairs pass, and the individual samples remain available.
++Profiling runs separately and never contributes to timing medians.
++
++The original MP3 retains its 17-ridge/15-group control.
++A different encoding requires an explicit declaration and the canonical WAV identity; it cannot inherit historical event counts or timing claims.
++Both new-encoding arms must still process the complete recording, consider every group, and produce exactly equal outputs.
++These regional computation controls use source-informed bounds and clock evidence.
++They do not establish independent location accuracy, nationwide completion time, or a cold-cache acquisition speedup.
diff --cc src/dopplergeist/acoustic_screen.py
index 54a3fca,54a3fca..f1711d7
--- a/src/dopplergeist/acoustic_screen.py
+++ b/src/dopplergeist/acoustic_screen.py
@@@ -1,7 -1,7 +1,10 @@@
"""Vectorized feasibility bounds for measured Doppler ridges."""
++import hashlib
++import sys
++
import numpy as np
--from .matching import _frequency_scale
++from .matching import _frequency_scale, _ridge_fit_cache
def ridge_trial_rejections(measurement, event, factors, emissions, *, score_floor=None, group_count=None):
@@@ -20,7 -20,7 +23,9 @@@
results return False so the ordinary physical fit handles them. When a
retention floor and group count are supplied, also return finite upper
scores for supported trials that cannot reach that floor. Other entries
-- in the second array are NaN.
++ in the second array are NaN. Identical inputs reuse the floor-independent
++ loss evidence inside one scoring context; each call applies its current
++ retention floor and group count to that evidence.
"""
factors = np.asarray(factors, dtype=float)
emissions = np.asarray(emissions, dtype=float)
@@@ -48,16 -48,16 +53,95 @@@
if measured.sum() < 10 or factors.shape[1] != measured.sum():
return result()
times, ridge, weight = times[measured], ridge[measured], weight[measured]
++ evidence = _cached_loss_lower_bounds(times, ridge, weight, factors, emissions, sigma, fraction, high)
++ if evidence is None:
++ return result()
++ active, valid, lower = evidence
++ with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
++ rejected[active] = (valid & np.isfinite(lower)
++ & (lower > (3*sigma)**2*(1+1e-8)+1e-9))
++ if (score_floor is not None and type(group_count) is int and group_count > 0
++ and np.isfinite(score_floor) and 0 <= group_count-score_floor < 1):
++ threshold = (3*sigma*(group_count-score_floor))**2*(1+1e-8)+1e-9
++ ceiling = group_count-np.sqrt(lower)/(3*sigma)
++ ceiling = np.maximum(0., np.nextafter(
++ ceiling + 64*np.finfo(float).eps*(1+group_count+np.abs(ceiling)), np.inf))
++ bounded = (valid & np.isfinite(lower) & (lower > threshold) & ~rejected[active]
++ & np.isfinite(ceiling) & (ceiling < score_floor))
++ upper[active] = np.where(bounded, ceiling, np.nan)
++ return result()
++
++
++def _cached_loss_lower_bounds(times, ridge, weight, factors, emissions, sigma, fraction, high):
++ """Reuse exact numerical inputs under the scoring context's memory limit."""
++ cache = _ridge_fit_cache.get()
++ arrays = times, ridge, weight, factors, emissions
++ if cache is None:
++ return _loss_lower_bounds(*arrays, sigma, fraction, high)
++ entries = cache.screen_entries
++ if cache.screen_limit <= 0 or cache.max_entries <= 0:
++ entries.clear()
++ cache.screen_bytes = 0
++ return _loss_lower_bounds(*arrays, sigma, fraction, high)
++ if np.geterr()["under"] != "ignore":
++ # The numerical kernel inherits underflow handling. Preserve any
++ # requested warning/exception instead of hiding it behind a cache hit.
++ return _loss_lower_bounds(*arrays, sigma, fraction, high)
++ # Layout affects reduction order. Keys retain input bytes and layout, but
++ # never the much larger propagation arrays themselves. Parameters have
++ # already been converted to finite Python floats by the public validator.
++ key = (_loss_lower_bounds, tuple(value.hex() for value in (sigma, fraction, high)),
++ tuple((value.dtype.str, value.shape, value.strides, value.flags.aligned,
++ hashlib.sha256(value.tobytes()).digest()) for value in arrays))
++ # A caller may lower a budget between requests; enforce that budget on hits
++ # as well as inserts rather than retaining an oversized previous context.
++ while entries and (len(entries) > cache.max_entries or
++ cache.screen_bytes + sys.getsizeof(entries) > cache.screen_limit):
++ _, (_, removed) = entries.popitem(last=False)
++ cache.screen_bytes -= removed
++ previous = entries.get(key)
++ if previous is not None:
++ entries.move_to_end(key)
++ return previous[0]
++ evidence = _loss_lower_bounds(*arrays, sigma, fraction, high)
++ if evidence is None:
++ return None
++
++ def key_size(value):
++ return sys.getsizeof(value) + (sum(map(key_size, value)) if isinstance(value, tuple) else 0)
++
++ # Charge array data conservatively even if getsizeof already includes it.
++ # Include entry containers and the OrderedDict's actual backing allocation.
++ size = key_size(key) + sum(sys.getsizeof(value) + value.nbytes for value in evidence) + 256
++ if size <= cache.screen_limit:
++ while entries and (len(entries) >= cache.max_entries or
++ cache.screen_bytes + size + sys.getsizeof(entries) > cache.screen_limit):
++ _, (_, removed) = entries.popitem(last=False)
++ cache.screen_bytes -= removed
++ # These arrays stay private. Public rejection and ceiling arrays are
++ # created anew, so caller mutations cannot change cached evidence.
++ for value in evidence:
++ value.setflags(write=False)
++ entries[key] = (evidence, size)
++ cache.screen_bytes += size
++ while entries and cache.screen_bytes + sys.getsizeof(entries) > cache.screen_limit:
++ _, (_, removed) = entries.popitem(last=False)
++ cache.screen_bytes -= removed
++ return evidence
++
++
++def _loss_lower_bounds(times, ridge, weight, factors, emissions, sigma, fraction, high):
++ """Compute the existing dual bound without any candidate retention floor."""
_, first = np.unique(times, return_index=True)
first = np.sort(first)
count = min(48, len(first))
if count < 3:
-- return result()
++ return None
selected = first[np.linspace(0, len(first)-1, count, dtype=int)]
active = np.flatnonzero(np.all(np.isfinite(factors), axis=1) & np.all(factors > 0, axis=1)
& np.all(np.isfinite(emissions), axis=1))
if not len(active):
-- return result()
++ return None
with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
x, full_emission = factors[active][:, selected], emissions[active]
samples, y, w = full_emission[:, selected], ridge[selected], weight[selected]
@@@ -90,15 -90,15 +174,4 @@@
error = 1e-7*(1+np.sum(np.abs(dual*y), axis=1)+np.sum(np.abs(conjugate), axis=1)
+source_box+drift_box)
lower = np.maximum(0., value-error)/np.sum(weight)
-- rejected[active] = (valid & np.isfinite(lower)
-- & (lower > (3*sigma)**2*(1+1e-8)+1e-9))
-- if (score_floor is not None and type(group_count) is int and group_count > 0
-- and np.isfinite(score_floor) and 0 <= group_count-score_floor < 1):
-- threshold = (3*sigma*(group_count-score_floor))**2*(1+1e-8)+1e-9
-- ceiling = group_count-np.sqrt(lower)/(3*sigma)
-- ceiling = np.maximum(0., np.nextafter(
-- ceiling + 64*np.finfo(float).eps*(1+group_count+np.abs(ceiling)), np.inf))
-- bounded = (valid & np.isfinite(lower) & (lower > threshold) & ~rejected[active]
-- & np.isfinite(ceiling) & (ceiling < score_floor))
-- upper[active] = np.where(bounded, ceiling, np.nan)
-- return result()
++ return active, valid, lower
diff --cc src/dopplergeist/batch_ridge.py
index bce2523,1434448..d9bc57a
--- a/src/dopplergeist/batch_ridge.py
+++ b/src/dopplergeist/batch_ridge.py
@@@ -1,5 -1,5 +1,6 @@@
"""Batched robust ridge fits with the scalar model's arithmetic order."""
import hashlib
++import math
import pickle
import numpy as np
@@@ -38,11 -37,11 +39,60 @@@ def _batch_fit_key(measurement, event,
def first_event_fits(measurement, event, factors, emissions, *, legacy_arithmetic=False):
"""Reuse an identical complete fit batch within the current scoring call."""
++ return _cached_first_event_fits(measurement, event, factors, emissions,
++ legacy_arithmetic=legacy_arithmetic)
++
++
++_CANONICAL_FIRST_EVENT_FITS = first_event_fits
++
++
++class _CeilingFitBatch:
++ """Private snapshot: independently copied fits and their validated ceilings."""
++
++ __slots__ = ("fits", "limit", "ceilings")
++
++ def __init__(self, fits, limit, ceilings):
++ self.fits, self.limit, self.ceilings = fits, limit, ceilings
++
++
++def _first_event_fits_with_ceilings(measurement, event, factors, emissions, limit, *,
++ legacy_arithmetic=False):
++ """Reuse a whole ceiling vector only for the unchanged, pure core validator.
++
++ Noncanonical inputs and custom hooks retain the caller's per-row validation
++ order. Fit-only snapshots can coexist with snapshots enriched by this path.
++ """
++ from . import search
++
++ bounds = event.get("f0_range_hz") if type(event) is dict else None
++ quality = event.get("quality", {}) if type(event) is dict else None
++ fraction = quality.get("source_drift_fraction", .02) if type(quality) is dict else None
++ canonical = (
++ first_event_fits is _CANONICAL_FIRST_EVENT_FITS
++ and _first_event_fits_uncached is _CANONICAL_BATCH_FITTER
++ and _fit_diagnostics is _CANONICAL_FIT_DIAGNOSTICS
++ and all(current is original for current, original in zip(
++ (search._association_event_ceiling, search._association_event_ceiling_uncached,
++ search._ridge_trial_classification), search._CANONICAL_CEILING_FUNCTIONS))
++ and type(limit) is float and math.isfinite(limit) and limit > 0
++ and type(bounds) in (list, tuple) and len(bounds) == 2
++ and all(type(value) is float for value in (*bounds, fraction))
++ and np.geterr() == {"divide": "warn", "over": "warn", "under": "ignore", "invalid": "warn"})
++ if not canonical:
++ return (first_event_fits(measurement, event, factors, emissions,
++ legacy_arithmetic=legacy_arithmetic), None)
++ return _cached_first_event_fits(measurement, event, factors, emissions,
++ legacy_arithmetic=legacy_arithmetic, ceiling_limit=limit)
++
++
++def _cached_first_event_fits(measurement, event, factors, emissions, *,
++ legacy_arithmetic=False, ceiling_limit=None):
options = {"legacy_arithmetic": True} if legacy_arithmetic else {}
cache = _ridge_fit_cache.get()
kernel = _first_event_fits_uncached
if cache is None or cache.max_entries < 1 or cache.batch_fit_limit <= 0:
-- return kernel(measurement, event, factors, emissions, **options)
++ result = kernel(measurement, event, factors, emissions, **options)
++ return result if ceiling_limit is None else (result, None)
# A changed fitter must not reuse its predecessor's snapshots.
if cache.batch_fit_function is not kernel:
cache.batch_fit_entries.clear()
@@@ -53,18 -52,18 +103,34 @@@
if legacy_arithmetic:
key = hashlib.sha256(b"legacy-array-v1" + key).digest()
except (TypeError, ValueError, KeyError, AttributeError):
-- return kernel(measurement, event, factors, emissions, **options)
++ result = kernel(measurement, event, factors, emissions, **options)
++ return result if ceiling_limit is None else (result, None)
entries = cache.batch_fit_entries
if key in entries:
entries.move_to_end(key)
# Only snapshots produced below from our own scalar-valued diagnostics
# enter this private memory cache. No files or external pickles are read.
-- return pickle.loads(entries[key])
-- result = kernel(measurement, event, factors, emissions, **options)
++ saved = pickle.loads(entries[key])
++ result = saved.fits if type(saved) is _CeilingFitBatch else saved
++ if ceiling_limit is None:
++ return result
++ if type(saved) is _CeilingFitBatch and saved.limit == ceiling_limit:
++ return result, saved.ceilings
++ else:
++ result = kernel(measurement, event, factors, emissions, **options)
++ ceilings = None
if result is not None:
-- snapshot = pickle.dumps(result, protocol=5)
++ if ceiling_limit is not None:
++ from .search import _association_event_ceiling
++ ceilings = [_association_event_ceiling(fit, fit["score"], fit["f0_hz"], event, ceiling_limit)
++ for fit in result]
++ saved = result if ceiling_limit is None else _CeilingFitBatch(result, ceiling_limit, ceilings)
++ snapshot = pickle.dumps(saved, protocol=5)
size = len(key) + len(snapshot)
if size <= cache.batch_fit_limit:
++ previous = entries.pop(key, None)
++ if previous is not None:
++ cache.batch_fit_bytes -= len(key) + len(previous)
while entries and (cache.batch_fit_bytes + size > cache.batch_fit_limit
or len(entries) >= cache.max_entries):
old_key, old_snapshot = entries.popitem(last=False)
@@@ -73,7 -72,7 +139,7 @@@
cache.batch_fit_bytes += size
# None fallbacks and exceptions are never cached. The first caller also
# owns its diagnostics: later mutations cannot change the stored bytes.
-- return result
++ return result if ceiling_limit is None else (result, ceilings)
def _first_event_fits_uncached(measurement, event, factors, emissions, *, legacy_arithmetic=False):
@@@ -203,13 -180,3 +269,17 @@@
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))]
++
++
++_CANONICAL_BATCH_FITTER = _first_event_fits_uncached
++_CANONICAL_FIT_DIAGNOSTICS = _fit_diagnostics
diff --cc src/dopplergeist/matching.py
index 6f6b3ac,b17cfa2..d099d99
--- a/src/dopplergeist/matching.py
+++ b/src/dopplergeist/matching.py
@@@ -82,6 -58,6 +82,9 @@@ class _RidgeFitCache
self.batch_fit_limit = 4 * 1024 * 1024
self.batch_fit_function = None
self.ceiling_entries = OrderedDict()
++ self.screen_entries = OrderedDict()
++ self.screen_bytes = 0
++ self.screen_limit = 8 * 1024 * 1024
def prepared_measurement(self, measurement, sigma_hz, drift_fraction, key):
"""Reuse selected samples only after checking their current content key."""
@@@ -175,9 -151,9 +178,11 @@@ def _cache_ridge_fits(function, *, max_
"""Reuse fits only while this batch's tracks stay unchanged.
Each fit cache has at most 4,096 entries by default. Serialized batch
-- snapshots and digest bytes are bounded to 4 MiB; Python object/container
-- overhead is additional. Prepared measurements use their own 4 MiB bound
-- and acoustic arrays use 32 MiB. Context-local state prevents
++ snapshots, including validated ceiling vectors, and digest bytes are bounded
++ to 4 MiB; Python object/container overhead is additional. Prepared measurements
++ use their own 4 MiB bound and acoustic arrays use 32 MiB. Acoustic screening
++ evidence has an additional 8 MiB budget, including conservatively charged
++ keys, arrays and containers. Context-local state prevents
reuse between concurrent jobs, nested batches or later calls. Cached results
are copied so candidate diagnostics remain independently mutable.
"""
diff --cc src/dopplergeist/search.py
index 18260aa,b1e5759..567f54c
--- a/src/dopplergeist/search.py
+++ b/src/dopplergeist/search.py
@@@ -438,6 -391,6 +438,10 @@@ def _association_event_ceiling_uncached
return float(np.nextafter(1 - (-score) / limit, np.inf))
++_CANONICAL_CEILING_FUNCTIONS = (_association_event_ceiling, _association_event_ceiling_uncached,
++ _ridge_trial_classification)
++
++
def _association_trial_bound(result, events):
"""Bound an incompletely supported association at one shared clock.
@@@ -547,7 -500,7 +551,7 @@@ def _batched_ridge_trials(tracks, event
scalar fits, including each clock's first acoustic-support error.
"""
from .acoustic_screen import ridge_trial_rejections
-- from .batch_ridge import first_event_fits
++ from .batch_ridge import first_event_fits, _first_event_fits_with_ceilings
from .matching import _frequency_scale, fit_ridge
diagnostics = [[] for _ in starts]
@@@ -577,12 -530,12 +581,16 @@@
eligible.append(trial)
else:
eligible = active
-- fitted = None
-- if batch is not None and len(eligible) >= 4:
-- fitted = first_event_fits(measurement, event,
-- batch[0][eligible], batch[1][eligible],
-- legacy_arithmetic=legacy_first_batch and index == 0)
++ fitted = fitted_ceilings = None
remaining = len(events) - index - 1
++ if batch is not None and len(eligible) >= 4:
++ arguments = (measurement, event, batch[0][eligible], batch[1][eligible])
++ legacy = legacy_first_batch and index == 0
++ if remaining and bound_enabled:
++ fitted, fitted_ceilings = _first_event_fits_with_ceilings(
++ *arguments, limits[index], legacy_arithmetic=legacy)
++ else:
++ fitted = first_event_fits(*arguments, legacy_arithmetic=legacy)
next_active = []
for fit_index, trial in enumerate(eligible):
try:
@@@ -600,8 -553,8 +608,8 @@@
diagnostics[trial].append(fit)
if remaining:
if bound_enabled:
-- contribution = _association_event_ceiling(
-- fit, fit["score"], fit["f0_hz"], event, limits[index])
++ contribution = (fitted_ceilings[fit_index] if fitted_ceilings is not None else
++ _association_event_ceiling(fit, fit["score"], fit["f0_hz"], event, limits[index]))
if contribution == -np.inf:
outcomes[trial] = (None, -np.inf, None)
continue
diff --cc src/dopplergeist/tiled_search.py
index 3faa01a,04acebe..274d0fa
--- a/src/dopplergeist/tiled_search.py
+++ b/src/dopplergeist/tiled_search.py
@@@ -22,12 -23,34 +23,35 @@@ 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 _verified_terrain_hash(path, cache):
+ """Reuse a digest only while the same file identity and timestamps hold."""
+ path = Path(path)
+
+ def identity():
+ stat = path.stat()
+ return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns
+
+ before = identity()
+ entry = cache.get(path)
+ if entry is not None and entry[0] == before:
+ cache.move_to_end(path)
+ return entry[1]
+ digest = sha256(path)
+ if identity() != before:
+ raise DataUnavailable(f"Terrain changed while hashing: {path}")
+ cache[path] = (before, digest)
+ cache.move_to_end(path)
+ if len(cache) > 256:
+ cache.popitem(last=False)
+ return digest
+
+
def _support_error(error):
result = {"track_id": error.track_id, "reason": error.reason}
for name in ("emission_intervals_s", "receive_intervals_s"):
diff --cc tests/test_real_acoustic_screen_cache.py
index 0000000,0000000..a0ead7f
new file mode 100644
--- /dev/null
+++ b/tests/test_real_acoustic_screen_cache.py
@@@ -1,0 -1,0 +1,180 @@@
++"""Exact screen-cache regressions using recorded ridges and aircraft tracks."""
++from copy import deepcopy
++import json
++import os
++from pathlib import Path
++import sys
++
++import numpy as np
++import pandas as pd
++import pytest
++
++from dopplergeist import acoustic_screen as screen
++from dopplergeist.data_access import FlightIndex
++from dopplergeist.geometry import ecef
++from dopplergeist.matching import (_cache_ridge_fits, _frequency_scale, _ridge_fit_cache,
++ batch_acoustic_trials, prepare_events)
++from dopplergeist.search import filter_association_event
++
++
[email protected](scope="module")
++def recorded_batches():
++ source = os.environ.get("DOPPLERGEIST_REAL_CPA_FIXTURE")
++ if not source:
++ pytest.skip("set DOPPLERGEIST_REAL_CPA_FIXTURE to a recorded CPA diagnostic")
++ fixture = json.loads(Path(source).read_text())
++ events, measurements = prepare_events(fixture["events"])
++ table = pd.DataFrame(fixture["cpa_rows"])
++ tracks = {track.id: track for track in FlightIndex(fixture["real_index"]).lookup(
++ sorted(set(table.flight_id)), max_tracks=2000, max_samples=2000000)}
++ point = fixture["point"]
++ observer = ecef(point["lat"], point["lon"], point["elev_m"])
++ batches = []
++ for event, measurement in zip(events, measurements):
++ rows = filter_association_event(table, event, 5., None, 5.)
++ for row in list(rows.itertuples())[:2]:
++ if row.flight_id not in tracks:
++ continue
++ starts = row.receive_time-event["cpa_receive_s"]+np.linspace(-5, 5, 21)
++ batch = batch_acoustic_trials([tracks[row.flight_id]], [measurement], observer, starts)[0]
++ if batch is not None and np.all(np.isfinite(batch)):
++ batches.append((measurement, event, *batch))
++ assert len(batches) > 2
++ return batches
++
++
++def same(actual, expected):
++ if isinstance(actual, tuple):
++ assert all(np.array_equal(a, b, equal_nan=True) for a, b in zip(actual, expected))
++ else:
++ assert np.array_equal(actual, expected)
++
++
++def test_real_cached_loss_evidence_uses_current_floor(recorded_batches, monkeypatch):
++ original = screen._loss_lower_bounds
++ calls = 0
++
++ def counted(*args):
++ nonlocal calls
++ calls += 1
++ return original(*args)
++
++ monkeypatch.setattr(screen, "_loss_lower_bounds", counted)
++ settings = [(group, floor) for group in (1, 3, 6, 16)
++ for floor in (0., group-1., group-.3, float(np.nextafter(group, -np.inf)),
++ float(group), float(group+1), float("nan"))]
++ expected = [[screen.ridge_trial_rejections(*values, score_floor=floor, group_count=group)
++ for group, floor in settings] for values in recorded_batches]
++ calls = 0
++
++ @_cache_ridge_fits
++ def compare():
++ for values, results in zip(recorded_batches, expected):
++ before = calls
++ for (group, floor), result in zip(settings, results):
++ actual = screen.ridge_trial_rejections(*values, score_floor=floor, group_count=group)
++ same(actual, result)
++ actual[0][:] = True
++ actual[1][:] = -12345. # Returned arrays cannot modify stored evidence.
++ assert calls == before + 1
++ cache = _ridge_fit_cache.get()
++ assert 0 < cache.screen_bytes + sys.getsizeof(cache.screen_entries) <= cache.screen_limit
++ assert len(cache.screen_entries) <= cache.max_entries
++
++ compare()
++ assert _ridge_fit_cache.get() is None
++
++
++def test_real_screen_cache_mutation_and_eviction(recorded_batches, monkeypatch):
++ base = recorded_batches[0]
++ changed = []
++ for index in range(5):
++ values = deepcopy(base)
++ array = (values[0][0].time, values[0][1], values[0][2], values[2], values[3])[index]
++ array.flat[0] = np.nextafter(array.flat[0], np.inf)
++ changed.append(values)
++ for name in ("sigma", "fraction", "high"):
++ values = deepcopy(base)
++ event = values[1]
++ if name == "sigma":
++ event["quality"]["frequency_loss_scale_hz"] = float(np.nextafter(_frequency_scale(event), np.inf))
++ elif name == "fraction":
++ event["quality"]["source_drift_fraction"] = float(np.nextafter(
++ event["quality"].get("source_drift_fraction", .02), np.inf))
++ else:
++ event["f0_range_hz"][1] = float(np.nextafter(event["f0_range_hz"][1], np.inf))
++ changed.append(values)
++ changed.append((*base[:2], np.asfortranarray(base[2]), np.asfortranarray(base[3])))
++ settings = {"score_floor": 2.7, "group_count": 3}
++ expected = [screen.ridge_trial_rejections(*values, **settings) for values in [base, *changed]]
++ original = screen._loss_lower_bounds
++ calls = 0
++
++ def counted(*args):
++ nonlocal calls
++ calls += 1
++ return original(*args)
++
++ monkeypatch.setattr(screen, "_loss_lower_bounds", counted)
++
++ @_cache_ridge_fits
++ def compare():
++ cache = _ridge_fit_cache.get()
++ same(screen.ridge_trial_rejections(*base, **settings), expected[0])
++ same(screen.ridge_trial_rejections(*deepcopy(base), **settings), expected[0])
++ assert calls == 1
++ for values, result in zip(changed, expected[1:]):
++ before = calls
++ same(screen.ridge_trial_rejections(*values, **settings), result)
++ assert calls == before+1
++ cache.max_entries = 1
++ for values, result in zip([base, changed[0], base], [expected[0], expected[1], expected[0]]):
++ before = calls
++ same(screen.ridge_trial_rejections(*values, **settings), result)
++ assert calls == before+1
++ assert len(cache.screen_entries) == 1
++ for limit in (1, 0):
++ cache.screen_limit = limit
++ before = calls
++ for _ in range(2):
++ same(screen.ridge_trial_rejections(*base, **settings), expected[0])
++ assert calls == before+2
++ assert not cache.screen_entries and cache.screen_bytes == 0
++
++ compare()
++
++
++def test_recorded_underflow_policy_is_not_hidden_by_a_cache_hit(recorded_batches, monkeypatch):
++ measurement, event, factors, emissions = recorded_batches[0]
++ # Preserve recorded samples and relative weights; force the numerical edge
++ # case by uniformly rescaling their weights below the determinant range.
++ measurement = (measurement[0], measurement[1], measurement[2] * 1e-200, measurement[3])
++ original = screen._loss_lower_bounds
++ calls = 0
++
++ def counted(*args):
++ nonlocal calls
++ calls += 1
++ return original(*args)
++
++ monkeypatch.setattr(screen, "_loss_lower_bounds", counted)
++
++ @_cache_ridge_fits
++ def compare():
++ with np.errstate(under="ignore"):
++ screen.ridge_trial_rejections(measurement, event, factors, emissions)
++ assert calls == 1
++ assert _ridge_fit_cache.get().screen_entries
++ for policy in ("warn", "raise"):
++ for _ in range(2):
++ before = calls
++ with np.errstate(under=policy):
++ if policy == "warn":
++ with pytest.warns(RuntimeWarning, match="underflow"):
++ screen.ridge_trial_rejections(measurement, event, factors, emissions)
++ else:
++ with pytest.raises(FloatingPointError, match="underflow"):
++ screen.ridge_trial_rejections(measurement, event, factors, emissions)
++ assert calls == before + 1
++
++ compare()
diff --cc tests/test_real_batch_ceilings.py
index 0000000,0000000..c9b1ff1
new file mode 100644
--- /dev/null
+++ b/tests/test_real_batch_ceilings.py
@@@ -1,0 -1,0 +1,173 @@@
++"""Whole-batch ceiling reuse on captured audio and historical ADS-B geometry."""
++from copy import deepcopy
++import json
++from pathlib import Path
++import pickle
++import sys
++import unittest
++from unittest.mock import patch
++
++import numpy as np
++
++from dopplergeist import batch_ridge, matching, search
++
++
++def recorded():
++ fixture = json.loads((Path(__file__).parent / "data/real-ridge-batch-arithmetic.json").read_text())
++ measurement = (matching.RidgeTimes(np.asarray(fixture["times"])),
++ np.asarray(fixture["ridge"]), np.asarray(fixture["weight"]), {})
++ return measurement, fixture["event"], np.asarray(fixture["factors"]), np.asarray(fixture["emissions"])
++
++
++def ceilings(fits, event, limit):
++ if fits is None:
++ return None
++ return [search._association_event_ceiling_uncached(fit, fit["score"], fit["f0_hz"], event, limit)
++ for fit in fits]
++
++
++class RecordedBatchCeilings(unittest.TestCase):
++ def test_reuse_enriches_fit_snapshot_and_copies_both_results(self):
++ measurement, event, factors, emissions = recorded()
++ limit = 3 * matching._frequency_scale(event)
++ expected = batch_ridge.first_event_fits(measurement, event, factors, emissions)
++ expected_ceilings = ceilings(expected, event, limit)
++ calls = []
++
++ def profile(frame, action, unused):
++ if action == "call" and frame.f_code is search._association_event_ceiling.__code__:
++ calls.append(1)
++
++ @matching._cache_ridge_fits
++ def run():
++ cache = matching._ridge_fit_cache.get()
++ self.assertEqual(batch_ridge.first_event_fits(measurement, event, factors, emissions), expected)
++ self.assertIs(type(pickle.loads(next(iter(cache.batch_fit_entries.values())))), list)
++ before = sys.getprofile()
++ sys.setprofile(profile)
++ try:
++ fits, upper = batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit)
++ self.assertEqual((fits, upper), (expected, expected_ceilings))
++ self.assertEqual(len(calls), len(fits))
++ fits[0].clear()
++ upper[0] = -123.
++ again = batch_ridge._first_event_fits_with_ceilings(
++ deepcopy(measurement), deepcopy(event), factors.copy(), emissions.copy(), limit)
++ self.assertEqual(again, (expected, expected_ceilings))
++ self.assertEqual(len(calls), len(expected))
++ self.assertEqual(batch_ridge.first_event_fits(measurement, event, factors, emissions), expected)
++ finally:
++ sys.setprofile(before)
++ self.assertEqual(len(cache.batch_fit_entries), 1)
++ self.assertEqual(cache.batch_fit_bytes,
++ sum(len(key) + len(value) for key, value in cache.batch_fit_entries.items()))
++ self.assertLessEqual(cache.batch_fit_bytes, cache.batch_fit_limit)
++
++ run()
++ self.assertIsNone(matching._ridge_fit_cache.get())
++
++ def test_event_limit_and_legacy_changes_keep_exact_scalar_ceilings(self):
++ measurement, event, factors, emissions = recorded()
++ limit = 3 * matching._frequency_scale(event)
++ events = [event]
++ for field in ("frequency_loss_scale_hz", "source_drift_fraction"):
++ changed = deepcopy(event)
++ original = matching._frequency_scale(event) if field.startswith("frequency") else .02
++ changed.setdefault("quality", {})[field] = float(np.nextafter(original, np.inf))
++ events.append(changed)
++ for index in range(2):
++ changed = deepcopy(event)
++ changed["f0_range_hz"][index] = float(np.nextafter(changed["f0_range_hz"][index], np.inf))
++ events.append(changed)
++
++ @matching._cache_ridge_fits
++ def run():
++ for configured in events:
++ for legacy in (False, True):
++ expected = batch_ridge._first_event_fits_uncached(
++ measurement, configured, factors, emissions, legacy_arithmetic=legacy)
++ for bound in (limit, float(np.nextafter(limit, np.inf))):
++ actual = batch_ridge._first_event_fits_with_ceilings(
++ measurement, configured, factors, emissions, bound, legacy_arithmetic=legacy)
++ self.assertEqual(actual, (expected, ceilings(expected, configured, bound)))
++
++ run()
++
++ def test_custom_classification_and_noncanonical_inputs_keep_per_row_path(self):
++ measurement, event, factors, emissions = recorded()
++ limit = 3 * matching._frequency_scale(event)
++
++ class Custom(dict):
++ pass
++
++ @matching._cache_ridge_fits
++ def run():
++ expected = batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit)
++ with patch.object(search, "_ridge_trial_classification", return_value=("unknown", "custom")):
++ fits, upper = batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit)
++ self.assertEqual(fits, expected[0])
++ self.assertIsNone(upper)
++ self.assertEqual(ceilings(fits, event, limit), [1.] * len(fits))
++ self.assertEqual(batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit), expected)
++ with np.errstate(all="raise"):
++ fits, upper = batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit)
++ self.assertEqual(fits, expected[0])
++ self.assertIsNone(upper)
++ for bound in (np.float64(limit), np.float32(limit), 1, 0., -0., float("nan"), float("inf")):
++ fits, upper = batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, bound)
++ self.assertEqual(fits, expected[0])
++ self.assertIsNone(upper)
++ for configured in (Custom(event), dict(event, quality=Custom(event["quality"]))):
++ fits, upper = batch_ridge._first_event_fits_with_ceilings(
++ measurement, configured, factors, emissions, limit)
++ self.assertEqual(fits, expected[0])
++ self.assertIsNone(upper)
++ with patch.object(batch_ridge, "first_event_fits", return_value=None) as fallback:
++ self.assertEqual(batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit), (None, None))
++ fallback.assert_called_once()
++
++ run()
++
++ def test_shared_byte_entry_budgets_and_nested_scopes(self):
++ measurement, event, factors, emissions = recorded()
++ limit = 3 * matching._frequency_scale(event)
++ expected = batch_ridge.first_event_fits(measurement, event, factors, emissions)
++
++ def run():
++ cache = matching._ridge_fit_cache.get()
++ batch_ridge._first_event_fits_with_ceilings(measurement, event, factors, emissions, limit)
++ batch_ridge._first_event_fits_with_ceilings(measurement, event, factors[::-1], emissions[::-1], limit)
++ self.assertEqual(len(cache.batch_fit_entries), 1)
++ actual = batch_ridge._first_event_fits_with_ceilings(measurement, event, factors, emissions, limit)
++ self.assertEqual(actual, (expected, ceilings(expected, event, limit)))
++
++ @matching._cache_ridge_fits
++ def nested():
++ self.assertIsNot(matching._ridge_fit_cache.get(), cache)
++ self.assertEqual(batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit), actual)
++ nested()
++ self.assertIs(matching._ridge_fit_cache.get(), cache)
++ cache.batch_fit_entries.clear()
++ cache.batch_fit_bytes = 0
++ for size in (1, 0):
++ cache.batch_fit_limit = size
++ fits, upper = batch_ridge._first_event_fits_with_ceilings(
++ measurement, event, factors, emissions, limit)
++ self.assertEqual(fits, expected)
++ self.assertEqual(upper, ceilings(expected, event, limit) if size else None)
++ self.assertEqual(cache.batch_fit_bytes, 0)
++ self.assertFalse(cache.batch_fit_entries)
++
++ matching._cache_ridge_fits(run, max_entries=1)()
++
++
++if __name__ == "__main__":
++ unittest.main()
diff --cc tests/test_real_native_acoustic.py
index 74ed1e4,0000000..0b8d576
mode 100644,000000..100644
--- a/tests/test_real_native_acoustic.py
+++ b/tests/test_real_native_acoustic.py
@@@ -1,187 -1,0 +1,192 @@@
+"""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):
++ original = getattr(track.spline, name)
++ try:
++ setattr(track.spline, name, value)
+ self.assert_parity(track, receive, observer)
++ finally:
++ # Newer SciPy exposes axis as a property without a deleter.
++ setattr(track.spline, name, original)
+ 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()