Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)
Python acoustic-geolocationads-baircraft-trackingairplaneaudio-forensicsdoppler-effectdoppler-shiftgeolocationosintsignal-processing
Reproduce measured NASA outcomes and add real browser verification while preserving current main
Cinna Davis4b2485b7c277
diff --cc benchmarks/README.mdindex b1c162c,b1c162c..bee74dd--- a/benchmarks/README.md+++ b/benchmarks/README.md@@@ -149,3 -149,3 +149,81 @@@ on the committed helper, without repeatThe missing microphone/UTC evidence described above still prevents these casesfrom qualifying as real geolocation acceptance. Further validation must use realrecordings and geolocations under the user's real-data-only directive.++++## Real NASA supplied-trajectory session benchmark++++`scripts/benchmark_nasa_session.py` uses original NASA pressure samples and measured++GPS trajectories. The [case manifest](nasa-session-cases-20261103.json) pins four++original MAT files from the++[public NASA archive](https://data.nasa.gov/docs/datasets/rfk401li/small_uav_acoustics.zip).++Retrieve only those original members, without downloading the complete archive:++++```sh++python scripts/download_nasa_cases.py --output data/nasa-originals++```++++The download directory must be new. If the original files already exist, add++`--verify-only` to check them without downloading or modifying anything.++The downloader verifies ZIP lengths and CRCs plus the manifest's byte sizes and++SHA256 values. Preparation also checks the original identities before reading them.++++The runner preserves channel 2 samples and original acoustic/GPS timestamps.++It uses synchronized seconds of day; calendar dates remain unresolved. It does++not invent an absolute UTC epoch. The local search domain comes from the full++GPS footprint with fixed padding. Microphone truth is read only during preparation++and later evaluation, not by search. One supplied trajectory does not imply one++encounter or one independent acoustic event.++++With the package installed, run each stage into a new output directory:++++```sh++PYTHONPATH=src .venv/bin/python scripts/benchmark_nasa_session.py prepare \++ --source-directory data/nasa-originals \++ --case-manifest benchmarks/nasa-session-cases-20261103.json \++ --output results/nasa-new/prepared++PYTHONPATH=src .venv/bin/python scripts/benchmark_nasa_session.py search \++ --inputs results/nasa-new/prepared/search-inputs.json \++ --domain results/nasa-new/prepared/search-domain.json \++ --output results/nasa-new/search++PYTHONPATH=src .venv/bin/python scripts/benchmark_nasa_session.py evaluate \++ --search-directory results/nasa-new/search \++ --truth results/nasa-new/prepared/evaluation-truth.json \++ --output results/nasa-new/evaluation.json++```++++Defaults use automatic discovery with a 2 s spectral window and 0.5 s hop,++50 m grid cells, zero clock offset, and separate constant-tone and 2% drift fits.++The [result table](nasa-session-results-20261103.csv) preserves every development++case and both discovery settings. These are supplied-track experiments, not an++automatic aircraft-association or nationwide validation corpus.++++| Recording | Proposals at 2 s / 0.5 s | Proposals at 0.5 s / 0.125 s | Primary result |++|---|---:|---:|---|++| Cub 107 | 0 | 0 | No fit or location |++| Edge 038 | 0 | 0 | No fit or location |++| Edge 065 | 1 | 0 | Conditional best-mode error 474.0 m; source identity unconfirmed |++| Edge 066 | 0 | 0 | No fit or location |++++Edge 065's proposal covers 1.5–19.0 s near 94–102 Hz. The strong harmonic flyover++and measured-track closest approach occur near 30.6 s. The publisher notes a++background propeller aircraft at the start, so the proposal may belong to it.++Both source-tone models rank the same point, but this does not validate drone++localization. Each grid has 3,632 supported points and 568 unknown points.++A competing mode is 1,899 m from truth, and similar losses extend over kilometres.++The CSV's 100/500/1,000 m fields describe only the conditional best-mode error;++they do not indicate accepted or correctly associated locations. The high-speed++pair's primary discovery and grid search took 6.56 s in the recorded run.++++The single shorter-window development comparison returned zero proposals in all++four recordings, with no fitting or truth access. It did not improve discovery.++To reproduce that setting, use a new search directory and add these search options:++++```sh++--discovery-window-s 0.5 --discovery-hop-s 0.125++```++++Every other default remains unchanged. No detector threshold was relaxed, no++synthetic data were generated, and all original negative results are retained.++The reusable CLI was also run against all four originals with the isolated++installed package. Preparation, default search, evaluation and the shorter-window++search all completed and reproduced the proposal counts above.diff --cc benchmarks/nasa-session-cases-20261103.jsonindex 0000000,0000000..3af5cbdnew file mode 100644--- /dev/null+++ b/benchmarks/nasa-session-cases-20261103.json@@@ -1,0 -1,0 +1,71 @@@++{++ "schema": "nasa_measured_case_selection_v1",++ "source_archive_url": "https://data.nasa.gov/docs/datasets/rfk401li/small_uav_acoustics.zip",++ "source_description_url": "https://data.nasa.gov/docs/datasets/rfk401li/Data_Description_20160203.pdf",++ "publisher_protocol_source": "Flight Number Description.xlsx in the original archive",++ "selection_rule": "First lexical Cub and Edge flyover members, then all publisher-labelled high-speed Edge members. The high-speed category was declared after the first two default-discovery failures and before inspecting either new recording.",++ "selection_uses_audio_or_location_error": false,++ "evaluation_split": "Public development cases; not a held-out corpus",++ "clock_scope": "Publisher synchronized UTC seconds of day; calendar dates unresolved. Subtract each recording sample zero from both acoustic and GPS times. No Unix epoch is assigned.",++ "mono_channel_one_based": 2,++ "supplied_trajectory_count_per_case": 1,++ "encounter_count_assumed": false,++ "cases": [++ {++ "case_id": "cub_flyover_107",++ "archive_member": "data/cub_flyover_107.mat",++ "size_bytes": 41935404,++ "sha256": "908ba29a68891fb6cb13087cbea9caf74f8385082d78842e1b91165e174365df",++ "selection_stage": "initial_first_lexical_by_fixed_wing_family",++ "publisher_protocol": {++ "vehicle": "Cub",++ "condition": "cruise",++ "nominal_agl_m": 10,++ "nominal_speed_mps": 25,++ "notes": "pilot descending towards mics under low power - not ideal flight trajectory"++ }++ },++ {++ "case_id": "edge_flyover_038",++ "archive_member": "data/edge_flyover_038.mat",++ "size_bytes": 35247930,++ "sha256": "81e02d387845614c4f9eea8761ec35211edcb5456a28d1b1c21dffb41fbd8cc8",++ "selection_stage": "initial_first_lexical_by_fixed_wing_family",++ "publisher_protocol": {++ "vehicle": "Edge",++ "condition": "cruise",++ "nominal_agl_m": 20,++ "nominal_speed_mps": 25,++ "notes": ""++ }++ },++ {++ "case_id": "edge_flyover_065",++ "publisher_protocol": {++ "vehicle": "Edge",++ "condition": "high speed",++ "nominal_agl_m": 100,++ "nominal_speed_mps": 40,++ "notes": "high speed pass, propeller plane in bg at start"++ },++ "size_bytes": 25249619,++ "sha256": "d06b708a460da233c550099698e5b69dadfbbe4f5404f77c30f32e1808717ccc",++ "archive_member": "data/edge_flyover_065.mat",++ "selection_stage": "all_publisher_high_speed_edge_members"++ },++ {++ "case_id": "edge_flyover_066",++ "publisher_protocol": {++ "vehicle": "Edge",++ "condition": "high speed",++ "nominal_agl_m": 75,++ "nominal_speed_mps": 40,++ "notes": "high speed pass"++ },++ "size_bytes": 33606044,++ "sha256": "0d4a1f7415e42f38ca64087400182e104ed7efface36de3cd7ed669aec9ad9bf",++ "archive_member": "data/edge_flyover_066.mat",++ "selection_stage": "all_publisher_high_speed_edge_members"++ }++ ]++}diff --cc benchmarks/nasa-session-results-20261103.csvindex 0000000,0000000..4610a0enew file mode 100644--- /dev/null+++ b/benchmarks/nasa-session-results-20261103.csv@@@ -1,0 -1,0 +1,9 @@@++case_id,discovery_window_s,discovery_hop_s,automatic_proposals,fit_scenarios,constant_best_error_m,drift002_best_error_m,constant_best_loss_hz,drift002_best_loss_hz,grid_points_per_scenario,supported_points_per_scenario,unknown_points_per_scenario,constant_runner_up_error_m,conditional_best_within_100m,conditional_best_within_500m,conditional_best_within_1000m,source_association,unique_location_established,product_acceptance,status,notes++cub_flyover_107,2.0,0.5,0,0,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,not_established,False,not_assessed,no_proposal,No fit or location; unchanged discovery returned zero proposals.++edge_flyover_038,2.0,0.5,0,0,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,not_established,False,not_assessed,no_proposal,No fit or location; unchanged discovery returned zero proposals.++edge_flyover_065,2.0,0.5,1,2,474.00443816380033,474.00443816380033,1.1542309300289004,1.152402675508945,4200,3632,568,1899.1459652693839,False,True,True,unconfirmed_background_aircraft_possible,False,not_assessed,conditional_fit_ambiguous_incomplete_support,Both models rank the same point. Proposal 1.5-19 s precedes supplied-track CPA 30.571 s and may be the publisher-noted background propeller aircraft. Region within 1 Hz extends 2304.9 m from best. Conditional error is not validated drone localization.++edge_flyover_066,2.0,0.5,0,0,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,not_established,False,not_assessed,no_proposal,No fit or location; unchanged discovery returned zero proposals.++cub_flyover_107,0.5,0.125,0,0,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,not_established,False,not_assessed,no_proposal,One fixed development comparison; only spectral window/hop changed. No fitting or truth access. No improvement over primary defaults.++edge_flyover_038,0.5,0.125,0,0,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,not_established,False,not_assessed,no_proposal,One fixed development comparison; only spectral window/hop changed. No fitting or truth access. No improvement over primary defaults.++edge_flyover_065,0.5,0.125,0,0,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,not_established,False,not_assessed,no_proposal,One fixed development comparison; only spectral window/hop changed. No fitting or truth access. No improvement over primary defaults.++edge_flyover_066,0.5,0.125,0,0,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,n.a.,not_established,False,not_assessed,no_proposal,One fixed development comparison; only spectral window/hop changed. No fitting or truth access. No improvement over primary defaults.diff --cc docs/verification/WORKER_E2E_2026-11-03.mdindex 073c01f,0000000..6d2bce3mode 100644,000000..100644--- a/docs/verification/WORKER_E2E_2026-11-03.md+++ b/docs/verification/WORKER_E2E_2026-11-03.md@@@ -1,285 -1,0 +1,313 @@@+# Worker verification results — 2026-11-03 UTC++**Experimental software. The complete real-recording localization goal remains open.**++The real HTTP run verified upload, intake, automatic discovery, persistence and shutdown.+It returned `needs_input / recording_time_required`, with no location result.+The configured real regional pipeline now completes and reproduces its historical ranking.- The first two independently timed NASA recordings produced no qualifying events.- Two further recordings were selected from the flight log before acoustic inspection.++Four NASA recordings with synchronized audio and trajectory times were tested with the unchanged detector.++Three produced no events; the fourth produced an unconfirmed background-source candidate.+This record does not close [#13](https://github.com/1337isnot1337/DOPPLERGEIST/issues/13)+or [#53](https://github.com/1337isnot1337/DOPPLERGEIST/issues/53).++The [owner directive](https://github.com/1337isnot1337/DOPPLERGEIST/issues/1#issuecomment-6595095639)+stopped new synthetic experiments.+All completed synthetic runs in this record preceded that directive.+The real experiments below preserve each outcome and its limits.++## Repository checkout++The primary imported the complete Git history from+[run 41577235564](https://github.com/1337isnot1337/DOPPLERGEIST/actions/runs/41577235564),+artifact `13204415457`.+The downloaded archive SHA-256 was `cd0267f186d384fa52a8484101f82917f3d6b9723032bd0805c2ba4b6d73e067`.+The primary imported all branch references under `live/*`.+The primary created `/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-current`+at `6670d74b1f6c41c3a655e219f91908ed7fbe7182`.+The primary reported `git fsck --full --no-reflogs` exit code 0, with only dangling historical objects and no corruption.+The application results in this record retain their own earlier source revisions.++## Real recording through HTTP++The input was the complete reference recording from+[the original video](https://www.youtube.com/watch?v=4CxVxuMVkMc).+The worker converted its retained WAV to MP3 without a time selection or frequency selection.+The conversion removed metadata and supplied no sample-zero UTC or recorder location.+The [source record](../../evidence/e2e-worker-20261103/real-source-provenance.json)+preserves the original WAV identity, artifact ID, conversion command and MP3 identity.++| Input | SHA-256 |+| --- | --- |+| Original complete WAV | `262d9c4eba1c80657813c604140ba2afbbaabed2b3aebc833cba7cafdc005e9f` |+| Uploaded complete MP3 | `e1c13dafd8d1634bbf84df843c31771318e15a31ebb86dd165af7ee312ab80a0` |++The MP3 contained 42,085,293 bytes.+The request selected `coverage: conus`, with an empty operator configuration and no recording clock.+The HTTP run started at `2026-11-03T04:14:50.484869Z`.++| Observation | Result |+| --- | --- |+| Job | `dcf5816d3d0f4a1a9a551b7269f27ec8` |+| Decoded recording | 3,600.1845 seconds, mono, 4,000 Hz |+| Automatic discovery | 60 overlapping chunks, 18 ridges, 16 acoustic proposals |+| Terminal status | `needs_input` |+| Reason | `recording_time_required` |+| Required input | A defensible UTC window for the first decoded sample |+| Candidate output | Zero candidates |+| Total verifier time | 20.433066061001227 seconds |+| Service shutdown | SIGINT, return code 0, no forced kill |++The [result summary](../../evidence/e2e-worker-20261103/real-result-summary.json)+contains the complete recording metadata and discovery settings.+The proposals are acoustic candidates. Their aircraft identities remain unconfirmed.++The [HTTP receipt](../../evidence/e2e-worker-20261103/real-http-verification.json)+records successful preservation checks for the input, request, operator configuration and result.+Downloads matched the original upload and stored result.+The terminal result remained unchanged after shutdown.+The [stage receipt](../../evidence/e2e-worker-20261103/real-pipeline-evidence.json)+verified `automatic_provenance`, `intake` and `discovery`.++These three checks establish stage consistency for this actual run.+They do not independently reproduce the decoder or establish a scientific decision.+The receipts explicitly record `full_pipeline_observed: false`, `supported_decision: false`,+`location_accuracy_evaluated: false` and `browser_verified: false`.+No geographic search or location-error claim follows from this result.++### Source revision and retained artifacts++The invocation started from integration commit `6497540f15a05af142e88dd34c67ee76d4ea583b`.+The recorded implementation hashes identify the code independently of later documentation commits.+The HTTP receipt preserves all 21 backend file hashes and the verifier hash.+Those implementation hashes match the frozen backend at `317b0d3fc93ec9cd50ca88c336bb771b26bf5b1e`.+The receipt also records that the implementation remained unchanged during verification.++Full local artifacts remain under:++```text+/workspace/scratch/e8a2a58f21d0/real-inputs/data/source/reference-recording.wav+/workspace/scratch/e8a2a58f21d0/DOPPLERGEIST-integration/results/real-reference-upload-20261103/+```++The compact evidence directory contains the existing source and HTTP receipts without media or numerical arrays.+It also contains a summary extracted from the original result and discovery files.+The recorded `aircraft_geoloc` package and command names are historical names.+The separate installed-package replay below verifies the renamed `dopplergeist` package.+Related implementation sources are [product integration #19](https://github.com/1337isnot1337/DOPPLERGEIST/pull/19),+[finite retention #71](https://github.com/1337isnot1337/DOPPLERGEIST/pull/71)+and [trajectory support #91](https://github.com/1337isnot1337/DOPPLERGEIST/pull/91).++## Current installed package and real upload++The current main branch incorporated product, support and finite-search work and+renamed the package to `dopplergeist`. The worker ported only the additional+bounded-score accounting and verification changes onto main `6670d74`.+The resulting runtime was frozen at `db9db65aad7a6fe6fa9fc5fd31a9c45c72f4f68d`.+Geometry, acoustic discovery, confidence thresholds and browser assets were unchanged.++An offline build produced `dopplergeist-0.1.0-py3-none-any.whl`. A separate virtual+environment installed the wheel and its dependencies without using the editable+checkout or system packages. All 25 packaged source/browser files matched the+checkout byte for byte. Dependency consistency, installed imports, all five CLI+commands in help, and readable browser assets passed.+See [installed-package receipt](../../evidence/e2e-worker-20261103/installed-package.json).++The standalone HTTP verifier then ran with that environment's isolated Python+against the same complete real MP3. It again found 16 proposals over+3,600.1845 seconds and returned `needs_input / recording_time_required`.+The verifier completed in 20.41445216200009 seconds; input/result persistence,+artifact downloads, source fingerprints and graceful service shutdown passed.+It verified the same three stages and made no location claim.+See the [installed HTTP receipt](../../evidence/e2e-worker-20261103/installed-real-http-verification.json)+and [installed stage receipt](../../evidence/e2e-worker-20261103/installed-real-pipeline-evidence.json).++This is a real installed-package run of the current namespace. It does not turn+the missing-clock response into a successful scientific localization.++## Configured real pipeline: reproduced crash and repair++The unchanged `reproduce-local.json`, complete WAV, measured regional tracks and+terrain first failed at source `db9db65`: one historical trajectory raised+`AcousticSupportError: non_subsonic_motion` after both flyovers were measured.+The configured pipeline did not isolate this typed failure as the tiled path did.++Source `69c507c` catches only typed acoustic-support failures. It retains supported+work and records the whole excluded track and receiver envelope at each stage.+It also marks legacy scoring envelopes without exhaustive clock accounting as+unknown. It changes no physical check, source trajectory, grid, threshold or input+configuration. The resulting research report always states `accepted_location: false`.+Concurrent upstream fit caching and unreported-work guards from main `6b8cbe0`+are preserved.++The worker built and installed a new wheel in a separate environment, then ran:++```bash+dopplergeist run /path/to/real-inputs/data/source/reproduce-local.json \+ --output /path/to/new-real-pipeline-output+```++The installed pipeline completed in **51.008 seconds**. It imported 583,176+observations as 3,587 trajectory segments, measured both events, searched the+2,525-point coarse grid, refined candidates and produced 283 ranked rows.+Its best coordinate was `(40.87693175890468, -73.52498229500986)`, with flights+`a1dfeb:1` and `ace391:3`. This exactly reproduced the baseline coordinate, clock+and flight IDs; the score difference was floating-point roundoff (`8.9e-16`).++Post-run comparison placed that coordinate **43.8585 m** from the published+reference `(40.8766, -73.5247)`, within 100, 500 and 1,000 m. That reference is not+a surveyed microphone position. Event windows, bands, regional bounds and timing+remain source-informed; this is an operational reproduction of the configured+method, not independent automatic accuracy.++Coverage remains partial: 228 tracks were unsupported in each of three CPA+stages (684 work evaluations), and all 290 scored candidate envelopes lacked+exhaustive legacy clock-trial reporting. The best row remained a research+hypothesis; `model_support_complete`, `model_assessment_complete` and+`accepted_location` were all false. Full reports and per-stage support records+remain under `integration-audit/current-package-real-pipeline/pipeline/` in the+worker workspace. An outer post-run receipt writer initially lacked `pyproj`;+evaluation was completed in the scientific environment after the search, without+rerunning the pipeline or changing its outputs.++## Historical bound verification on six failed tiles++This work preceded the owner directive.+It replayed six archived tiles from the earlier synthetic four-event HTTP run at source `134f617`.+The production bound source was `7a96fdb33fb787a9376432b2086f3673a4f4dc37`.+The replay used the archived discovery, flight index, tracks and terrain.+It did not load location truth or change scores.++For an association with `k` matched groups, the declared score is:++\[+S=\sum_{i=1}^{k}\left(1-\frac{\ell_i}{L_i}\right),\qquad L_i>0,\quad \ell_i\geq0.+\]++A validated event loss greater than its limit rejects the entire association.+For each unknown event loss, its score contribution cannot exceed one.+Validated supported losses can therefore tighten the general bound `S ≤ k`.+The candidate bound covers every scheduled clock trial.+The implementation rounds contributions and sums upward to protect the floating-point bound.++The code requires the declared score kind and validates the event diagnostics before it uses a loss.+It also validates disjoint trial counts and their sum against the scheduled count.+Unsupported motion errors remain unbounded.+Missing support remains unknown despite a finite score bound.+The bound applies to the enumerated grid and scheduled clocks, without a continuous-space claim.++| Tile | Unknown candidates | Rejected by a supported event | Largest remaining upper bound |+| --- | ---: | ---: | ---: |+| `-5_29` | 2 | 1 | 1 |+| `-20_36` | 96 | 7 | 2 |+| `-21_36` | 756 | 389 | 3 |+| `-6_29` | 177 | 64 | 2 |+| `8_20` | 304 | 201 | 2 |+| `8_21` | 177 | 53 | 2 |+| **Total** | **1,512** | **715** | **3** |++All 1,512 unknown candidates acquired valid bounds. None became an evaluated fit.+The other 797 candidates had upper bounds of at most three.+Forty-four unknown candidates matched four groups, so group count alone did not settle every case.+All six replays reproduced the archived counts.+Their ledger evidence remained identical after each database reopened.+The [six-tile summary](../../evidence/e2e-worker-20261103/historical-six-tile-bounds.json)+preserves the counts and persistence results.++The full diagnostics remain at+`/workspace/scratch/e8a2a58f21d0/integration-audit/production-bound-replays-7a96fdb/`.+The archived input is `integration-audit/http-four-event-134f617.zip` in the same workspace.+This result verifies a finite-search correction. It does not establish real-recording localization accuracy.++## Historical tests and interrupted positive run++Before the directive, the primary ran this command at integration commit+`317b0d3fc93ec9cd50ca88c336bb771b26bf5b1e`:++```bash+PYTHONPATH=src OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 \+ ../.venv/bin/python -m pytest -q+```++Observed terminal result: **620 passed, 1 skipped, 17 subtests in 77.82 seconds**.+The observation came from terminal session `45606`. No separate raw log accompanies this record.+This historical command is not a current instruction to run synthetic tests.++Earlier actual CLI and HTTP negative controls used source `91f2684f70eac7fecfe7810f09eecdb38cc839a7`.+Undated audio returned `needs_input`, corrupt input returned `failed`, and silence returned `inconclusive`.+Input preservation, stored results, restart persistence and graceful shutdown passed.+The [negative-control summary](../../evidence/e2e-worker-20261103/historical-negative-paths.json)+identifies these controls as synthetic and makes no accuracy claim.++When the owner directive arrived, the primary stopped the later positive synthetic run at `317b0d3`.+Terminal session `84810` ended with exit code 130.+Its retained job `2575b2f261db4c128a39e71c643d0704` still records `running / search`, with `search_complete: false`.+It produced no terminal HTTP verification receipt or accepted location result.+The partial artifacts remain in `results/e2e-bounded-four-20261103/` in the integration worktree.+**This interrupted run is not a successful end-to-end verification.**++## NASA measured recordings: negative automatic-discovery baseline++Original files came from NASA's [Small UAS flyover acoustics release](https://data.nasa.gov/dataset/small-uas-flyover-acoustics-data).+The first lexical Cub and Edge recordings were selected before acoustic inspection:+`cub_flyover_107.mat` and `edge_flyover_038.mat`. Downloaded original lengths,+ZIP CRCs and SHA-256 checks passed. The publisher supplies measured GPS trajectories,+microphone positions and acoustic sample times synchronized to the trajectory's+UTC seconds-of-day. The calendar day is not securely bound, so this experiment+uses the common session time axis and invents no absolute recording date.++The experimental adapter retained every GPS row and original pressure sample,+used the preselected second microphone channel, and ran the unchanged automatic+detector without event windows or bands. Its planned search grid came from the+aircraft's measured footprint plus a 1 km margin, with microphone truth in a+separate evaluation file opened only after the search was frozen. This is a+limited measured-trajectory experiment, not national flight acquisition.++| Recording | Measured audio duration | Automatic proposals | Localization result |+| --- | ---: | ---: | --- |+| Cub107 | 98.2016 s | 0 | No fit or location |+| Edge038 | 59.4094 s | 0 | No fit or location |++| Edge065 | 43.8950 s | 1 | Ambiguous conditional fit; source association unconfirmed |++| Edge066 | 60.0000 s | 0 | No fit or location |++Both baseline runs completed. No distance metric or successful acceptance can be+assigned to these misses. Subsequent diagnosis found that nearly all tracked+fragments failed the detector's 12-second duration rule; the three paths surviving+the other shape gates failed the jump rule. Those rules were not relaxed.+Cub107 contains more than one close approach; the adapter's original one-flyover+label was an assumption, not a measured encounter count, and is corrected to+unknown in the versioned extension.+- The next extension predeclared **both** publisher `Edge / high speed` rows,- Edge065 and Edge066, before downloading their audio. The selection retains065- despite its background-aircraft note. Discovery and search settings stay unchanged.- The first two negative outcomes remain part of the result set. Raw inputs and- outputs are retained under `real-inputs/nasa-release/` and- `integration-audit/nasa-real-experiment/` in the worker workspace.++The extension predeclared **both** publisher `Edge / high speed` rows,++Edge065 and Edge066, before downloading their audio. The selection retained 065++despite its background-aircraft note. Discovery and search settings stayed unchanged.++Both cases completed preparation, search and evaluation; search took 6.560 s.++++Edge065's sole proposal covered 1.5–19.0 s near 94–102 Hz. Both the constant-source++and two-percent-drift searches ranked the same 50 m grid cell first, **474.004 m**++from the supplied microphone position. That conditional error is outside 100 m and++inside 500/1,000 m. It is **not validated drone localization**: 568 of 4,200 grid++locations lacked fit support, a competing minimum was 1,899 m from the microphone,++and the descriptive near-best region extended over 2.3 km from the leader.++++Post-freeze source diagnosis found the measured drone's nominal received closest++approach near 30.57 s. The early proposal was visibly separate from the strong++harmonic flyover around that time and consistent with the publisher's warning++about a background propeller aircraft at the recording's start. Its actual++identity remains unknown. A small conditional location error cannot validate a++wrong or unconfirmed source association.++++A single controlled development comparison changed only the spectral window++from 2.0 s to 0.5 s and the hop from 0.5 s to 0.125 s. Every other acceptance setting++stayed unchanged. **All four recordings then produced zero proposals.** This++supplied no positive evidence for changing production defaults, which remain unchanged.++++The reusable measured-session runner and pinned case list are under `scripts/`++and `benchmarks/`; see `benchmarks/README.md`. Raw inputs and complete outputs++remain under `real-inputs/nasa-release/`, `real-inputs/nasa-highspeed-release/`++and `integration-audit/nasa-real-experiment/` in the worker workspace.++++The local HTTP service was also started from the final installed wheel. The++available browser-automation backend failed to start (`Connection closed`) before++any page interaction, so no browser verification is claimed. The service was stopped.++The independent real automatic localization goal remains open.diff --cc scripts/benchmark_nasa_session.pyindex 0000000,0000000..16dca49new file mode 100644--- /dev/null+++ b/scripts/benchmark_nasa_session.py@@@ -1,0 -1,0 +1,405 @@@++#!/usr/bin/env python3++"""Real NASA supplied-trajectory benchmark, outside the absolute UTC API.++++Prepare, search and evaluate are separate commands. Search never reads microphone++truth. No calendar date, waveform or flight is generated, and no product acceptance++decision is made. Use the current dopplergeist package through explicit PYTHONPATH.++"""++import argparse++from collections import Counter++from dataclasses import asdict++import hashlib++import json++from pathlib import Path++import re++++import numpy as np++from pyproj import Transformer++from scipy import ndimage++from scipy.io import loadmat, wavfile++from dopplergeist.discovery import DiscoverySettings, discover_events++from dopplergeist.geometry import AcousticSupportError, Track, ecef, velocity_ecef++from dopplergeist.matching import RidgeTimes, fit_ridge, prepare_events++++SCOPE = "real_NASA_supplied_trajectory_session_clock"++SOURCE = "https://data.nasa.gov/docs/datasets/rfk401li/small_uav_acoustics.zip"++DESCRIPTION = "https://data.nasa.gov/docs/datasets/rfk401li/Data_Description_20160203.pdf"++REFERENCE_FRAMES = {++ "cub": dict(++ origin="mic1", lat=38.0953507, lon=-77.2633382, height=20.726,++ warning="Supplied GPS only; RTK unused. See publisher flight protocol and source quality fields."),++ "edge": dict(++ origin="mic3", lat=36.6797443, lon=-76.0376444, height=0.0,++ warning="Supplied GPS only; delivered coordinates may already be interpolated. Absolute microphone height and weather unmeasured."),++}++++++def sha(path):++ h = hashlib.sha256()++ with Path(path).open("rb") as f:++ for block in iter(lambda: f.read(1024 * 1024), b""):++ h.update(block)++ return h.hexdigest()++++++def clean(x):++ if isinstance(x, dict): return {str(k): clean(v) for k, v in x.items()}++ if isinstance(x, (list, tuple)): return [clean(v) for v in x]++ if isinstance(x, np.ndarray): return clean(x.tolist())++ if isinstance(x, np.integer): return int(x)++ if isinstance(x, np.bool_): return bool(x)++ if isinstance(x, (float, np.floating)): return float(x) if np.isfinite(x) else None++ return x++++++def write(path, x):++ Path(path).write_text(json.dumps(clean(x), indent=2, allow_nan=False) + "\n")++++++def read(path): return json.loads(Path(path).read_text())++++++def pinned_cases(path):++ selection = read(path)++ if selection.get("schema") != "nasa_measured_case_selection_v1":++ raise ValueError("Wrong pinned case selection schema")++ if not isinstance(selection.get("selection_rule"), str) or not selection["selection_rule"].strip():++ raise ValueError("Declare a selection rule before examining the recordings")++ if selection.get("selection_uses_audio_or_location_error") is not False:++ raise ValueError("This extension requires publisher-metadata-only selection")++ result = {}++ for item in selection["cases"]:++ name = item["case_id"]++ match = re.fullmatch(r"(cub|edge)_flyover_[0-9]{3}", name)++ digest, size = item["sha256"], item["size_bytes"]++ if not match or name in result or not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):++ raise ValueError("Invalid or duplicate pinned public case")++ if type(size) is not int or size <= 0:++ raise ValueError("Pinned source size must be a positive integer")++ result[name] = dict(REFERENCE_FRAMES[match.group(1)], sha256=digest, size_bytes=size,++ publisher_protocol=item.get("publisher_protocol"))++ if not result: raise ValueError("No pinned measured cases")++ return result, selection++++++def newdir(path):++ p = Path(path).resolve()++ p.mkdir(parents=True, exist_ok=False)++ return p++++++def enu(ned): return np.asarray(ned)[..., [1, 0, 2]] * [1, 1, -1]++++++def ordered(t):++ t = np.asarray(t)++ if t.ndim != 1 or len(t) < 3 or not np.all(np.isfinite(t)) or not np.all(np.diff(t) > 0):++ raise ValueError("Measured times must be finite, strictly ordered; no repair is performed")++ if t[0] < 0 or t[-1] >= 86400: raise ValueError("Only within-day publisher clocks are supported")++ return t++++++def timing(t, sr=None):++ d = np.diff(t)++ x = dict(count=len(t), first=t[0], last=t[-1], min_step_s=d.min(), median_step_s=np.median(d), max_step_s=d.max())++ if sr:++ error = t - t[0] - np.arange(len(t)) / sr++ x.update(nominal_rate_hz=sr, endpoint_effective_rate_hz=(len(t)-1)/(t[-1]-t[0]),++ max_nominal_clock_deviation_s=np.max(np.abs(error)), end_nominal_clock_deviation_s=error[-1])++ return x++++++def prepare(args):++ selected, selection = pinned_cases(args.case_manifest)++ out = newdir(args.output)++ cases, domains, truth = [], {}, {}++ for name, published in selected.items():++ source = Path(args.source_directory)/(name + ".mat")++ if source.stat().st_size != published["size_bytes"] or sha(source) != published["sha256"]:++ raise ValueError("Not the pinned NASA source: " + str(source))++ original = loadmat(source, simplify_cells=True)++ a, v = original["acoustics"], original["vehicle_data"]++ if a["origin"] != published["origin"] or v["origin"] != published["origin"]:++ raise ValueError("Audio and GPS coordinate frames disagree")++ at, gt = ordered(a["utc_time"]), ordered(v["gps_utc_time"])++ pressure, gps = np.asarray(a["incident_pascals"]), np.asarray(v["gps_ned_meters"])++ if pressure.shape != (len(at), 4) or gps.shape != (len(gt), 3): raise ValueError("Unexpected source shape")++ if not np.all(np.isfinite(pressure)) or not np.all(np.isfinite(gps)): raise ValueError("Nonfinite real input")++ # Channel 2 is predeclared and differs from both survey-frame origins.++ arrays = dict(mono_pressure=pressure[:, 1], audio_seconds_of_day=at,++ gps_seconds_of_day=gt, gps_ned_meters=gps)++ folder = out/name++ folder.mkdir()++ files = {}++ for key, data in arrays.items():++ path = folder/(key + ".npy")++ np.save(path, data, allow_pickle=False)++ files[key] = dict(path=str(path), sha256=sha(path), shape=data.shape, dtype=str(data.dtype))++ wavfile.write(folder/"mono_pressure_20000hz.wav", 20000, arrays["mono_pressure"])++ xyz = enu(gps)++ low = np.floor((xyz[:, :2].min(axis=0)-args.padding_m)/500)*500++ high = np.ceil((xyz[:, :2].max(axis=0)+args.padding_m)/500)*500++ domains[name] = dict(east_bounds_m=[low[0], high[0]], north_bounds_m=[low[1], high[1]],++ padding_m=args.padding_m, nominal_receiver_up_m=0,++ definition="Measured GPS footprint, fixed padding, rounded outward to500m survey-frame lattice.",++ target_positions_or_acoustic_fit_used=False,++ limitation="Conditional local domain from supplied flight, not national or blind-site search.")++ speed = np.linalg.norm(np.diff(xyz, axis=0), axis=1)/np.diff(gt)++ met = original.get("met_data")++ temp = np.asarray(met["temperature_celsius"]) if isinstance(met, dict) else np.array([])++ if temp.size and not np.all(np.isfinite(temp)): raise ValueError("Nonfinite measured weather")++ c = np.sqrt(1.4*287.05*(273.15+np.median(temp))) if temp.size else 343.0++ cases.append(dict(case_id=name, files=files, source_sha256=published["sha256"], source_url=SOURCE,++ source_size_bytes=published["size_bytes"], publisher_protocol=published["publisher_protocol"],++ mono_channel_one_based=2, reference={k: published[k] for k in ("lat", "lon", "height", "origin")},++ reference_role="Publisher coordinate origin distinct from target; rigid conversion only.",++ clock=dict(kind="publisher_UTC_seconds_of_day", calendar_date=None, unix_epoch=None,++ sample_zero_seconds_of_day=at[0], origin_shift="Subtract acoustic sample zero from both axes.",++ publisher_GPS_leap_seconds_already_applied=True, measured_absolute_clock_uncertainty=False),++ audio_timing=timing(at, 20000), gps_timing=timing(gt),++ gps_chord_speed_mps=dict(min=speed.min(), median=np.median(speed), max=speed.max()),++ waveform_resampled=False, all_original_GPS_rows_retained=True, source_warning=published["warning"],++ nominal_sound_speed_mps=c, measured_temperatures_celsius=temp,++ sound_speed_basis="Dry-air approximation from measured temperature; wind/humidity unmodeled." if temp.size else "Nominal343m/s; no weather measurement."))++ mic = np.asarray(a["mic_ned_meters"])++ if mic.shape != (4, 3) or not np.all(np.isfinite(mic)): raise ValueError("Invalid microphone table")++ truth[name] = dict(microphone_one_based=2, receiver_enu_m=enu(mic[1]), source_description=DESCRIPTION)++ write(out/"search-inputs.json", dict(scope=SCOPE, cases=cases, target_coordinates_in_objective=False,++ case_selection=selection, case_manifest_sha256=sha(args.case_manifest)))++ write(out/"search-domain.json", dict(scope=SCOPE, cases=domains))++ write(out/"evaluation-truth.json", dict(scope=SCOPE, cases=truth))++ write(out/"preparation.json", dict(scope=SCOPE, case_manifest_sha256=sha(args.case_manifest),++ search_inputs_sha256=sha(out/"search-inputs.json"), domain_sha256=sha(out/"search-domain.json"),++ truth_sha256=sha(out/"evaluation-truth.json"), synthetic_data_generated=False, localization_performed=False))++ print(json.dumps(dict(prepared=str(out), cases=list(selected))))++++++class OriginalMono:++ def __init__(self, mono, source_sha):++ self.mono = mono++ self.metadata = dict(sample_rate_hz=20000, duration_s=len(mono)/20000, source_sha256=source_sha)++++ def iter_chunks(self, chunk_s=120, overlap_s=60):++ size, overlap = round(chunk_s*20000), round(overlap_s*20000)++ for first in range(0, len(self.mono), size-overlap):++ yield first/20000, self.mono[first:first+size]++ if first+size >= len(self.mono): break++++++def load_arrays(case):++ result = {}++ for key, item in case["files"].items():++ if sha(item["path"]) != item["sha256"]: raise ValueError("Measured data changed: " + key)++ result[key] = np.load(item["path"], mmap_mode="r", allow_pickle=False)++ return result++++++def make_track(case, arrays):++ ref = case["reference"]++ base = ecef(ref["lat"], ref["lon"], ref["height"])++ def to_xyz(point):++ point = np.asarray(point)++ return base + velocity_ecef(ref["lat"], ref["lon"], point[..., 0], point[..., 1], point[..., 2])++ xyz = to_xyz(enu(arrays["gps_ned_meters"]))++ transform = Transformer.from_crs("EPSG:4978", "EPSG:4979", always_xy=True)++ lon, lat, h = transform.transform(xyz[:, 0], xyz[:, 1], xyz[:, 2])++ t = arrays["gps_seconds_of_day"]-arrays["audio_seconds_of_day"][0]++ track = Track(case["case_id"], t, lat, lon, h, "NASA measured GPS")++ error = np.max(np.linalg.norm(xyz-track.xyz, axis=1))++ if error > 1e-4: raise ValueError("Coordinate round-trip error exceeds0.1mm")++ return track, to_xyz, error++++++def measurements(events, audio_time):++ settings, original = prepare_events(events)++ result = []++ for spec, freq, weight, extra in original:++ index = np.rint(spec.time*20000).astype(np.int64)++ if np.any(index < 0) or np.any(index >= len(audio_time)) or np.max(np.abs(index/20000-spec.time)) > 1e-8:++ raise ValueError("FFT centers do not map to exact original sample indices")++ result.append((RidgeTimes(audio_time[index]-audio_time[0]), freq, weight, extra))++ return settings, result++++++def fit_at(track, to_xyz, measurement, event, point, c, clock, drift):++ try:++ fit = fit_ridge(track, to_xyz(point), measurement, clock, event["f0_range_hz"], c,++ event["quality"]["frequency_loss_scale_hz"], drift)++ except AcousticSupportError as error:++ return None, error.reason++ if not np.isfinite(fit.get("score", np.nan)) or fit.get("support_fraction") != 1.0:++ return None, "incomplete_acoustic_or_ridge_support"++ return fit, None++++++def modes(loss, east, north, separation):++ finite = np.isfinite(loss)++ values = np.where(finite, loss, np.inf)++ local = finite & (values == ndimage.minimum_filter(values, size=3, mode="constant", cval=np.inf))++ points = sorted(np.argwhere(local), key=lambda ij: values[tuple(ij)])++ result = []++ for iy, ix in points:++ if any(np.hypot(east[ix]-m["east_m"], north[iy]-m["north_m"]) < separation for m in result): continue++ result.append(dict(east_m=east[ix], north_m=north[iy], loss_hz=values[iy, ix],++ domain_edge=ix in (0, len(east)-1) or iy in (0, len(north)-1)))++ if len(result) >= 8: break++ return result++++++def search(args):++ source, domains = read(args.inputs), read(args.domain)++ if source.get("scope") != SCOPE or domains.get("scope") != SCOPE: raise ValueError("Wrong input scope")++ out = newdir(args.output)++ if not np.isfinite(args.grid_step_m) or args.grid_step_m <= 0: raise ValueError("Invalid grid step")++ if not all(0 <= d <= 0.1 for d in args.drift_fractions): raise ValueError("Invalid drift domain")++ settings = DiscoverySettings(window_s=args.discovery_window_s, hop_s=args.discovery_hop_s)++ manifest = dict(scope=SCOPE, case_manifest_sha256=source.get("case_manifest_sha256"),++ case_selection=source.get("case_selection"),++ inputs_sha256=sha(args.inputs), domain_sha256=sha(args.domain), grid_step_m=args.grid_step_m,++ clock_offsets_s=args.clock_offsets_s, drift_fractions=args.drift_fractions, receiver_up_m=args.receiver_up_m,++ grid_nodes="Cell centers, with no target coordinate inserted", discovery_settings=asdict(settings),++ target_truth_loaded=False, synthetic_data_generated=False, absolute_UTC_validated=False,++ historical_traffic_acquisition_validated=False, product_acceptance=None, calendar_date=None, cases=[])++ write(out/"run-manifest.json", manifest)++ for case in source["cases"]:++ name = case["case_id"]++ folder = out/name++ folder.mkdir()++ arrays = load_arrays(case)++ # This phase gets no GPS or microphone position inputs.++ events = discover_events(OriginalMono(arrays["mono_pressure"], case["source_sha256"]), settings=settings)++ write(folder/"audio-only-discovery.json", dict(events=events, settings=asdict(settings),++ selection="Every returned audio proposal retained; no location-based selection",++ supplied_trajectory_count=1, encounter_count=None, encounter_count_assumed=False))++ event_settings, measured = measurements(events, arrays["audio_seconds_of_day"])++ track, to_xyz, transform_error = make_track(case, arrays)++ c = case["nominal_sound_speed_mps"] if args.sound_speed_mps is None else args.sound_speed_mps++ if not np.isfinite(c) or c <= 0: raise ValueError("Invalid sound speed")++ motion = dict(globally_subsonic=True)++ try:++ track.validate_motion_support(c)++ except AcousticSupportError as error:++ motion = dict(globally_subsonic=False, reason=error.reason,++ unsupported_emission_intervals_s=error.emission_intervals_s)++ domain = domains["cases"][name]++ def centers(bounds): return np.arange(bounds[0]+args.grid_step_m/2, bounds[1], args.grid_step_m)++ east, north = centers(domain["east_bounds_m"]), centers(domain["north_bounds_m"])++ if not len(east) or not len(north) or len(east)*len(north) > args.max_grid_points:++ raise ValueError("Grid exceeds explicit budget or is empty; no truncated search")++ summary = dict(case_id=name, supplied_trajectory_count=1, encounter_count=None, encounter_count_assumed=False,++ acoustic_proposals=len(events), track_support=motion,++ transform_roundtrip_max_m=transform_error, sound_speed_mps=c,++ sound_speed_basis=case["sound_speed_basis"] if args.sound_speed_mps is None else "Explicit sensitivity override",++ source_warning=case["source_warning"], audio_timing=case["audio_timing"], gps_timing=case["gps_timing"], results=[])++ for i, (event, measured_ridge) in enumerate(zip(event_settings, measured)):++ np.savez_compressed(folder/f"ridge-{i:03d}.npz", time_s=measured_ridge[0].time,++ frequency_hz=measured_ridge[1], weight=measured_ridge[2])++ write(folder/f"event-{i:03d}.json", event)++ for clock in args.clock_offsets_s:++ for drift in args.drift_fractions:++ for up in args.receiver_up_m:++ identity = f"ridge-{i:03d}-clock-{clock:g}-drift-{drift:g}-up-{up:g}"++ loss = np.full((len(north), len(east)), np.nan)++ reasons = Counter()++ for iy, y in enumerate(north):++ for ix, x in enumerate(east):++ fit, reason = fit_at(track, to_xyz, measured_ridge, event, [x, y, up], c, clock, drift)++ if reason: reasons[reason] += 1++ else: loss[iy, ix] = -fit["score"]++ found = modes(loss, east, north, max(100, 2*args.grid_step_m))++ for mode in found:++ mode["fit"], _ = fit_at(track, to_xyz, measured_ridge, event,++ [mode["east_m"], mode["north_m"], up], c, clock, drift)++ grid_path = folder/(identity + ".npz")++ np.savez_compressed(grid_path, east_m=east, north_m=north, loss_hz=loss, evaluated=np.isfinite(loss))++ item = dict(id=identity, event_index=i, event_id=event["event_id"], clock_offset_s=clock,++ drift_fraction=drift, receiver_up_m=up, grid_points=loss.size,++ evaluated_grid_points=np.isfinite(loss).sum(), unknown_grid_points=(~np.isfinite(loss)).sum(),++ unknown_reasons=reasons, grid_assessment_complete=not reasons, local_modes=found,++ diagnostic_loss_scale_hz=event["quality"]["frequency_loss_scale_hz"],++ conditional_scenario=True, unique_location_established=False,++ status="supported_grid_minima_only" if found else "no_supported_fit")++ if found:++ mask = np.isfinite(loss) & (loss <= found[0]["loss_hz"]+item["diagnostic_loss_scale_hz"])++ yy, xx = np.where(mask)++ item["within_one_loss_scale"] = dict(count=len(xx),++ east_bounds_m=[east[xx].min(), east[xx].max()], north_bounds_m=[north[yy].min(), north[yy].max()],++ max_distance_from_best_m=np.max(np.hypot(east[xx]-found[0]["east_m"], north[yy]-found[0]["north_m"])),++ interpretation="Descriptive contour, not a probability or confidence interval")++ write(folder/(identity + ".json"), item)++ summary["results"].append(item)++ write(folder/"case-results.json", summary)++ print(json.dumps(clean(dict(case=name, result=identity, evaluated=item["evaluated_grid_points"],++ unknown=item["unknown_grid_points"], best=found[0] if found else None))), flush=True)++ if not events: summary["status"] = "no_proposal_from_configured_discovery"++ write(folder/"case-results.json", summary)++ manifest["cases"].append(summary)++ write(out/"run-manifest.json", manifest)++ write(out/"frozen-search.json", dict(scope=SCOPE, target_truth_loaded=False,++ run_manifest_sha256=sha(out/"run-manifest.json"), product_acceptance=None))++++++def evaluate(args):++ folder = Path(args.search_directory)++ frozen = read(folder/"frozen-search.json")++ if sha(folder/"run-manifest.json") != frozen["run_manifest_sha256"]: raise ValueError("Search changed after freezing")++ manifest, truth = read(folder/"run-manifest.json"), read(args.truth)++ if truth.get("scope") != SCOPE or manifest["target_truth_loaded"] is not False: raise ValueError("Invalid truth separation")++ if Path(args.output).exists(): raise FileExistsError("Evaluation output exists")++ rows = []++ for case in manifest["cases"]:++ target = np.asarray(truth["cases"][case["case_id"]]["receiver_enu_m"])++ for result in case["results"]:++ for rank, mode in enumerate(result["local_modes"], 1):++ point = np.array([mode["east_m"], mode["north_m"], result["receiver_up_m"]])++ rows.append(dict(case_id=case["case_id"], result_id=result["id"], mode_rank=rank,++ horizontal_error_m=np.linalg.norm(point[:2]-target[:2]), position_error_m=np.linalg.norm(point-target),++ loss_hz=mode["loss_hz"], grid_support_complete=result["grid_assessment_complete"]))++ write(args.output, dict(scope=SCOPE, frozen_search_sha256=sha(folder/"frozen-search.json"),++ truth_sha256=sha(args.truth), rows=rows, product_acceptance=None, generalization_established=False,++ interpretation="Measured errors for frozen conditional modes; no unique national localization or calibrated accuracy claim."))++ print(json.dumps(dict(evaluation=args.output, mode_rows=len(rows))))++++++def numbers(text):++ values = [float(x) for x in text.split(",")]++ if not values or not np.all(np.isfinite(values)) or len(set(values)) != len(values):++ raise argparse.ArgumentTypeError("Need distinct finite comma-separated numbers")++ return values++++++def main():++ parser = argparse.ArgumentParser(description=__doc__)++ commands = parser.add_subparsers(dest="command", required=True)++ p = commands.add_parser("prepare")++ p.add_argument("--source-directory", required=True)++ p.add_argument("--case-manifest", required=True)++ p.add_argument("--output", required=True)++ p.add_argument("--padding-m", type=float, default=1000.0)++ p.set_defaults(func=prepare)++ p = commands.add_parser("search")++ p.add_argument("--inputs", required=True)++ p.add_argument("--domain", required=True)++ p.add_argument("--output", required=True)++ p.add_argument("--discovery-window-s", type=float, default=2.0)++ p.add_argument("--discovery-hop-s", type=float, default=0.5)++ p.add_argument("--grid-step-m", type=float, default=50.0)++ p.add_argument("--max-grid-points", type=int, default=25000)++ p.add_argument("--clock-offsets-s", type=numbers, default=[0.0])++ p.add_argument("--drift-fractions", type=numbers, default=[0.0, 0.02])++ p.add_argument("--receiver-up-m", type=numbers, default=[0.0])++ p.add_argument("--sound-speed-mps", type=float)++ p.set_defaults(func=search)++ p = commands.add_parser("evaluate")++ p.add_argument("--search-directory", required=True)++ p.add_argument("--truth", required=True)++ p.add_argument("--output", required=True)++ p.set_defaults(func=evaluate)++ args = parser.parse_args()++ if hasattr(args, "padding_m") and (not np.isfinite(args.padding_m) or args.padding_m <= 0):++ parser.error("Padding must be finite and positive")++ args.func(args)++++++if __name__ == "__main__":++ main()diff --cc scripts/download_nasa_cases.pyindex 0000000,0000000..76b62c8new file mode 100644--- /dev/null+++ b/scripts/download_nasa_cases.py@@@ -1,0 -1,0 +1,249 @@@++#!/usr/bin/env python3++"""Retrieve the original NASA MAT files pinned by the session-case manifest.++++Download: python scripts/download_nasa_cases.py --output data/nasa-originals++Verify existing originals or file symlinks: add --verify-only to that command.++Downloads require a new directory. Verification writes nothing and uses no network.++"""++import argparse++import errno++import hashlib++import http.client++import json++import os++from pathlib import Path++import re++import socket++import ssl++import stat++import struct++import sys++import time++import urllib.error++import urllib.request++import zlib++++++URL = "https://data.nasa.gov/docs/datasets/rfk401li/small_uav_acoustics.zip"++MANIFEST = Path(__file__).resolve().parents[1] / "benchmarks/nasa-session-cases-20261103.json"++LIMIT = 64 * 1024**2++RETRIES = 3++TRANSIENT_HTTP = {408, 429, 500, 502, 503, 504}++TRANSIENT_ERRNO = {errno.ECONNABORTED, errno.ECONNREFUSED, errno.ECONNRESET,++ errno.ENETDOWN, errno.ENETUNREACH, errno.EHOSTUNREACH,++ errno.ETIMEDOUT, errno.EPIPE}++++++def pinned_cases():++ manifest = json.loads(MANIFEST.read_text())++ if (not isinstance(manifest, dict)++ or manifest.get("schema") != "nasa_measured_case_selection_v1"++ or manifest.get("source_archive_url") != URL):++ raise ValueError("The pinned manifest must identify the official NASA archive")++ cases = manifest.get("cases")++ if not isinstance(cases, list) or not cases:++ raise ValueError("The pinned manifest contains no cases")++ seen = set()++ for case in cases:++ if not isinstance(case, dict):++ raise ValueError("Invalid pinned NASA case")++ name = case.get("case_id")++ size, digest = case.get("size_bytes"), case.get("sha256")++ if (not isinstance(name, str) or not re.fullmatch(r"(?:cub|edge)_flyover_[0-9]{3}", name)++ or name in seen or case.get("archive_member") != f"data/{name}.mat"++ or type(size) is not int or not 0 < size <= LIMIT++ or not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest)):++ raise ValueError("Invalid, duplicate, or oversized pinned NASA member")++ seen.add(name)++ return cases++++++def transient(error):++ if isinstance(error, urllib.error.HTTPError):++ return error.code in TRANSIENT_HTTP++ if isinstance(error, urllib.error.URLError):++ return transient(error.reason)++ if isinstance(error, socket.gaierror):++ return error.errno == socket.EAI_AGAIN++ return (isinstance(error, (TimeoutError, http.client.IncompleteRead,++ http.client.RemoteDisconnected, ssl.SSLEOFError))++ or isinstance(error, OSError) and error.errno in TRANSIENT_ERRNO)++++++class FixedSourceRedirect(urllib.request.HTTPRedirectHandler):++ def redirect_request(self, request, response, code, message, headers, newurl):++ if newurl != URL:++ raise ValueError("NASA redirected outside the fixed source URL")++ return super().redirect_request(request, response, code, message, headers, newurl)++++++class Archive:++ """Bounded ZIP reader adapted from PR #96, commit 5582002be34e0e1e9df6735e7a4227ca4c0fc899."""++++ def __init__(self):++ self.opener = urllib.request.build_opener(FixedSourceRedirect())++ tail, start, self.size = self.fetch(suffix=131072)++ self.tail, self.tail_start = tail, start++ position = tail.rfind(b"PK\x05\x06")++ if position < 0 or position + 22 > len(tail):++ raise ValueError("Missing ZIP directory terminator")++ end = struct.unpack_from("<4s4H2LH", tail, position)++ if (end[1:3] != (0, 0) or end[3] != end[4] or end[4] == 65535++ or position + 22 + end[7] != len(tail)):++ raise ValueError("Unsupported split/ZIP64 archive or invalid ZIP length")++ self.directory_offset = end[6]++ cursor = end[6] - start++ if cursor < 0 or cursor + end[5] != position:++ raise ValueError("Central directory does not fit the bounded suffix")++ self.members = {}++ while cursor < position:++ if cursor + 46 > position:++ raise ValueError("Truncated central directory entry")++ header = struct.unpack_from("<4s6H3L5H2L", tail, cursor)++ n, extra, comment = header[10:13]++ next_cursor = cursor + 46 + n + extra + comment++ if (header[0] != b"PK\x01\x02" or header[13] != 0 or next_cursor > position++ or any(header[i] == 0xffffffff for i in (8, 9, 16))):++ raise ValueError("Invalid or unsupported central directory entry")++ name = tail[cursor + 46:cursor + 46 + n].decode("utf-8")++ if name in self.members:++ raise ValueError("Duplicate ZIP member name")++ self.members[name] = dict(name=name, flags=header[3], method=header[4], crc32=header[7],++ compressed_bytes=header[8], bytes=header[9], local_header_offset=header[16])++ cursor = next_cursor++ if len(self.members) != end[4] or cursor != position:++ raise ValueError("Central directory count/length mismatch")++++ def fetch(self, lo=None, hi=None, suffix=None):++ if suffix is not None:++ if type(suffix) is not int or not 0 < suffix <= LIMIT:++ raise ValueError("Invalid suffix budget")++ value = f"bytes=-{suffix}"++ else:++ if (type(lo) is not int or type(hi) is not int or not 0 <= lo <= hi++ or hi - lo + 1 > LIMIT or hasattr(self, "size") and hi >= self.size):++ raise ValueError("Invalid or oversized range")++ value = f"bytes={lo}-{hi}"++ if hasattr(self, "tail") and self.tail_start <= lo <= hi < self.size:++ return self.tail[lo - self.tail_start:hi - self.tail_start + 1], lo, self.size++ request = urllib.request.Request(URL, headers={"Range": value, "Accept-Encoding": "identity"})++ for attempt in range(RETRIES + 1):++ try:++ with self.opener.open(request, timeout=30) as response:++ match = re.fullmatch(r"bytes (\d+)-(\d+)/(\d+)", response.headers.get("Content-Range", ""))++ if (response.status != 206 or not match++ or response.headers.get("Content-Encoding", "identity").lower() != "identity"):++ raise ValueError("Server did not honor the exact unencoded range request")++ start, stop, total = map(int, match.groups())++ expected = stop - start + 1++ if (not 0 <= start <= stop < total or expected > LIMIT++ or suffix is not None and (start, stop) != (max(0, total - suffix), total - 1)++ or suffix is None and (start, stop) != (lo, hi)++ or hasattr(self, "size") and total != self.size):++ raise ValueError("Unexpected range bounds or changed archive length")++ length = response.headers.get("Content-Length")++ if length is not None and (not length.isdecimal() or int(length) != expected):++ raise ValueError("Range Content-Length mismatch")++ data = response.read(expected + 1)++ if len(data) != expected:++ raise ValueError("Source range length mismatch")++ return data, start, total++ except (urllib.error.URLError, OSError, http.client.IncompleteRead,++ http.client.RemoteDisconnected) as error:++ retry = attempt < RETRIES and transient(error)++ if isinstance(error, urllib.error.HTTPError):++ error.close()++ if not retry:++ raise++ print(f"Transient NASA transfer failure; retry {attempt + 1}/{RETRIES}", file=sys.stderr)++ time.sleep(2**attempt)++++ def member(self, entry):++ offset = entry["local_header_offset"]++ if (not 0 < entry["bytes"] <= LIMIT or not 0 < entry["compressed_bytes"] <= LIMIT++ or not 0 <= offset < self.directory_offset - 29):++ raise ValueError("Member exceeds the declared download budget")++ header, _, _ = self.fetch(offset, offset + 29)++ h = struct.unpack("<4s5H3L2H", header)++ if (h[0] != b"PK\x03\x04" or h[2] != entry["flags"] or h[2] & (1 | 64)++ or h[3] != entry["method"]):++ raise ValueError("Unsupported or inconsistent local ZIP header")++ if not h[2] & 8 and (h[6], h[7], h[8]) != (entry["crc32"], entry["compressed_bytes"], entry["bytes"]):++ raise ValueError("Local and central ZIP lengths/CRC differ")++ name = entry["name"].encode("utf-8")++ if h[9] != len(name):++ raise ValueError("Local and central ZIP filenames differ")++ local_name, _, _ = self.fetch(offset + 30, offset + 29 + h[9])++ if local_name != name:++ raise ValueError("Local and central ZIP filenames differ")++ start = offset + 30 + h[9] + h[10]++ stop = start + entry["compressed_bytes"] - 1++ if stop >= self.directory_offset:++ raise ValueError("Member overlaps the ZIP directory")++ raw, _, _ = self.fetch(start, stop)++ if entry["method"] == 8:++ decoder = zlib.decompressobj(-15)++ data = decoder.decompress(raw, entry["bytes"] + 1)++ if not decoder.eof or decoder.unconsumed_tail or decoder.unused_data:++ raise ValueError("Member decompression exceeded its declared length")++ elif entry["method"] == 0:++ data = raw++ else:++ raise ValueError("Unsupported member compression")++ if len(data) != entry["bytes"] or zlib.crc32(data) != entry["crc32"]:++ raise ValueError("Member length/CRC mismatch")++ return data++++++def verify_existing(path, case):++ if not path.is_file():++ raise ValueError(f"Original file is absent or not regular: {path}")++ digest, size = hashlib.sha256(), 0++ with path.open("rb") as stream:++ info = os.fstat(stream.fileno())++ if not stat.S_ISREG(info.st_mode) or info.st_size != case["size_bytes"]:++ raise ValueError(f"Original file size/type mismatch: {path}")++ while chunk := stream.read(min(1024**2, case["size_bytes"] + 1 - size)):++ digest.update(chunk)++ size += len(chunk)++ if size > case["size_bytes"]:++ raise ValueError(f"Original file grew during verification: {path}")++ if size != case["size_bytes"] or digest.hexdigest() != case["sha256"]:++ raise ValueError(f"Original file SHA256/length mismatch: {path}")++++++def main():++ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)++ parser.add_argument("--output", type=Path, required=True, help="New download directory, or existing originals with --verify-only")++ parser.add_argument("--verify-only", action="store_true", help="Verify existing originals or file symlinks without network access or writes")++ args = parser.parse_args()++ cases = pinned_cases()++ if not args.verify_only and (args.output.exists() or args.output.is_symlink()):++ raise FileExistsError("Downloads require a new output directory")++ output = args.output.resolve()++ if args.verify_only:++ if not output.is_dir():++ raise ValueError("Verification requires an existing directory")++ for case in cases:++ path = output / f"{case['case_id']}.mat"++ verify_existing(path, case)++ print(f"Verified {path.name} ({case['size_bytes']} bytes)")++ else:++ output.mkdir(parents=True, exist_ok=False)++ archive = Archive()++ for case in cases:++ entry = archive.members.get(case["archive_member"])++ if entry is None or entry["bytes"] != case["size_bytes"]:++ raise ValueError(f"Pinned NASA member is missing or changed: {case['archive_member']}")++ data = archive.member(entry)++ if hashlib.sha256(data).hexdigest() != case["sha256"]:++ raise ValueError(f"Pinned NASA SHA256 mismatch: {case['archive_member']}")++ path = output / f"{case['case_id']}.mat"++ with path.open("xb") as stream:++ stream.write(data)++ print(f"Downloaded and verified {path.name} ({len(data)} bytes)")++ print(f"Verified {len(cases)} original NASA files in {output}")++++++if __name__ == "__main__":++ main()diff --cc scripts/verify_real_upload_browser.pyindex 0000000,0000000..c38afd2new file mode 100644--- /dev/null+++ b/scripts/verify_real_upload_browser.py@@@ -1,0 -1,0 +1,235 @@@++#!/usr/bin/env python3++"""Verify the real browser upload and saved needs-input result for a supplied MP3.++++Requires an installed dopplergeist package, Playwright, and its Chromium browser.++Playwright is an optional verification dependency, not a production dependency.++Use a real recording without a trustworthy embedded clock. No audio is generated.++A passing browser check does not establish location accuracy.++"""++import argparse++from datetime import datetime, timezone++import hashlib++import json++import math++import os++from pathlib import Path++import re++import signal++import subprocess++import sys++import time++++++def require(condition, message):++ if not condition:++ raise AssertionError(message)++++++def digest(path):++ with Path(path).open("rb") as stream:++ return hashlib.file_digest(stream, "sha256").hexdigest()++++++def stop_service(process):++ """Signal only the process group created by this verifier."""++ sent = []++ for signum, grace in ((signal.SIGINT, 10), (signal.SIGTERM, 3), (signal.SIGKILL, 3)):++ if process.poll() is not None:++ break++ try:++ os.killpg(process.pid, signum)++ sent.append(signal.Signals(signum).name)++ except ProcessLookupError:++ pass++ try:++ process.wait(timeout=grace)++ except subprocess.TimeoutExpired:++ continue++ return {"returncode": process.poll(), "signals": sent,++ "clean": process.poll() == 0 and not any(s != "SIGINT" for s in sent)}++++++def main():++ parser = argparse.ArgumentParser(description=__doc__)++ parser.add_argument("audio", type=Path, help="Existing real MP3 recording")++ parser.add_argument("--output", required=True, type=Path, help="New directory; existing paths are refused")++ parser.add_argument("--timeout", type=float, default=900, help="Overall verification budget in seconds")++ args = parser.parse_args()++ audio, output = args.audio.resolve(), args.output.resolve()++ if os.name != "posix":++ parser.error("This verifier requires POSIX process groups (for example, Ubuntu CI)")++ if not audio.is_file() or audio.suffix.lower() != ".mp3" or audio.stat().st_size == 0:++ parser.error("Supply a nonempty existing MP3 file")++ if not math.isfinite(args.timeout) or args.timeout <= 0:++ parser.error("--timeout must be finite and positive")++ output.mkdir(parents=True, exist_ok=False)++ jobs = output / "jobs"++ started = time.monotonic()++ deadline = started + args.timeout++ errors, screenshots = [], []++ summary = {"scope": "actual_browser_real_upload", "passed": False,++ "started_utc": datetime.now(timezone.utc).isoformat(),++ "audio": str(audio), "source_sha256": digest(audio),++ "page_errors": errors, "screenshots": screenshots,++ "location_accuracy_evaluated": False}++ process = log = None++ final = job_directory = None++ old_handlers = {}++++ def milliseconds(cap=None):++ left = deadline - time.monotonic()++ if left <= 0:++ raise TimeoutError("Browser verification exceeded its time budget")++ return max(1, int(1000 * (min(left, cap) if cap else left)))++++ def interrupted(signum, _frame):++ raise InterruptedError(f"Interrupted by {signal.Signals(signum).name}")++++ try:++ for signum in (signal.SIGINT, signal.SIGTERM):++ old_handlers[signum] = signal.signal(signum, interrupted)++ # Lazy import keeps --help usable without the optional browser dependency.++ from playwright.sync_api import expect, sync_playwright++ command = [sys.executable, "-I", "-m", "dopplergeist.cli", "serve",++ "--port", "0", "--jobs", str(jobs), "--max-runtime", str(args.timeout)]++ summary["service_command"] = command++ log_path = output / "service.log"++ log = log_path.open("xb")++ process = subprocess.Popen(command, cwd=output, stdout=log, stderr=subprocess.STDOUT,++ start_new_session=True)++ startup_deadline = min(deadline, time.monotonic() + 30)++ while True:++ require(process.poll() is None, "Service exited during startup; inspect service.log")++ match = re.search(r"DOPPLERGEIST: (http://127\.0\.0\.1:\d+) ", log_path.read_text())++ if match:++ origin = match.group(1)++ break++ if time.monotonic() >= startup_deadline:++ raise TimeoutError("Service did not start within the startup budget")++ time.sleep(0.1)++++ with sync_playwright() as playwright:++ browser = page = None++ try:++ browser = playwright.chromium.launch(headless=True, timeout=milliseconds(30))++ context = browser.new_context(viewport={"width": 1440, "height": 1000})++ context.set_default_timeout(milliseconds(30))++ page = context.new_page()++ page.on("pageerror", lambda error: errors.append(str(error)))++ page.goto(origin, wait_until="domcontentloaded", timeout=milliseconds(30))++ for selector in ("#start", "#end", "#time-source"):++ expect(page.locator(selector)).to_have_value("", timeout=milliseconds(10))++ page.locator("#audio").set_input_files(str(audio), timeout=milliseconds(30))++ with page.expect_response(lambda response: response.url == origin + "/api/jobs"++ and response.request.method == "POST",++ timeout=milliseconds()) as uploaded:++ page.locator("#submit").click(timeout=milliseconds(30))++ response = uploaded.value++ require(response.status == 202, f"UI upload returned HTTP {response.status}")++ job_id = response.json()["job_id"]++ require(re.fullmatch(r"[0-9a-f]{32}", job_id), "Invalid submitted job identifier")++ job_directory = jobs / job_id++ saved_url = origin + "/?job=" + job_id++ summary.update(job_id=job_id, saved_job_url=saved_url)++ page.wait_for_url(saved_url, timeout=milliseconds(30))++ terminal = re.compile(r"^(needs input|succeeded|inconclusive|failed|cancelled)$")++ expect(page.locator("#status")).to_have_text(terminal, timeout=milliseconds())++++ def api_result():++ reply = context.request.get(origin + "/api/jobs/" + job_id, timeout=milliseconds(30))++ require(reply.status == 200, f"Job API returned HTTP {reply.status}")++ return reply.json()++++ final = api_result()++ summary.update(status=final.get("status"), reason_code=final.get("reason_code"),++ event_count=len(final.get("events", [])))++ require(final.get("job_id") == job_id, "API returned a different job")++ require(final.get("status") == "needs_input", "Expected needs_input")++ require(final.get("reason_code") == "recording_time_required", "Expected recording_time_required")++ require("time_window" in final.get("required_fields", []), "API omitted required time_window")++ require(not final.get("candidates"), "Undated result contains location candidates")++++ def check_display():++ expect(page.locator("#status")).to_have_text("needs input", timeout=milliseconds(30))++ expect(page.locator("#job-id")).to_have_text("JOB " + job_id, timeout=milliseconds(10))++ expect(page.locator("#events .event")).to_have_count(len(final.get("events", [])), timeout=milliseconds(30))++ expect(page.locator("#required")).to_be_visible(timeout=milliseconds(10))++ expect(page.locator("#required")).to_contain_text("time_window", timeout=milliseconds(10))++ expect(page.locator("#candidates .candidate")).to_have_count(0, timeout=milliseconds(10))++ expect(page.locator("#upload-error")).to_have_text("", timeout=milliseconds(10))++ expect(page.locator("#connection")).to_have_text("", timeout=milliseconds(10))++++ check_display()++ summary["displayed_event_count"] = page.locator("#events .event").count()++ summary["required_message"] = page.locator("#required").inner_text()++ page.locator("#required").scroll_into_view_if_needed(timeout=milliseconds(10))++ page.screenshot(path=str(output / "result.png"), timeout=milliseconds(10))++ screenshots.append("result.png")++ figure = page.locator("#diagnostics figure.diagnostic").first++ figure.wait_for(state="visible", timeout=milliseconds(30))++ figure.scroll_into_view_if_needed(timeout=milliseconds(10))++ page.wait_for_function("""() => {++ const image = document.querySelector('#diagnostics figure.diagnostic img');++ return image && image.complete && image.naturalWidth > 0 && image.naturalHeight > 0;++ }""", timeout=milliseconds(30))++ image = figure.locator("img").evaluate("image => ({src: image.getAttribute('src'), width: image.naturalWidth, height: image.naturalHeight})")++ require(image["src"].startswith(f"/api/jobs/{job_id}/artifacts/"), "Evidence image belongs to a different job")++ summary["loaded_evidence_image"] = image++ figure.screenshot(path=str(output / "evidence.png"), timeout=milliseconds(10))++ screenshots.append("evidence.png")++++ # Reload the real saved URL; the application's startup code must restore the job.++ require(page.url == saved_url, "Saved job URL changed")++ page.reload(wait_until="domcontentloaded", timeout=milliseconds(30))++ check_display()++ page.locator("#diagnostics figure.diagnostic").first.wait_for(state="visible", timeout=milliseconds(30))++ expect(page.locator("#connection")).to_have_text("", timeout=milliseconds(10))++ require(api_result() == final, "Terminal API result changed after reload")++ summary["saved_job_reload_verified"] = True++ request = json.loads((job_directory / "request.json").read_text())++ require(not request.get("time_window"), "Browser unexpectedly supplied a recording time")++ require(digest(job_directory / "input.mp3") == summary["source_sha256"], "Uploaded original bytes changed")++ summary["original_preserved"] = True++ require(not errors, "Browser reported uncaught page errors")++ summary["passed"] = True++ except BaseException:++ if page is not None and len(screenshots) < 2:++ try:++ page.screenshot(path=str(output / "failure.png"), timeout=5000)++ screenshots.append("failure.png")++ except Exception:++ pass++ raise++ finally:++ if browser is not None:++ browser.close()++ except BaseException as error:++ summary.update(passed=False, error=f"{type(error).__name__}: {error}")++ finally:++ # Repeated cancellation must not interrupt shutdown of our own service.++ for signum in old_handlers:++ signal.signal(signum, signal.SIG_IGN)++ try:++ if process is not None:++ summary["service_shutdown"] = stop_service(process)++ require(summary["service_shutdown"]["clean"], "Service did not stop cleanly")++ if final is not None and job_directory is not None:++ retained = json.loads((job_directory / "result.json").read_text()) == final++ summary["terminal_result_preserved"] = retained++ require(retained, "Persisted terminal result differs from the API result")++ except BaseException as error:++ summary["passed"] = False++ summary["cleanup_error"] = f"{type(error).__name__}: {error}"++ finally:++ if log is not None:++ log.close()++ for signum, handler in old_handlers.items():++ signal.signal(signum, handler)++ summary["elapsed_s"] = time.monotonic() - started++ (output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")++ print(json.dumps(summary, indent=2))++ return 0 if summary["passed"] else 1++++++if __name__ == "__main__":++ raise SystemExit(main())diff --cc src/dopplergeist/search.pyindex 6dcb790,351922f..3c4049d--- a/src/dopplergeist/search.py+++ b/src/dopplergeist/search.py@@@ -206,134 -206,10 +206,128 @@@ def event_score(track, observer, spectrf0 = np.clip(np.sum(w*factor[valid]*ridge[valid])/np.sum(w*factor[valid]**2),*f0_bounds)rmse = np.sqrt(np.average((f0*factor[valid]-ridge[valid])**2,weights=w))return -float(rmse),float(f0)- frequencies = np.linspace(*f0_bounds,max(3,int(np.ceil((f0_bounds[1]-f0_bounds[0])/frequency_step))+1))- predicted = frequencies[:,None]*factor[None,:]- contrast = spectrum.sample(times[None,:],predicted)- # Fixed support: candidates do not gain points by leaving the frequency band.- scores = np.where(np.mean(np.isfinite(contrast),axis=1)>=0.95,- np.mean(np.nan_to_num(contrast,nan=-4.0),axis=1),-np.inf)- best = np.argmax(scores)- return float(scores[best]),float(frequencies[best])+ from .spectral_grid import best_frequency+ return best_frequency(spectrum, times, factor, f0_bounds, frequency_step)+def _ridge_trial_classification(result, events, association):+ """Classify recorded core fits, without changing their score or rejection rule.++ Missing support and numerical failures are unknown. A supported finite fit+ can be rejected only by the existing association residual thresholds.+ """+ def finite(value):+ return (isinstance(value, (int, float, np.integer, np.floating))+ and not isinstance(value, (bool, np.bool_)) and np.isfinite(value))++ diagnostics = result.get("event_diagnostics")+ scores, frequencies = result.get("event_scores"), result.get("f0_hz")+ if (not isinstance(diagnostics, list) or not isinstance(scores, list) or not isinstance(frequencies, list)+ or not len(diagnostics) == len(scores) == len(frequencies) == len(events)):+ return "unknown", "missing_event_fit_evidence"+ fields = ("score", "f0_hz", "source_drift_hz", "source_drift_hz_s",+ "source_reference_emission_time_s", "source_span_s", "drift_bound_hz", "rmse_hz", "outlier_fraction")+ for diagnostic, score, frequency, event in zip(diagnostics, scores, frequencies, events):+ if (not isinstance(diagnostic, dict) or not finite(diagnostic.get("support_fraction"))+ or diagnostic["support_fraction"] != 1.0):+ return "unknown", "incomplete_acoustic_support"+ if (not all(finite(diagnostic.get(name)) for name in fields)+ or not finite(score) or not finite(frequency)):+ return "unknown", "nonfinite_fit_evidence"+ count, independent = diagnostic.get("sample_count"), diagnostic.get("independent_sample_count")+ if (type(count) is not int or type(independent) is not int or not 1 <= independent <= count+ or count < 10 or diagnostic["source_span_s"] <= 0 or diagnostic["drift_bound_hz"] < 0+ or diagnostic["rmse_hz"] < 0 or not 0 <= diagnostic["outlier_fraction"] <= 1+ or diagnostic["f0_hz"] <= 0 or diagnostic["score"] > 0):+ return "unknown", "invalid_fit_evidence"+ if "optimizer_success" in diagnostic and diagnostic["optimizer_success"] is not True:+ return "unknown", "failed_optimizer"+ if score != diagnostic["score"] or frequency != diagnostic["f0_hz"]:+ return "unknown", "inconsistent_event_fit_evidence"+ bounds = event.get("f0_range_hz")+ fraction = event.get("quality", {}).get("source_drift_fraction", 0.02)+ if (not isinstance(bounds, (list, tuple)) or len(bounds) != 2+ or not all(finite(value) for value in bounds) or not 0 < bounds[0] <= bounds[1]+ or not bounds[0] <= frequency <= bounds[1]+ or not finite(fraction) or not 0 <= fraction <= 0.1):+ return "unknown", "fit_outside_declared_frequency_domain"+ drift, cap = diagnostic["source_drift_hz"], diagnostic["drift_bound_hz"]+ if not bounds[0] * fraction <= cap <= bounds[1] * fraction or abs(drift) > cap:+ return "unknown", "fit_outside_declared_drift_domain"+ if not np.isclose(diagnostic["source_drift_hz_s"] * diagnostic["source_span_s"], drift,+ rtol=1e-12, atol=1e-12):+ return "unknown", "inconsistent_source_drift"+ if "optimizer_success" in result and result["optimizer_success"] is not True:+ return "unknown", "failed_optimizer"+ residual = float(sum(scores))+ if not finite(residual):+ return "unknown", "nonfinite_residual_score"+ if not association:+ if (result.get("score_kind") == "negative_robust_ridge_loss_hz"+ and finite(result.get("score")) and result["score"] == residual):+ return "evaluated", None+ return "unknown", "inconsistent_residual_score"+ from .matching import _frequency_scale+ limits = [3 * _frequency_scale(event) for event in events]+ if (result.get("score_kind") != "matched_group_support_minus_normalized_residual"+ or not finite(result.get("residual_score")) or result["residual_score"] != residual+ or not all(finite(v) and v > 0 for v in limits)):+ return "unknown", "inconsistent_association_evidence"+ supported = all(-score <= limit for score, limit in zip(scores, limits))+ if supported:+ expected = float(sum(1 - (-score) / limit for score, limit in zip(scores, limits)))+ if finite(result.get("score")) and result["score"] == expected:+ return "evaluated", None+ elif result.get("score") == -np.inf:+ return "rejected", "association_residual_limit"+ return "unknown", "unexplained_association_score"++++def _association_trial_bound(result, events):+ """Bound an incompletely supported association at one shared clock.++ The declared score is sum(1 - loss_i / limit_i), or -inf if any event+ fails its residual limit. Each nonnegative unknown loss contributes at+ most one. Only a fully validated core fit can tighten that ceiling or+ establish a residual rejection. Missing support is still unknown.+ """+ kind = "matched_group_support_minus_normalized_residual"+ if not events or not isinstance(result, dict) or result.get("score_kind") != kind:+ return None+ from .matching import _frequency_scale+ try:+ limits = [3 * _frequency_scale(event) for event in events]+ except (TypeError, ValueError, KeyError):+ return None+ if not all(np.isfinite(value) and value > 0 for value in limits):+ return None+ maximum = float(len(events))+ diagnostics, scores, frequencies = (result.get(name) for name in ("event_diagnostics", "event_scores", "f0_hz"))+ if (not all(isinstance(values, list) and len(values) == len(events)+ for values in (diagnostics, scores, frequencies))+ or result.get("optimizer_success", True) is not True):+ return maximum+ contributions = []+ for diagnostic, score, frequency, event, limit in zip(diagnostics, scores, frequencies, events, limits):+ single = {"score_kind": "negative_robust_ridge_loss_hz", "score": score,+ "event_scores": [score], "f0_hz": [frequency], "event_diagnostics": [diagnostic]}+ classification, _ = _ridge_trial_classification(single, [event], False)+ if classification != "evaluated":+ contributions.append(1.0)+ continue+ if -score > limit:+ return -np.inf+ # Use the scorer's per-event arithmetic, then round every contribution+ # and positive accumulation upward. Subtracting losses from k instead+ # changes the operation order and can understate a floating-point score.+ contributions.append(float(np.nextafter(1 - (-score) / limit, np.inf)))+ upper = 0.0+ for contribution in contributions:+ upper = float(np.nextafter(upper + contribution, np.inf))+ return min(maximum, upper)++def score_candidate(candidate, point, tracks, events, measurements, mode="brightness",time_origin=None, time_sweep_s=5.0, time_step_s=0.5, c=343.0):association = "event_indices" in candidate